Client.php 16 KB

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