Client.php 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733
  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. * @deprecated since Symfony 4.3, use "\Symfony\Component\BrowserKit\AbstractBrowser" instead
  27. */
  28. abstract class Client
  29. {
  30. protected $history;
  31. protected $cookieJar;
  32. protected $server = [];
  33. protected $internalRequest;
  34. protected $request;
  35. protected $internalResponse;
  36. protected $response;
  37. protected $crawler;
  38. protected $insulated = false;
  39. protected $redirect;
  40. protected $followRedirects = true;
  41. protected $followMetaRefresh = false;
  42. private $maxRedirects = -1;
  43. private $redirectCount = 0;
  44. private $redirects = [];
  45. private $isMainRequest = true;
  46. /**
  47. * @param array $server The server parameters (equivalent of $_SERVER)
  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 mixed $default A default value when key is undefined
  139. *
  140. * @return mixed 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.', static::class.'::'.__FUNCTION__), 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.', static::class.'::'.__FUNCTION__), 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.', static::class.'::'.__FUNCTION__), 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.', static::class.'::'.__FUNCTION__), 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.', static::class.'::'.__FUNCTION__), 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 array $values An array of form field values
  276. * @param array $serverParameters An array of server parameters
  277. *
  278. * @return Crawler
  279. */
  280. public function submit(Form $form, array $values = []/*, array $serverParameters = []*/)
  281. {
  282. if (\func_num_args() < 3 && __CLASS__ !== static::class && __CLASS__ !== (new \ReflectionMethod($this, __FUNCTION__))->getDeclaringClass()->getName() && !$this instanceof \PHPUnit\Framework\MockObject\MockObject && !$this instanceof \Prophecy\Prophecy\ProphecySubjectInterface) {
  283. @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.', static::class.'::'.__FUNCTION__), E_USER_DEPRECATED);
  284. }
  285. $form->setValues($values);
  286. $serverParameters = 2 < \func_num_args() ? func_get_arg(2) : [];
  287. return $this->request($form->getMethod(), $form->getUri(), $form->getPhpValues(), $form->getPhpFiles(), $serverParameters);
  288. }
  289. /**
  290. * Finds the first form that contains a button with the given content and
  291. * uses it to submit the given form field values.
  292. *
  293. * @param string $button The text content, id, value or name of the form <button> or <input type="submit">
  294. * @param array $fieldValues Use this syntax: ['my_form[name]' => '...', 'my_form[email]' => '...']
  295. * @param string $method The HTTP method used to submit the form
  296. * @param array $serverParameters These values override the ones stored in $_SERVER (HTTP headers must include a HTTP_ prefix as PHP does)
  297. */
  298. public function submitForm(string $button, array $fieldValues = [], string $method = 'POST', array $serverParameters = []): Crawler
  299. {
  300. if (null === $this->crawler) {
  301. throw new BadMethodCallException(sprintf('The "request()" method must be called before "%s()".', __METHOD__));
  302. }
  303. $buttonNode = $this->crawler->selectButton($button);
  304. $form = $buttonNode->form($fieldValues, $method);
  305. return $this->submit($form, [], $serverParameters);
  306. }
  307. /**
  308. * Calls a URI.
  309. *
  310. * @param string $method The request method
  311. * @param string $uri The URI to fetch
  312. * @param array $parameters The Request parameters
  313. * @param array $files The files
  314. * @param array $server The server parameters (HTTP headers are referenced with a HTTP_ prefix as PHP does)
  315. * @param string $content The raw body data
  316. * @param bool $changeHistory Whether to update the history or not (only used internally for back(), forward(), and reload())
  317. *
  318. * @return Crawler
  319. */
  320. public function request(string $method, string $uri, array $parameters = [], array $files = [], array $server = [], string $content = null, bool $changeHistory = true)
  321. {
  322. if ($this->isMainRequest) {
  323. $this->redirectCount = 0;
  324. } else {
  325. ++$this->redirectCount;
  326. }
  327. $originalUri = $uri;
  328. $uri = $this->getAbsoluteUri($uri);
  329. $server = array_merge($this->server, $server);
  330. if (!empty($server['HTTP_HOST']) && null === parse_url($originalUri, PHP_URL_HOST)) {
  331. $uri = preg_replace('{^(https?\://)'.preg_quote($this->extractHost($uri)).'}', '${1}'.$server['HTTP_HOST'], $uri);
  332. }
  333. if (isset($server['HTTPS']) && null === parse_url($originalUri, PHP_URL_SCHEME)) {
  334. $uri = preg_replace('{^'.parse_url($uri, PHP_URL_SCHEME).'}', $server['HTTPS'] ? 'https' : 'http', $uri);
  335. }
  336. if (!$this->history->isEmpty()) {
  337. $server['HTTP_REFERER'] = $this->history->current()->getUri();
  338. }
  339. if (empty($server['HTTP_HOST'])) {
  340. $server['HTTP_HOST'] = $this->extractHost($uri);
  341. }
  342. $server['HTTPS'] = 'https' == parse_url($uri, PHP_URL_SCHEME);
  343. $this->internalRequest = new Request($uri, $method, $parameters, $files, $this->cookieJar->allValues($uri), $server, $content);
  344. $this->request = $this->filterRequest($this->internalRequest);
  345. if (true === $changeHistory) {
  346. $this->history->add($this->internalRequest);
  347. }
  348. if ($this->insulated) {
  349. $this->response = $this->doRequestInProcess($this->request);
  350. } else {
  351. $this->response = $this->doRequest($this->request);
  352. }
  353. $this->internalResponse = $this->filterResponse($this->response);
  354. $this->cookieJar->updateFromResponse($this->internalResponse, $uri);
  355. $status = $this->internalResponse->getStatusCode();
  356. if ($status >= 300 && $status < 400) {
  357. $this->redirect = $this->internalResponse->getHeader('Location');
  358. } else {
  359. $this->redirect = null;
  360. }
  361. if ($this->followRedirects && $this->redirect) {
  362. $this->redirects[serialize($this->history->current())] = true;
  363. return $this->crawler = $this->followRedirect();
  364. }
  365. $this->crawler = $this->createCrawlerFromContent($this->internalRequest->getUri(), $this->internalResponse->getContent(), $this->internalResponse->getHeader('Content-Type'));
  366. // Check for meta refresh redirect
  367. if ($this->followMetaRefresh && null !== $redirect = $this->getMetaRefreshUrl()) {
  368. $this->redirect = $redirect;
  369. $this->redirects[serialize($this->history->current())] = true;
  370. $this->crawler = $this->followRedirect();
  371. }
  372. return $this->crawler;
  373. }
  374. /**
  375. * Makes a request in another process.
  376. *
  377. * @param object $request An origin request instance
  378. *
  379. * @return object An origin response instance
  380. *
  381. * @throws \RuntimeException When processing returns exit code
  382. */
  383. protected function doRequestInProcess($request)
  384. {
  385. $deprecationsFile = tempnam(sys_get_temp_dir(), 'deprec');
  386. putenv('SYMFONY_DEPRECATIONS_SERIALIZE='.$deprecationsFile);
  387. $_ENV['SYMFONY_DEPRECATIONS_SERIALIZE'] = $deprecationsFile;
  388. $process = new PhpProcess($this->getScript($request), null, null);
  389. $process->run();
  390. if (file_exists($deprecationsFile)) {
  391. $deprecations = file_get_contents($deprecationsFile);
  392. unlink($deprecationsFile);
  393. foreach ($deprecations ? unserialize($deprecations) : [] as $deprecation) {
  394. if ($deprecation[0]) {
  395. // unsilenced on purpose
  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. * @return object An origin request instance
  430. */
  431. protected function filterRequest(Request $request)
  432. {
  433. return $request;
  434. }
  435. /**
  436. * Filters the origin response to the BrowserKit one.
  437. *
  438. * @param object $response The origin response to filter
  439. *
  440. * @return Response An BrowserKit Response instance
  441. */
  442. protected function filterResponse($response)
  443. {
  444. return $response;
  445. }
  446. /**
  447. * Creates a crawler.
  448. *
  449. * This method returns null if the DomCrawler component is not available.
  450. *
  451. * @param string $uri A URI
  452. * @param string $content Content for the crawler to use
  453. * @param string $type Content type
  454. *
  455. * @return Crawler|null
  456. */
  457. protected function createCrawlerFromContent($uri, $content, $type)
  458. {
  459. if (!class_exists('Symfony\Component\DomCrawler\Crawler')) {
  460. return null;
  461. }
  462. $crawler = new Crawler(null, $uri);
  463. $crawler->addContent($content, $type);
  464. return $crawler;
  465. }
  466. /**
  467. * Goes back in the browser history.
  468. *
  469. * @return Crawler
  470. */
  471. public function back()
  472. {
  473. do {
  474. $request = $this->history->back();
  475. } while (\array_key_exists(serialize($request), $this->redirects));
  476. return $this->requestFromRequest($request, false);
  477. }
  478. /**
  479. * Goes forward in the browser history.
  480. *
  481. * @return Crawler
  482. */
  483. public function forward()
  484. {
  485. do {
  486. $request = $this->history->forward();
  487. } while (\array_key_exists(serialize($request), $this->redirects));
  488. return $this->requestFromRequest($request, false);
  489. }
  490. /**
  491. * Reloads the current browser.
  492. *
  493. * @return Crawler
  494. */
  495. public function reload()
  496. {
  497. return $this->requestFromRequest($this->history->current(), false);
  498. }
  499. /**
  500. * Follow redirects?
  501. *
  502. * @return Crawler
  503. *
  504. * @throws \LogicException If request was not a redirect
  505. */
  506. public function followRedirect()
  507. {
  508. if (empty($this->redirect)) {
  509. throw new \LogicException('The request was not redirected.');
  510. }
  511. if (-1 !== $this->maxRedirects) {
  512. if ($this->redirectCount > $this->maxRedirects) {
  513. $this->redirectCount = 0;
  514. throw new \LogicException(sprintf('The maximum number (%d) of redirections was reached.', $this->maxRedirects));
  515. }
  516. }
  517. $request = $this->internalRequest;
  518. if (\in_array($this->internalResponse->getStatusCode(), [301, 302, 303])) {
  519. $method = 'GET';
  520. $files = [];
  521. $content = null;
  522. } else {
  523. $method = $request->getMethod();
  524. $files = $request->getFiles();
  525. $content = $request->getContent();
  526. }
  527. if ('GET' === strtoupper($method)) {
  528. // Don't forward parameters for GET request as it should reach the redirection URI
  529. $parameters = [];
  530. } else {
  531. $parameters = $request->getParameters();
  532. }
  533. $server = $request->getServer();
  534. $server = $this->updateServerFromUri($server, $this->redirect);
  535. $this->isMainRequest = false;
  536. $response = $this->request($method, $this->redirect, $parameters, $files, $server, $content);
  537. $this->isMainRequest = true;
  538. return $response;
  539. }
  540. /**
  541. * @see https://dev.w3.org/html5/spec-preview/the-meta-element.html#attr-meta-http-equiv-refresh
  542. */
  543. private function getMetaRefreshUrl(): ?string
  544. {
  545. $metaRefresh = $this->getCrawler()->filter('head meta[http-equiv="refresh"]');
  546. foreach ($metaRefresh->extract(['content']) as $content) {
  547. if (preg_match('/^\s*0\s*;\s*URL\s*=\s*(?|\'([^\']++)|"([^"]++)|([^\'"].*))/i', $content, $m)) {
  548. return str_replace("\t\r\n", '', rtrim($m[1]));
  549. }
  550. }
  551. return null;
  552. }
  553. /**
  554. * Restarts the client.
  555. *
  556. * It flushes history and all cookies.
  557. */
  558. public function restart()
  559. {
  560. $this->cookieJar->clear();
  561. $this->history->clear();
  562. }
  563. /**
  564. * Takes a URI and converts it to absolute if it is not already absolute.
  565. *
  566. * @param string $uri A URI
  567. *
  568. * @return string An absolute URI
  569. */
  570. protected function getAbsoluteUri($uri)
  571. {
  572. // already absolute?
  573. if (0 === strpos($uri, 'http://') || 0 === strpos($uri, 'https://')) {
  574. return $uri;
  575. }
  576. if (!$this->history->isEmpty()) {
  577. $currentUri = $this->history->current()->getUri();
  578. } else {
  579. $currentUri = sprintf('http%s://%s/',
  580. isset($this->server['HTTPS']) ? 's' : '',
  581. isset($this->server['HTTP_HOST']) ? $this->server['HTTP_HOST'] : 'localhost'
  582. );
  583. }
  584. // protocol relative URL
  585. if (0 === strpos($uri, '//')) {
  586. return parse_url($currentUri, PHP_URL_SCHEME).':'.$uri;
  587. }
  588. // anchor or query string parameters?
  589. if (!$uri || '#' == $uri[0] || '?' == $uri[0]) {
  590. return preg_replace('/[#?].*?$/', '', $currentUri).$uri;
  591. }
  592. if ('/' !== $uri[0]) {
  593. $path = parse_url($currentUri, PHP_URL_PATH);
  594. if ('/' !== substr($path, -1)) {
  595. $path = substr($path, 0, strrpos($path, '/') + 1);
  596. }
  597. $uri = $path.$uri;
  598. }
  599. return preg_replace('#^(.*?//[^/]+)\/.*$#', '$1', $currentUri).$uri;
  600. }
  601. /**
  602. * Makes a request from a Request object directly.
  603. *
  604. * @param bool $changeHistory Whether to update the history or not (only used internally for back(), forward(), and reload())
  605. *
  606. * @return Crawler
  607. */
  608. protected function requestFromRequest(Request $request, $changeHistory = true)
  609. {
  610. return $this->request($request->getMethod(), $request->getUri(), $request->getParameters(), $request->getFiles(), $request->getServer(), $request->getContent(), $changeHistory);
  611. }
  612. private function updateServerFromUri(array $server, string $uri): array
  613. {
  614. $server['HTTP_HOST'] = $this->extractHost($uri);
  615. $scheme = parse_url($uri, PHP_URL_SCHEME);
  616. $server['HTTPS'] = null === $scheme ? $server['HTTPS'] : 'https' == $scheme;
  617. unset($server['HTTP_IF_NONE_MATCH'], $server['HTTP_IF_MODIFIED_SINCE']);
  618. return $server;
  619. }
  620. private function extractHost(string $uri): ?string
  621. {
  622. $host = parse_url($uri, PHP_URL_HOST);
  623. if ($port = parse_url($uri, PHP_URL_PORT)) {
  624. return $host.':'.$port;
  625. }
  626. return $host;
  627. }
  628. }