4 * This file is part of the Symfony package.
6 * (c) Fabien Potencier <fabien@symfony.com>
8 * For the full copyright and license information, please view the LICENSE
9 * file that was distributed with this source code.
12 namespace Symfony\Component\BrowserKit;
14 use Symfony\Component\DomCrawler\Crawler;
15 use Symfony\Component\DomCrawler\Link;
16 use Symfony\Component\DomCrawler\Form;
17 use Symfony\Component\Process\PhpProcess;
20 * Client simulates a browser.
22 * To make the actual request, you need to implement the doRequest() method.
24 * If you want to be able to run requests in their own process (insulated flag),
25 * you need to also implement the getScript() method.
27 * @author Fabien Potencier <fabien@symfony.com>
33 protected $server = array();
34 protected $internalRequest;
36 protected $internalResponse;
39 protected $insulated = false;
41 protected $followRedirects = true;
43 private $maxRedirects = -1;
44 private $redirectCount = 0;
45 private $isMainRequest = true;
50 * @param array $server The server parameters (equivalent of $_SERVER)
51 * @param History $history A History instance to store the browser history
52 * @param CookieJar $cookieJar A CookieJar instance to store the cookies
54 public function __construct(array $server = array(), History $history = null, CookieJar $cookieJar = null)
56 $this->setServerParameters($server);
57 $this->history = $history ?: new History();
58 $this->cookieJar = $cookieJar ?: new CookieJar();
62 * Sets whether to automatically follow redirects or not.
64 * @param bool $followRedirect Whether to follow redirects
66 public function followRedirects($followRedirect = true)
68 $this->followRedirects = (bool) $followRedirect;
72 * Returns whether client automatically follows redirects or not.
76 public function isFollowingRedirects()
78 return $this->followRedirects;
82 * Sets the maximum number of requests that crawler can follow.
84 * @param int $maxRedirects
86 public function setMaxRedirects($maxRedirects)
88 $this->maxRedirects = $maxRedirects < 0 ? -1 : $maxRedirects;
89 $this->followRedirects = -1 != $this->maxRedirects;
93 * Returns the maximum number of requests that crawler can follow.
97 public function getMaxRedirects()
99 return $this->maxRedirects;
103 * Sets the insulated flag.
105 * @param bool $insulated Whether to insulate the requests or not
107 * @throws \RuntimeException When Symfony Process Component is not installed
109 public function insulate($insulated = true)
111 if ($insulated && !class_exists('Symfony\\Component\\Process\\Process')) {
112 throw new \RuntimeException('Unable to isolate requests as the Symfony Process Component is not installed.');
115 $this->insulated = (bool) $insulated;
119 * Sets server parameters.
121 * @param array $server An array of server parameters
123 public function setServerParameters(array $server)
125 $this->server = array_merge(array(
126 'HTTP_USER_AGENT' => 'Symfony BrowserKit',
131 * Sets single server parameter.
133 * @param string $key A key of the parameter
134 * @param string $value A value of the parameter
136 public function setServerParameter($key, $value)
138 $this->server[$key] = $value;
142 * Gets single server parameter for specified key.
144 * @param string $key A key of the parameter to get
145 * @param string $default A default value when key is undefined
147 * @return string A value of the parameter
149 public function getServerParameter($key, $default = '')
151 return isset($this->server[$key]) ? $this->server[$key] : $default;
155 * Returns the History instance.
157 * @return History A History instance
159 public function getHistory()
161 return $this->history;
165 * Returns the CookieJar instance.
167 * @return CookieJar A CookieJar instance
169 public function getCookieJar()
171 return $this->cookieJar;
175 * Returns the current Crawler instance.
177 * @return Crawler|null A Crawler instance
179 public function getCrawler()
181 return $this->crawler;
185 * Returns the current BrowserKit Response instance.
187 * @return Response|null A BrowserKit Response instance
189 public function getInternalResponse()
191 return $this->internalResponse;
195 * Returns the current origin response instance.
197 * The origin response is the response instance that is returned
198 * by the code that handles requests.
200 * @return object|null A response instance
204 public function getResponse()
206 return $this->response;
210 * Returns the current BrowserKit Request instance.
212 * @return Request|null A BrowserKit Request instance
214 public function getInternalRequest()
216 return $this->internalRequest;
220 * Returns the current origin Request instance.
222 * The origin request is the request instance that is sent
223 * to the code that handles requests.
225 * @return object|null A Request instance
229 public function getRequest()
231 return $this->request;
235 * Clicks on a given link.
237 * @param Link $link A Link instance
241 public function click(Link $link)
243 if ($link instanceof Form) {
244 return $this->submit($link);
247 return $this->request($link->getMethod(), $link->getUri());
253 * @param Form $form A Form instance
254 * @param array $values An array of form field values
258 public function submit(Form $form, array $values = array())
260 $form->setValues($values);
262 return $this->request($form->getMethod(), $form->getUri(), $form->getPhpValues(), $form->getPhpFiles());
268 * @param string $method The request method
269 * @param string $uri The URI to fetch
270 * @param array $parameters The Request parameters
271 * @param array $files The files
272 * @param array $server The server parameters (HTTP headers are referenced with a HTTP_ prefix as PHP does)
273 * @param string $content The raw body data
274 * @param bool $changeHistory Whether to update the history or not (only used internally for back(), forward(), and reload())
278 public function request($method, $uri, array $parameters = array(), array $files = array(), array $server = array(), $content = null, $changeHistory = true)
280 if ($this->isMainRequest) {
281 $this->redirectCount = 0;
283 ++$this->redirectCount;
286 $uri = $this->getAbsoluteUri($uri);
288 $server = array_merge($this->server, $server);
290 if (isset($server['HTTPS'])) {
291 $uri = preg_replace('{^'.parse_url($uri, PHP_URL_SCHEME).'}', $server['HTTPS'] ? 'https' : 'http', $uri);
294 if (!$this->history->isEmpty()) {
295 $server['HTTP_REFERER'] = $this->history->current()->getUri();
298 if (empty($server['HTTP_HOST'])) {
299 $server['HTTP_HOST'] = $this->extractHost($uri);
302 $server['HTTPS'] = 'https' == parse_url($uri, PHP_URL_SCHEME);
304 $this->internalRequest = new Request($uri, $method, $parameters, $files, $this->cookieJar->allValues($uri), $server, $content);
306 $this->request = $this->filterRequest($this->internalRequest);
308 if (true === $changeHistory) {
309 $this->history->add($this->internalRequest);
312 if ($this->insulated) {
313 $this->response = $this->doRequestInProcess($this->request);
315 $this->response = $this->doRequest($this->request);
318 $this->internalResponse = $this->filterResponse($this->response);
320 $this->cookieJar->updateFromResponse($this->internalResponse, $uri);
322 $status = $this->internalResponse->getStatus();
324 if ($status >= 300 && $status < 400) {
325 $this->redirect = $this->internalResponse->getHeader('Location');
327 $this->redirect = null;
330 if ($this->followRedirects && $this->redirect) {
331 return $this->crawler = $this->followRedirect();
334 return $this->crawler = $this->createCrawlerFromContent($this->internalRequest->getUri(), $this->internalResponse->getContent(), $this->internalResponse->getHeader('Content-Type'));
338 * Makes a request in another process.
340 * @param object $request An origin request instance
342 * @return object An origin response instance
344 * @throws \RuntimeException When processing returns exit code
346 protected function doRequestInProcess($request)
348 $process = new PhpProcess($this->getScript($request), null, null);
351 if (!$process->isSuccessful() || !preg_match('/^O\:\d+\:/', $process->getOutput())) {
352 throw new \RuntimeException(sprintf('OUTPUT: %s ERROR OUTPUT: %s', $process->getOutput(), $process->getErrorOutput()));
355 return unserialize($process->getOutput());
361 * @param object $request An origin request instance
363 * @return object An origin response instance
365 abstract protected function doRequest($request);
368 * Returns the script to execute when the request must be insulated.
370 * @param object $request An origin request instance
372 * @throws \LogicException When this abstract class is not implemented
374 protected function getScript($request)
376 throw new \LogicException('To insulate requests, you need to override the getScript() method.');
380 * Filters the BrowserKit request to the origin one.
382 * @param Request $request The BrowserKit Request to filter
384 * @return object An origin request instance
386 protected function filterRequest(Request $request)
392 * Filters the origin response to the BrowserKit one.
394 * @param object $response The origin response to filter
396 * @return Response An BrowserKit Response instance
398 protected function filterResponse($response)
406 * This method returns null if the DomCrawler component is not available.
408 * @param string $uri A URI
409 * @param string $content Content for the crawler to use
410 * @param string $type Content type
412 * @return Crawler|null
414 protected function createCrawlerFromContent($uri, $content, $type)
416 if (!class_exists('Symfony\Component\DomCrawler\Crawler')) {
420 $crawler = new Crawler(null, $uri);
421 $crawler->addContent($content, $type);
427 * Goes back in the browser history.
431 public function back()
433 return $this->requestFromRequest($this->history->back(), false);
437 * Goes forward in the browser history.
441 public function forward()
443 return $this->requestFromRequest($this->history->forward(), false);
447 * Reloads the current browser.
451 public function reload()
453 return $this->requestFromRequest($this->history->current(), false);
461 * @throws \LogicException If request was not a redirect
463 public function followRedirect()
465 if (empty($this->redirect)) {
466 throw new \LogicException('The request was not redirected.');
469 if (-1 !== $this->maxRedirects) {
470 if ($this->redirectCount > $this->maxRedirects) {
471 throw new \LogicException(sprintf('The maximum number (%d) of redirections was reached.', $this->maxRedirects));
475 $request = $this->internalRequest;
477 if (in_array($this->internalResponse->getStatus(), array(302, 303))) {
482 $method = $request->getMethod();
483 $files = $request->getFiles();
484 $content = $request->getContent();
487 if ('GET' === strtoupper($method)) {
488 // Don't forward parameters for GET request as it should reach the redirection URI
489 $parameters = array();
491 $parameters = $request->getParameters();
494 $server = $request->getServer();
495 $server = $this->updateServerFromUri($server, $this->redirect);
497 $this->isMainRequest = false;
499 $response = $this->request($method, $this->redirect, $parameters, $files, $server, $content);
501 $this->isMainRequest = true;
507 * Restarts the client.
509 * It flushes history and all cookies.
511 public function restart()
513 $this->cookieJar->clear();
514 $this->history->clear();
518 * Takes a URI and converts it to absolute if it is not already absolute.
520 * @param string $uri A URI
522 * @return string An absolute URI
524 protected function getAbsoluteUri($uri)
527 if (0 === strpos($uri, 'http://') || 0 === strpos($uri, 'https://')) {
531 if (!$this->history->isEmpty()) {
532 $currentUri = $this->history->current()->getUri();
534 $currentUri = sprintf('http%s://%s/',
535 isset($this->server['HTTPS']) ? 's' : '',
536 isset($this->server['HTTP_HOST']) ? $this->server['HTTP_HOST'] : 'localhost'
540 // protocol relative URL
541 if (0 === strpos($uri, '//')) {
542 return parse_url($currentUri, PHP_URL_SCHEME).':'.$uri;
545 // anchor or query string parameters?
546 if (!$uri || '#' == $uri[0] || '?' == $uri[0]) {
547 return preg_replace('/[#?].*?$/', '', $currentUri).$uri;
550 if ('/' !== $uri[0]) {
551 $path = parse_url($currentUri, PHP_URL_PATH);
553 if ('/' !== substr($path, -1)) {
554 $path = substr($path, 0, strrpos($path, '/') + 1);
560 return preg_replace('#^(.*?//[^/]+)\/.*$#', '$1', $currentUri).$uri;
564 * Makes a request from a Request object directly.
566 * @param Request $request A Request instance
567 * @param bool $changeHistory Whether to update the history or not (only used internally for back(), forward(), and reload())
571 protected function requestFromRequest(Request $request, $changeHistory = true)
573 return $this->request($request->getMethod(), $request->getUri(), $request->getParameters(), $request->getFiles(), $request->getServer(), $request->getContent(), $changeHistory);
576 private function updateServerFromUri($server, $uri)
578 $server['HTTP_HOST'] = $this->extractHost($uri);
579 $scheme = parse_url($uri, PHP_URL_SCHEME);
580 $server['HTTPS'] = null === $scheme ? $server['HTTPS'] : 'https' == $scheme;
581 unset($server['HTTP_IF_NONE_MATCH'], $server['HTTP_IF_MODIFIED_SINCE']);
586 private function extractHost($uri)
588 $host = parse_url($uri, PHP_URL_HOST);
590 if ($port = parse_url($uri, PHP_URL_PORT)) {
591 return $host.':'.$port;