Client.php 16 KB

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