Client.php 24 KB

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