renamed Client to Browser
This commit is contained in:
parent
0e2ea87199
commit
dbe4f8605b
@ -4,6 +4,7 @@ UPGRADE FROM 4.2 to 4.3
|
||||
BrowserKit
|
||||
----------
|
||||
|
||||
* Renamed `Client` to `AbstractBrowser`
|
||||
* Marked `Response` final.
|
||||
* Deprecated `Response::buildHeader()`
|
||||
* Deprecated `Response::getStatus()`, use `Response::getStatusCode()` instead
|
||||
@ -51,6 +52,11 @@ HttpFoundation
|
||||
* The `FileinfoMimeTypeGuesser` class has been deprecated,
|
||||
use `Symfony\Component\Mime\FileinfoMimeTypeGuesser` instead.
|
||||
|
||||
HttpKernel
|
||||
----------
|
||||
|
||||
* renamed `Client` to `HttpKernelBrowser`
|
||||
|
||||
Messenger
|
||||
---------
|
||||
|
||||
|
@ -4,6 +4,7 @@ UPGRADE FROM 4.x to 5.0
|
||||
BrowserKit
|
||||
----------
|
||||
|
||||
* Removed `Client`, use `AbstractBrowser` instead
|
||||
* Removed the possibility to extend `Response` by making it final.
|
||||
* Removed `Response::buildHeader()`
|
||||
* Removed `Response::getStatus()`, use `Response::getStatusCode()` instead
|
||||
@ -199,6 +200,7 @@ HttpFoundation
|
||||
HttpKernel
|
||||
----------
|
||||
|
||||
* Removed `Client`, use `HttpKernelBrowser` instead
|
||||
* The `Kernel::getRootDir()` and the `kernel.root_dir` parameter have been removed
|
||||
* The `KernelInterface::getName()` and the `kernel.name` parameter have been removed
|
||||
* Removed the first and second constructor argument of `ConfigDataCollector`
|
||||
|
@ -4,6 +4,7 @@ CHANGELOG
|
||||
4.3.0
|
||||
-----
|
||||
|
||||
* renamed `Client` to `KernelBrowser`
|
||||
* Not passing the project directory to the constructor of the `AssetsInstallCommand` is deprecated. This argument will
|
||||
be mandatory in 5.0.
|
||||
* Deprecated the "Psr\SimpleCache\CacheInterface" / "cache.app.simple" service, use "Symfony\Contracts\Cache\CacheInterface" / "cache.app" instead
|
||||
|
@ -11,196 +11,8 @@
|
||||
|
||||
namespace Symfony\Bundle\FrameworkBundle;
|
||||
|
||||
use Symfony\Component\BrowserKit\CookieJar;
|
||||
use Symfony\Component\BrowserKit\History;
|
||||
use Symfony\Component\DependencyInjection\ContainerInterface;
|
||||
use Symfony\Component\HttpFoundation\Request;
|
||||
use Symfony\Component\HttpFoundation\Response;
|
||||
use Symfony\Component\HttpKernel\Client as BaseClient;
|
||||
use Symfony\Component\HttpKernel\KernelInterface;
|
||||
use Symfony\Component\HttpKernel\Profiler\Profile as HttpProfile;
|
||||
@trigger_error(sprintf('The "%s" class is deprecated since Symfony 4.3, use "%s" instead.', Client::class, KernelBrowser::class), E_USER_DEPRECATED);
|
||||
|
||||
/**
|
||||
* Client simulates a browser and makes requests to a Kernel object.
|
||||
*
|
||||
* @author Fabien Potencier <fabien@symfony.com>
|
||||
*/
|
||||
class Client extends BaseClient
|
||||
class Client extends KernelBrowser
|
||||
{
|
||||
private $hasPerformedRequest = false;
|
||||
private $profiler = false;
|
||||
private $reboot = true;
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function __construct(KernelInterface $kernel, array $server = [], History $history = null, CookieJar $cookieJar = null)
|
||||
{
|
||||
parent::__construct($kernel, $server, $history, $cookieJar);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the container.
|
||||
*
|
||||
* @return ContainerInterface|null Returns null when the Kernel has been shutdown or not started yet
|
||||
*/
|
||||
public function getContainer()
|
||||
{
|
||||
return $this->kernel->getContainer();
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the kernel.
|
||||
*
|
||||
* @return KernelInterface
|
||||
*/
|
||||
public function getKernel()
|
||||
{
|
||||
return $this->kernel;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the profile associated with the current Response.
|
||||
*
|
||||
* @return HttpProfile|false A Profile instance
|
||||
*/
|
||||
public function getProfile()
|
||||
{
|
||||
if (!$this->kernel->getContainer()->has('profiler')) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return $this->kernel->getContainer()->get('profiler')->loadProfileFromResponse($this->response);
|
||||
}
|
||||
|
||||
/**
|
||||
* Enables the profiler for the very next request.
|
||||
*
|
||||
* If the profiler is not enabled, the call to this method does nothing.
|
||||
*/
|
||||
public function enableProfiler()
|
||||
{
|
||||
if ($this->kernel->getContainer()->has('profiler')) {
|
||||
$this->profiler = true;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Disables kernel reboot between requests.
|
||||
*
|
||||
* By default, the Client reboots the Kernel for each request. This method
|
||||
* allows to keep the same kernel across requests.
|
||||
*/
|
||||
public function disableReboot()
|
||||
{
|
||||
$this->reboot = false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Enables kernel reboot between requests.
|
||||
*/
|
||||
public function enableReboot()
|
||||
{
|
||||
$this->reboot = true;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*
|
||||
* @param Request $request A Request instance
|
||||
*
|
||||
* @return Response A Response instance
|
||||
*/
|
||||
protected function doRequest($request)
|
||||
{
|
||||
// avoid shutting down the Kernel if no request has been performed yet
|
||||
// WebTestCase::createClient() boots the Kernel but do not handle a request
|
||||
if ($this->hasPerformedRequest && $this->reboot) {
|
||||
$this->kernel->shutdown();
|
||||
} else {
|
||||
$this->hasPerformedRequest = true;
|
||||
}
|
||||
|
||||
if ($this->profiler) {
|
||||
$this->profiler = false;
|
||||
|
||||
$this->kernel->boot();
|
||||
$this->kernel->getContainer()->get('profiler')->enable();
|
||||
}
|
||||
|
||||
return parent::doRequest($request);
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*
|
||||
* @param Request $request A Request instance
|
||||
*
|
||||
* @return Response A Response instance
|
||||
*/
|
||||
protected function doRequestInProcess($request)
|
||||
{
|
||||
$response = parent::doRequestInProcess($request);
|
||||
|
||||
$this->profiler = false;
|
||||
|
||||
return $response;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the script to execute when the request must be insulated.
|
||||
*
|
||||
* It assumes that the autoloader is named 'autoload.php' and that it is
|
||||
* stored in the same directory as the kernel (this is the case for the
|
||||
* Symfony Standard Edition). If this is not your case, create your own
|
||||
* client and override this method.
|
||||
*
|
||||
* @param Request $request A Request instance
|
||||
*
|
||||
* @return string The script content
|
||||
*/
|
||||
protected function getScript($request)
|
||||
{
|
||||
$kernel = var_export(serialize($this->kernel), true);
|
||||
$request = var_export(serialize($request), true);
|
||||
$errorReporting = error_reporting();
|
||||
|
||||
$requires = '';
|
||||
foreach (get_declared_classes() as $class) {
|
||||
if (0 === strpos($class, 'ComposerAutoloaderInit')) {
|
||||
$r = new \ReflectionClass($class);
|
||||
$file = \dirname(\dirname($r->getFileName())).'/autoload.php';
|
||||
if (file_exists($file)) {
|
||||
$requires .= 'require_once '.var_export($file, true).";\n";
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (!$requires) {
|
||||
throw new \RuntimeException('Composer autoloader not found.');
|
||||
}
|
||||
|
||||
$requires .= 'require_once '.var_export((new \ReflectionObject($this->kernel))->getFileName(), true).";\n";
|
||||
|
||||
$profilerCode = '';
|
||||
if ($this->profiler) {
|
||||
$profilerCode = '$kernel->getContainer()->get(\'profiler\')->enable();';
|
||||
}
|
||||
|
||||
$code = <<<EOF
|
||||
<?php
|
||||
|
||||
error_reporting($errorReporting);
|
||||
|
||||
$requires
|
||||
|
||||
\$kernel = unserialize($kernel);
|
||||
\$kernel->boot();
|
||||
$profilerCode
|
||||
|
||||
\$request = unserialize($request);
|
||||
EOF;
|
||||
|
||||
return $code.$this->getHandleScript();
|
||||
}
|
||||
}
|
||||
|
@ -22,7 +22,7 @@ use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
|
||||
use Symfony\Bundle\FrameworkBundle\Routing\AnnotatedRouteControllerLoader;
|
||||
use Symfony\Bundle\FrameworkBundle\Routing\RedirectableUrlMatcher;
|
||||
use Symfony\Bundle\FullStack;
|
||||
use Symfony\Component\BrowserKit\Client;
|
||||
use Symfony\Component\BrowserKit\AbstractBrowser;
|
||||
use Symfony\Component\Cache\Adapter\AbstractAdapter;
|
||||
use Symfony\Component\Cache\Adapter\AdapterInterface;
|
||||
use Symfony\Component\Cache\Adapter\ArrayAdapter;
|
||||
@ -207,7 +207,7 @@ class FrameworkExtension extends Extension
|
||||
if (!empty($config['test'])) {
|
||||
$loader->load('test.xml');
|
||||
|
||||
if (!class_exists(Client::class)) {
|
||||
if (!class_exists(AbstractBrowser::class)) {
|
||||
$container->removeDefinition('test.client');
|
||||
}
|
||||
}
|
||||
|
206
src/Symfony/Bundle/FrameworkBundle/KernelBrowser.php
Normal file
206
src/Symfony/Bundle/FrameworkBundle/KernelBrowser.php
Normal file
@ -0,0 +1,206 @@
|
||||
<?php
|
||||
|
||||
/*
|
||||
* This file is part of the Symfony package.
|
||||
*
|
||||
* (c) Fabien Potencier <fabien@symfony.com>
|
||||
*
|
||||
* For the full copyright and license information, please view the LICENSE
|
||||
* file that was distributed with this source code.
|
||||
*/
|
||||
|
||||
namespace Symfony\Bundle\FrameworkBundle;
|
||||
|
||||
use Symfony\Component\BrowserKit\CookieJar;
|
||||
use Symfony\Component\BrowserKit\History;
|
||||
use Symfony\Component\DependencyInjection\ContainerInterface;
|
||||
use Symfony\Component\HttpFoundation\Request;
|
||||
use Symfony\Component\HttpFoundation\Response;
|
||||
use Symfony\Component\HttpKernel\HttpKernelBrowser;
|
||||
use Symfony\Component\HttpKernel\KernelInterface;
|
||||
use Symfony\Component\HttpKernel\Profiler\Profile as HttpProfile;
|
||||
|
||||
/**
|
||||
* Client simulates a browser and makes requests to a Kernel object.
|
||||
*
|
||||
* @author Fabien Potencier <fabien@symfony.com>
|
||||
*/
|
||||
class KernelBrowser extends HttpKernelBrowser
|
||||
{
|
||||
private $hasPerformedRequest = false;
|
||||
private $profiler = false;
|
||||
private $reboot = true;
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function __construct(KernelInterface $kernel, array $server = [], History $history = null, CookieJar $cookieJar = null)
|
||||
{
|
||||
parent::__construct($kernel, $server, $history, $cookieJar);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the container.
|
||||
*
|
||||
* @return ContainerInterface|null Returns null when the Kernel has been shutdown or not started yet
|
||||
*/
|
||||
public function getContainer()
|
||||
{
|
||||
return $this->kernel->getContainer();
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the kernel.
|
||||
*
|
||||
* @return KernelInterface
|
||||
*/
|
||||
public function getKernel()
|
||||
{
|
||||
return $this->kernel;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the profile associated with the current Response.
|
||||
*
|
||||
* @return HttpProfile|false A Profile instance
|
||||
*/
|
||||
public function getProfile()
|
||||
{
|
||||
if (!$this->kernel->getContainer()->has('profiler')) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return $this->kernel->getContainer()->get('profiler')->loadProfileFromResponse($this->response);
|
||||
}
|
||||
|
||||
/**
|
||||
* Enables the profiler for the very next request.
|
||||
*
|
||||
* If the profiler is not enabled, the call to this method does nothing.
|
||||
*/
|
||||
public function enableProfiler()
|
||||
{
|
||||
if ($this->kernel->getContainer()->has('profiler')) {
|
||||
$this->profiler = true;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Disables kernel reboot between requests.
|
||||
*
|
||||
* By default, the Client reboots the Kernel for each request. This method
|
||||
* allows to keep the same kernel across requests.
|
||||
*/
|
||||
public function disableReboot()
|
||||
{
|
||||
$this->reboot = false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Enables kernel reboot between requests.
|
||||
*/
|
||||
public function enableReboot()
|
||||
{
|
||||
$this->reboot = true;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*
|
||||
* @param Request $request A Request instance
|
||||
*
|
||||
* @return Response A Response instance
|
||||
*/
|
||||
protected function doRequest($request)
|
||||
{
|
||||
// avoid shutting down the Kernel if no request has been performed yet
|
||||
// WebTestCase::createClient() boots the Kernel but do not handle a request
|
||||
if ($this->hasPerformedRequest && $this->reboot) {
|
||||
$this->kernel->shutdown();
|
||||
} else {
|
||||
$this->hasPerformedRequest = true;
|
||||
}
|
||||
|
||||
if ($this->profiler) {
|
||||
$this->profiler = false;
|
||||
|
||||
$this->kernel->boot();
|
||||
$this->kernel->getContainer()->get('profiler')->enable();
|
||||
}
|
||||
|
||||
return parent::doRequest($request);
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*
|
||||
* @param Request $request A Request instance
|
||||
*
|
||||
* @return Response A Response instance
|
||||
*/
|
||||
protected function doRequestInProcess($request)
|
||||
{
|
||||
$response = parent::doRequestInProcess($request);
|
||||
|
||||
$this->profiler = false;
|
||||
|
||||
return $response;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the script to execute when the request must be insulated.
|
||||
*
|
||||
* It assumes that the autoloader is named 'autoload.php' and that it is
|
||||
* stored in the same directory as the kernel (this is the case for the
|
||||
* Symfony Standard Edition). If this is not your case, create your own
|
||||
* client and override this method.
|
||||
*
|
||||
* @param Request $request A Request instance
|
||||
*
|
||||
* @return string The script content
|
||||
*/
|
||||
protected function getScript($request)
|
||||
{
|
||||
$kernel = var_export(serialize($this->kernel), true);
|
||||
$request = var_export(serialize($request), true);
|
||||
$errorReporting = error_reporting();
|
||||
|
||||
$requires = '';
|
||||
foreach (get_declared_classes() as $class) {
|
||||
if (0 === strpos($class, 'ComposerAutoloaderInit')) {
|
||||
$r = new \ReflectionClass($class);
|
||||
$file = \dirname(\dirname($r->getFileName())).'/autoload.php';
|
||||
if (file_exists($file)) {
|
||||
$requires .= 'require_once '.var_export($file, true).";\n";
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (!$requires) {
|
||||
throw new \RuntimeException('Composer autoloader not found.');
|
||||
}
|
||||
|
||||
$requires .= 'require_once '.var_export((new \ReflectionObject($this->kernel))->getFileName(), true).";\n";
|
||||
|
||||
$profilerCode = '';
|
||||
if ($this->profiler) {
|
||||
$profilerCode = '$kernel->getContainer()->get(\'profiler\')->enable();';
|
||||
}
|
||||
|
||||
$code = <<<EOF
|
||||
<?php
|
||||
|
||||
error_reporting($errorReporting);
|
||||
|
||||
$requires
|
||||
|
||||
\$kernel = unserialize($kernel);
|
||||
\$kernel->boot();
|
||||
$profilerCode
|
||||
|
||||
\$request = unserialize($request);
|
||||
EOF;
|
||||
|
||||
return $code.$this->getHandleScript();
|
||||
}
|
||||
}
|
@ -11,7 +11,7 @@
|
||||
<services>
|
||||
<defaults public="false" />
|
||||
|
||||
<service id="test.client" class="Symfony\Bundle\FrameworkBundle\Client" shared="false" public="true">
|
||||
<service id="test.client" class="Symfony\Bundle\FrameworkBundle\KernelBrowser" shared="false" public="true">
|
||||
<argument type="service" id="kernel" />
|
||||
<argument>%test.client.parameters%</argument>
|
||||
<argument type="service" id="test.client.history" />
|
||||
|
@ -11,7 +11,7 @@
|
||||
|
||||
namespace Symfony\Bundle\FrameworkBundle\Test;
|
||||
|
||||
use Symfony\Bundle\FrameworkBundle\Client;
|
||||
use Symfony\Bundle\FrameworkBundle\KernelBrowser;
|
||||
use Symfony\Component\DependencyInjection\Exception\ServiceNotFoundException;
|
||||
|
||||
/**
|
||||
@ -22,12 +22,12 @@ use Symfony\Component\DependencyInjection\Exception\ServiceNotFoundException;
|
||||
abstract class WebTestCase extends KernelTestCase
|
||||
{
|
||||
/**
|
||||
* Creates a Client.
|
||||
* Creates a KernelBrowser.
|
||||
*
|
||||
* @param array $options An array of options to pass to the createKernel method
|
||||
* @param array $server An array of server parameters
|
||||
*
|
||||
* @return Client A Client instance
|
||||
* @return KernelBrowser A KernelBrowser instance
|
||||
*/
|
||||
protected static function createClient(array $options = [], array $server = [])
|
||||
{
|
||||
|
@ -11,18 +11,18 @@
|
||||
|
||||
namespace Symfony\Bundle\FrameworkBundle\Tests;
|
||||
|
||||
use Symfony\Bundle\FrameworkBundle\Client;
|
||||
use Symfony\Bundle\FrameworkBundle\KernelBrowser;
|
||||
use Symfony\Bundle\FrameworkBundle\Tests\Functional\WebTestCase;
|
||||
use Symfony\Component\HttpFoundation\Response;
|
||||
|
||||
class ClientTest extends WebTestCase
|
||||
class KernelBrowserTest extends WebTestCase
|
||||
{
|
||||
public function testRebootKernelBetweenRequests()
|
||||
{
|
||||
$mock = $this->getKernelMock();
|
||||
$mock->expects($this->once())->method('shutdown');
|
||||
|
||||
$client = new Client($mock);
|
||||
$client = new KernelBrowser($mock);
|
||||
$client->request('GET', '/');
|
||||
$client->request('GET', '/');
|
||||
}
|
||||
@ -32,7 +32,7 @@ class ClientTest extends WebTestCase
|
||||
$mock = $this->getKernelMock();
|
||||
$mock->expects($this->never())->method('shutdown');
|
||||
|
||||
$client = new Client($mock);
|
||||
$client = new KernelBrowser($mock);
|
||||
$client->disableReboot();
|
||||
$client->request('GET', '/');
|
||||
$client->request('GET', '/');
|
||||
@ -43,7 +43,7 @@ class ClientTest extends WebTestCase
|
||||
$mock = $this->getKernelMock();
|
||||
$mock->expects($this->once())->method('shutdown');
|
||||
|
||||
$client = new Client($mock);
|
||||
$client = new KernelBrowser($mock);
|
||||
$client->disableReboot();
|
||||
$client->request('GET', '/');
|
||||
$client->request('GET', '/');
|
@ -34,7 +34,7 @@
|
||||
"doctrine/cache": "~1.0",
|
||||
"fig/link-util": "^1.0",
|
||||
"symfony/asset": "~3.4|~4.0",
|
||||
"symfony/browser-kit": "~3.4|~4.0",
|
||||
"symfony/browser-kit": "^4.3",
|
||||
"symfony/console": "~3.4|~4.0",
|
||||
"symfony/css-selector": "~3.4|~4.0",
|
||||
"symfony/dom-crawler": "~3.4|~4.0",
|
||||
@ -67,6 +67,7 @@
|
||||
"phpdocumentor/type-resolver": "<0.2.1",
|
||||
"phpunit/phpunit": "<4.8.35|<5.4.3,>=5.0",
|
||||
"symfony/asset": "<3.4",
|
||||
"symfony/browser-kit": "<4.3",
|
||||
"symfony/console": "<3.4",
|
||||
"symfony/dotenv": "<4.2",
|
||||
"symfony/form": "<4.3",
|
||||
|
739
src/Symfony/Component/BrowserKit/AbstractBrowser.php
Normal file
739
src/Symfony/Component/BrowserKit/AbstractBrowser.php
Normal file
@ -0,0 +1,739 @@
|
||||
<?php
|
||||
|
||||
/*
|
||||
* This file is part of the Symfony package.
|
||||
*
|
||||
* (c) Fabien Potencier <fabien@symfony.com>
|
||||
*
|
||||
* For the full copyright and license information, please view the LICENSE
|
||||
* file that was distributed with this source code.
|
||||
*/
|
||||
|
||||
namespace Symfony\Component\BrowserKit;
|
||||
|
||||
use Symfony\Component\BrowserKit\Exception\BadMethodCallException;
|
||||
use Symfony\Component\DomCrawler\Crawler;
|
||||
use Symfony\Component\DomCrawler\Form;
|
||||
use Symfony\Component\DomCrawler\Link;
|
||||
use Symfony\Component\Process\PhpProcess;
|
||||
|
||||
/**
|
||||
* Simulates a browser.
|
||||
*
|
||||
* To make the actual request, you need to implement the doRequest() method.
|
||||
*
|
||||
* HttpBrowser is an implementation that uses the HttpClient component
|
||||
* to make real HTTP requests.
|
||||
*
|
||||
* If you want to be able to run requests in their own process (insulated flag),
|
||||
* you need to also implement the getScript() method.
|
||||
*
|
||||
* @author Fabien Potencier <fabien@symfony.com>
|
||||
*/
|
||||
abstract class AbstractBrowser
|
||||
{
|
||||
protected $history;
|
||||
protected $cookieJar;
|
||||
protected $server = [];
|
||||
protected $internalRequest;
|
||||
protected $request;
|
||||
protected $internalResponse;
|
||||
protected $response;
|
||||
protected $crawler;
|
||||
protected $insulated = false;
|
||||
protected $redirect;
|
||||
protected $followRedirects = true;
|
||||
protected $followMetaRefresh = false;
|
||||
|
||||
private $maxRedirects = -1;
|
||||
private $redirectCount = 0;
|
||||
private $redirects = [];
|
||||
private $isMainRequest = true;
|
||||
|
||||
/**
|
||||
* @param array $server The server parameters (equivalent of $_SERVER)
|
||||
* @param History $history A History instance to store the browser history
|
||||
* @param CookieJar $cookieJar A CookieJar instance to store the cookies
|
||||
*/
|
||||
public function __construct(array $server = [], History $history = null, CookieJar $cookieJar = null)
|
||||
{
|
||||
$this->setServerParameters($server);
|
||||
$this->history = $history ?: new History();
|
||||
$this->cookieJar = $cookieJar ?: new CookieJar();
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets whether to automatically follow redirects or not.
|
||||
*
|
||||
* @param bool $followRedirect Whether to follow redirects
|
||||
*/
|
||||
public function followRedirects($followRedirect = true)
|
||||
{
|
||||
$this->followRedirects = (bool) $followRedirect;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets whether to automatically follow meta refresh redirects or not.
|
||||
*/
|
||||
public function followMetaRefresh(bool $followMetaRefresh = true)
|
||||
{
|
||||
$this->followMetaRefresh = $followMetaRefresh;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns whether client automatically follows redirects or not.
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
public function isFollowingRedirects()
|
||||
{
|
||||
return $this->followRedirects;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the maximum number of redirects that crawler can follow.
|
||||
*
|
||||
* @param int $maxRedirects
|
||||
*/
|
||||
public function setMaxRedirects($maxRedirects)
|
||||
{
|
||||
$this->maxRedirects = $maxRedirects < 0 ? -1 : $maxRedirects;
|
||||
$this->followRedirects = -1 != $this->maxRedirects;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the maximum number of redirects that crawler can follow.
|
||||
*
|
||||
* @return int
|
||||
*/
|
||||
public function getMaxRedirects()
|
||||
{
|
||||
return $this->maxRedirects;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the insulated flag.
|
||||
*
|
||||
* @param bool $insulated Whether to insulate the requests or not
|
||||
*
|
||||
* @throws \RuntimeException When Symfony Process Component is not installed
|
||||
*/
|
||||
public function insulate($insulated = true)
|
||||
{
|
||||
if ($insulated && !class_exists('Symfony\\Component\\Process\\Process')) {
|
||||
throw new \LogicException('Unable to isolate requests as the Symfony Process Component is not installed.');
|
||||
}
|
||||
|
||||
$this->insulated = (bool) $insulated;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets server parameters.
|
||||
*
|
||||
* @param array $server An array of server parameters
|
||||
*/
|
||||
public function setServerParameters(array $server)
|
||||
{
|
||||
$this->server = array_merge([
|
||||
'HTTP_USER_AGENT' => 'Symfony BrowserKit',
|
||||
], $server);
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets single server parameter.
|
||||
*
|
||||
* @param string $key A key of the parameter
|
||||
* @param string $value A value of the parameter
|
||||
*/
|
||||
public function setServerParameter($key, $value)
|
||||
{
|
||||
$this->server[$key] = $value;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets single server parameter for specified key.
|
||||
*
|
||||
* @param string $key A key of the parameter to get
|
||||
* @param string $default A default value when key is undefined
|
||||
*
|
||||
* @return string A value of the parameter
|
||||
*/
|
||||
public function getServerParameter($key, $default = '')
|
||||
{
|
||||
return isset($this->server[$key]) ? $this->server[$key] : $default;
|
||||
}
|
||||
|
||||
public function xmlHttpRequest(string $method, string $uri, array $parameters = [], array $files = [], array $server = [], string $content = null, bool $changeHistory = true): Crawler
|
||||
{
|
||||
$this->setServerParameter('HTTP_X_REQUESTED_WITH', 'XMLHttpRequest');
|
||||
|
||||
try {
|
||||
return $this->request($method, $uri, $parameters, $files, $server, $content, $changeHistory);
|
||||
} finally {
|
||||
unset($this->server['HTTP_X_REQUESTED_WITH']);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the History instance.
|
||||
*
|
||||
* @return History A History instance
|
||||
*/
|
||||
public function getHistory()
|
||||
{
|
||||
return $this->history;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the CookieJar instance.
|
||||
*
|
||||
* @return CookieJar A CookieJar instance
|
||||
*/
|
||||
public function getCookieJar()
|
||||
{
|
||||
return $this->cookieJar;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the current Crawler instance.
|
||||
*
|
||||
* @return Crawler A Crawler instance
|
||||
*/
|
||||
public function getCrawler()
|
||||
{
|
||||
if (null === $this->crawler) {
|
||||
@trigger_error(sprintf('Calling the "%s()" method before the "request()" one is deprecated since Symfony 4.1 and will throw an exception in 5.0.', __METHOD__), E_USER_DEPRECATED);
|
||||
// throw new BadMethodCallException(sprintf('The "request()" method must be called before "%s()".', __METHOD__));
|
||||
}
|
||||
|
||||
return $this->crawler;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the current BrowserKit Response instance.
|
||||
*
|
||||
* @return Response A BrowserKit Response instance
|
||||
*/
|
||||
public function getInternalResponse()
|
||||
{
|
||||
if (null === $this->internalResponse) {
|
||||
@trigger_error(sprintf('Calling the "%s()" method before the "request()" one is deprecated since Symfony 4.1 and will throw an exception in 5.0.', __METHOD__), E_USER_DEPRECATED);
|
||||
// throw new BadMethodCallException(sprintf('The "request()" method must be called before "%s()".', __METHOD__));
|
||||
}
|
||||
|
||||
return $this->internalResponse;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the current origin response instance.
|
||||
*
|
||||
* The origin response is the response instance that is returned
|
||||
* by the code that handles requests.
|
||||
*
|
||||
* @return object A response instance
|
||||
*
|
||||
* @see doRequest()
|
||||
*/
|
||||
public function getResponse()
|
||||
{
|
||||
if (null === $this->response) {
|
||||
@trigger_error(sprintf('Calling the "%s()" method before the "request()" one is deprecated since Symfony 4.1 and will throw an exception in 5.0.', __METHOD__), E_USER_DEPRECATED);
|
||||
// throw new BadMethodCallException(sprintf('The "request()" method must be called before "%s()".', __METHOD__));
|
||||
}
|
||||
|
||||
return $this->response;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the current BrowserKit Request instance.
|
||||
*
|
||||
* @return Request A BrowserKit Request instance
|
||||
*/
|
||||
public function getInternalRequest()
|
||||
{
|
||||
if (null === $this->internalRequest) {
|
||||
@trigger_error(sprintf('Calling the "%s()" method before the "request()" one is deprecated since Symfony 4.1 and will throw an exception in 5.0.', __METHOD__), E_USER_DEPRECATED);
|
||||
// throw new BadMethodCallException(sprintf('The "request()" method must be called before "%s()".', __METHOD__));
|
||||
}
|
||||
|
||||
return $this->internalRequest;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the current origin Request instance.
|
||||
*
|
||||
* The origin request is the request instance that is sent
|
||||
* to the code that handles requests.
|
||||
*
|
||||
* @return object A Request instance
|
||||
*
|
||||
* @see doRequest()
|
||||
*/
|
||||
public function getRequest()
|
||||
{
|
||||
if (null === $this->request) {
|
||||
@trigger_error(sprintf('Calling the "%s()" method before the "request()" one is deprecated since Symfony 4.1 and will throw an exception in 5.0.', __METHOD__), E_USER_DEPRECATED);
|
||||
// throw new BadMethodCallException(sprintf('The "request()" method must be called before "%s()".', __METHOD__));
|
||||
}
|
||||
|
||||
return $this->request;
|
||||
}
|
||||
|
||||
/**
|
||||
* Clicks on a given link.
|
||||
*
|
||||
* @return Crawler
|
||||
*/
|
||||
public function click(Link $link)
|
||||
{
|
||||
if ($link instanceof Form) {
|
||||
return $this->submit($link);
|
||||
}
|
||||
|
||||
return $this->request($link->getMethod(), $link->getUri());
|
||||
}
|
||||
|
||||
/**
|
||||
* Clicks the first link (or clickable image) that contains the given text.
|
||||
*
|
||||
* @param string $linkText The text of the link or the alt attribute of the clickable image
|
||||
*/
|
||||
public function clickLink(string $linkText): Crawler
|
||||
{
|
||||
if (null === $this->crawler) {
|
||||
throw new BadMethodCallException(sprintf('The "request()" method must be called before "%s()".', __METHOD__));
|
||||
}
|
||||
|
||||
return $this->click($this->crawler->selectLink($linkText)->link());
|
||||
}
|
||||
|
||||
/**
|
||||
* Submits a form.
|
||||
*
|
||||
* @param Form $form A Form instance
|
||||
* @param array $values An array of form field values
|
||||
* @param array $serverParameters An array of server parameters
|
||||
*
|
||||
* @return Crawler
|
||||
*/
|
||||
public function submit(Form $form, array $values = []/*, array $serverParameters = []*/)
|
||||
{
|
||||
if (\func_num_args() < 3 && __CLASS__ !== \get_class($this) && __CLASS__ !== (new \ReflectionMethod($this, __FUNCTION__))->getDeclaringClass()->getName() && !$this instanceof \PHPUnit\Framework\MockObject\MockObject && !$this instanceof \Prophecy\Prophecy\ProphecySubjectInterface) {
|
||||
@trigger_error(sprintf('The "%s()" method will have a new "array $serverParameters = []" argument in version 5.0, not defining it is deprecated since Symfony 4.2.', __METHOD__), E_USER_DEPRECATED);
|
||||
}
|
||||
|
||||
$form->setValues($values);
|
||||
$serverParameters = 2 < \func_num_args() ? func_get_arg(2) : [];
|
||||
|
||||
return $this->request($form->getMethod(), $form->getUri(), $form->getPhpValues(), $form->getPhpFiles(), $serverParameters);
|
||||
}
|
||||
|
||||
/**
|
||||
* Finds the first form that contains a button with the given content and
|
||||
* uses it to submit the given form field values.
|
||||
*
|
||||
* @param string $button The text content, id, value or name of the form <button> or <input type="submit">
|
||||
* @param array $fieldValues Use this syntax: ['my_form[name]' => '...', 'my_form[email]' => '...']
|
||||
* @param string $method The HTTP method used to submit the form
|
||||
* @param array $serverParameters These values override the ones stored in $_SERVER (HTTP headers must include a HTTP_ prefix as PHP does)
|
||||
*/
|
||||
public function submitForm(string $button, array $fieldValues = [], string $method = 'POST', array $serverParameters = []): Crawler
|
||||
{
|
||||
if (null === $this->crawler) {
|
||||
throw new BadMethodCallException(sprintf('The "request()" method must be called before "%s()".', __METHOD__));
|
||||
}
|
||||
|
||||
$buttonNode = $this->crawler->selectButton($button);
|
||||
$form = $buttonNode->form($fieldValues, $method);
|
||||
|
||||
return $this->submit($form, [], $serverParameters);
|
||||
}
|
||||
|
||||
/**
|
||||
* Calls a URI.
|
||||
*
|
||||
* @param string $method The request method
|
||||
* @param string $uri The URI to fetch
|
||||
* @param array $parameters The Request parameters
|
||||
* @param array $files The files
|
||||
* @param array $server The server parameters (HTTP headers are referenced with a HTTP_ prefix as PHP does)
|
||||
* @param string $content The raw body data
|
||||
* @param bool $changeHistory Whether to update the history or not (only used internally for back(), forward(), and reload())
|
||||
*
|
||||
* @return Crawler
|
||||
*/
|
||||
public function request(string $method, string $uri, array $parameters = [], array $files = [], array $server = [], string $content = null, bool $changeHistory = true)
|
||||
{
|
||||
if ($this->isMainRequest) {
|
||||
$this->redirectCount = 0;
|
||||
} else {
|
||||
++$this->redirectCount;
|
||||
}
|
||||
|
||||
$originalUri = $uri;
|
||||
|
||||
$uri = $this->getAbsoluteUri($uri);
|
||||
|
||||
$server = array_merge($this->server, $server);
|
||||
|
||||
if (!empty($server['HTTP_HOST']) && null === parse_url($originalUri, PHP_URL_HOST)) {
|
||||
$uri = preg_replace('{^(https?\://)'.preg_quote($this->extractHost($uri)).'}', '${1}'.$server['HTTP_HOST'], $uri);
|
||||
}
|
||||
|
||||
if (isset($server['HTTPS']) && null === parse_url($originalUri, PHP_URL_SCHEME)) {
|
||||
$uri = preg_replace('{^'.parse_url($uri, PHP_URL_SCHEME).'}', $server['HTTPS'] ? 'https' : 'http', $uri);
|
||||
}
|
||||
|
||||
if (!$this->history->isEmpty()) {
|
||||
$server['HTTP_REFERER'] = $this->history->current()->getUri();
|
||||
}
|
||||
|
||||
if (empty($server['HTTP_HOST'])) {
|
||||
$server['HTTP_HOST'] = $this->extractHost($uri);
|
||||
}
|
||||
|
||||
$server['HTTPS'] = 'https' == parse_url($uri, PHP_URL_SCHEME);
|
||||
|
||||
$this->internalRequest = new Request($uri, $method, $parameters, $files, $this->cookieJar->allValues($uri), $server, $content);
|
||||
|
||||
$this->request = $this->filterRequest($this->internalRequest);
|
||||
|
||||
if (true === $changeHistory) {
|
||||
$this->history->add($this->internalRequest);
|
||||
}
|
||||
|
||||
if ($this->insulated) {
|
||||
$this->response = $this->doRequestInProcess($this->request);
|
||||
} else {
|
||||
$this->response = $this->doRequest($this->request);
|
||||
}
|
||||
|
||||
$this->internalResponse = $this->filterResponse($this->response);
|
||||
|
||||
$this->cookieJar->updateFromResponse($this->internalResponse, $uri);
|
||||
|
||||
$status = $this->internalResponse->getStatusCode();
|
||||
|
||||
if ($status >= 300 && $status < 400) {
|
||||
$this->redirect = $this->internalResponse->getHeader('Location');
|
||||
} else {
|
||||
$this->redirect = null;
|
||||
}
|
||||
|
||||
if ($this->followRedirects && $this->redirect) {
|
||||
$this->redirects[serialize($this->history->current())] = true;
|
||||
|
||||
return $this->crawler = $this->followRedirect();
|
||||
}
|
||||
|
||||
$this->crawler = $this->createCrawlerFromContent($this->internalRequest->getUri(), $this->internalResponse->getContent(), $this->internalResponse->getHeader('Content-Type'));
|
||||
|
||||
// Check for meta refresh redirect
|
||||
if ($this->followMetaRefresh && null !== $redirect = $this->getMetaRefreshUrl()) {
|
||||
$this->redirect = $redirect;
|
||||
$this->redirects[serialize($this->history->current())] = true;
|
||||
$this->crawler = $this->followRedirect();
|
||||
}
|
||||
|
||||
return $this->crawler;
|
||||
}
|
||||
|
||||
/**
|
||||
* Makes a request in another process.
|
||||
*
|
||||
* @param object $request An origin request instance
|
||||
*
|
||||
* @return object An origin response instance
|
||||
*
|
||||
* @throws \RuntimeException When processing returns exit code
|
||||
*/
|
||||
protected function doRequestInProcess($request)
|
||||
{
|
||||
$deprecationsFile = tempnam(sys_get_temp_dir(), 'deprec');
|
||||
putenv('SYMFONY_DEPRECATIONS_SERIALIZE='.$deprecationsFile);
|
||||
$_ENV['SYMFONY_DEPRECATIONS_SERIALIZE'] = $deprecationsFile;
|
||||
$process = new PhpProcess($this->getScript($request), null, null);
|
||||
$process->run();
|
||||
|
||||
if (file_exists($deprecationsFile)) {
|
||||
$deprecations = file_get_contents($deprecationsFile);
|
||||
unlink($deprecationsFile);
|
||||
foreach ($deprecations ? unserialize($deprecations) : [] as $deprecation) {
|
||||
if ($deprecation[0]) {
|
||||
@trigger_error($deprecation[1], E_USER_DEPRECATED);
|
||||
} else {
|
||||
@trigger_error($deprecation[1], E_USER_DEPRECATED);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (!$process->isSuccessful() || !preg_match('/^O\:\d+\:/', $process->getOutput())) {
|
||||
throw new \RuntimeException(sprintf('OUTPUT: %s ERROR OUTPUT: %s', $process->getOutput(), $process->getErrorOutput()));
|
||||
}
|
||||
|
||||
return unserialize($process->getOutput());
|
||||
}
|
||||
|
||||
/**
|
||||
* Makes a request.
|
||||
*
|
||||
* @param object $request An origin request instance
|
||||
*
|
||||
* @return object An origin response instance
|
||||
*/
|
||||
abstract protected function doRequest($request);
|
||||
|
||||
/**
|
||||
* Returns the script to execute when the request must be insulated.
|
||||
*
|
||||
* @param object $request An origin request instance
|
||||
*
|
||||
* @throws \LogicException When this abstract class is not implemented
|
||||
*/
|
||||
protected function getScript($request)
|
||||
{
|
||||
throw new \LogicException('To insulate requests, you need to override the getScript() method.');
|
||||
}
|
||||
|
||||
/**
|
||||
* Filters the BrowserKit request to the origin one.
|
||||
*
|
||||
* @param Request $request The BrowserKit Request to filter
|
||||
*
|
||||
* @return object An origin request instance
|
||||
*/
|
||||
protected function filterRequest(Request $request)
|
||||
{
|
||||
return $request;
|
||||
}
|
||||
|
||||
/**
|
||||
* Filters the origin response to the BrowserKit one.
|
||||
*
|
||||
* @param object $response The origin response to filter
|
||||
*
|
||||
* @return Response An BrowserKit Response instance
|
||||
*/
|
||||
protected function filterResponse($response)
|
||||
{
|
||||
return $response;
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a crawler.
|
||||
*
|
||||
* This method returns null if the DomCrawler component is not available.
|
||||
*
|
||||
* @param string $uri A URI
|
||||
* @param string $content Content for the crawler to use
|
||||
* @param string $type Content type
|
||||
*
|
||||
* @return Crawler|null
|
||||
*/
|
||||
protected function createCrawlerFromContent($uri, $content, $type)
|
||||
{
|
||||
if (!class_exists('Symfony\Component\DomCrawler\Crawler')) {
|
||||
return;
|
||||
}
|
||||
|
||||
$crawler = new Crawler(null, $uri);
|
||||
$crawler->addContent($content, $type);
|
||||
|
||||
return $crawler;
|
||||
}
|
||||
|
||||
/**
|
||||
* Goes back in the browser history.
|
||||
*
|
||||
* @return Crawler
|
||||
*/
|
||||
public function back()
|
||||
{
|
||||
do {
|
||||
$request = $this->history->back();
|
||||
} while (\array_key_exists(serialize($request), $this->redirects));
|
||||
|
||||
return $this->requestFromRequest($request, false);
|
||||
}
|
||||
|
||||
/**
|
||||
* Goes forward in the browser history.
|
||||
*
|
||||
* @return Crawler
|
||||
*/
|
||||
public function forward()
|
||||
{
|
||||
do {
|
||||
$request = $this->history->forward();
|
||||
} while (\array_key_exists(serialize($request), $this->redirects));
|
||||
|
||||
return $this->requestFromRequest($request, false);
|
||||
}
|
||||
|
||||
/**
|
||||
* Reloads the current browser.
|
||||
*
|
||||
* @return Crawler
|
||||
*/
|
||||
public function reload()
|
||||
{
|
||||
return $this->requestFromRequest($this->history->current(), false);
|
||||
}
|
||||
|
||||
/**
|
||||
* Follow redirects?
|
||||
*
|
||||
* @return Crawler
|
||||
*
|
||||
* @throws \LogicException If request was not a redirect
|
||||
*/
|
||||
public function followRedirect()
|
||||
{
|
||||
if (empty($this->redirect)) {
|
||||
throw new \LogicException('The request was not redirected.');
|
||||
}
|
||||
|
||||
if (-1 !== $this->maxRedirects) {
|
||||
if ($this->redirectCount > $this->maxRedirects) {
|
||||
$this->redirectCount = 0;
|
||||
throw new \LogicException(sprintf('The maximum number (%d) of redirections was reached.', $this->maxRedirects));
|
||||
}
|
||||
}
|
||||
|
||||
$request = $this->internalRequest;
|
||||
|
||||
if (\in_array($this->internalResponse->getStatusCode(), [301, 302, 303])) {
|
||||
$method = 'GET';
|
||||
$files = [];
|
||||
$content = null;
|
||||
} else {
|
||||
$method = $request->getMethod();
|
||||
$files = $request->getFiles();
|
||||
$content = $request->getContent();
|
||||
}
|
||||
|
||||
if ('GET' === strtoupper($method)) {
|
||||
// Don't forward parameters for GET request as it should reach the redirection URI
|
||||
$parameters = [];
|
||||
} else {
|
||||
$parameters = $request->getParameters();
|
||||
}
|
||||
|
||||
$server = $request->getServer();
|
||||
$server = $this->updateServerFromUri($server, $this->redirect);
|
||||
|
||||
$this->isMainRequest = false;
|
||||
|
||||
$response = $this->request($method, $this->redirect, $parameters, $files, $server, $content);
|
||||
|
||||
$this->isMainRequest = true;
|
||||
|
||||
return $response;
|
||||
}
|
||||
|
||||
/**
|
||||
* @see https://dev.w3.org/html5/spec-preview/the-meta-element.html#attr-meta-http-equiv-refresh
|
||||
*/
|
||||
private function getMetaRefreshUrl(): ?string
|
||||
{
|
||||
$metaRefresh = $this->getCrawler()->filter('head meta[http-equiv="refresh"]');
|
||||
foreach ($metaRefresh->extract(['content']) as $content) {
|
||||
if (preg_match('/^\s*0\s*;\s*URL\s*=\s*(?|\'([^\']++)|"([^"]++)|([^\'"].*))/i', $content, $m)) {
|
||||
return str_replace("\t\r\n", '', rtrim($m[1]));
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Restarts the client.
|
||||
*
|
||||
* It flushes history and all cookies.
|
||||
*/
|
||||
public function restart()
|
||||
{
|
||||
$this->cookieJar->clear();
|
||||
$this->history->clear();
|
||||
}
|
||||
|
||||
/**
|
||||
* Takes a URI and converts it to absolute if it is not already absolute.
|
||||
*
|
||||
* @param string $uri A URI
|
||||
*
|
||||
* @return string An absolute URI
|
||||
*/
|
||||
protected function getAbsoluteUri($uri)
|
||||
{
|
||||
// already absolute?
|
||||
if (0 === strpos($uri, 'http://') || 0 === strpos($uri, 'https://')) {
|
||||
return $uri;
|
||||
}
|
||||
|
||||
if (!$this->history->isEmpty()) {
|
||||
$currentUri = $this->history->current()->getUri();
|
||||
} else {
|
||||
$currentUri = sprintf('http%s://%s/',
|
||||
isset($this->server['HTTPS']) ? 's' : '',
|
||||
isset($this->server['HTTP_HOST']) ? $this->server['HTTP_HOST'] : 'localhost'
|
||||
);
|
||||
}
|
||||
|
||||
// protocol relative URL
|
||||
if (0 === strpos($uri, '//')) {
|
||||
return parse_url($currentUri, PHP_URL_SCHEME).':'.$uri;
|
||||
}
|
||||
|
||||
// anchor or query string parameters?
|
||||
if (!$uri || '#' == $uri[0] || '?' == $uri[0]) {
|
||||
return preg_replace('/[#?].*?$/', '', $currentUri).$uri;
|
||||
}
|
||||
|
||||
if ('/' !== $uri[0]) {
|
||||
$path = parse_url($currentUri, PHP_URL_PATH);
|
||||
|
||||
if ('/' !== substr($path, -1)) {
|
||||
$path = substr($path, 0, strrpos($path, '/') + 1);
|
||||
}
|
||||
|
||||
$uri = $path.$uri;
|
||||
}
|
||||
|
||||
return preg_replace('#^(.*?//[^/]+)\/.*$#', '$1', $currentUri).$uri;
|
||||
}
|
||||
|
||||
/**
|
||||
* Makes a request from a Request object directly.
|
||||
*
|
||||
* @param Request $request A Request instance
|
||||
* @param bool $changeHistory Whether to update the history or not (only used internally for back(), forward(), and reload())
|
||||
*
|
||||
* @return Crawler
|
||||
*/
|
||||
protected function requestFromRequest(Request $request, $changeHistory = true)
|
||||
{
|
||||
return $this->request($request->getMethod(), $request->getUri(), $request->getParameters(), $request->getFiles(), $request->getServer(), $request->getContent(), $changeHistory);
|
||||
}
|
||||
|
||||
private function updateServerFromUri($server, $uri)
|
||||
{
|
||||
$server['HTTP_HOST'] = $this->extractHost($uri);
|
||||
$scheme = parse_url($uri, PHP_URL_SCHEME);
|
||||
$server['HTTPS'] = null === $scheme ? $server['HTTPS'] : 'https' == $scheme;
|
||||
unset($server['HTTP_IF_NONE_MATCH'], $server['HTTP_IF_MODIFIED_SINCE']);
|
||||
|
||||
return $server;
|
||||
}
|
||||
|
||||
private function extractHost($uri)
|
||||
{
|
||||
$host = parse_url($uri, PHP_URL_HOST);
|
||||
|
||||
if ($port = parse_url($uri, PHP_URL_PORT)) {
|
||||
return $host.':'.$port;
|
||||
}
|
||||
|
||||
return $host;
|
||||
}
|
||||
}
|
@ -4,6 +4,7 @@ CHANGELOG
|
||||
4.3.0
|
||||
-----
|
||||
|
||||
* Renamed `Client` to `AbstractBrowser`
|
||||
* Marked `Response` final.
|
||||
* Deprecated `Response::buildHeader()`
|
||||
* Deprecated `Response::getStatus()`, use `Response::getStatusCode()` instead
|
||||
|
@ -11,726 +11,8 @@
|
||||
|
||||
namespace Symfony\Component\BrowserKit;
|
||||
|
||||
use Symfony\Component\BrowserKit\Exception\BadMethodCallException;
|
||||
use Symfony\Component\DomCrawler\Crawler;
|
||||
use Symfony\Component\DomCrawler\Form;
|
||||
use Symfony\Component\DomCrawler\Link;
|
||||
use Symfony\Component\Process\PhpProcess;
|
||||
@trigger_error(sprintf('The "%s" class is deprecated since Symfony 4.3, use "%s" instead.', Client::class, AbstractBrowser::class), E_USER_DEPRECATED);
|
||||
|
||||
/**
|
||||
* Client simulates a browser.
|
||||
*
|
||||
* To make the actual request, you need to implement the doRequest() method.
|
||||
*
|
||||
* If you want to be able to run requests in their own process (insulated flag),
|
||||
* you need to also implement the getScript() method.
|
||||
*
|
||||
* @author Fabien Potencier <fabien@symfony.com>
|
||||
*/
|
||||
abstract class Client
|
||||
abstract class Client extends AbstractBrowser
|
||||
{
|
||||
protected $history;
|
||||
protected $cookieJar;
|
||||
protected $server = [];
|
||||
protected $internalRequest;
|
||||
protected $request;
|
||||
protected $internalResponse;
|
||||
protected $response;
|
||||
protected $crawler;
|
||||
protected $insulated = false;
|
||||
protected $redirect;
|
||||
protected $followRedirects = true;
|
||||
protected $followMetaRefresh = false;
|
||||
|
||||
private $maxRedirects = -1;
|
||||
private $redirectCount = 0;
|
||||
private $redirects = [];
|
||||
private $isMainRequest = true;
|
||||
|
||||
/**
|
||||
* @param array $server The server parameters (equivalent of $_SERVER)
|
||||
* @param History $history A History instance to store the browser history
|
||||
* @param CookieJar $cookieJar A CookieJar instance to store the cookies
|
||||
*/
|
||||
public function __construct(array $server = [], History $history = null, CookieJar $cookieJar = null)
|
||||
{
|
||||
$this->setServerParameters($server);
|
||||
$this->history = $history ?: new History();
|
||||
$this->cookieJar = $cookieJar ?: new CookieJar();
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets whether to automatically follow redirects or not.
|
||||
*
|
||||
* @param bool $followRedirect Whether to follow redirects
|
||||
*/
|
||||
public function followRedirects($followRedirect = true)
|
||||
{
|
||||
$this->followRedirects = (bool) $followRedirect;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets whether to automatically follow meta refresh redirects or not.
|
||||
*/
|
||||
public function followMetaRefresh(bool $followMetaRefresh = true)
|
||||
{
|
||||
$this->followMetaRefresh = $followMetaRefresh;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns whether client automatically follows redirects or not.
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
public function isFollowingRedirects()
|
||||
{
|
||||
return $this->followRedirects;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the maximum number of redirects that crawler can follow.
|
||||
*
|
||||
* @param int $maxRedirects
|
||||
*/
|
||||
public function setMaxRedirects($maxRedirects)
|
||||
{
|
||||
$this->maxRedirects = $maxRedirects < 0 ? -1 : $maxRedirects;
|
||||
$this->followRedirects = -1 != $this->maxRedirects;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the maximum number of redirects that crawler can follow.
|
||||
*
|
||||
* @return int
|
||||
*/
|
||||
public function getMaxRedirects()
|
||||
{
|
||||
return $this->maxRedirects;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the insulated flag.
|
||||
*
|
||||
* @param bool $insulated Whether to insulate the requests or not
|
||||
*
|
||||
* @throws \RuntimeException When Symfony Process Component is not installed
|
||||
*/
|
||||
public function insulate($insulated = true)
|
||||
{
|
||||
if ($insulated && !class_exists('Symfony\\Component\\Process\\Process')) {
|
||||
throw new \LogicException('Unable to isolate requests as the Symfony Process Component is not installed.');
|
||||
}
|
||||
|
||||
$this->insulated = (bool) $insulated;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets server parameters.
|
||||
*
|
||||
* @param array $server An array of server parameters
|
||||
*/
|
||||
public function setServerParameters(array $server)
|
||||
{
|
||||
$this->server = array_merge([
|
||||
'HTTP_USER_AGENT' => 'Symfony BrowserKit',
|
||||
], $server);
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets single server parameter.
|
||||
*
|
||||
* @param string $key A key of the parameter
|
||||
* @param string $value A value of the parameter
|
||||
*/
|
||||
public function setServerParameter($key, $value)
|
||||
{
|
||||
$this->server[$key] = $value;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets single server parameter for specified key.
|
||||
*
|
||||
* @param string $key A key of the parameter to get
|
||||
* @param string $default A default value when key is undefined
|
||||
*
|
||||
* @return string A value of the parameter
|
||||
*/
|
||||
public function getServerParameter($key, $default = '')
|
||||
{
|
||||
return isset($this->server[$key]) ? $this->server[$key] : $default;
|
||||
}
|
||||
|
||||
public function xmlHttpRequest(string $method, string $uri, array $parameters = [], array $files = [], array $server = [], string $content = null, bool $changeHistory = true): Crawler
|
||||
{
|
||||
$this->setServerParameter('HTTP_X_REQUESTED_WITH', 'XMLHttpRequest');
|
||||
|
||||
try {
|
||||
return $this->request($method, $uri, $parameters, $files, $server, $content, $changeHistory);
|
||||
} finally {
|
||||
unset($this->server['HTTP_X_REQUESTED_WITH']);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the History instance.
|
||||
*
|
||||
* @return History A History instance
|
||||
*/
|
||||
public function getHistory()
|
||||
{
|
||||
return $this->history;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the CookieJar instance.
|
||||
*
|
||||
* @return CookieJar A CookieJar instance
|
||||
*/
|
||||
public function getCookieJar()
|
||||
{
|
||||
return $this->cookieJar;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the current Crawler instance.
|
||||
*
|
||||
* @return Crawler A Crawler instance
|
||||
*/
|
||||
public function getCrawler()
|
||||
{
|
||||
if (null === $this->crawler) {
|
||||
@trigger_error(sprintf('Calling the "%s()" method before the "request()" one is deprecated since Symfony 4.1 and will throw an exception in 5.0.', __METHOD__), E_USER_DEPRECATED);
|
||||
// throw new BadMethodCallException(sprintf('The "request()" method must be called before "%s()".', __METHOD__));
|
||||
}
|
||||
|
||||
return $this->crawler;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the current BrowserKit Response instance.
|
||||
*
|
||||
* @return Response A BrowserKit Response instance
|
||||
*/
|
||||
public function getInternalResponse()
|
||||
{
|
||||
if (null === $this->internalResponse) {
|
||||
@trigger_error(sprintf('Calling the "%s()" method before the "request()" one is deprecated since Symfony 4.1 and will throw an exception in 5.0.', __METHOD__), E_USER_DEPRECATED);
|
||||
// throw new BadMethodCallException(sprintf('The "request()" method must be called before "%s()".', __METHOD__));
|
||||
}
|
||||
|
||||
return $this->internalResponse;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the current origin response instance.
|
||||
*
|
||||
* The origin response is the response instance that is returned
|
||||
* by the code that handles requests.
|
||||
*
|
||||
* @return object A response instance
|
||||
*
|
||||
* @see doRequest()
|
||||
*/
|
||||
public function getResponse()
|
||||
{
|
||||
if (null === $this->response) {
|
||||
@trigger_error(sprintf('Calling the "%s()" method before the "request()" one is deprecated since Symfony 4.1 and will throw an exception in 5.0.', __METHOD__), E_USER_DEPRECATED);
|
||||
// throw new BadMethodCallException(sprintf('The "request()" method must be called before "%s()".', __METHOD__));
|
||||
}
|
||||
|
||||
return $this->response;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the current BrowserKit Request instance.
|
||||
*
|
||||
* @return Request A BrowserKit Request instance
|
||||
*/
|
||||
public function getInternalRequest()
|
||||
{
|
||||
if (null === $this->internalRequest) {
|
||||
@trigger_error(sprintf('Calling the "%s()" method before the "request()" one is deprecated since Symfony 4.1 and will throw an exception in 5.0.', __METHOD__), E_USER_DEPRECATED);
|
||||
// throw new BadMethodCallException(sprintf('The "request()" method must be called before "%s()".', __METHOD__));
|
||||
}
|
||||
|
||||
return $this->internalRequest;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the current origin Request instance.
|
||||
*
|
||||
* The origin request is the request instance that is sent
|
||||
* to the code that handles requests.
|
||||
*
|
||||
* @return object A Request instance
|
||||
*
|
||||
* @see doRequest()
|
||||
*/
|
||||
public function getRequest()
|
||||
{
|
||||
if (null === $this->request) {
|
||||
@trigger_error(sprintf('Calling the "%s()" method before the "request()" one is deprecated since Symfony 4.1 and will throw an exception in 5.0.', __METHOD__), E_USER_DEPRECATED);
|
||||
// throw new BadMethodCallException(sprintf('The "request()" method must be called before "%s()".', __METHOD__));
|
||||
}
|
||||
|
||||
return $this->request;
|
||||
}
|
||||
|
||||
/**
|
||||
* Clicks on a given link.
|
||||
*
|
||||
* @return Crawler
|
||||
*/
|
||||
public function click(Link $link)
|
||||
{
|
||||
if ($link instanceof Form) {
|
||||
return $this->submit($link);
|
||||
}
|
||||
|
||||
return $this->request($link->getMethod(), $link->getUri());
|
||||
}
|
||||
|
||||
/**
|
||||
* Clicks the first link (or clickable image) that contains the given text.
|
||||
*
|
||||
* @param string $linkText The text of the link or the alt attribute of the clickable image
|
||||
*/
|
||||
public function clickLink(string $linkText): Crawler
|
||||
{
|
||||
if (null === $this->crawler) {
|
||||
throw new BadMethodCallException(sprintf('The "request()" method must be called before "%s()".', __METHOD__));
|
||||
}
|
||||
|
||||
return $this->click($this->crawler->selectLink($linkText)->link());
|
||||
}
|
||||
|
||||
/**
|
||||
* Submits a form.
|
||||
*
|
||||
* @param Form $form A Form instance
|
||||
* @param array $values An array of form field values
|
||||
* @param array $serverParameters An array of server parameters
|
||||
*
|
||||
* @return Crawler
|
||||
*/
|
||||
public function submit(Form $form, array $values = []/*, array $serverParameters = []*/)
|
||||
{
|
||||
if (\func_num_args() < 3 && __CLASS__ !== \get_class($this) && __CLASS__ !== (new \ReflectionMethod($this, __FUNCTION__))->getDeclaringClass()->getName() && !$this instanceof \PHPUnit\Framework\MockObject\MockObject && !$this instanceof \Prophecy\Prophecy\ProphecySubjectInterface) {
|
||||
@trigger_error(sprintf('The "%s()" method will have a new "array $serverParameters = []" argument in version 5.0, not defining it is deprecated since Symfony 4.2.', __METHOD__), E_USER_DEPRECATED);
|
||||
}
|
||||
|
||||
$form->setValues($values);
|
||||
$serverParameters = 2 < \func_num_args() ? func_get_arg(2) : [];
|
||||
|
||||
return $this->request($form->getMethod(), $form->getUri(), $form->getPhpValues(), $form->getPhpFiles(), $serverParameters);
|
||||
}
|
||||
|
||||
/**
|
||||
* Finds the first form that contains a button with the given content and
|
||||
* uses it to submit the given form field values.
|
||||
*
|
||||
* @param string $button The text content, id, value or name of the form <button> or <input type="submit">
|
||||
* @param array $fieldValues Use this syntax: ['my_form[name]' => '...', 'my_form[email]' => '...']
|
||||
* @param string $method The HTTP method used to submit the form
|
||||
* @param array $serverParameters These values override the ones stored in $_SERVER (HTTP headers must include a HTTP_ prefix as PHP does)
|
||||
*/
|
||||
public function submitForm(string $button, array $fieldValues = [], string $method = 'POST', array $serverParameters = []): Crawler
|
||||
{
|
||||
if (null === $this->crawler) {
|
||||
throw new BadMethodCallException(sprintf('The "request()" method must be called before "%s()".', __METHOD__));
|
||||
}
|
||||
|
||||
$buttonNode = $this->crawler->selectButton($button);
|
||||
$form = $buttonNode->form($fieldValues, $method);
|
||||
|
||||
return $this->submit($form, [], $serverParameters);
|
||||
}
|
||||
|
||||
/**
|
||||
* Calls a URI.
|
||||
*
|
||||
* @param string $method The request method
|
||||
* @param string $uri The URI to fetch
|
||||
* @param array $parameters The Request parameters
|
||||
* @param array $files The files
|
||||
* @param array $server The server parameters (HTTP headers are referenced with a HTTP_ prefix as PHP does)
|
||||
* @param string $content The raw body data
|
||||
* @param bool $changeHistory Whether to update the history or not (only used internally for back(), forward(), and reload())
|
||||
*
|
||||
* @return Crawler
|
||||
*/
|
||||
public function request(string $method, string $uri, array $parameters = [], array $files = [], array $server = [], string $content = null, bool $changeHistory = true)
|
||||
{
|
||||
if ($this->isMainRequest) {
|
||||
$this->redirectCount = 0;
|
||||
} else {
|
||||
++$this->redirectCount;
|
||||
}
|
||||
|
||||
$originalUri = $uri;
|
||||
|
||||
$uri = $this->getAbsoluteUri($uri);
|
||||
|
||||
$server = array_merge($this->server, $server);
|
||||
|
||||
if (!empty($server['HTTP_HOST']) && null === parse_url($originalUri, PHP_URL_HOST)) {
|
||||
$uri = preg_replace('{^(https?\://)'.preg_quote($this->extractHost($uri)).'}', '${1}'.$server['HTTP_HOST'], $uri);
|
||||
}
|
||||
|
||||
if (isset($server['HTTPS']) && null === parse_url($originalUri, PHP_URL_SCHEME)) {
|
||||
$uri = preg_replace('{^'.parse_url($uri, PHP_URL_SCHEME).'}', $server['HTTPS'] ? 'https' : 'http', $uri);
|
||||
}
|
||||
|
||||
if (!$this->history->isEmpty()) {
|
||||
$server['HTTP_REFERER'] = $this->history->current()->getUri();
|
||||
}
|
||||
|
||||
if (empty($server['HTTP_HOST'])) {
|
||||
$server['HTTP_HOST'] = $this->extractHost($uri);
|
||||
}
|
||||
|
||||
$server['HTTPS'] = 'https' == parse_url($uri, PHP_URL_SCHEME);
|
||||
|
||||
$this->internalRequest = new Request($uri, $method, $parameters, $files, $this->cookieJar->allValues($uri), $server, $content);
|
||||
|
||||
$this->request = $this->filterRequest($this->internalRequest);
|
||||
|
||||
if (true === $changeHistory) {
|
||||
$this->history->add($this->internalRequest);
|
||||
}
|
||||
|
||||
if ($this->insulated) {
|
||||
$this->response = $this->doRequestInProcess($this->request);
|
||||
} else {
|
||||
$this->response = $this->doRequest($this->request);
|
||||
}
|
||||
|
||||
$this->internalResponse = $this->filterResponse($this->response);
|
||||
|
||||
$this->cookieJar->updateFromResponse($this->internalResponse, $uri);
|
||||
|
||||
$status = $this->internalResponse->getStatusCode();
|
||||
|
||||
if ($status >= 300 && $status < 400) {
|
||||
$this->redirect = $this->internalResponse->getHeader('Location');
|
||||
} else {
|
||||
$this->redirect = null;
|
||||
}
|
||||
|
||||
if ($this->followRedirects && $this->redirect) {
|
||||
$this->redirects[serialize($this->history->current())] = true;
|
||||
|
||||
return $this->crawler = $this->followRedirect();
|
||||
}
|
||||
|
||||
$this->crawler = $this->createCrawlerFromContent($this->internalRequest->getUri(), $this->internalResponse->getContent(), $this->internalResponse->getHeader('Content-Type'));
|
||||
|
||||
// Check for meta refresh redirect
|
||||
if ($this->followMetaRefresh && null !== $redirect = $this->getMetaRefreshUrl()) {
|
||||
$this->redirect = $redirect;
|
||||
$this->redirects[serialize($this->history->current())] = true;
|
||||
$this->crawler = $this->followRedirect();
|
||||
}
|
||||
|
||||
return $this->crawler;
|
||||
}
|
||||
|
||||
/**
|
||||
* Makes a request in another process.
|
||||
*
|
||||
* @param object $request An origin request instance
|
||||
*
|
||||
* @return object An origin response instance
|
||||
*
|
||||
* @throws \RuntimeException When processing returns exit code
|
||||
*/
|
||||
protected function doRequestInProcess($request)
|
||||
{
|
||||
$deprecationsFile = tempnam(sys_get_temp_dir(), 'deprec');
|
||||
putenv('SYMFONY_DEPRECATIONS_SERIALIZE='.$deprecationsFile);
|
||||
$_ENV['SYMFONY_DEPRECATIONS_SERIALIZE'] = $deprecationsFile;
|
||||
$process = new PhpProcess($this->getScript($request), null, null);
|
||||
$process->run();
|
||||
|
||||
if (file_exists($deprecationsFile)) {
|
||||
$deprecations = file_get_contents($deprecationsFile);
|
||||
unlink($deprecationsFile);
|
||||
foreach ($deprecations ? unserialize($deprecations) : [] as $deprecation) {
|
||||
if ($deprecation[0]) {
|
||||
@trigger_error($deprecation[1], E_USER_DEPRECATED);
|
||||
} else {
|
||||
@trigger_error($deprecation[1], E_USER_DEPRECATED);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (!$process->isSuccessful() || !preg_match('/^O\:\d+\:/', $process->getOutput())) {
|
||||
throw new \RuntimeException(sprintf('OUTPUT: %s ERROR OUTPUT: %s', $process->getOutput(), $process->getErrorOutput()));
|
||||
}
|
||||
|
||||
return unserialize($process->getOutput());
|
||||
}
|
||||
|
||||
/**
|
||||
* Makes a request.
|
||||
*
|
||||
* @param object $request An origin request instance
|
||||
*
|
||||
* @return object An origin response instance
|
||||
*/
|
||||
abstract protected function doRequest($request);
|
||||
|
||||
/**
|
||||
* Returns the script to execute when the request must be insulated.
|
||||
*
|
||||
* @param object $request An origin request instance
|
||||
*
|
||||
* @throws \LogicException When this abstract class is not implemented
|
||||
*/
|
||||
protected function getScript($request)
|
||||
{
|
||||
throw new \LogicException('To insulate requests, you need to override the getScript() method.');
|
||||
}
|
||||
|
||||
/**
|
||||
* Filters the BrowserKit request to the origin one.
|
||||
*
|
||||
* @param Request $request The BrowserKit Request to filter
|
||||
*
|
||||
* @return object An origin request instance
|
||||
*/
|
||||
protected function filterRequest(Request $request)
|
||||
{
|
||||
return $request;
|
||||
}
|
||||
|
||||
/**
|
||||
* Filters the origin response to the BrowserKit one.
|
||||
*
|
||||
* @param object $response The origin response to filter
|
||||
*
|
||||
* @return Response An BrowserKit Response instance
|
||||
*/
|
||||
protected function filterResponse($response)
|
||||
{
|
||||
return $response;
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a crawler.
|
||||
*
|
||||
* This method returns null if the DomCrawler component is not available.
|
||||
*
|
||||
* @param string $uri A URI
|
||||
* @param string $content Content for the crawler to use
|
||||
* @param string $type Content type
|
||||
*
|
||||
* @return Crawler|null
|
||||
*/
|
||||
protected function createCrawlerFromContent($uri, $content, $type)
|
||||
{
|
||||
if (!class_exists('Symfony\Component\DomCrawler\Crawler')) {
|
||||
return;
|
||||
}
|
||||
|
||||
$crawler = new Crawler(null, $uri);
|
||||
$crawler->addContent($content, $type);
|
||||
|
||||
return $crawler;
|
||||
}
|
||||
|
||||
/**
|
||||
* Goes back in the browser history.
|
||||
*
|
||||
* @return Crawler
|
||||
*/
|
||||
public function back()
|
||||
{
|
||||
do {
|
||||
$request = $this->history->back();
|
||||
} while (\array_key_exists(serialize($request), $this->redirects));
|
||||
|
||||
return $this->requestFromRequest($request, false);
|
||||
}
|
||||
|
||||
/**
|
||||
* Goes forward in the browser history.
|
||||
*
|
||||
* @return Crawler
|
||||
*/
|
||||
public function forward()
|
||||
{
|
||||
do {
|
||||
$request = $this->history->forward();
|
||||
} while (\array_key_exists(serialize($request), $this->redirects));
|
||||
|
||||
return $this->requestFromRequest($request, false);
|
||||
}
|
||||
|
||||
/**
|
||||
* Reloads the current browser.
|
||||
*
|
||||
* @return Crawler
|
||||
*/
|
||||
public function reload()
|
||||
{
|
||||
return $this->requestFromRequest($this->history->current(), false);
|
||||
}
|
||||
|
||||
/**
|
||||
* Follow redirects?
|
||||
*
|
||||
* @return Crawler
|
||||
*
|
||||
* @throws \LogicException If request was not a redirect
|
||||
*/
|
||||
public function followRedirect()
|
||||
{
|
||||
if (empty($this->redirect)) {
|
||||
throw new \LogicException('The request was not redirected.');
|
||||
}
|
||||
|
||||
if (-1 !== $this->maxRedirects) {
|
||||
if ($this->redirectCount > $this->maxRedirects) {
|
||||
$this->redirectCount = 0;
|
||||
throw new \LogicException(sprintf('The maximum number (%d) of redirections was reached.', $this->maxRedirects));
|
||||
}
|
||||
}
|
||||
|
||||
$request = $this->internalRequest;
|
||||
|
||||
if (\in_array($this->internalResponse->getStatusCode(), [301, 302, 303])) {
|
||||
$method = 'GET';
|
||||
$files = [];
|
||||
$content = null;
|
||||
} else {
|
||||
$method = $request->getMethod();
|
||||
$files = $request->getFiles();
|
||||
$content = $request->getContent();
|
||||
}
|
||||
|
||||
if ('GET' === strtoupper($method)) {
|
||||
// Don't forward parameters for GET request as it should reach the redirection URI
|
||||
$parameters = [];
|
||||
} else {
|
||||
$parameters = $request->getParameters();
|
||||
}
|
||||
|
||||
$server = $request->getServer();
|
||||
$server = $this->updateServerFromUri($server, $this->redirect);
|
||||
|
||||
$this->isMainRequest = false;
|
||||
|
||||
$response = $this->request($method, $this->redirect, $parameters, $files, $server, $content);
|
||||
|
||||
$this->isMainRequest = true;
|
||||
|
||||
return $response;
|
||||
}
|
||||
|
||||
/**
|
||||
* @see https://dev.w3.org/html5/spec-preview/the-meta-element.html#attr-meta-http-equiv-refresh
|
||||
*/
|
||||
private function getMetaRefreshUrl(): ?string
|
||||
{
|
||||
$metaRefresh = $this->getCrawler()->filter('head meta[http-equiv="refresh"]');
|
||||
foreach ($metaRefresh->extract(['content']) as $content) {
|
||||
if (preg_match('/^\s*0\s*;\s*URL\s*=\s*(?|\'([^\']++)|"([^"]++)|([^\'"].*))/i', $content, $m)) {
|
||||
return str_replace("\t\r\n", '', rtrim($m[1]));
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Restarts the client.
|
||||
*
|
||||
* It flushes history and all cookies.
|
||||
*/
|
||||
public function restart()
|
||||
{
|
||||
$this->cookieJar->clear();
|
||||
$this->history->clear();
|
||||
}
|
||||
|
||||
/**
|
||||
* Takes a URI and converts it to absolute if it is not already absolute.
|
||||
*
|
||||
* @param string $uri A URI
|
||||
*
|
||||
* @return string An absolute URI
|
||||
*/
|
||||
protected function getAbsoluteUri($uri)
|
||||
{
|
||||
// already absolute?
|
||||
if (0 === strpos($uri, 'http://') || 0 === strpos($uri, 'https://')) {
|
||||
return $uri;
|
||||
}
|
||||
|
||||
if (!$this->history->isEmpty()) {
|
||||
$currentUri = $this->history->current()->getUri();
|
||||
} else {
|
||||
$currentUri = sprintf('http%s://%s/',
|
||||
isset($this->server['HTTPS']) ? 's' : '',
|
||||
isset($this->server['HTTP_HOST']) ? $this->server['HTTP_HOST'] : 'localhost'
|
||||
);
|
||||
}
|
||||
|
||||
// protocol relative URL
|
||||
if (0 === strpos($uri, '//')) {
|
||||
return parse_url($currentUri, PHP_URL_SCHEME).':'.$uri;
|
||||
}
|
||||
|
||||
// anchor or query string parameters?
|
||||
if (!$uri || '#' == $uri[0] || '?' == $uri[0]) {
|
||||
return preg_replace('/[#?].*?$/', '', $currentUri).$uri;
|
||||
}
|
||||
|
||||
if ('/' !== $uri[0]) {
|
||||
$path = parse_url($currentUri, PHP_URL_PATH);
|
||||
|
||||
if ('/' !== substr($path, -1)) {
|
||||
$path = substr($path, 0, strrpos($path, '/') + 1);
|
||||
}
|
||||
|
||||
$uri = $path.$uri;
|
||||
}
|
||||
|
||||
return preg_replace('#^(.*?//[^/]+)\/.*$#', '$1', $currentUri).$uri;
|
||||
}
|
||||
|
||||
/**
|
||||
* Makes a request from a Request object directly.
|
||||
*
|
||||
* @param Request $request A Request instance
|
||||
* @param bool $changeHistory Whether to update the history or not (only used internally for back(), forward(), and reload())
|
||||
*
|
||||
* @return Crawler
|
||||
*/
|
||||
protected function requestFromRequest(Request $request, $changeHistory = true)
|
||||
{
|
||||
return $this->request($request->getMethod(), $request->getUri(), $request->getParameters(), $request->getFiles(), $request->getServer(), $request->getContent(), $changeHistory);
|
||||
}
|
||||
|
||||
private function updateServerFromUri($server, $uri)
|
||||
{
|
||||
$server['HTTP_HOST'] = $this->extractHost($uri);
|
||||
$scheme = parse_url($uri, PHP_URL_SCHEME);
|
||||
$server['HTTPS'] = null === $scheme ? $server['HTTPS'] : 'https' == $scheme;
|
||||
unset($server['HTTP_IF_NONE_MATCH'], $server['HTTP_IF_MODIFIED_SINCE']);
|
||||
|
||||
return $server;
|
||||
}
|
||||
|
||||
private function extractHost($uri)
|
||||
{
|
||||
$host = parse_url($uri, PHP_URL_HOST);
|
||||
|
||||
if ($port = parse_url($uri, PHP_URL_PORT)) {
|
||||
return $host.':'.$port;
|
||||
}
|
||||
|
||||
return $host;
|
||||
}
|
||||
}
|
||||
|
@ -12,7 +12,7 @@
|
||||
namespace Symfony\Component\BrowserKit\Tests;
|
||||
|
||||
use PHPUnit\Framework\TestCase;
|
||||
use Symfony\Component\BrowserKit\Client;
|
||||
use Symfony\Component\BrowserKit\AbstractBrowser;
|
||||
use Symfony\Component\BrowserKit\CookieJar;
|
||||
use Symfony\Component\BrowserKit\History;
|
||||
use Symfony\Component\BrowserKit\Response;
|
||||
@ -22,7 +22,7 @@ class SpecialResponse extends Response
|
||||
{
|
||||
}
|
||||
|
||||
class TestClient extends Client
|
||||
class TestClient extends AbstractBrowser
|
||||
{
|
||||
protected $nextResponse = null;
|
||||
protected $nextScript = null;
|
||||
@ -73,7 +73,7 @@ EOF;
|
||||
}
|
||||
}
|
||||
|
||||
class ClientTest extends TestCase
|
||||
class AbstractBrowserTest extends TestCase
|
||||
{
|
||||
public function testGetHistory()
|
||||
{
|
||||
@ -97,7 +97,7 @@ class ClientTest extends TestCase
|
||||
|
||||
/**
|
||||
* @group legacy
|
||||
* @expectedDeprecation Calling the "Symfony\Component\BrowserKit\Client::getRequest()" method before the "request()" one is deprecated since Symfony 4.1 and will throw an exception in 5.0.
|
||||
* @expectedDeprecation Calling the "Symfony\Component\BrowserKit\AbstractBrowser::getRequest()" method before the "request()" one is deprecated since Symfony 4.1 and will throw an exception in 5.0.
|
||||
*/
|
||||
public function testGetRequestNull()
|
||||
{
|
||||
@ -135,7 +135,7 @@ class ClientTest extends TestCase
|
||||
|
||||
/**
|
||||
* @group legacy
|
||||
* @expectedDeprecation Calling the "Symfony\Component\BrowserKit\Client::getResponse()" method before the "request()" one is deprecated since Symfony 4.1 and will throw an exception in 5.0.
|
||||
* @expectedDeprecation Calling the "Symfony\Component\BrowserKit\AbstractBrowser::getResponse()" method before the "request()" one is deprecated since Symfony 4.1 and will throw an exception in 5.0.
|
||||
*/
|
||||
public function testGetResponseNull()
|
||||
{
|
||||
@ -156,7 +156,7 @@ class ClientTest extends TestCase
|
||||
|
||||
/**
|
||||
* @group legacy
|
||||
* @expectedDeprecation Calling the "Symfony\Component\BrowserKit\Client::getInternalResponse()" method before the "request()" one is deprecated since Symfony 4.1 and will throw an exception in 5.0.
|
||||
* @expectedDeprecation Calling the "Symfony\Component\BrowserKit\AbstractBrowser::getInternalResponse()" method before the "request()" one is deprecated since Symfony 4.1 and will throw an exception in 5.0.
|
||||
*/
|
||||
public function testGetInternalResponseNull()
|
||||
{
|
||||
@ -184,7 +184,7 @@ class ClientTest extends TestCase
|
||||
|
||||
/**
|
||||
* @group legacy
|
||||
* @expectedDeprecation Calling the "Symfony\Component\BrowserKit\Client::getCrawler()" method before the "request()" one is deprecated since Symfony 4.1 and will throw an exception in 5.0.
|
||||
* @expectedDeprecation Calling the "Symfony\Component\BrowserKit\AbstractBrowser::getCrawler()" method before the "request()" one is deprecated since Symfony 4.1 and will throw an exception in 5.0.
|
||||
*/
|
||||
public function testGetCrawlerNull()
|
||||
{
|
||||
@ -886,7 +886,7 @@ class ClientTest extends TestCase
|
||||
|
||||
/**
|
||||
* @group legacy
|
||||
* @expectedDeprecation Calling the "Symfony\Component\BrowserKit\Client::getInternalRequest()" method before the "request()" one is deprecated since Symfony 4.1 and will throw an exception in 5.0.
|
||||
* @expectedDeprecation Calling the "Symfony\Component\BrowserKit\AbstractBrowser::getInternalRequest()" method before the "request()" one is deprecated since Symfony 4.1 and will throw an exception in 5.0.
|
||||
*/
|
||||
public function testInternalRequestNull()
|
||||
{
|
||||
@ -896,7 +896,7 @@ class ClientTest extends TestCase
|
||||
|
||||
/**
|
||||
* @group legacy
|
||||
* @expectedDeprecation The "Symfony\Component\BrowserKit\Client::submit()" method will have a new "array $serverParameters = []" argument in version 5.0, not defining it is deprecated since Symfony 4.2.
|
||||
* @expectedDeprecation The "Symfony\Component\BrowserKit\AbstractBrowser::submit()" method will have a new "array $serverParameters = []" argument in version 5.0, not defining it is deprecated since Symfony 4.2.
|
||||
*/
|
||||
public function testInheritedClassCallSubmitWithTwoArguments()
|
||||
{
|
||||
@ -906,7 +906,7 @@ class ClientTest extends TestCase
|
||||
}
|
||||
}
|
||||
|
||||
class ClassThatInheritClient extends Client
|
||||
class ClassThatInheritClient extends AbstractBrowser
|
||||
{
|
||||
protected $nextResponse = null;
|
||||
|
@ -4,6 +4,7 @@ CHANGELOG
|
||||
4.3.0
|
||||
-----
|
||||
|
||||
* renamed `Client` to `HttpKernelBrowser`
|
||||
* `KernelInterface` doesn't extend `Serializable` anymore
|
||||
* deprecated the `Kernel::serialize()` and `unserialize()` methods
|
||||
* increased the priority of `Symfony\Component\HttpKernel\EventListener\AddRequestFormatsListener`
|
||||
|
@ -11,194 +11,8 @@
|
||||
|
||||
namespace Symfony\Component\HttpKernel;
|
||||
|
||||
use Symfony\Component\BrowserKit\Client as BaseClient;
|
||||
use Symfony\Component\BrowserKit\CookieJar;
|
||||
use Symfony\Component\BrowserKit\History;
|
||||
use Symfony\Component\BrowserKit\Request as DomRequest;
|
||||
use Symfony\Component\BrowserKit\Response as DomResponse;
|
||||
use Symfony\Component\HttpFoundation\File\UploadedFile;
|
||||
use Symfony\Component\HttpFoundation\Request;
|
||||
use Symfony\Component\HttpFoundation\Response;
|
||||
@trigger_error(sprintf('The "%s" class is deprecated since Symfony 4.3, use "%s" instead.', Client::class, HttpKernelBrowser::class), E_USER_DEPRECATED);
|
||||
|
||||
/**
|
||||
* Client simulates a browser and makes requests to a Kernel object.
|
||||
*
|
||||
* @author Fabien Potencier <fabien@symfony.com>
|
||||
*
|
||||
* @method Request getRequest() A Request instance
|
||||
* @method Response getResponse() A Response instance
|
||||
*/
|
||||
class Client extends BaseClient
|
||||
class Client extends HttpKernelBrowser
|
||||
{
|
||||
protected $kernel;
|
||||
private $catchExceptions = true;
|
||||
|
||||
/**
|
||||
* @param HttpKernelInterface $kernel An HttpKernel instance
|
||||
* @param array $server The server parameters (equivalent of $_SERVER)
|
||||
* @param History $history A History instance to store the browser history
|
||||
* @param CookieJar $cookieJar A CookieJar instance to store the cookies
|
||||
*/
|
||||
public function __construct(HttpKernelInterface $kernel, array $server = [], History $history = null, CookieJar $cookieJar = null)
|
||||
{
|
||||
// These class properties must be set before calling the parent constructor, as it may depend on it.
|
||||
$this->kernel = $kernel;
|
||||
$this->followRedirects = false;
|
||||
|
||||
parent::__construct($server, $history, $cookieJar);
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets whether to catch exceptions when the kernel is handling a request.
|
||||
*
|
||||
* @param bool $catchExceptions Whether to catch exceptions
|
||||
*/
|
||||
public function catchExceptions($catchExceptions)
|
||||
{
|
||||
$this->catchExceptions = $catchExceptions;
|
||||
}
|
||||
|
||||
/**
|
||||
* Makes a request.
|
||||
*
|
||||
* @return Response A Response instance
|
||||
*/
|
||||
protected function doRequest($request)
|
||||
{
|
||||
$response = $this->kernel->handle($request, HttpKernelInterface::MASTER_REQUEST, $this->catchExceptions);
|
||||
|
||||
if ($this->kernel instanceof TerminableInterface) {
|
||||
$this->kernel->terminate($request, $response);
|
||||
}
|
||||
|
||||
return $response;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the script to execute when the request must be insulated.
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
protected function getScript($request)
|
||||
{
|
||||
$kernel = var_export(serialize($this->kernel), true);
|
||||
$request = var_export(serialize($request), true);
|
||||
|
||||
$errorReporting = error_reporting();
|
||||
|
||||
$requires = '';
|
||||
foreach (get_declared_classes() as $class) {
|
||||
if (0 === strpos($class, 'ComposerAutoloaderInit')) {
|
||||
$r = new \ReflectionClass($class);
|
||||
$file = \dirname(\dirname($r->getFileName())).'/autoload.php';
|
||||
if (file_exists($file)) {
|
||||
$requires .= 'require_once '.var_export($file, true).";\n";
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (!$requires) {
|
||||
throw new \RuntimeException('Composer autoloader not found.');
|
||||
}
|
||||
|
||||
$code = <<<EOF
|
||||
<?php
|
||||
|
||||
error_reporting($errorReporting);
|
||||
|
||||
$requires
|
||||
|
||||
\$kernel = unserialize($kernel);
|
||||
\$request = unserialize($request);
|
||||
EOF;
|
||||
|
||||
return $code.$this->getHandleScript();
|
||||
}
|
||||
|
||||
protected function getHandleScript()
|
||||
{
|
||||
return <<<'EOF'
|
||||
$response = $kernel->handle($request);
|
||||
|
||||
if ($kernel instanceof Symfony\Component\HttpKernel\TerminableInterface) {
|
||||
$kernel->terminate($request, $response);
|
||||
}
|
||||
|
||||
echo serialize($response);
|
||||
EOF;
|
||||
}
|
||||
|
||||
/**
|
||||
* Converts the BrowserKit request to a HttpKernel request.
|
||||
*
|
||||
* @return Request A Request instance
|
||||
*/
|
||||
protected function filterRequest(DomRequest $request)
|
||||
{
|
||||
$httpRequest = Request::create($request->getUri(), $request->getMethod(), $request->getParameters(), $request->getCookies(), $request->getFiles(), $request->getServer(), $request->getContent());
|
||||
|
||||
foreach ($this->filterFiles($httpRequest->files->all()) as $key => $value) {
|
||||
$httpRequest->files->set($key, $value);
|
||||
}
|
||||
|
||||
return $httpRequest;
|
||||
}
|
||||
|
||||
/**
|
||||
* Filters an array of files.
|
||||
*
|
||||
* This method created test instances of UploadedFile so that the move()
|
||||
* method can be called on those instances.
|
||||
*
|
||||
* If the size of a file is greater than the allowed size (from php.ini) then
|
||||
* an invalid UploadedFile is returned with an error set to UPLOAD_ERR_INI_SIZE.
|
||||
*
|
||||
* @see UploadedFile
|
||||
*
|
||||
* @return array An array with all uploaded files marked as already moved
|
||||
*/
|
||||
protected function filterFiles(array $files)
|
||||
{
|
||||
$filtered = [];
|
||||
foreach ($files as $key => $value) {
|
||||
if (\is_array($value)) {
|
||||
$filtered[$key] = $this->filterFiles($value);
|
||||
} elseif ($value instanceof UploadedFile) {
|
||||
if ($value->isValid() && $value->getSize() > UploadedFile::getMaxFilesize()) {
|
||||
$filtered[$key] = new UploadedFile(
|
||||
'',
|
||||
$value->getClientOriginalName(),
|
||||
$value->getClientMimeType(),
|
||||
UPLOAD_ERR_INI_SIZE,
|
||||
true
|
||||
);
|
||||
} else {
|
||||
$filtered[$key] = new UploadedFile(
|
||||
$value->getPathname(),
|
||||
$value->getClientOriginalName(),
|
||||
$value->getClientMimeType(),
|
||||
$value->getError(),
|
||||
true
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return $filtered;
|
||||
}
|
||||
|
||||
/**
|
||||
* Converts the HttpKernel response to a BrowserKit response.
|
||||
*
|
||||
* @return DomResponse A DomResponse instance
|
||||
*/
|
||||
protected function filterResponse($response)
|
||||
{
|
||||
// this is needed to support StreamedResponse
|
||||
ob_start();
|
||||
$response->sendContent();
|
||||
$content = ob_get_clean();
|
||||
|
||||
return new DomResponse($content, $response->getStatusCode(), $response->headers->all());
|
||||
}
|
||||
}
|
||||
|
204
src/Symfony/Component/HttpKernel/HttpKernelBrowser.php
Normal file
204
src/Symfony/Component/HttpKernel/HttpKernelBrowser.php
Normal file
@ -0,0 +1,204 @@
|
||||
<?php
|
||||
|
||||
/*
|
||||
* This file is part of the Symfony package.
|
||||
*
|
||||
* (c) Fabien Potencier <fabien@symfony.com>
|
||||
*
|
||||
* For the full copyright and license information, please view the LICENSE
|
||||
* file that was distributed with this source code.
|
||||
*/
|
||||
|
||||
namespace Symfony\Component\HttpKernel;
|
||||
|
||||
use Symfony\Component\BrowserKit\AbstractBrowser;
|
||||
use Symfony\Component\BrowserKit\CookieJar;
|
||||
use Symfony\Component\BrowserKit\History;
|
||||
use Symfony\Component\BrowserKit\Request as DomRequest;
|
||||
use Symfony\Component\BrowserKit\Response as DomResponse;
|
||||
use Symfony\Component\HttpFoundation\File\UploadedFile;
|
||||
use Symfony\Component\HttpFoundation\Request;
|
||||
use Symfony\Component\HttpFoundation\Response;
|
||||
|
||||
/**
|
||||
* Client simulates a browser and makes requests to an HttpKernel instance.
|
||||
*
|
||||
* @author Fabien Potencier <fabien@symfony.com>
|
||||
*
|
||||
* @method Request getRequest() A Request instance
|
||||
* @method Response getResponse() A Response instance
|
||||
*/
|
||||
class HttpKernelBrowser extends AbstractBrowser
|
||||
{
|
||||
protected $kernel;
|
||||
private $catchExceptions = true;
|
||||
|
||||
/**
|
||||
* @param HttpKernelInterface $kernel An HttpKernel instance
|
||||
* @param array $server The server parameters (equivalent of $_SERVER)
|
||||
* @param History $history A History instance to store the browser history
|
||||
* @param CookieJar $cookieJar A CookieJar instance to store the cookies
|
||||
*/
|
||||
public function __construct(HttpKernelInterface $kernel, array $server = [], History $history = null, CookieJar $cookieJar = null)
|
||||
{
|
||||
// These class properties must be set before calling the parent constructor, as it may depend on it.
|
||||
$this->kernel = $kernel;
|
||||
$this->followRedirects = false;
|
||||
|
||||
parent::__construct($server, $history, $cookieJar);
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets whether to catch exceptions when the kernel is handling a request.
|
||||
*
|
||||
* @param bool $catchExceptions Whether to catch exceptions
|
||||
*/
|
||||
public function catchExceptions($catchExceptions)
|
||||
{
|
||||
$this->catchExceptions = $catchExceptions;
|
||||
}
|
||||
|
||||
/**
|
||||
* Makes a request.
|
||||
*
|
||||
* @return Response A Response instance
|
||||
*/
|
||||
protected function doRequest($request)
|
||||
{
|
||||
$response = $this->kernel->handle($request, HttpKernelInterface::MASTER_REQUEST, $this->catchExceptions);
|
||||
|
||||
if ($this->kernel instanceof TerminableInterface) {
|
||||
$this->kernel->terminate($request, $response);
|
||||
}
|
||||
|
||||
return $response;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the script to execute when the request must be insulated.
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
protected function getScript($request)
|
||||
{
|
||||
$kernel = var_export(serialize($this->kernel), true);
|
||||
$request = var_export(serialize($request), true);
|
||||
|
||||
$errorReporting = error_reporting();
|
||||
|
||||
$requires = '';
|
||||
foreach (get_declared_classes() as $class) {
|
||||
if (0 === strpos($class, 'ComposerAutoloaderInit')) {
|
||||
$r = new \ReflectionClass($class);
|
||||
$file = \dirname(\dirname($r->getFileName())).'/autoload.php';
|
||||
if (file_exists($file)) {
|
||||
$requires .= 'require_once '.var_export($file, true).";\n";
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (!$requires) {
|
||||
throw new \RuntimeException('Composer autoloader not found.');
|
||||
}
|
||||
|
||||
$code = <<<EOF
|
||||
<?php
|
||||
|
||||
error_reporting($errorReporting);
|
||||
|
||||
$requires
|
||||
|
||||
\$kernel = unserialize($kernel);
|
||||
\$request = unserialize($request);
|
||||
EOF;
|
||||
|
||||
return $code.$this->getHandleScript();
|
||||
}
|
||||
|
||||
protected function getHandleScript()
|
||||
{
|
||||
return <<<'EOF'
|
||||
$response = $kernel->handle($request);
|
||||
|
||||
if ($kernel instanceof Symfony\Component\HttpKernel\TerminableInterface) {
|
||||
$kernel->terminate($request, $response);
|
||||
}
|
||||
|
||||
echo serialize($response);
|
||||
EOF;
|
||||
}
|
||||
|
||||
/**
|
||||
* Converts the BrowserKit request to a HttpKernel request.
|
||||
*
|
||||
* @return Request A Request instance
|
||||
*/
|
||||
protected function filterRequest(DomRequest $request)
|
||||
{
|
||||
$httpRequest = Request::create($request->getUri(), $request->getMethod(), $request->getParameters(), $request->getCookies(), $request->getFiles(), $request->getServer(), $request->getContent());
|
||||
|
||||
foreach ($this->filterFiles($httpRequest->files->all()) as $key => $value) {
|
||||
$httpRequest->files->set($key, $value);
|
||||
}
|
||||
|
||||
return $httpRequest;
|
||||
}
|
||||
|
||||
/**
|
||||
* Filters an array of files.
|
||||
*
|
||||
* This method created test instances of UploadedFile so that the move()
|
||||
* method can be called on those instances.
|
||||
*
|
||||
* If the size of a file is greater than the allowed size (from php.ini) then
|
||||
* an invalid UploadedFile is returned with an error set to UPLOAD_ERR_INI_SIZE.
|
||||
*
|
||||
* @see UploadedFile
|
||||
*
|
||||
* @return array An array with all uploaded files marked as already moved
|
||||
*/
|
||||
protected function filterFiles(array $files)
|
||||
{
|
||||
$filtered = [];
|
||||
foreach ($files as $key => $value) {
|
||||
if (\is_array($value)) {
|
||||
$filtered[$key] = $this->filterFiles($value);
|
||||
} elseif ($value instanceof UploadedFile) {
|
||||
if ($value->isValid() && $value->getSize() > UploadedFile::getMaxFilesize()) {
|
||||
$filtered[$key] = new UploadedFile(
|
||||
'',
|
||||
$value->getClientOriginalName(),
|
||||
$value->getClientMimeType(),
|
||||
UPLOAD_ERR_INI_SIZE,
|
||||
true
|
||||
);
|
||||
} else {
|
||||
$filtered[$key] = new UploadedFile(
|
||||
$value->getPathname(),
|
||||
$value->getClientOriginalName(),
|
||||
$value->getClientMimeType(),
|
||||
$value->getError(),
|
||||
true
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return $filtered;
|
||||
}
|
||||
|
||||
/**
|
||||
* Converts the HttpKernel response to a BrowserKit response.
|
||||
*
|
||||
* @return DomResponse A DomResponse instance
|
||||
*/
|
||||
protected function filterResponse($response)
|
||||
{
|
||||
// this is needed to support StreamedResponse
|
||||
ob_start();
|
||||
$response->sendContent();
|
||||
$content = ob_get_clean();
|
||||
|
||||
return new DomResponse($content, $response->getStatusCode(), $response->headers->all());
|
||||
}
|
||||
}
|
@ -11,9 +11,9 @@
|
||||
|
||||
namespace Symfony\Component\HttpKernel\Tests\Fixtures;
|
||||
|
||||
use Symfony\Component\HttpKernel\Client;
|
||||
use Symfony\Component\HttpKernel\HttpKernelBrowser;
|
||||
|
||||
class TestClient extends Client
|
||||
class TestClient extends HttpKernelBrowser
|
||||
{
|
||||
protected function getScript($request)
|
||||
{
|
||||
|
@ -16,17 +16,17 @@ use Symfony\Component\HttpFoundation\Cookie;
|
||||
use Symfony\Component\HttpFoundation\File\UploadedFile;
|
||||
use Symfony\Component\HttpFoundation\Response;
|
||||
use Symfony\Component\HttpFoundation\StreamedResponse;
|
||||
use Symfony\Component\HttpKernel\Client;
|
||||
use Symfony\Component\HttpKernel\HttpKernelBrowser;
|
||||
use Symfony\Component\HttpKernel\Tests\Fixtures\TestClient;
|
||||
|
||||
/**
|
||||
* @group time-sensitive
|
||||
*/
|
||||
class ClientTest extends TestCase
|
||||
class HttpKernelBrowserTest extends TestCase
|
||||
{
|
||||
public function testDoRequest()
|
||||
{
|
||||
$client = new Client(new TestHttpKernel());
|
||||
$client = new HttpKernelBrowser(new TestHttpKernel());
|
||||
|
||||
$client->request('GET', '/');
|
||||
$this->assertEquals('Request: /', $client->getResponse()->getContent(), '->doRequest() uses the request handler to make the request');
|
||||
@ -54,7 +54,7 @@ class ClientTest extends TestCase
|
||||
|
||||
public function testFilterResponseConvertsCookies()
|
||||
{
|
||||
$client = new Client(new TestHttpKernel());
|
||||
$client = new HttpKernelBrowser(new TestHttpKernel());
|
||||
|
||||
$r = new \ReflectionObject($client);
|
||||
$m = $r->getMethod('filterResponse');
|
||||
@ -75,7 +75,7 @@ class ClientTest extends TestCase
|
||||
|
||||
public function testFilterResponseSupportsStreamedResponses()
|
||||
{
|
||||
$client = new Client(new TestHttpKernel());
|
||||
$client = new HttpKernelBrowser(new TestHttpKernel());
|
||||
|
||||
$r = new \ReflectionObject($client);
|
||||
$m = $r->getMethod('filterResponse');
|
||||
@ -97,7 +97,7 @@ class ClientTest extends TestCase
|
||||
@unlink($target);
|
||||
|
||||
$kernel = new TestHttpKernel();
|
||||
$client = new Client($kernel);
|
||||
$client = new HttpKernelBrowser($kernel);
|
||||
|
||||
$files = [
|
||||
['tmp_name' => $source, 'name' => 'original', 'type' => 'mime/original', 'size' => null, 'error' => UPLOAD_ERR_OK],
|
||||
@ -128,7 +128,7 @@ class ClientTest extends TestCase
|
||||
public function testUploadedFileWhenNoFileSelected()
|
||||
{
|
||||
$kernel = new TestHttpKernel();
|
||||
$client = new Client($kernel);
|
||||
$client = new HttpKernelBrowser($kernel);
|
||||
|
||||
$file = ['tmp_name' => '', 'name' => '', 'type' => '', 'size' => 0, 'error' => UPLOAD_ERR_NO_FILE];
|
||||
|
||||
@ -145,7 +145,7 @@ class ClientTest extends TestCase
|
||||
$source = tempnam(sys_get_temp_dir(), 'source');
|
||||
|
||||
$kernel = new TestHttpKernel();
|
||||
$client = new Client($kernel);
|
||||
$client = new HttpKernelBrowser($kernel);
|
||||
|
||||
$file = $this
|
||||
->getMockBuilder('Symfony\Component\HttpFoundation\File\UploadedFile')
|
@ -25,7 +25,7 @@
|
||||
"psr/log": "~1.0"
|
||||
},
|
||||
"require-dev": {
|
||||
"symfony/browser-kit": "~3.4|~4.0",
|
||||
"symfony/browser-kit": "^4.3",
|
||||
"symfony/config": "~3.4|~4.0",
|
||||
"symfony/console": "~3.4|~4.0",
|
||||
"symfony/css-selector": "~3.4|~4.0",
|
||||
@ -45,6 +45,7 @@
|
||||
"psr/log-implementation": "1.0"
|
||||
},
|
||||
"conflict": {
|
||||
"symfony/browser-kit": "<4.3",
|
||||
"symfony/config": "<3.4",
|
||||
"symfony/dependency-injection": "<4.2",
|
||||
"symfony/translation": "<4.2",
|
||||
|
Reference in New Issue
Block a user