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