Client.php 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626
  1. <?php
  2. /*
  3. * This file is part of the Symfony package.
  4. *
  5. * (c) Fabien Potencier <fabien@symfony.com>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace Symfony\Component\BrowserKit;
  11. use Symfony\Component\DomCrawler\Crawler;
  12. use Symfony\Component\DomCrawler\Form;
  13. use Symfony\Component\DomCrawler\Link;
  14. use Symfony\Component\Process\PhpProcess;
  15. /**
  16. * Client simulates a browser.
  17. *
  18. * To make the actual request, you need to implement the doRequest() method.
  19. *
  20. * If you want to be able to run requests in their own process (insulated flag),
  21. * you need to also implement the getScript() method.
  22. *
  23. * @author Fabien Potencier <fabien@symfony.com>
  24. */
  25. abstract class Client
  26. {
  27. protected $history;
  28. protected $cookieJar;
  29. protected $server = [];
  30. protected $internalRequest;
  31. protected $request;
  32. protected $internalResponse;
  33. protected $response;
  34. protected $crawler;
  35. protected $insulated = false;
  36. protected $redirect;
  37. protected $followRedirects = true;
  38. private $maxRedirects = -1;
  39. private $redirectCount = 0;
  40. private $redirects = [];
  41. private $isMainRequest = true;
  42. /**
  43. * @param array $server The server parameters (equivalent of $_SERVER)
  44. * @param History $history A History instance to store the browser history
  45. * @param CookieJar $cookieJar A CookieJar instance to store the cookies
  46. */
  47. public function __construct(array $server = [], History $history = null, CookieJar $cookieJar = null)
  48. {
  49. $this->setServerParameters($server);
  50. $this->history = $history ?: new History();
  51. $this->cookieJar = $cookieJar ?: new CookieJar();
  52. }
  53. /**
  54. * Sets whether to automatically follow redirects or not.
  55. *
  56. * @param bool $followRedirect Whether to follow redirects
  57. */
  58. public function followRedirects($followRedirect = true)
  59. {
  60. $this->followRedirects = (bool) $followRedirect;
  61. }
  62. /**
  63. * Returns whether client automatically follows redirects or not.
  64. *
  65. * @return bool
  66. */
  67. public function isFollowingRedirects()
  68. {
  69. return $this->followRedirects;
  70. }
  71. /**
  72. * Sets the maximum number of redirects that crawler can follow.
  73. *
  74. * @param int $maxRedirects
  75. */
  76. public function setMaxRedirects($maxRedirects)
  77. {
  78. $this->maxRedirects = $maxRedirects < 0 ? -1 : $maxRedirects;
  79. $this->followRedirects = -1 != $this->maxRedirects;
  80. }
  81. /**
  82. * Returns the maximum number of redirects that crawler can follow.
  83. *
  84. * @return int
  85. */
  86. public function getMaxRedirects()
  87. {
  88. return $this->maxRedirects;
  89. }
  90. /**
  91. * Sets the insulated flag.
  92. *
  93. * @param bool $insulated Whether to insulate the requests or not
  94. *
  95. * @throws \RuntimeException When Symfony Process Component is not installed
  96. */
  97. public function insulate($insulated = true)
  98. {
  99. if ($insulated && !class_exists('Symfony\\Component\\Process\\Process')) {
  100. throw new \RuntimeException('Unable to isolate requests as the Symfony Process Component is not installed.');
  101. }
  102. $this->insulated = (bool) $insulated;
  103. }
  104. /**
  105. * Sets server parameters.
  106. *
  107. * @param array $server An array of server parameters
  108. */
  109. public function setServerParameters(array $server)
  110. {
  111. $this->server = array_merge([
  112. 'HTTP_USER_AGENT' => 'Symfony BrowserKit',
  113. ], $server);
  114. }
  115. /**
  116. * Sets single server parameter.
  117. *
  118. * @param string $key A key of the parameter
  119. * @param string $value A value of the parameter
  120. */
  121. public function setServerParameter($key, $value)
  122. {
  123. $this->server[$key] = $value;
  124. }
  125. /**
  126. * Gets single server parameter for specified key.
  127. *
  128. * @param string $key A key of the parameter to get
  129. * @param mixed $default A default value when key is undefined
  130. *
  131. * @return mixed A value of the parameter
  132. */
  133. public function getServerParameter($key, $default = '')
  134. {
  135. return isset($this->server[$key]) ? $this->server[$key] : $default;
  136. }
  137. /**
  138. * Returns the History instance.
  139. *
  140. * @return History A History instance
  141. */
  142. public function getHistory()
  143. {
  144. return $this->history;
  145. }
  146. /**
  147. * Returns the CookieJar instance.
  148. *
  149. * @return CookieJar A CookieJar instance
  150. */
  151. public function getCookieJar()
  152. {
  153. return $this->cookieJar;
  154. }
  155. /**
  156. * Returns the current Crawler instance.
  157. *
  158. * @return Crawler|null A Crawler instance
  159. */
  160. public function getCrawler()
  161. {
  162. return $this->crawler;
  163. }
  164. /**
  165. * Returns the current BrowserKit Response instance.
  166. *
  167. * @return Response|null A BrowserKit Response instance
  168. */
  169. public function getInternalResponse()
  170. {
  171. return $this->internalResponse;
  172. }
  173. /**
  174. * Returns the current origin response instance.
  175. *
  176. * The origin response is the response instance that is returned
  177. * by the code that handles requests.
  178. *
  179. * @return object|null A response instance
  180. *
  181. * @see doRequest()
  182. */
  183. public function getResponse()
  184. {
  185. return $this->response;
  186. }
  187. /**
  188. * Returns the current BrowserKit Request instance.
  189. *
  190. * @return Request|null A BrowserKit Request instance
  191. */
  192. public function getInternalRequest()
  193. {
  194. return $this->internalRequest;
  195. }
  196. /**
  197. * Returns the current origin Request instance.
  198. *
  199. * The origin request is the request instance that is sent
  200. * to the code that handles requests.
  201. *
  202. * @return object|null A Request instance
  203. *
  204. * @see doRequest()
  205. */
  206. public function getRequest()
  207. {
  208. return $this->request;
  209. }
  210. /**
  211. * Clicks on a given link.
  212. *
  213. * @return Crawler
  214. */
  215. public function click(Link $link)
  216. {
  217. if ($link instanceof Form) {
  218. return $this->submit($link);
  219. }
  220. return $this->request($link->getMethod(), $link->getUri());
  221. }
  222. /**
  223. * Submits a form.
  224. *
  225. * @param Form $form A Form instance
  226. * @param array $values An array of form field values
  227. *
  228. * @return Crawler
  229. */
  230. public function submit(Form $form, array $values = [])
  231. {
  232. $form->setValues($values);
  233. return $this->request($form->getMethod(), $form->getUri(), $form->getPhpValues(), $form->getPhpFiles());
  234. }
  235. /**
  236. * Calls a URI.
  237. *
  238. * @param string $method The request method
  239. * @param string $uri The URI to fetch
  240. * @param array $parameters The Request parameters
  241. * @param array $files The files
  242. * @param array $server The server parameters (HTTP headers are referenced with a HTTP_ prefix as PHP does)
  243. * @param string $content The raw body data
  244. * @param bool $changeHistory Whether to update the history or not (only used internally for back(), forward(), and reload())
  245. *
  246. * @return Crawler
  247. */
  248. public function request($method, $uri, array $parameters = [], array $files = [], array $server = [], $content = null, $changeHistory = true)
  249. {
  250. if ($this->isMainRequest) {
  251. $this->redirectCount = 0;
  252. } else {
  253. ++$this->redirectCount;
  254. }
  255. $originalUri = $uri;
  256. $uri = $this->getAbsoluteUri($uri);
  257. $server = array_merge($this->server, $server);
  258. if (!empty($server['HTTP_HOST']) && null === parse_url($originalUri, PHP_URL_HOST)) {
  259. $uri = preg_replace('{^(https?\://)'.preg_quote($this->extractHost($uri)).'}', '${1}'.$server['HTTP_HOST'], $uri);
  260. }
  261. if (isset($server['HTTPS']) && null === parse_url($originalUri, PHP_URL_SCHEME)) {
  262. $uri = preg_replace('{^'.parse_url($uri, PHP_URL_SCHEME).'}', $server['HTTPS'] ? 'https' : 'http', $uri);
  263. }
  264. if (!$this->history->isEmpty()) {
  265. $server['HTTP_REFERER'] = $this->history->current()->getUri();
  266. }
  267. if (empty($server['HTTP_HOST'])) {
  268. $server['HTTP_HOST'] = $this->extractHost($uri);
  269. }
  270. $server['HTTPS'] = 'https' == parse_url($uri, PHP_URL_SCHEME);
  271. $this->internalRequest = new Request($uri, $method, $parameters, $files, $this->cookieJar->allValues($uri), $server, $content);
  272. $this->request = $this->filterRequest($this->internalRequest);
  273. if (true === $changeHistory) {
  274. $this->history->add($this->internalRequest);
  275. }
  276. if ($this->insulated) {
  277. $this->response = $this->doRequestInProcess($this->request);
  278. } else {
  279. $this->response = $this->doRequest($this->request);
  280. }
  281. $this->internalResponse = $this->filterResponse($this->response);
  282. $this->cookieJar->updateFromResponse($this->internalResponse, $uri);
  283. $status = $this->internalResponse->getStatus();
  284. if ($status >= 300 && $status < 400) {
  285. $this->redirect = $this->internalResponse->getHeader('Location');
  286. } else {
  287. $this->redirect = null;
  288. }
  289. if ($this->followRedirects && $this->redirect) {
  290. $this->redirects[serialize($this->history->current())] = true;
  291. return $this->crawler = $this->followRedirect();
  292. }
  293. return $this->crawler = $this->createCrawlerFromContent($this->internalRequest->getUri(), $this->internalResponse->getContent(), $this->internalResponse->getHeader('Content-Type'));
  294. }
  295. /**
  296. * Makes a request in another process.
  297. *
  298. * @param object $request An origin request instance
  299. *
  300. * @return object An origin response instance
  301. *
  302. * @throws \RuntimeException When processing returns exit code
  303. */
  304. protected function doRequestInProcess($request)
  305. {
  306. $deprecationsFile = tempnam(sys_get_temp_dir(), 'deprec');
  307. putenv('SYMFONY_DEPRECATIONS_SERIALIZE='.$deprecationsFile);
  308. $_ENV['SYMFONY_DEPRECATIONS_SERIALIZE'] = $deprecationsFile;
  309. $process = new PhpProcess($this->getScript($request), null, null);
  310. $process->run();
  311. if (file_exists($deprecationsFile)) {
  312. $deprecations = file_get_contents($deprecationsFile);
  313. unlink($deprecationsFile);
  314. foreach ($deprecations ? unserialize($deprecations) : [] as $deprecation) {
  315. if ($deprecation[0]) {
  316. // unsilenced on purpose
  317. trigger_error($deprecation[1], E_USER_DEPRECATED);
  318. } else {
  319. @trigger_error($deprecation[1], E_USER_DEPRECATED);
  320. }
  321. }
  322. }
  323. if (!$process->isSuccessful() || !preg_match('/^O\:\d+\:/', $process->getOutput())) {
  324. throw new \RuntimeException(sprintf('OUTPUT: %s ERROR OUTPUT: %s', $process->getOutput(), $process->getErrorOutput()));
  325. }
  326. return unserialize($process->getOutput());
  327. }
  328. /**
  329. * Makes a request.
  330. *
  331. * @param object $request An origin request instance
  332. *
  333. * @return object An origin response instance
  334. */
  335. abstract protected function doRequest($request);
  336. /**
  337. * Returns the script to execute when the request must be insulated.
  338. *
  339. * @param object $request An origin request instance
  340. *
  341. * @throws \LogicException When this abstract class is not implemented
  342. */
  343. protected function getScript($request)
  344. {
  345. throw new \LogicException('To insulate requests, you need to override the getScript() method.');
  346. }
  347. /**
  348. * Filters the BrowserKit request to the origin one.
  349. *
  350. * @param Request $request The BrowserKit Request to filter
  351. *
  352. * @return object An origin request instance
  353. */
  354. protected function filterRequest(Request $request)
  355. {
  356. return $request;
  357. }
  358. /**
  359. * Filters the origin response to the BrowserKit one.
  360. *
  361. * @param object $response The origin response to filter
  362. *
  363. * @return Response An BrowserKit Response instance
  364. */
  365. protected function filterResponse($response)
  366. {
  367. return $response;
  368. }
  369. /**
  370. * Creates a crawler.
  371. *
  372. * This method returns null if the DomCrawler component is not available.
  373. *
  374. * @param string $uri A URI
  375. * @param string $content Content for the crawler to use
  376. * @param string $type Content type
  377. *
  378. * @return Crawler|null
  379. */
  380. protected function createCrawlerFromContent($uri, $content, $type)
  381. {
  382. if (!class_exists('Symfony\Component\DomCrawler\Crawler')) {
  383. return null;
  384. }
  385. $crawler = new Crawler(null, $uri);
  386. $crawler->addContent($content, $type);
  387. return $crawler;
  388. }
  389. /**
  390. * Goes back in the browser history.
  391. *
  392. * @return Crawler
  393. */
  394. public function back()
  395. {
  396. do {
  397. $request = $this->history->back();
  398. } while (\array_key_exists(serialize($request), $this->redirects));
  399. return $this->requestFromRequest($request, false);
  400. }
  401. /**
  402. * Goes forward in the browser history.
  403. *
  404. * @return Crawler
  405. */
  406. public function forward()
  407. {
  408. do {
  409. $request = $this->history->forward();
  410. } while (\array_key_exists(serialize($request), $this->redirects));
  411. return $this->requestFromRequest($request, false);
  412. }
  413. /**
  414. * Reloads the current browser.
  415. *
  416. * @return Crawler
  417. */
  418. public function reload()
  419. {
  420. return $this->requestFromRequest($this->history->current(), false);
  421. }
  422. /**
  423. * Follow redirects?
  424. *
  425. * @return Crawler
  426. *
  427. * @throws \LogicException If request was not a redirect
  428. */
  429. public function followRedirect()
  430. {
  431. if (empty($this->redirect)) {
  432. throw new \LogicException('The request was not redirected.');
  433. }
  434. if (-1 !== $this->maxRedirects) {
  435. if ($this->redirectCount > $this->maxRedirects) {
  436. $this->redirectCount = 0;
  437. throw new \LogicException(sprintf('The maximum number (%d) of redirections was reached.', $this->maxRedirects));
  438. }
  439. }
  440. $request = $this->internalRequest;
  441. if (\in_array($this->internalResponse->getStatus(), [301, 302, 303])) {
  442. $method = 'GET';
  443. $files = [];
  444. $content = null;
  445. } else {
  446. $method = $request->getMethod();
  447. $files = $request->getFiles();
  448. $content = $request->getContent();
  449. }
  450. if ('GET' === strtoupper($method)) {
  451. // Don't forward parameters for GET request as it should reach the redirection URI
  452. $parameters = [];
  453. } else {
  454. $parameters = $request->getParameters();
  455. }
  456. $server = $request->getServer();
  457. $server = $this->updateServerFromUri($server, $this->redirect);
  458. $this->isMainRequest = false;
  459. $response = $this->request($method, $this->redirect, $parameters, $files, $server, $content);
  460. $this->isMainRequest = true;
  461. return $response;
  462. }
  463. /**
  464. * Restarts the client.
  465. *
  466. * It flushes history and all cookies.
  467. */
  468. public function restart()
  469. {
  470. $this->cookieJar->clear();
  471. $this->history->clear();
  472. }
  473. /**
  474. * Takes a URI and converts it to absolute if it is not already absolute.
  475. *
  476. * @param string $uri A URI
  477. *
  478. * @return string An absolute URI
  479. */
  480. protected function getAbsoluteUri($uri)
  481. {
  482. // already absolute?
  483. if (0 === strpos($uri, 'http://') || 0 === strpos($uri, 'https://')) {
  484. return $uri;
  485. }
  486. if (!$this->history->isEmpty()) {
  487. $currentUri = $this->history->current()->getUri();
  488. } else {
  489. $currentUri = sprintf('http%s://%s/',
  490. isset($this->server['HTTPS']) ? 's' : '',
  491. isset($this->server['HTTP_HOST']) ? $this->server['HTTP_HOST'] : 'localhost'
  492. );
  493. }
  494. // protocol relative URL
  495. if (0 === strpos($uri, '//')) {
  496. return parse_url($currentUri, PHP_URL_SCHEME).':'.$uri;
  497. }
  498. // anchor or query string parameters?
  499. if (!$uri || '#' == $uri[0] || '?' == $uri[0]) {
  500. return preg_replace('/[#?].*?$/', '', $currentUri).$uri;
  501. }
  502. if ('/' !== $uri[0]) {
  503. $path = parse_url($currentUri, PHP_URL_PATH);
  504. if ('/' !== substr($path, -1)) {
  505. $path = substr($path, 0, strrpos($path, '/') + 1);
  506. }
  507. $uri = $path.$uri;
  508. }
  509. return preg_replace('#^(.*?//[^/]+)\/.*$#', '$1', $currentUri).$uri;
  510. }
  511. /**
  512. * Makes a request from a Request object directly.
  513. *
  514. * @param Request $request A Request instance
  515. * @param bool $changeHistory Whether to update the history or not (only used internally for back(), forward(), and reload())
  516. *
  517. * @return Crawler
  518. */
  519. protected function requestFromRequest(Request $request, $changeHistory = true)
  520. {
  521. return $this->request($request->getMethod(), $request->getUri(), $request->getParameters(), $request->getFiles(), $request->getServer(), $request->getContent(), $changeHistory);
  522. }
  523. private function updateServerFromUri($server, $uri)
  524. {
  525. $server['HTTP_HOST'] = $this->extractHost($uri);
  526. $scheme = parse_url($uri, PHP_URL_SCHEME);
  527. $server['HTTPS'] = null === $scheme ? $server['HTTPS'] : 'https' == $scheme;
  528. unset($server['HTTP_IF_NONE_MATCH'], $server['HTTP_IF_MODIFIED_SINCE']);
  529. return $server;
  530. }
  531. private function extractHost($uri)
  532. {
  533. $host = parse_url($uri, PHP_URL_HOST);
  534. if ($port = parse_url($uri, PHP_URL_PORT)) {
  535. return $host.':'.$port;
  536. }
  537. return $host;
  538. }
  539. }