Client.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595
  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. * @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' => 'Symfony 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. * @param Link $link A Link instance
  213. *
  214. * @return Crawler
  215. */
  216. public function click(Link $link)
  217. {
  218. if ($link instanceof Form) {
  219. return $this->submit($link);
  220. }
  221. return $this->request($link->getMethod(), $link->getUri());
  222. }
  223. /**
  224. * Submits a form.
  225. *
  226. * @param Form $form A Form instance
  227. * @param array $values An array of form field values
  228. *
  229. * @return Crawler
  230. */
  231. public function submit(Form $form, array $values = array())
  232. {
  233. $form->setValues($values);
  234. return $this->request($form->getMethod(), $form->getUri(), $form->getPhpValues(), $form->getPhpFiles());
  235. }
  236. /**
  237. * Calls a URI.
  238. *
  239. * @param string $method The request method
  240. * @param string $uri The URI to fetch
  241. * @param array $parameters The Request parameters
  242. * @param array $files The files
  243. * @param array $server The server parameters (HTTP headers are referenced with a HTTP_ prefix as PHP does)
  244. * @param string $content The raw body data
  245. * @param bool $changeHistory Whether to update the history or not (only used internally for back(), forward(), and reload())
  246. *
  247. * @return Crawler
  248. */
  249. public function request($method, $uri, array $parameters = array(), array $files = array(), array $server = array(), $content = null, $changeHistory = true)
  250. {
  251. if ($this->isMainRequest) {
  252. $this->redirectCount = 0;
  253. } else {
  254. ++$this->redirectCount;
  255. }
  256. $uri = $this->getAbsoluteUri($uri);
  257. $server = array_merge($this->server, $server);
  258. if (isset($server['HTTPS'])) {
  259. $uri = preg_replace('{^'.parse_url($uri, PHP_URL_SCHEME).'}', $server['HTTPS'] ? 'https' : 'http', $uri);
  260. }
  261. if (!$this->history->isEmpty()) {
  262. $server['HTTP_REFERER'] = $this->history->current()->getUri();
  263. }
  264. if (empty($server['HTTP_HOST'])) {
  265. $server['HTTP_HOST'] = $this->extractHost($uri);
  266. }
  267. $server['HTTPS'] = 'https' == parse_url($uri, PHP_URL_SCHEME);
  268. $this->internalRequest = new Request($uri, $method, $parameters, $files, $this->cookieJar->allValues($uri), $server, $content);
  269. $this->request = $this->filterRequest($this->internalRequest);
  270. if (true === $changeHistory) {
  271. $this->history->add($this->internalRequest);
  272. }
  273. if ($this->insulated) {
  274. $this->response = $this->doRequestInProcess($this->request);
  275. } else {
  276. $this->response = $this->doRequest($this->request);
  277. }
  278. $this->internalResponse = $this->filterResponse($this->response);
  279. $this->cookieJar->updateFromResponse($this->internalResponse, $uri);
  280. $status = $this->internalResponse->getStatus();
  281. if ($status >= 300 && $status < 400) {
  282. $this->redirect = $this->internalResponse->getHeader('Location');
  283. } else {
  284. $this->redirect = null;
  285. }
  286. if ($this->followRedirects && $this->redirect) {
  287. return $this->crawler = $this->followRedirect();
  288. }
  289. return $this->crawler = $this->createCrawlerFromContent($this->internalRequest->getUri(), $this->internalResponse->getContent(), $this->internalResponse->getHeader('Content-Type'));
  290. }
  291. /**
  292. * Makes a request in another process.
  293. *
  294. * @param object $request An origin request instance
  295. *
  296. * @return object An origin response instance
  297. *
  298. * @throws \RuntimeException When processing returns exit code
  299. */
  300. protected function doRequestInProcess($request)
  301. {
  302. $process = new PhpProcess($this->getScript($request), null, null);
  303. $process->run();
  304. if (!$process->isSuccessful() || !preg_match('/^O\:\d+\:/', $process->getOutput())) {
  305. throw new \RuntimeException(sprintf('OUTPUT: %s ERROR OUTPUT: %s', $process->getOutput(), $process->getErrorOutput()));
  306. }
  307. return unserialize($process->getOutput());
  308. }
  309. /**
  310. * Makes a request.
  311. *
  312. * @param object $request An origin request instance
  313. *
  314. * @return object An origin response instance
  315. */
  316. abstract protected function doRequest($request);
  317. /**
  318. * Returns the script to execute when the request must be insulated.
  319. *
  320. * @param object $request An origin request instance
  321. *
  322. * @throws \LogicException When this abstract class is not implemented
  323. */
  324. protected function getScript($request)
  325. {
  326. throw new \LogicException('To insulate requests, you need to override the getScript() method.');
  327. }
  328. /**
  329. * Filters the BrowserKit request to the origin one.
  330. *
  331. * @param Request $request The BrowserKit Request to filter
  332. *
  333. * @return object An origin request instance
  334. */
  335. protected function filterRequest(Request $request)
  336. {
  337. return $request;
  338. }
  339. /**
  340. * Filters the origin response to the BrowserKit one.
  341. *
  342. * @param object $response The origin response to filter
  343. *
  344. * @return Response An BrowserKit Response instance
  345. */
  346. protected function filterResponse($response)
  347. {
  348. return $response;
  349. }
  350. /**
  351. * Creates a crawler.
  352. *
  353. * This method returns null if the DomCrawler component is not available.
  354. *
  355. * @param string $uri A URI
  356. * @param string $content Content for the crawler to use
  357. * @param string $type Content type
  358. *
  359. * @return Crawler|null
  360. */
  361. protected function createCrawlerFromContent($uri, $content, $type)
  362. {
  363. if (!class_exists('Symfony\Component\DomCrawler\Crawler')) {
  364. return;
  365. }
  366. $crawler = new Crawler(null, $uri);
  367. $crawler->addContent($content, $type);
  368. return $crawler;
  369. }
  370. /**
  371. * Goes back in the browser history.
  372. *
  373. * @return Crawler
  374. */
  375. public function back()
  376. {
  377. return $this->requestFromRequest($this->history->back(), false);
  378. }
  379. /**
  380. * Goes forward in the browser history.
  381. *
  382. * @return Crawler
  383. */
  384. public function forward()
  385. {
  386. return $this->requestFromRequest($this->history->forward(), false);
  387. }
  388. /**
  389. * Reloads the current browser.
  390. *
  391. * @return Crawler
  392. */
  393. public function reload()
  394. {
  395. return $this->requestFromRequest($this->history->current(), false);
  396. }
  397. /**
  398. * Follow redirects?
  399. *
  400. * @return Crawler
  401. *
  402. * @throws \LogicException If request was not a redirect
  403. */
  404. public function followRedirect()
  405. {
  406. if (empty($this->redirect)) {
  407. throw new \LogicException('The request was not redirected.');
  408. }
  409. if (-1 !== $this->maxRedirects) {
  410. if ($this->redirectCount > $this->maxRedirects) {
  411. $this->redirectCount = 0;
  412. throw new \LogicException(sprintf('The maximum number (%d) of redirections was reached.', $this->maxRedirects));
  413. }
  414. }
  415. $request = $this->internalRequest;
  416. if (in_array($this->internalResponse->getStatus(), array(301, 302, 303))) {
  417. $method = 'GET';
  418. $files = array();
  419. $content = null;
  420. } else {
  421. $method = $request->getMethod();
  422. $files = $request->getFiles();
  423. $content = $request->getContent();
  424. }
  425. if ('GET' === strtoupper($method)) {
  426. // Don't forward parameters for GET request as it should reach the redirection URI
  427. $parameters = array();
  428. } else {
  429. $parameters = $request->getParameters();
  430. }
  431. $server = $request->getServer();
  432. $server = $this->updateServerFromUri($server, $this->redirect);
  433. $this->isMainRequest = false;
  434. $response = $this->request($method, $this->redirect, $parameters, $files, $server, $content);
  435. $this->isMainRequest = true;
  436. return $response;
  437. }
  438. /**
  439. * Restarts the client.
  440. *
  441. * It flushes history and all cookies.
  442. */
  443. public function restart()
  444. {
  445. $this->cookieJar->clear();
  446. $this->history->clear();
  447. }
  448. /**
  449. * Takes a URI and converts it to absolute if it is not already absolute.
  450. *
  451. * @param string $uri A URI
  452. *
  453. * @return string An absolute URI
  454. */
  455. protected function getAbsoluteUri($uri)
  456. {
  457. // already absolute?
  458. if (0 === strpos($uri, 'http://') || 0 === strpos($uri, 'https://')) {
  459. return $uri;
  460. }
  461. if (!$this->history->isEmpty()) {
  462. $currentUri = $this->history->current()->getUri();
  463. } else {
  464. $currentUri = sprintf('http%s://%s/',
  465. isset($this->server['HTTPS']) ? 's' : '',
  466. isset($this->server['HTTP_HOST']) ? $this->server['HTTP_HOST'] : 'localhost'
  467. );
  468. }
  469. // protocol relative URL
  470. if (0 === strpos($uri, '//')) {
  471. return parse_url($currentUri, PHP_URL_SCHEME).':'.$uri;
  472. }
  473. // anchor or query string parameters?
  474. if (!$uri || '#' == $uri[0] || '?' == $uri[0]) {
  475. return preg_replace('/[#?].*?$/', '', $currentUri).$uri;
  476. }
  477. if ('/' !== $uri[0]) {
  478. $path = parse_url($currentUri, PHP_URL_PATH);
  479. if ('/' !== substr($path, -1)) {
  480. $path = substr($path, 0, strrpos($path, '/') + 1);
  481. }
  482. $uri = $path.$uri;
  483. }
  484. return preg_replace('#^(.*?//[^/]+)\/.*$#', '$1', $currentUri).$uri;
  485. }
  486. /**
  487. * Makes a request from a Request object directly.
  488. *
  489. * @param Request $request A Request instance
  490. * @param bool $changeHistory Whether to update the history or not (only used internally for back(), forward(), and reload())
  491. *
  492. * @return Crawler
  493. */
  494. protected function requestFromRequest(Request $request, $changeHistory = true)
  495. {
  496. return $this->request($request->getMethod(), $request->getUri(), $request->getParameters(), $request->getFiles(), $request->getServer(), $request->getContent(), $changeHistory);
  497. }
  498. private function updateServerFromUri($server, $uri)
  499. {
  500. $server['HTTP_HOST'] = $this->extractHost($uri);
  501. $scheme = parse_url($uri, PHP_URL_SCHEME);
  502. $server['HTTPS'] = null === $scheme ? $server['HTTPS'] : 'https' == $scheme;
  503. unset($server['HTTP_IF_NONE_MATCH'], $server['HTTP_IF_MODIFIED_SINCE']);
  504. return $server;
  505. }
  506. private function extractHost($uri)
  507. {
  508. $host = parse_url($uri, PHP_URL_HOST);
  509. if ($port = parse_url($uri, PHP_URL_PORT)) {
  510. return $host.':'.$port;
  511. }
  512. return $host;
  513. }
  514. }