Client.php 17 KB

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