Client.php 24 KB

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