Added Laravel project

This commit is contained in:
2017-09-17 00:35:10 +02:00
parent a3c19304d5
commit ecf605b8f5
6246 changed files with 682270 additions and 2 deletions

View File

@@ -0,0 +1,100 @@
<?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\Tests\Bundle;
use PHPUnit\Framework\TestCase;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\HttpKernel\Bundle\Bundle;
use Symfony\Component\HttpKernel\Tests\Fixtures\ExtensionNotValidBundle\ExtensionNotValidBundle;
use Symfony\Component\HttpKernel\Tests\Fixtures\ExtensionPresentBundle\ExtensionPresentBundle;
use Symfony\Component\HttpKernel\Tests\Fixtures\ExtensionAbsentBundle\ExtensionAbsentBundle;
use Symfony\Component\HttpKernel\Tests\Fixtures\ExtensionPresentBundle\Command\FooCommand;
class BundleTest extends TestCase
{
public function testGetContainerExtension()
{
$bundle = new ExtensionPresentBundle();
$this->assertInstanceOf(
'Symfony\Component\HttpKernel\Tests\Fixtures\ExtensionPresentBundle\DependencyInjection\ExtensionPresentExtension',
$bundle->getContainerExtension()
);
}
public function testRegisterCommands()
{
$cmd = new FooCommand();
$app = $this->getMockBuilder('Symfony\Component\Console\Application')->getMock();
$app->expects($this->once())->method('add')->with($this->equalTo($cmd));
$bundle = new ExtensionPresentBundle();
$bundle->registerCommands($app);
$bundle2 = new ExtensionAbsentBundle();
$this->assertNull($bundle2->registerCommands($app));
}
/**
* @expectedException \LogicException
* @expectedExceptionMessage must implement Symfony\Component\DependencyInjection\Extension\ExtensionInterface
*/
public function testGetContainerExtensionWithInvalidClass()
{
$bundle = new ExtensionNotValidBundle();
$bundle->getContainerExtension();
}
public function testHttpKernelRegisterCommandsIgnoresCommandsThatAreRegisteredAsServices()
{
$container = new ContainerBuilder();
$container->register('console.command.symfony_component_httpkernel_tests_fixtures_extensionpresentbundle_command_foocommand', 'Symfony\Component\HttpKernel\Tests\Fixtures\ExtensionPresentBundle\Command\FooCommand');
$application = $this->getMockBuilder('Symfony\Component\Console\Application')->getMock();
// add() is never called when the found command classes are already registered as services
$application->expects($this->never())->method('add');
$bundle = new ExtensionPresentBundle();
$bundle->setContainer($container);
$bundle->registerCommands($application);
}
public function testBundleNameIsGuessedFromClass()
{
$bundle = new GuessedNameBundle();
$this->assertSame('Symfony\Component\HttpKernel\Tests\Bundle', $bundle->getNamespace());
$this->assertSame('GuessedNameBundle', $bundle->getName());
}
public function testBundleNameCanBeExplicitlyProvided()
{
$bundle = new NamedBundle();
$this->assertSame('ExplicitlyNamedBundle', $bundle->getName());
$this->assertSame('Symfony\Component\HttpKernel\Tests\Bundle', $bundle->getNamespace());
$this->assertSame('ExplicitlyNamedBundle', $bundle->getName());
}
}
class NamedBundle extends Bundle
{
public function __construct()
{
$this->name = 'ExplicitlyNamedBundle';
}
}
class GuessedNameBundle extends Bundle
{
}

View File

@@ -0,0 +1,58 @@
<?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\Tests\CacheClearer;
use PHPUnit\Framework\TestCase;
use Symfony\Component\HttpKernel\CacheClearer\ChainCacheClearer;
class ChainCacheClearerTest extends TestCase
{
protected static $cacheDir;
public static function setUpBeforeClass()
{
self::$cacheDir = tempnam(sys_get_temp_dir(), 'sf2_cache_clearer_dir');
}
public static function tearDownAfterClass()
{
@unlink(self::$cacheDir);
}
public function testInjectClearersInConstructor()
{
$clearer = $this->getMockClearer();
$clearer
->expects($this->once())
->method('clear');
$chainClearer = new ChainCacheClearer(array($clearer));
$chainClearer->clear(self::$cacheDir);
}
public function testInjectClearerUsingAdd()
{
$clearer = $this->getMockClearer();
$clearer
->expects($this->once())
->method('clear');
$chainClearer = new ChainCacheClearer();
$chainClearer->add($clearer);
$chainClearer->clear(self::$cacheDir);
}
protected function getMockClearer()
{
return $this->getMockBuilder('Symfony\Component\HttpKernel\CacheClearer\CacheClearerInterface')->getMock();
}
}

View File

@@ -0,0 +1,69 @@
<?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\Tests\CacheClearer;
use PHPUnit\Framework\TestCase;
use Symfony\Component\HttpKernel\CacheClearer\Psr6CacheClearer;
use Psr\Cache\CacheItemPoolInterface;
class Psr6CacheClearerTest extends TestCase
{
public function testClearPoolsInjectedInConstructor()
{
$pool = $this->getMockBuilder(CacheItemPoolInterface::class)->getMock();
$pool
->expects($this->once())
->method('clear');
(new Psr6CacheClearer(array('pool' => $pool)))->clear('');
}
public function testClearPool()
{
$pool = $this->getMockBuilder(CacheItemPoolInterface::class)->getMock();
$pool
->expects($this->once())
->method('clear');
(new Psr6CacheClearer(array('pool' => $pool)))->clearPool('pool');
}
/**
* @expectedException \InvalidArgumentException
* @expectedExceptionMessage Cache pool not found: unknown
*/
public function testClearPoolThrowsExceptionOnUnreferencedPool()
{
(new Psr6CacheClearer())->clearPool('unknown');
}
/**
* @group legacy
* @expectedDeprecation The Symfony\Component\HttpKernel\CacheClearer\Psr6CacheClearer::addPool() method is deprecated since version 3.3 and will be removed in 4.0. Pass an array of pools indexed by name to the constructor instead.
*/
public function testClearPoolsInjectedByAdder()
{
$pool1 = $this->getMockBuilder(CacheItemPoolInterface::class)->getMock();
$pool1
->expects($this->once())
->method('clear');
$pool2 = $this->getMockBuilder(CacheItemPoolInterface::class)->getMock();
$pool2
->expects($this->once())
->method('clear');
$clearer = new Psr6CacheClearer(array('pool1' => $pool1));
$clearer->addPool($pool2);
$clearer->clear('');
}
}

View File

@@ -0,0 +1,101 @@
<?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\Tests\CacheWarmer;
use PHPUnit\Framework\TestCase;
use Symfony\Component\HttpKernel\CacheWarmer\CacheWarmerAggregate;
class CacheWarmerAggregateTest extends TestCase
{
protected static $cacheDir;
public static function setUpBeforeClass()
{
self::$cacheDir = tempnam(sys_get_temp_dir(), 'sf2_cache_warmer_dir');
}
public static function tearDownAfterClass()
{
@unlink(self::$cacheDir);
}
public function testInjectWarmersUsingConstructor()
{
$warmer = $this->getCacheWarmerMock();
$warmer
->expects($this->once())
->method('warmUp');
$aggregate = new CacheWarmerAggregate(array($warmer));
$aggregate->warmUp(self::$cacheDir);
}
public function testInjectWarmersUsingAdd()
{
$warmer = $this->getCacheWarmerMock();
$warmer
->expects($this->once())
->method('warmUp');
$aggregate = new CacheWarmerAggregate();
$aggregate->add($warmer);
$aggregate->warmUp(self::$cacheDir);
}
public function testInjectWarmersUsingSetWarmers()
{
$warmer = $this->getCacheWarmerMock();
$warmer
->expects($this->once())
->method('warmUp');
$aggregate = new CacheWarmerAggregate();
$aggregate->setWarmers(array($warmer));
$aggregate->warmUp(self::$cacheDir);
}
public function testWarmupDoesCallWarmupOnOptionalWarmersWhenEnableOptionalWarmersIsEnabled()
{
$warmer = $this->getCacheWarmerMock();
$warmer
->expects($this->never())
->method('isOptional');
$warmer
->expects($this->once())
->method('warmUp');
$aggregate = new CacheWarmerAggregate(array($warmer));
$aggregate->enableOptionalWarmers();
$aggregate->warmUp(self::$cacheDir);
}
public function testWarmupDoesNotCallWarmupOnOptionalWarmersWhenEnableOptionalWarmersIsNotEnabled()
{
$warmer = $this->getCacheWarmerMock();
$warmer
->expects($this->once())
->method('isOptional')
->will($this->returnValue(true));
$warmer
->expects($this->never())
->method('warmUp');
$aggregate = new CacheWarmerAggregate(array($warmer));
$aggregate->warmUp(self::$cacheDir);
}
protected function getCacheWarmerMock()
{
$warmer = $this->getMockBuilder('Symfony\Component\HttpKernel\CacheWarmer\CacheWarmerInterface')
->disableOriginalConstructor()
->getMock();
return $warmer;
}
}

View File

@@ -0,0 +1,68 @@
<?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\Tests\CacheWarmer;
use PHPUnit\Framework\TestCase;
use Symfony\Component\HttpKernel\CacheWarmer\CacheWarmer;
class CacheWarmerTest extends TestCase
{
protected static $cacheFile;
public static function setUpBeforeClass()
{
self::$cacheFile = tempnam(sys_get_temp_dir(), 'sf2_cache_warmer_dir');
}
public static function tearDownAfterClass()
{
@unlink(self::$cacheFile);
}
public function testWriteCacheFileCreatesTheFile()
{
$warmer = new TestCacheWarmer(self::$cacheFile);
$warmer->warmUp(dirname(self::$cacheFile));
$this->assertFileExists(self::$cacheFile);
}
/**
* @expectedException \RuntimeException
*/
public function testWriteNonWritableCacheFileThrowsARuntimeException()
{
$nonWritableFile = '/this/file/is/very/probably/not/writable';
$warmer = new TestCacheWarmer($nonWritableFile);
$warmer->warmUp(dirname($nonWritableFile));
}
}
class TestCacheWarmer extends CacheWarmer
{
protected $file;
public function __construct($file)
{
$this->file = $file;
}
public function warmUp($cacheDir)
{
$this->writeCacheFile($this->file, 'content');
}
public function isOptional()
{
return false;
}
}

View File

@@ -0,0 +1,183 @@
<?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\Tests;
use PHPUnit\Framework\TestCase;
use Symfony\Component\HttpKernel\Client;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\StreamedResponse;
use Symfony\Component\HttpFoundation\Cookie;
use Symfony\Component\HttpFoundation\File\UploadedFile;
use Symfony\Component\HttpKernel\Tests\Fixtures\TestClient;
/**
* @group time-sensitive
*/
class ClientTest extends TestCase
{
public function testDoRequest()
{
$client = new Client(new TestHttpKernel());
$client->request('GET', '/');
$this->assertEquals('Request: /', $client->getResponse()->getContent(), '->doRequest() uses the request handler to make the request');
$this->assertInstanceOf('Symfony\Component\BrowserKit\Request', $client->getInternalRequest());
$this->assertInstanceOf('Symfony\Component\HttpFoundation\Request', $client->getRequest());
$this->assertInstanceOf('Symfony\Component\BrowserKit\Response', $client->getInternalResponse());
$this->assertInstanceOf('Symfony\Component\HttpFoundation\Response', $client->getResponse());
$client->request('GET', 'http://www.example.com/');
$this->assertEquals('Request: /', $client->getResponse()->getContent(), '->doRequest() uses the request handler to make the request');
$this->assertEquals('www.example.com', $client->getRequest()->getHost(), '->doRequest() uses the request handler to make the request');
$client->request('GET', 'http://www.example.com/?parameter=http://google.com');
$this->assertEquals('http://www.example.com/?parameter='.urlencode('http://google.com'), $client->getRequest()->getUri(), '->doRequest() uses the request handler to make the request');
}
public function testGetScript()
{
$client = new TestClient(new TestHttpKernel());
$client->insulate();
$client->request('GET', '/');
$this->assertEquals('Request: /', $client->getResponse()->getContent(), '->getScript() returns a script that uses the request handler to make the request');
}
public function testFilterResponseConvertsCookies()
{
$client = new Client(new TestHttpKernel());
$r = new \ReflectionObject($client);
$m = $r->getMethod('filterResponse');
$m->setAccessible(true);
$expected = array(
'foo=bar; expires=Sun, 15-Feb-2009 20:00:00 GMT; max-age='.(strtotime('Sun, 15-Feb-2009 20:00:00 GMT') - time()).'; path=/foo; domain=http://example.com; secure; httponly',
'foo1=bar1; expires=Sun, 15-Feb-2009 20:00:00 GMT; max-age='.(strtotime('Sun, 15-Feb-2009 20:00:00 GMT') - time()).'; path=/foo; domain=http://example.com; secure; httponly',
);
$response = new Response();
$response->headers->setCookie(new Cookie('foo', 'bar', \DateTime::createFromFormat('j-M-Y H:i:s T', '15-Feb-2009 20:00:00 GMT')->format('U'), '/foo', 'http://example.com', true, true));
$domResponse = $m->invoke($client, $response);
$this->assertEquals($expected[0], $domResponse->getHeader('Set-Cookie'));
$response = new Response();
$response->headers->setCookie(new Cookie('foo', 'bar', \DateTime::createFromFormat('j-M-Y H:i:s T', '15-Feb-2009 20:00:00 GMT')->format('U'), '/foo', 'http://example.com', true, true));
$response->headers->setCookie(new Cookie('foo1', 'bar1', \DateTime::createFromFormat('j-M-Y H:i:s T', '15-Feb-2009 20:00:00 GMT')->format('U'), '/foo', 'http://example.com', true, true));
$domResponse = $m->invoke($client, $response);
$this->assertEquals($expected[0], $domResponse->getHeader('Set-Cookie'));
$this->assertEquals($expected, $domResponse->getHeader('Set-Cookie', false));
}
public function testFilterResponseSupportsStreamedResponses()
{
$client = new Client(new TestHttpKernel());
$r = new \ReflectionObject($client);
$m = $r->getMethod('filterResponse');
$m->setAccessible(true);
$response = new StreamedResponse(function () {
echo 'foo';
});
$domResponse = $m->invoke($client, $response);
$this->assertEquals('foo', $domResponse->getContent());
}
public function testUploadedFile()
{
$source = tempnam(sys_get_temp_dir(), 'source');
$target = sys_get_temp_dir().'/sf.moved.file';
@unlink($target);
$kernel = new TestHttpKernel();
$client = new Client($kernel);
$files = array(
array('tmp_name' => $source, 'name' => 'original', 'type' => 'mime/original', 'size' => 123, 'error' => UPLOAD_ERR_OK),
new UploadedFile($source, 'original', 'mime/original', 123, UPLOAD_ERR_OK, true),
);
$file = null;
foreach ($files as $file) {
$client->request('POST', '/', array(), array('foo' => $file));
$files = $client->getRequest()->files->all();
$this->assertCount(1, $files);
$file = $files['foo'];
$this->assertEquals('original', $file->getClientOriginalName());
$this->assertEquals('mime/original', $file->getClientMimeType());
$this->assertEquals('123', $file->getClientSize());
$this->assertTrue($file->isValid());
}
$file->move(dirname($target), basename($target));
$this->assertFileExists($target);
unlink($target);
}
public function testUploadedFileWhenNoFileSelected()
{
$kernel = new TestHttpKernel();
$client = new Client($kernel);
$file = array('tmp_name' => '', 'name' => '', 'type' => '', 'size' => 0, 'error' => UPLOAD_ERR_NO_FILE);
$client->request('POST', '/', array(), array('foo' => $file));
$files = $client->getRequest()->files->all();
$this->assertCount(1, $files);
$this->assertNull($files['foo']);
}
public function testUploadedFileWhenSizeExceedsUploadMaxFileSize()
{
$source = tempnam(sys_get_temp_dir(), 'source');
$kernel = new TestHttpKernel();
$client = new Client($kernel);
$file = $this
->getMockBuilder('Symfony\Component\HttpFoundation\File\UploadedFile')
->setConstructorArgs(array($source, 'original', 'mime/original', 123, UPLOAD_ERR_OK, true))
->setMethods(array('getSize'))
->getMock()
;
$file->expects($this->once())
->method('getSize')
->will($this->returnValue(INF))
;
$client->request('POST', '/', array(), array($file));
$files = $client->getRequest()->files->all();
$this->assertCount(1, $files);
$file = $files[0];
$this->assertFalse($file->isValid());
$this->assertEquals(UPLOAD_ERR_INI_SIZE, $file->getError());
$this->assertEquals('mime/original', $file->getClientMimeType());
$this->assertEquals('original', $file->getClientOriginalName());
$this->assertEquals(0, $file->getClientSize());
unlink($source);
}
}

View File

@@ -0,0 +1,107 @@
<?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\Tests\Config;
use PHPUnit\Framework\TestCase;
use Symfony\Component\HttpKernel\Config\EnvParametersResource;
class EnvParametersResourceTest extends TestCase
{
protected $prefix = '__DUMMY_';
protected $initialEnv;
protected $resource;
protected function setUp()
{
$this->initialEnv = array(
$this->prefix.'1' => 'foo',
$this->prefix.'2' => 'bar',
);
foreach ($this->initialEnv as $key => $value) {
$_SERVER[$key] = $value;
}
$this->resource = new EnvParametersResource($this->prefix);
}
protected function tearDown()
{
foreach ($_SERVER as $key => $value) {
if (0 === strpos($key, $this->prefix)) {
unset($_SERVER[$key]);
}
}
}
public function testGetResource()
{
$this->assertSame(
array('prefix' => $this->prefix, 'variables' => $this->initialEnv),
$this->resource->getResource(),
'->getResource() returns the resource'
);
}
public function testToString()
{
$this->assertSame(
serialize(array('prefix' => $this->prefix, 'variables' => $this->initialEnv)),
(string) $this->resource
);
}
public function testIsFreshNotChanged()
{
$this->assertTrue(
$this->resource->isFresh(time()),
'->isFresh() returns true if the variables have not changed'
);
}
public function testIsFreshValueChanged()
{
reset($this->initialEnv);
$_SERVER[key($this->initialEnv)] = 'baz';
$this->assertFalse(
$this->resource->isFresh(time()),
'->isFresh() returns false if a variable has been changed'
);
}
public function testIsFreshValueRemoved()
{
reset($this->initialEnv);
unset($_SERVER[key($this->initialEnv)]);
$this->assertFalse(
$this->resource->isFresh(time()),
'->isFresh() returns false if a variable has been removed'
);
}
public function testIsFreshValueAdded()
{
$_SERVER[$this->prefix.'3'] = 'foo';
$this->assertFalse(
$this->resource->isFresh(time()),
'->isFresh() returns false if a variable has been added'
);
}
public function testSerializeUnserialize()
{
$this->assertEquals($this->resource, unserialize(serialize($this->resource)));
}
}

View File

@@ -0,0 +1,48 @@
<?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\Tests\Config;
use PHPUnit\Framework\TestCase;
use Symfony\Component\HttpKernel\Config\FileLocator;
class FileLocatorTest extends TestCase
{
public function testLocate()
{
$kernel = $this->getMockBuilder('Symfony\Component\HttpKernel\KernelInterface')->getMock();
$kernel
->expects($this->atLeastOnce())
->method('locateResource')
->with('@BundleName/some/path', null, true)
->will($this->returnValue('/bundle-name/some/path'));
$locator = new FileLocator($kernel);
$this->assertEquals('/bundle-name/some/path', $locator->locate('@BundleName/some/path'));
$kernel
->expects($this->never())
->method('locateResource');
$this->{method_exists($this, $_ = 'expectException') ? $_ : 'setExpectedException'}('LogicException');
$locator->locate('/some/path');
}
public function testLocateWithGlobalResourcePath()
{
$kernel = $this->getMockBuilder('Symfony\Component\HttpKernel\KernelInterface')->getMock();
$kernel
->expects($this->atLeastOnce())
->method('locateResource')
->with('@BundleName/some/path', '/global/resource/path', false);
$locator = new FileLocator($kernel, '/global/resource/path');
$locator->locate('@BundleName/some/path', null, false);
}
}

View File

@@ -0,0 +1,349 @@
<?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\Tests\Controller;
use PHPUnit\Framework\TestCase;
use Symfony\Component\HttpFoundation\Session\Session;
use Symfony\Component\HttpFoundation\Session\SessionInterface;
use Symfony\Component\HttpFoundation\Session\Storage\MockArraySessionStorage;
use Symfony\Component\HttpKernel\Controller\ArgumentResolver;
use Symfony\Component\HttpKernel\Controller\ArgumentResolver\RequestAttributeValueResolver;
use Symfony\Component\HttpKernel\Controller\ArgumentValueResolverInterface;
use Symfony\Component\HttpKernel\ControllerMetadata\ArgumentMetadataFactory;
use Symfony\Component\HttpKernel\Tests\Fixtures\Controller\ExtendingRequest;
use Symfony\Component\HttpKernel\Tests\Fixtures\Controller\ExtendingSession;
use Symfony\Component\HttpKernel\Tests\Fixtures\Controller\NullableController;
use Symfony\Component\HttpKernel\Tests\Fixtures\Controller\VariadicController;
use Symfony\Component\HttpFoundation\Request;
class ArgumentResolverTest extends TestCase
{
/** @var ArgumentResolver */
private static $resolver;
public static function setUpBeforeClass()
{
$factory = new ArgumentMetadataFactory();
self::$resolver = new ArgumentResolver($factory);
}
public function testDefaultState()
{
$this->assertEquals(self::$resolver, new ArgumentResolver());
$this->assertNotEquals(self::$resolver, new ArgumentResolver(null, array(new RequestAttributeValueResolver())));
}
public function testGetArguments()
{
$request = Request::create('/');
$request->attributes->set('foo', 'foo');
$controller = array(new self(), 'controllerWithFoo');
$this->assertEquals(array('foo'), self::$resolver->getArguments($request, $controller), '->getArguments() returns an array of arguments for the controller method');
}
public function testGetArgumentsReturnsEmptyArrayWhenNoArguments()
{
$request = Request::create('/');
$controller = array(new self(), 'controllerWithoutArguments');
$this->assertEquals(array(), self::$resolver->getArguments($request, $controller), '->getArguments() returns an empty array if the method takes no arguments');
}
public function testGetArgumentsUsesDefaultValue()
{
$request = Request::create('/');
$request->attributes->set('foo', 'foo');
$controller = array(new self(), 'controllerWithFooAndDefaultBar');
$this->assertEquals(array('foo', null), self::$resolver->getArguments($request, $controller), '->getArguments() uses default values if present');
}
public function testGetArgumentsOverrideDefaultValueByRequestAttribute()
{
$request = Request::create('/');
$request->attributes->set('foo', 'foo');
$request->attributes->set('bar', 'bar');
$controller = array(new self(), 'controllerWithFooAndDefaultBar');
$this->assertEquals(array('foo', 'bar'), self::$resolver->getArguments($request, $controller), '->getArguments() overrides default values if provided in the request attributes');
}
public function testGetArgumentsFromClosure()
{
$request = Request::create('/');
$request->attributes->set('foo', 'foo');
$controller = function ($foo) {};
$this->assertEquals(array('foo'), self::$resolver->getArguments($request, $controller));
}
public function testGetArgumentsUsesDefaultValueFromClosure()
{
$request = Request::create('/');
$request->attributes->set('foo', 'foo');
$controller = function ($foo, $bar = 'bar') {};
$this->assertEquals(array('foo', 'bar'), self::$resolver->getArguments($request, $controller));
}
public function testGetArgumentsFromInvokableObject()
{
$request = Request::create('/');
$request->attributes->set('foo', 'foo');
$controller = new self();
$this->assertEquals(array('foo', null), self::$resolver->getArguments($request, $controller));
// Test default bar overridden by request attribute
$request->attributes->set('bar', 'bar');
$this->assertEquals(array('foo', 'bar'), self::$resolver->getArguments($request, $controller));
}
public function testGetArgumentsFromFunctionName()
{
$request = Request::create('/');
$request->attributes->set('foo', 'foo');
$request->attributes->set('foobar', 'foobar');
$controller = __NAMESPACE__.'\controller_function';
$this->assertEquals(array('foo', 'foobar'), self::$resolver->getArguments($request, $controller));
}
public function testGetArgumentsFailsOnUnresolvedValue()
{
$request = Request::create('/');
$request->attributes->set('foo', 'foo');
$request->attributes->set('foobar', 'foobar');
$controller = array(new self(), 'controllerWithFooBarFoobar');
try {
self::$resolver->getArguments($request, $controller);
$this->fail('->getArguments() throws a \RuntimeException exception if it cannot determine the argument value');
} catch (\Exception $e) {
$this->assertInstanceOf('\RuntimeException', $e, '->getArguments() throws a \RuntimeException exception if it cannot determine the argument value');
}
}
public function testGetArgumentsInjectsRequest()
{
$request = Request::create('/');
$controller = array(new self(), 'controllerWithRequest');
$this->assertEquals(array($request), self::$resolver->getArguments($request, $controller), '->getArguments() injects the request');
}
public function testGetArgumentsInjectsExtendingRequest()
{
$request = ExtendingRequest::create('/');
$controller = array(new self(), 'controllerWithExtendingRequest');
$this->assertEquals(array($request), self::$resolver->getArguments($request, $controller), '->getArguments() injects the request when extended');
}
/**
* @requires PHP 5.6
*/
public function testGetVariadicArguments()
{
$request = Request::create('/');
$request->attributes->set('foo', 'foo');
$request->attributes->set('bar', array('foo', 'bar'));
$controller = array(new VariadicController(), 'action');
$this->assertEquals(array('foo', 'foo', 'bar'), self::$resolver->getArguments($request, $controller));
}
/**
* @requires PHP 5.6
* @expectedException \InvalidArgumentException
*/
public function testGetVariadicArgumentsWithoutArrayInRequest()
{
$request = Request::create('/');
$request->attributes->set('foo', 'foo');
$request->attributes->set('bar', 'foo');
$controller = array(new VariadicController(), 'action');
self::$resolver->getArguments($request, $controller);
}
/**
* @requires PHP 5.6
* @expectedException \InvalidArgumentException
*/
public function testGetArgumentWithoutArray()
{
$factory = new ArgumentMetadataFactory();
$valueResolver = $this->getMockBuilder(ArgumentValueResolverInterface::class)->getMock();
$resolver = new ArgumentResolver($factory, array($valueResolver));
$valueResolver->expects($this->any())->method('supports')->willReturn(true);
$valueResolver->expects($this->any())->method('resolve')->willReturn('foo');
$request = Request::create('/');
$request->attributes->set('foo', 'foo');
$request->attributes->set('bar', 'foo');
$controller = array($this, 'controllerWithFooAndDefaultBar');
$resolver->getArguments($request, $controller);
}
/**
* @expectedException \RuntimeException
*/
public function testIfExceptionIsThrownWhenMissingAnArgument()
{
$request = Request::create('/');
$controller = array($this, 'controllerWithFoo');
self::$resolver->getArguments($request, $controller);
}
/**
* @requires PHP 7.1
*/
public function testGetNullableArguments()
{
$request = Request::create('/');
$request->attributes->set('foo', 'foo');
$request->attributes->set('bar', new \stdClass());
$request->attributes->set('mandatory', 'mandatory');
$controller = array(new NullableController(), 'action');
$this->assertEquals(array('foo', new \stdClass(), 'value', 'mandatory'), self::$resolver->getArguments($request, $controller));
}
/**
* @requires PHP 7.1
*/
public function testGetNullableArgumentsWithDefaults()
{
$request = Request::create('/');
$request->attributes->set('mandatory', 'mandatory');
$controller = array(new NullableController(), 'action');
$this->assertEquals(array(null, null, 'value', 'mandatory'), self::$resolver->getArguments($request, $controller));
}
public function testGetSessionArguments()
{
$session = new Session(new MockArraySessionStorage());
$request = Request::create('/');
$request->setSession($session);
$controller = array($this, 'controllerWithSession');
$this->assertEquals(array($session), self::$resolver->getArguments($request, $controller));
}
public function testGetSessionArgumentsWithExtendedSession()
{
$session = new ExtendingSession(new MockArraySessionStorage());
$request = Request::create('/');
$request->setSession($session);
$controller = array($this, 'controllerWithExtendingSession');
$this->assertEquals(array($session), self::$resolver->getArguments($request, $controller));
}
public function testGetSessionArgumentsWithInterface()
{
$session = $this->getMockBuilder(SessionInterface::class)->getMock();
$request = Request::create('/');
$request->setSession($session);
$controller = array($this, 'controllerWithSessionInterface');
$this->assertEquals(array($session), self::$resolver->getArguments($request, $controller));
}
/**
* @expectedException \RuntimeException
*/
public function testGetSessionMissMatchWithInterface()
{
$session = $this->getMockBuilder(SessionInterface::class)->getMock();
$request = Request::create('/');
$request->setSession($session);
$controller = array($this, 'controllerWithExtendingSession');
self::$resolver->getArguments($request, $controller);
}
/**
* @expectedException \RuntimeException
*/
public function testGetSessionMissMatchWithImplementation()
{
$session = new Session(new MockArraySessionStorage());
$request = Request::create('/');
$request->setSession($session);
$controller = array($this, 'controllerWithExtendingSession');
self::$resolver->getArguments($request, $controller);
}
/**
* @expectedException \RuntimeException
*/
public function testGetSessionMissMatchOnNull()
{
$request = Request::create('/');
$controller = array($this, 'controllerWithExtendingSession');
self::$resolver->getArguments($request, $controller);
}
public function __invoke($foo, $bar = null)
{
}
public function controllerWithFoo($foo)
{
}
public function controllerWithoutArguments()
{
}
protected function controllerWithFooAndDefaultBar($foo, $bar = null)
{
}
protected function controllerWithFooBarFoobar($foo, $bar, $foobar)
{
}
protected function controllerWithRequest(Request $request)
{
}
protected function controllerWithExtendingRequest(ExtendingRequest $request)
{
}
protected function controllerWithSession(Session $session)
{
}
protected function controllerWithSessionInterface(SessionInterface $session)
{
}
protected function controllerWithExtendingSession(ExtendingSession $session)
{
}
}
function controller_function($foo, $foobar)
{
}

View File

@@ -0,0 +1,148 @@
<?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\Tests\Controller;
use Psr\Container\ContainerInterface;
use Psr\Log\LoggerInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Controller\ContainerControllerResolver;
class ContainerControllerResolverTest extends ControllerResolverTest
{
public function testGetControllerService()
{
$container = $this->createMockContainer();
$container->expects($this->once())
->method('get')
->with('foo')
->will($this->returnValue($this))
;
$resolver = $this->createControllerResolver(null, $container);
$request = Request::create('/');
$request->attributes->set('_controller', 'foo:controllerMethod1');
$controller = $resolver->getController($request);
$this->assertInstanceOf(get_class($this), $controller[0]);
$this->assertSame('controllerMethod1', $controller[1]);
}
public function testGetControllerInvokableService()
{
$invokableController = new InvokableController('bar');
$container = $this->createMockContainer();
$container->expects($this->once())
->method('has')
->with('foo')
->will($this->returnValue(true))
;
$container->expects($this->once())
->method('get')
->with('foo')
->will($this->returnValue($invokableController))
;
$resolver = $this->createControllerResolver(null, $container);
$request = Request::create('/');
$request->attributes->set('_controller', 'foo');
$controller = $resolver->getController($request);
$this->assertEquals($invokableController, $controller);
}
public function testGetControllerInvokableServiceWithClassNameAsName()
{
$invokableController = new InvokableController('bar');
$className = __NAMESPACE__.'\InvokableController';
$container = $this->createMockContainer();
$container->expects($this->once())
->method('has')
->with($className)
->will($this->returnValue(true))
;
$container->expects($this->once())
->method('get')
->with($className)
->will($this->returnValue($invokableController))
;
$resolver = $this->createControllerResolver(null, $container);
$request = Request::create('/');
$request->attributes->set('_controller', $className);
$controller = $resolver->getController($request);
$this->assertEquals($invokableController, $controller);
}
/**
* @dataProvider getUndefinedControllers
*/
public function testGetControllerOnNonUndefinedFunction($controller, $exceptionName = null, $exceptionMessage = null)
{
// All this logic needs to be duplicated, since calling parent::testGetControllerOnNonUndefinedFunction will override the expected excetion and not use the regex
$resolver = $this->createControllerResolver();
if (method_exists($this, 'expectException')) {
$this->expectException($exceptionName);
$this->expectExceptionMessageRegExp($exceptionMessage);
} else {
$this->setExpectedExceptionRegExp($exceptionName, $exceptionMessage);
}
$request = Request::create('/');
$request->attributes->set('_controller', $controller);
$resolver->getController($request);
}
public function getUndefinedControllers()
{
return array(
array('foo', \LogicException::class, '/Unable to parse the controller name "foo"\./'),
array('oof::bar', \InvalidArgumentException::class, '/Class "oof" does not exist\./'),
array('stdClass', \LogicException::class, '/Unable to parse the controller name "stdClass"\./'),
array(
'Symfony\Component\HttpKernel\Tests\Controller\ControllerResolverTest::bar',
\InvalidArgumentException::class,
'/.?[cC]ontroller(.*?) for URI "\/" is not callable\.( Expected method(.*) Available methods)?/',
),
);
}
protected function createControllerResolver(LoggerInterface $logger = null, ContainerInterface $container = null)
{
if (!$container) {
$container = $this->createMockContainer();
}
return new ContainerControllerResolver($container, $logger);
}
protected function createMockContainer()
{
return $this->getMockBuilder(ContainerInterface::class)->getMock();
}
}
class InvokableController
{
public function __construct($bar) // mandatory argument to prevent automatic instantiation
{
}
public function __invoke()
{
}
}

View File

@@ -0,0 +1,331 @@
<?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\Tests\Controller;
use PHPUnit\Framework\TestCase;
use Psr\Log\LoggerInterface;
use Symfony\Component\HttpKernel\Controller\ControllerResolver;
use Symfony\Component\HttpKernel\Tests\Fixtures\Controller\NullableController;
use Symfony\Component\HttpKernel\Tests\Fixtures\Controller\VariadicController;
use Symfony\Component\HttpFoundation\Request;
class ControllerResolverTest extends TestCase
{
public function testGetControllerWithoutControllerParameter()
{
$logger = $this->getMockBuilder('Psr\Log\LoggerInterface')->getMock();
$logger->expects($this->once())->method('warning')->with('Unable to look for the controller as the "_controller" parameter is missing.');
$resolver = $this->createControllerResolver($logger);
$request = Request::create('/');
$this->assertFalse($resolver->getController($request), '->getController() returns false when the request has no _controller attribute');
}
public function testGetControllerWithLambda()
{
$resolver = $this->createControllerResolver();
$request = Request::create('/');
$request->attributes->set('_controller', $lambda = function () {});
$controller = $resolver->getController($request);
$this->assertSame($lambda, $controller);
}
public function testGetControllerWithObjectAndInvokeMethod()
{
$resolver = $this->createControllerResolver();
$request = Request::create('/');
$request->attributes->set('_controller', $this);
$controller = $resolver->getController($request);
$this->assertSame($this, $controller);
}
public function testGetControllerWithObjectAndMethod()
{
$resolver = $this->createControllerResolver();
$request = Request::create('/');
$request->attributes->set('_controller', array($this, 'controllerMethod1'));
$controller = $resolver->getController($request);
$this->assertSame(array($this, 'controllerMethod1'), $controller);
}
public function testGetControllerWithClassAndMethod()
{
$resolver = $this->createControllerResolver();
$request = Request::create('/');
$request->attributes->set('_controller', array('Symfony\Component\HttpKernel\Tests\Controller\ControllerResolverTest', 'controllerMethod4'));
$controller = $resolver->getController($request);
$this->assertSame(array('Symfony\Component\HttpKernel\Tests\Controller\ControllerResolverTest', 'controllerMethod4'), $controller);
}
public function testGetControllerWithObjectAndMethodAsString()
{
$resolver = $this->createControllerResolver();
$request = Request::create('/');
$request->attributes->set('_controller', 'Symfony\Component\HttpKernel\Tests\Controller\ControllerResolverTest::controllerMethod1');
$controller = $resolver->getController($request);
$this->assertInstanceOf('Symfony\Component\HttpKernel\Tests\Controller\ControllerResolverTest', $controller[0], '->getController() returns a PHP callable');
}
public function testGetControllerWithClassAndInvokeMethod()
{
$resolver = $this->createControllerResolver();
$request = Request::create('/');
$request->attributes->set('_controller', 'Symfony\Component\HttpKernel\Tests\Controller\ControllerResolverTest');
$controller = $resolver->getController($request);
$this->assertInstanceOf('Symfony\Component\HttpKernel\Tests\Controller\ControllerResolverTest', $controller);
}
/**
* @expectedException \InvalidArgumentException
*/
public function testGetControllerOnObjectWithoutInvokeMethod()
{
$resolver = $this->createControllerResolver();
$request = Request::create('/');
$request->attributes->set('_controller', new \stdClass());
$resolver->getController($request);
}
public function testGetControllerWithFunction()
{
$resolver = $this->createControllerResolver();
$request = Request::create('/');
$request->attributes->set('_controller', 'Symfony\Component\HttpKernel\Tests\Controller\some_controller_function');
$controller = $resolver->getController($request);
$this->assertSame('Symfony\Component\HttpKernel\Tests\Controller\some_controller_function', $controller);
}
/**
* @dataProvider getUndefinedControllers
*/
public function testGetControllerOnNonUndefinedFunction($controller, $exceptionName = null, $exceptionMessage = null)
{
$resolver = $this->createControllerResolver();
if (method_exists($this, 'expectException')) {
$this->expectException($exceptionName);
$this->expectExceptionMessage($exceptionMessage);
} else {
$this->setExpectedException($exceptionName, $exceptionMessage);
}
$request = Request::create('/');
$request->attributes->set('_controller', $controller);
$resolver->getController($request);
}
public function getUndefinedControllers()
{
return array(
array(1, 'InvalidArgumentException', 'Unable to find controller "1".'),
array('foo', 'InvalidArgumentException', 'Unable to find controller "foo".'),
array('oof::bar', 'InvalidArgumentException', 'Class "oof" does not exist.'),
array('stdClass', 'InvalidArgumentException', 'Unable to find controller "stdClass".'),
array('Symfony\Component\HttpKernel\Tests\Controller\ControllerTest::staticsAction', 'InvalidArgumentException', 'The controller for URI "/" is not callable. Expected method "staticsAction" on class "Symfony\Component\HttpKernel\Tests\Controller\ControllerTest", did you mean "staticAction"?'),
array('Symfony\Component\HttpKernel\Tests\Controller\ControllerTest::privateAction', 'InvalidArgumentException', 'The controller for URI "/" is not callable. Method "privateAction" on class "Symfony\Component\HttpKernel\Tests\Controller\ControllerTest" should be public and non-abstract'),
array('Symfony\Component\HttpKernel\Tests\Controller\ControllerTest::protectedAction', 'InvalidArgumentException', 'The controller for URI "/" is not callable. Method "protectedAction" on class "Symfony\Component\HttpKernel\Tests\Controller\ControllerTest" should be public and non-abstract'),
array('Symfony\Component\HttpKernel\Tests\Controller\ControllerTest::undefinedAction', 'InvalidArgumentException', 'The controller for URI "/" is not callable. Expected method "undefinedAction" on class "Symfony\Component\HttpKernel\Tests\Controller\ControllerTest". Available methods: "publicAction", "staticAction"'),
);
}
/**
* @group legacy
*/
public function testGetArguments()
{
$resolver = $this->createControllerResolver();
$request = Request::create('/');
$controller = array(new self(), 'testGetArguments');
$this->assertEquals(array(), $resolver->getArguments($request, $controller), '->getArguments() returns an empty array if the method takes no arguments');
$request = Request::create('/');
$request->attributes->set('foo', 'foo');
$controller = array(new self(), 'controllerMethod1');
$this->assertEquals(array('foo'), $resolver->getArguments($request, $controller), '->getArguments() returns an array of arguments for the controller method');
$request = Request::create('/');
$request->attributes->set('foo', 'foo');
$controller = array(new self(), 'controllerMethod2');
$this->assertEquals(array('foo', null), $resolver->getArguments($request, $controller), '->getArguments() uses default values if present');
$request->attributes->set('bar', 'bar');
$this->assertEquals(array('foo', 'bar'), $resolver->getArguments($request, $controller), '->getArguments() overrides default values if provided in the request attributes');
$request = Request::create('/');
$request->attributes->set('foo', 'foo');
$controller = function ($foo) {};
$this->assertEquals(array('foo'), $resolver->getArguments($request, $controller));
$request = Request::create('/');
$request->attributes->set('foo', 'foo');
$controller = function ($foo, $bar = 'bar') {};
$this->assertEquals(array('foo', 'bar'), $resolver->getArguments($request, $controller));
$request = Request::create('/');
$request->attributes->set('foo', 'foo');
$controller = new self();
$this->assertEquals(array('foo', null), $resolver->getArguments($request, $controller));
$request->attributes->set('bar', 'bar');
$this->assertEquals(array('foo', 'bar'), $resolver->getArguments($request, $controller));
$request = Request::create('/');
$request->attributes->set('foo', 'foo');
$request->attributes->set('foobar', 'foobar');
$controller = 'Symfony\Component\HttpKernel\Tests\Controller\some_controller_function';
$this->assertEquals(array('foo', 'foobar'), $resolver->getArguments($request, $controller));
$request = Request::create('/');
$request->attributes->set('foo', 'foo');
$request->attributes->set('foobar', 'foobar');
$controller = array(new self(), 'controllerMethod3');
try {
$resolver->getArguments($request, $controller);
$this->fail('->getArguments() throws a \RuntimeException exception if it cannot determine the argument value');
} catch (\Exception $e) {
$this->assertInstanceOf('\RuntimeException', $e, '->getArguments() throws a \RuntimeException exception if it cannot determine the argument value');
}
$request = Request::create('/');
$controller = array(new self(), 'controllerMethod5');
$this->assertEquals(array($request), $resolver->getArguments($request, $controller), '->getArguments() injects the request');
}
/**
* @requires PHP 5.6
* @group legacy
*/
public function testGetVariadicArguments()
{
$resolver = new ControllerResolver();
$request = Request::create('/');
$request->attributes->set('foo', 'foo');
$request->attributes->set('bar', array('foo', 'bar'));
$controller = array(new VariadicController(), 'action');
$this->assertEquals(array('foo', 'foo', 'bar'), $resolver->getArguments($request, $controller));
}
public function testCreateControllerCanReturnAnyCallable()
{
$mock = $this->getMockBuilder('Symfony\Component\HttpKernel\Controller\ControllerResolver')->setMethods(array('createController'))->getMock();
$mock->expects($this->once())->method('createController')->will($this->returnValue('Symfony\Component\HttpKernel\Tests\Controller\some_controller_function'));
$request = Request::create('/');
$request->attributes->set('_controller', 'foobar');
$mock->getController($request);
}
/**
* @expectedException \RuntimeException
* @group legacy
*/
public function testIfExceptionIsThrownWhenMissingAnArgument()
{
$resolver = new ControllerResolver();
$request = Request::create('/');
$controller = array($this, 'controllerMethod1');
$resolver->getArguments($request, $controller);
}
/**
* @requires PHP 7.1
* @group legacy
*/
public function testGetNullableArguments()
{
$resolver = new ControllerResolver();
$request = Request::create('/');
$request->attributes->set('foo', 'foo');
$request->attributes->set('bar', new \stdClass());
$request->attributes->set('mandatory', 'mandatory');
$controller = array(new NullableController(), 'action');
$this->assertEquals(array('foo', new \stdClass(), 'value', 'mandatory'), $resolver->getArguments($request, $controller));
}
/**
* @requires PHP 7.1
* @group legacy
*/
public function testGetNullableArgumentsWithDefaults()
{
$resolver = new ControllerResolver();
$request = Request::create('/');
$request->attributes->set('mandatory', 'mandatory');
$controller = array(new NullableController(), 'action');
$this->assertEquals(array(null, null, 'value', 'mandatory'), $resolver->getArguments($request, $controller));
}
protected function createControllerResolver(LoggerInterface $logger = null)
{
return new ControllerResolver($logger);
}
public function __invoke($foo, $bar = null)
{
}
public function controllerMethod1($foo)
{
}
protected function controllerMethod2($foo, $bar = null)
{
}
protected function controllerMethod3($foo, $bar, $foobar)
{
}
protected static function controllerMethod4()
{
}
protected function controllerMethod5(Request $request)
{
}
}
function some_controller_function($foo, $foobar)
{
}
class ControllerTest
{
public function publicAction()
{
}
private function privateAction()
{
}
protected function protectedAction()
{
}
public static function staticAction()
{
}
}

View File

@@ -0,0 +1,148 @@
<?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\Tests\ControllerMetadata;
use Fake\ImportedAndFake;
use PHPUnit\Framework\TestCase;
use Symfony\Component\HttpKernel\ControllerMetadata\ArgumentMetadata;
use Symfony\Component\HttpKernel\ControllerMetadata\ArgumentMetadataFactory;
use Symfony\Component\HttpKernel\Tests\Fixtures\Controller\BasicTypesController;
use Symfony\Component\HttpKernel\Tests\Fixtures\Controller\NullableController;
use Symfony\Component\HttpKernel\Tests\Fixtures\Controller\VariadicController;
class ArgumentMetadataFactoryTest extends TestCase
{
/**
* @var ArgumentMetadataFactory
*/
private $factory;
protected function setUp()
{
$this->factory = new ArgumentMetadataFactory();
}
public function testSignature1()
{
$arguments = $this->factory->createArgumentMetadata(array($this, 'signature1'));
$this->assertEquals(array(
new ArgumentMetadata('foo', self::class, false, false, null),
new ArgumentMetadata('bar', 'array', false, false, null),
new ArgumentMetadata('baz', 'callable', false, false, null),
), $arguments);
}
public function testSignature2()
{
$arguments = $this->factory->createArgumentMetadata(array($this, 'signature2'));
$this->assertEquals(array(
new ArgumentMetadata('foo', self::class, false, true, null, true),
new ArgumentMetadata('bar', __NAMESPACE__.'\FakeClassThatDoesNotExist', false, true, null, true),
new ArgumentMetadata('baz', 'Fake\ImportedAndFake', false, true, null, true),
), $arguments);
}
public function testSignature3()
{
$arguments = $this->factory->createArgumentMetadata(array($this, 'signature3'));
$this->assertEquals(array(
new ArgumentMetadata('bar', __NAMESPACE__.'\FakeClassThatDoesNotExist', false, false, null),
new ArgumentMetadata('baz', 'Fake\ImportedAndFake', false, false, null),
), $arguments);
}
public function testSignature4()
{
$arguments = $this->factory->createArgumentMetadata(array($this, 'signature4'));
$this->assertEquals(array(
new ArgumentMetadata('foo', null, false, true, 'default'),
new ArgumentMetadata('bar', null, false, true, 500),
new ArgumentMetadata('baz', null, false, true, array()),
), $arguments);
}
public function testSignature5()
{
$arguments = $this->factory->createArgumentMetadata(array($this, 'signature5'));
$this->assertEquals(array(
new ArgumentMetadata('foo', 'array', false, true, null, true),
new ArgumentMetadata('bar', null, false, false, null),
), $arguments);
}
/**
* @requires PHP 5.6
*/
public function testVariadicSignature()
{
$arguments = $this->factory->createArgumentMetadata(array(new VariadicController(), 'action'));
$this->assertEquals(array(
new ArgumentMetadata('foo', null, false, false, null),
new ArgumentMetadata('bar', null, true, false, null),
), $arguments);
}
/**
* @requires PHP 7.0
*/
public function testBasicTypesSignature()
{
$arguments = $this->factory->createArgumentMetadata(array(new BasicTypesController(), 'action'));
$this->assertEquals(array(
new ArgumentMetadata('foo', 'string', false, false, null),
new ArgumentMetadata('bar', 'int', false, false, null),
new ArgumentMetadata('baz', 'float', false, false, null),
), $arguments);
}
/**
* @requires PHP 7.1
*/
public function testNullableTypesSignature()
{
$arguments = $this->factory->createArgumentMetadata(array(new NullableController(), 'action'));
$this->assertEquals(array(
new ArgumentMetadata('foo', 'string', false, false, null, true),
new ArgumentMetadata('bar', \stdClass::class, false, false, null, true),
new ArgumentMetadata('baz', 'string', false, true, 'value', true),
new ArgumentMetadata('mandatory', null, false, false, null, true),
), $arguments);
}
private function signature1(ArgumentMetadataFactoryTest $foo, array $bar, callable $baz)
{
}
private function signature2(ArgumentMetadataFactoryTest $foo = null, FakeClassThatDoesNotExist $bar = null, ImportedAndFake $baz = null)
{
}
private function signature3(FakeClassThatDoesNotExist $bar, ImportedAndFake $baz)
{
}
private function signature4($foo = 'default', $bar = 500, $baz = array())
{
}
private function signature5(array $foo = null, $bar)
{
}
}

View File

@@ -0,0 +1,46 @@
<?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\Tests\ControllerMetadata;
use PHPUnit\Framework\TestCase;
use Symfony\Component\HttpKernel\ControllerMetadata\ArgumentMetadata;
class ArgumentMetadataTest extends TestCase
{
public function testWithBcLayerWithDefault()
{
$argument = new ArgumentMetadata('foo', 'string', false, true, 'default value');
$this->assertFalse($argument->isNullable());
}
public function testDefaultValueAvailable()
{
$argument = new ArgumentMetadata('foo', 'string', false, true, 'default value', true);
$this->assertTrue($argument->isNullable());
$this->assertTrue($argument->hasDefaultValue());
$this->assertSame('default value', $argument->getDefaultValue());
}
/**
* @expectedException \LogicException
*/
public function testDefaultValueUnavailable()
{
$argument = new ArgumentMetadata('foo', 'string', false, false, null, false);
$this->assertFalse($argument->isNullable());
$this->assertFalse($argument->hasDefaultValue());
$argument->getDefaultValue();
}
}

View File

@@ -0,0 +1,4 @@
Symfony\Component\DependencyInjection\Compiler\RemovePrivateAliasesPass: Removed service "Psr\Container\ContainerInterface"; reason: private alias.
Symfony\Component\DependencyInjection\Compiler\RemovePrivateAliasesPass: Removed service "Symfony\Component\DependencyInjection\ContainerInterface"; reason: private alias.
Some custom logging message
With ending :

View File

@@ -0,0 +1,66 @@
<?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\Tests\DataCollector;
use PHPUnit\Framework\TestCase;
use Symfony\Component\HttpKernel\DataCollector\ConfigDataCollector;
use Symfony\Component\HttpKernel\Kernel;
use Symfony\Component\Config\Loader\LoaderInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
class ConfigDataCollectorTest extends TestCase
{
public function testCollect()
{
$kernel = new KernelForTest('test', true);
$c = new ConfigDataCollector();
$c->setKernel($kernel);
$c->collect(new Request(), new Response());
$this->assertSame('test', $c->getEnv());
$this->assertTrue($c->isDebug());
$this->assertSame('config', $c->getName());
$this->assertSame('testkernel', $c->getAppName());
$this->assertRegExp('~^'.preg_quote($c->getPhpVersion(), '~').'~', PHP_VERSION);
$this->assertRegExp('~'.preg_quote((string) $c->getPhpVersionExtra(), '~').'$~', PHP_VERSION);
$this->assertSame(PHP_INT_SIZE * 8, $c->getPhpArchitecture());
$this->assertSame(class_exists('Locale', false) && \Locale::getDefault() ? \Locale::getDefault() : 'n/a', $c->getPhpIntlLocale());
$this->assertSame(date_default_timezone_get(), $c->getPhpTimezone());
$this->assertSame(Kernel::VERSION, $c->getSymfonyVersion());
$this->assertNull($c->getToken());
$this->assertSame(extension_loaded('xdebug'), $c->hasXDebug());
$this->assertSame(extension_loaded('Zend OPcache') && ini_get('opcache.enable'), $c->hasZendOpcache());
$this->assertSame(extension_loaded('apcu') && ini_get('apc.enabled'), $c->hasApcu());
}
}
class KernelForTest extends Kernel
{
public function getName()
{
return 'testkernel';
}
public function registerBundles()
{
}
public function getBundles()
{
return array();
}
public function registerContainerConfiguration(LoaderInterface $loader)
{
}
}

View File

@@ -0,0 +1,38 @@
<?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\Tests\DataCollector;
use PHPUnit\Framework\TestCase;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Tests\Fixtures\DataCollector\CloneVarDataCollector;
use Symfony\Component\VarDumper\Cloner\VarCloner;
class DataCollectorTest extends TestCase
{
public function testCloneVarStringWithScheme()
{
$c = new CloneVarDataCollector('scheme://foo');
$c->collect(new Request(), new Response());
$cloner = new VarCloner();
$this->assertEquals($cloner->cloneVar('scheme://foo'), $c->getData());
}
public function testCloneVarExistingFilePath()
{
$c = new CloneVarDataCollector(array($filePath = tempnam(sys_get_temp_dir(), 'clone_var_data_collector_')));
$c->collect(new Request(), new Response());
$this->assertSame($filePath, $c->getData()[0]);
}
}

View File

@@ -0,0 +1,115 @@
<?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\Tests\DataCollector;
use PHPUnit\Framework\TestCase;
use Symfony\Component\HttpKernel\DataCollector\DumpDataCollector;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\VarDumper\Cloner\Data;
/**
* @author Nicolas Grekas <p@tchwork.com>
*/
class DumpDataCollectorTest extends TestCase
{
public function testDump()
{
$data = new Data(array(array(123)));
$collector = new DumpDataCollector();
$this->assertSame('dump', $collector->getName());
$collector->dump($data);
$line = __LINE__ - 1;
$this->assertSame(1, $collector->getDumpsCount());
$dump = $collector->getDumps('html');
$this->assertTrue(isset($dump[0]['data']));
$dump[0]['data'] = preg_replace('/^.*?<pre/', '<pre', $dump[0]['data']);
$dump[0]['data'] = preg_replace('/sf-dump-\d+/', 'sf-dump', $dump[0]['data']);
$xDump = array(
array(
'data' => "<pre class=sf-dump id=sf-dump data-indent-pad=\" \"><span class=sf-dump-num>123</span>\n</pre><script>Sfdump(\"sf-dump\")</script>\n",
'name' => 'DumpDataCollectorTest.php',
'file' => __FILE__,
'line' => $line,
'fileExcerpt' => false,
),
);
$this->assertEquals($xDump, $dump);
$this->assertStringMatchesFormat('a:3:{i:0;a:5:{s:4:"data";%c:39:"Symfony\Component\VarDumper\Cloner\Data":%a', $collector->serialize());
$this->assertSame(0, $collector->getDumpsCount());
$this->assertSame('a:2:{i:0;b:0;i:1;s:5:"UTF-8";}', $collector->serialize());
}
public function testCollectDefault()
{
$data = new Data(array(array(123)));
$collector = new DumpDataCollector();
$collector->dump($data);
$line = __LINE__ - 1;
ob_start();
$collector->collect(new Request(), new Response());
$output = ob_get_clean();
$this->assertSame("DumpDataCollectorTest.php on line {$line}:\n123\n", $output);
$this->assertSame(1, $collector->getDumpsCount());
$collector->serialize();
}
public function testCollectHtml()
{
$data = new Data(array(array(123)));
$collector = new DumpDataCollector(null, 'test://%f:%l');
$collector->dump($data);
$line = __LINE__ - 1;
$file = __FILE__;
$xOutput = <<<EOTXT
<pre class=sf-dump id=sf-dump data-indent-pad=" "><a href="test://{$file}:{$line}" title="{$file}"><span class=sf-dump-meta>DumpDataCollectorTest.php</span></a> on line <span class=sf-dump-meta>{$line}</span>:
<span class=sf-dump-num>123</span>
</pre>
EOTXT;
ob_start();
$response = new Response();
$response->headers->set('Content-Type', 'text/html');
$collector->collect(new Request(), $response);
$output = ob_get_clean();
$output = preg_replace('#<(script|style).*?</\1>#s', '', $output);
$output = preg_replace('/sf-dump-\d+/', 'sf-dump', $output);
$this->assertSame($xOutput, trim($output));
$this->assertSame(1, $collector->getDumpsCount());
$collector->serialize();
}
public function testFlush()
{
$data = new Data(array(array(456)));
$collector = new DumpDataCollector();
$collector->dump($data);
$line = __LINE__ - 1;
ob_start();
$collector->__destruct();
$this->assertSame("DumpDataCollectorTest.php on line {$line}:\n456\n", ob_get_clean());
}
}

View File

@@ -0,0 +1,40 @@
<?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\Tests\DataCollector;
use PHPUnit\Framework\TestCase;
use Symfony\Component\Debug\Exception\FlattenException;
use Symfony\Component\HttpKernel\DataCollector\ExceptionDataCollector;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
class ExceptionDataCollectorTest extends TestCase
{
public function testCollect()
{
$e = new \Exception('foo', 500);
$c = new ExceptionDataCollector();
$flattened = FlattenException::create($e);
$trace = $flattened->getTrace();
$this->assertFalse($c->hasException());
$c->collect(new Request(), new Response(), $e);
$this->assertTrue($c->hasException());
$this->assertEquals($flattened, $c->getException());
$this->assertSame('foo', $c->getMessage());
$this->assertSame(500, $c->getCode());
$this->assertSame('exception', $c->getName());
$this->assertSame($trace, $c->getTrace());
}
}

View File

@@ -0,0 +1,126 @@
<?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\Tests\DataCollector;
use PHPUnit\Framework\TestCase;
use Symfony\Component\Debug\Exception\SilencedErrorContext;
use Symfony\Component\HttpKernel\DataCollector\LoggerDataCollector;
class LoggerDataCollectorTest extends TestCase
{
public function testCollectWithUnexpectedFormat()
{
$logger = $this->getMockBuilder('Symfony\Component\HttpKernel\Log\DebugLoggerInterface')->getMock();
$logger->expects($this->once())->method('countErrors')->will($this->returnValue('foo'));
$logger->expects($this->exactly(2))->method('getLogs')->will($this->returnValue(array()));
$c = new LoggerDataCollector($logger, __DIR__.'/');
$c->lateCollect();
$compilerLogs = $c->getCompilerLogs()->getValue('message');
$this->assertSame(array(
array('message' => 'Removed service "Psr\Container\ContainerInterface"; reason: private alias.'),
array('message' => 'Removed service "Symfony\Component\DependencyInjection\ContainerInterface"; reason: private alias.'),
), $compilerLogs['Symfony\Component\DependencyInjection\Compiler\RemovePrivateAliasesPass']);
$this->assertSame(array(
array('message' => 'Some custom logging message'),
array('message' => 'With ending :'),
), $compilerLogs['Unknown Compiler Pass']);
}
/**
* @dataProvider getCollectTestData
*/
public function testCollect($nb, $logs, $expectedLogs, $expectedDeprecationCount, $expectedScreamCount, $expectedPriorities = null)
{
$logger = $this->getMockBuilder('Symfony\Component\HttpKernel\Log\DebugLoggerInterface')->getMock();
$logger->expects($this->once())->method('countErrors')->will($this->returnValue($nb));
$logger->expects($this->exactly(2))->method('getLogs')->will($this->returnValue($logs));
$c = new LoggerDataCollector($logger);
$c->lateCollect();
$this->assertEquals('logger', $c->getName());
$this->assertEquals($nb, $c->countErrors());
$logs = array_map(function ($v) {
if (isset($v['context']['exception'])) {
$e = &$v['context']['exception'];
$e = isset($e["\0*\0message"]) ? array($e["\0*\0message"], $e["\0*\0severity"]) : array($e["\0Symfony\Component\Debug\Exception\SilencedErrorContext\0severity"]);
}
return $v;
}, $c->getLogs()->getValue(true));
$this->assertEquals($expectedLogs, $logs);
$this->assertEquals($expectedDeprecationCount, $c->countDeprecations());
$this->assertEquals($expectedScreamCount, $c->countScreams());
if (isset($expectedPriorities)) {
$this->assertSame($expectedPriorities, $c->getPriorities()->getValue(true));
}
}
public function getCollectTestData()
{
yield 'simple log' => array(
1,
array(array('message' => 'foo', 'context' => array(), 'priority' => 100, 'priorityName' => 'DEBUG')),
array(array('message' => 'foo', 'context' => array(), 'priority' => 100, 'priorityName' => 'DEBUG')),
0,
0,
);
yield 'log with a context' => array(
1,
array(array('message' => 'foo', 'context' => array('foo' => 'bar'), 'priority' => 100, 'priorityName' => 'DEBUG')),
array(array('message' => 'foo', 'context' => array('foo' => 'bar'), 'priority' => 100, 'priorityName' => 'DEBUG')),
0,
0,
);
if (!class_exists(SilencedErrorContext::class)) {
return;
}
yield 'logs with some deprecations' => array(
1,
array(
array('message' => 'foo3', 'context' => array('exception' => new \ErrorException('warning', 0, E_USER_WARNING)), 'priority' => 100, 'priorityName' => 'DEBUG'),
array('message' => 'foo', 'context' => array('exception' => new \ErrorException('deprecated', 0, E_DEPRECATED)), 'priority' => 100, 'priorityName' => 'DEBUG'),
array('message' => 'foo2', 'context' => array('exception' => new \ErrorException('deprecated', 0, E_USER_DEPRECATED)), 'priority' => 100, 'priorityName' => 'DEBUG'),
),
array(
array('message' => 'foo3', 'context' => array('exception' => array('warning', E_USER_WARNING)), 'priority' => 100, 'priorityName' => 'DEBUG'),
array('message' => 'foo', 'context' => array('exception' => array('deprecated', E_DEPRECATED)), 'priority' => 100, 'priorityName' => 'DEBUG', 'errorCount' => 1, 'scream' => false),
array('message' => 'foo2', 'context' => array('exception' => array('deprecated', E_USER_DEPRECATED)), 'priority' => 100, 'priorityName' => 'DEBUG', 'errorCount' => 1, 'scream' => false),
),
2,
0,
array(100 => array('count' => 3, 'name' => 'DEBUG')),
);
yield 'logs with some silent errors' => array(
1,
array(
array('message' => 'foo3', 'context' => array('exception' => new \ErrorException('warning', 0, E_USER_WARNING)), 'priority' => 100, 'priorityName' => 'DEBUG'),
array('message' => 'foo3', 'context' => array('exception' => new SilencedErrorContext(E_USER_WARNING, __FILE__, __LINE__)), 'priority' => 100, 'priorityName' => 'DEBUG'),
),
array(
array('message' => 'foo3', 'context' => array('exception' => array('warning', E_USER_WARNING)), 'priority' => 100, 'priorityName' => 'DEBUG'),
array('message' => 'foo3', 'context' => array('exception' => array(E_USER_WARNING)), 'priority' => 100, 'priorityName' => 'DEBUG', 'errorCount' => 1, 'scream' => true),
),
0,
1,
);
}
}

View File

@@ -0,0 +1,59 @@
<?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\Tests\DataCollector;
use PHPUnit\Framework\TestCase;
use Symfony\Component\HttpKernel\DataCollector\MemoryDataCollector;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
class MemoryDataCollectorTest extends TestCase
{
public function testCollect()
{
$collector = new MemoryDataCollector();
$collector->collect(new Request(), new Response());
$this->assertInternalType('integer', $collector->getMemory());
$this->assertInternalType('integer', $collector->getMemoryLimit());
$this->assertSame('memory', $collector->getName());
}
/** @dataProvider getBytesConversionTestData */
public function testBytesConversion($limit, $bytes)
{
$collector = new MemoryDataCollector();
$method = new \ReflectionMethod($collector, 'convertToBytes');
$method->setAccessible(true);
$this->assertEquals($bytes, $method->invoke($collector, $limit));
}
public function getBytesConversionTestData()
{
return array(
array('2k', 2048),
array('2 k', 2048),
array('8m', 8 * 1024 * 1024),
array('+2 k', 2048),
array('+2???k', 2048),
array('0x10', 16),
array('0xf', 15),
array('010', 8),
array('+0x10 k', 16 * 1024),
array('1g', 1024 * 1024 * 1024),
array('1G', 1024 * 1024 * 1024),
array('-1', -1),
array('0', 0),
array('2mk', 2048), // the unit must be the last char, so in this case 'k', not 'm'
);
}
}

View File

@@ -0,0 +1,287 @@
<?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\Tests\DataCollector;
use PHPUnit\Framework\TestCase;
use Symfony\Component\HttpFoundation\ParameterBag;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Session\Session;
use Symfony\Component\HttpFoundation\Session\Storage\MockArraySessionStorage;
use Symfony\Component\HttpKernel\Controller\ArgumentResolverInterface;
use Symfony\Component\HttpKernel\Event\FilterResponseEvent;
use Symfony\Component\HttpKernel\HttpKernel;
use Symfony\Component\HttpKernel\HttpKernelInterface;
use Symfony\Component\HttpKernel\DataCollector\RequestDataCollector;
use Symfony\Component\HttpKernel\Event\FilterControllerEvent;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Cookie;
use Symfony\Component\EventDispatcher\EventDispatcher;
class RequestDataCollectorTest extends TestCase
{
public function testCollect()
{
$c = new RequestDataCollector();
$c->collect($request = $this->createRequest(), $this->createResponse());
$c->lateCollect();
$attributes = $c->getRequestAttributes();
$this->assertSame('request', $c->getName());
$this->assertInstanceOf('Symfony\Component\HttpFoundation\ParameterBag', $c->getRequestHeaders());
$this->assertInstanceOf('Symfony\Component\HttpFoundation\ParameterBag', $c->getRequestServer());
$this->assertInstanceOf('Symfony\Component\HttpFoundation\ParameterBag', $c->getRequestCookies());
$this->assertInstanceOf('Symfony\Component\HttpFoundation\ParameterBag', $attributes);
$this->assertInstanceOf('Symfony\Component\HttpFoundation\ParameterBag', $c->getRequestRequest());
$this->assertInstanceOf('Symfony\Component\HttpFoundation\ParameterBag', $c->getRequestQuery());
$this->assertInstanceOf(ParameterBag::class, $c->getResponseCookies());
$this->assertSame('html', $c->getFormat());
$this->assertEquals('foobar', $c->getRoute());
$this->assertEquals(array('name' => 'foo'), $c->getRouteParams());
$this->assertSame(array(), $c->getSessionAttributes());
$this->assertSame('en', $c->getLocale());
$this->assertContains(__FILE__, $attributes->get('resource'));
$this->assertSame('stdClass', $attributes->get('object')->getType());
$this->assertInstanceOf('Symfony\Component\HttpFoundation\ParameterBag', $c->getResponseHeaders());
$this->assertSame('OK', $c->getStatusText());
$this->assertSame(200, $c->getStatusCode());
$this->assertSame('application/json', $c->getContentType());
}
public function testCollectWithoutRouteParams()
{
$request = $this->createRequest(array());
$c = new RequestDataCollector();
$c->collect($request, $this->createResponse());
$c->lateCollect();
$this->assertEquals(array(), $c->getRouteParams());
}
public function testKernelResponseDoesNotStartSession()
{
$kernel = $this->getMockBuilder(HttpKernelInterface::class)->getMock();
$request = new Request();
$session = new Session(new MockArraySessionStorage());
$request->setSession($session);
$response = new Response();
$c = new RequestDataCollector();
$c->onKernelResponse(new FilterResponseEvent($kernel, $request, HttpKernelInterface::MASTER_REQUEST, $response));
$this->assertFalse($session->isStarted());
}
/**
* @dataProvider provideControllerCallables
*/
public function testControllerInspection($name, $callable, $expected)
{
$c = new RequestDataCollector();
$request = $this->createRequest();
$response = $this->createResponse();
$this->injectController($c, $callable, $request);
$c->collect($request, $response);
$c->lateCollect();
$this->assertSame($expected, $c->getController()->getValue(true), sprintf('Testing: %s', $name));
}
public function provideControllerCallables()
{
// make sure we always match the line number
$r1 = new \ReflectionMethod($this, 'testControllerInspection');
$r2 = new \ReflectionMethod($this, 'staticControllerMethod');
$r3 = new \ReflectionClass($this);
// test name, callable, expected
return array(
array(
'"Regular" callable',
array($this, 'testControllerInspection'),
array(
'class' => __NAMESPACE__.'\RequestDataCollectorTest',
'method' => 'testControllerInspection',
'file' => __FILE__,
'line' => $r1->getStartLine(),
),
),
array(
'Closure',
function () { return 'foo'; },
array(
'class' => __NAMESPACE__.'\{closure}',
'method' => null,
'file' => __FILE__,
'line' => __LINE__ - 5,
),
),
array(
'Static callback as string',
__NAMESPACE__.'\RequestDataCollectorTest::staticControllerMethod',
array(
'class' => 'Symfony\Component\HttpKernel\Tests\DataCollector\RequestDataCollectorTest',
'method' => 'staticControllerMethod',
'file' => __FILE__,
'line' => $r2->getStartLine(),
),
),
array(
'Static callable with instance',
array($this, 'staticControllerMethod'),
array(
'class' => 'Symfony\Component\HttpKernel\Tests\DataCollector\RequestDataCollectorTest',
'method' => 'staticControllerMethod',
'file' => __FILE__,
'line' => $r2->getStartLine(),
),
),
array(
'Static callable with class name',
array('Symfony\Component\HttpKernel\Tests\DataCollector\RequestDataCollectorTest', 'staticControllerMethod'),
array(
'class' => 'Symfony\Component\HttpKernel\Tests\DataCollector\RequestDataCollectorTest',
'method' => 'staticControllerMethod',
'file' => __FILE__,
'line' => $r2->getStartLine(),
),
),
array(
'Callable with instance depending on __call()',
array($this, 'magicMethod'),
array(
'class' => 'Symfony\Component\HttpKernel\Tests\DataCollector\RequestDataCollectorTest',
'method' => 'magicMethod',
'file' => 'n/a',
'line' => 'n/a',
),
),
array(
'Callable with class name depending on __callStatic()',
array('Symfony\Component\HttpKernel\Tests\DataCollector\RequestDataCollectorTest', 'magicMethod'),
array(
'class' => 'Symfony\Component\HttpKernel\Tests\DataCollector\RequestDataCollectorTest',
'method' => 'magicMethod',
'file' => 'n/a',
'line' => 'n/a',
),
),
array(
'Invokable controller',
$this,
array(
'class' => 'Symfony\Component\HttpKernel\Tests\DataCollector\RequestDataCollectorTest',
'method' => null,
'file' => __FILE__,
'line' => $r3->getStartLine(),
),
),
);
}
public function testItIgnoresInvalidCallables()
{
$request = $this->createRequestWithSession();
$response = new RedirectResponse('/');
$c = new RequestDataCollector();
$c->collect($request, $response);
$this->assertSame('n/a', $c->getController());
}
protected function createRequest($routeParams = array('name' => 'foo'))
{
$request = Request::create('http://test.com/foo?bar=baz');
$request->attributes->set('foo', 'bar');
$request->attributes->set('_route', 'foobar');
$request->attributes->set('_route_params', $routeParams);
$request->attributes->set('resource', fopen(__FILE__, 'r'));
$request->attributes->set('object', new \stdClass());
return $request;
}
private function createRequestWithSession()
{
$request = $this->createRequest();
$request->attributes->set('_controller', 'Foo::bar');
$request->setSession(new Session(new MockArraySessionStorage()));
$request->getSession()->start();
return $request;
}
protected function createResponse()
{
$response = new Response();
$response->setStatusCode(200);
$response->headers->set('Content-Type', 'application/json');
$response->headers->set('X-Foo-Bar', null);
$response->headers->setCookie(new Cookie('foo', 'bar', 1, '/foo', 'localhost', true, true));
$response->headers->setCookie(new Cookie('bar', 'foo', new \DateTime('@946684800')));
$response->headers->setCookie(new Cookie('bazz', 'foo', '2000-12-12'));
return $response;
}
/**
* Inject the given controller callable into the data collector.
*/
protected function injectController($collector, $controller, $request)
{
$resolver = $this->getMockBuilder('Symfony\\Component\\HttpKernel\\Controller\\ControllerResolverInterface')->getMock();
$httpKernel = new HttpKernel(new EventDispatcher(), $resolver, null, $this->getMockBuilder(ArgumentResolverInterface::class)->getMock());
$event = new FilterControllerEvent($httpKernel, $controller, $request, HttpKernelInterface::MASTER_REQUEST);
$collector->onKernelController($event);
}
/**
* Dummy method used as controller callable.
*/
public static function staticControllerMethod()
{
throw new \LogicException('Unexpected method call');
}
/**
* Magic method to allow non existing methods to be called and delegated.
*/
public function __call($method, $args)
{
throw new \LogicException('Unexpected method call');
}
/**
* Magic method to allow non existing methods to be called and delegated.
*/
public static function __callStatic($method, $args)
{
throw new \LogicException('Unexpected method call');
}
public function __invoke()
{
throw new \LogicException('Unexpected method call');
}
}

View File

@@ -0,0 +1,55 @@
<?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\Tests\DataCollector;
use PHPUnit\Framework\TestCase;
use Symfony\Component\HttpKernel\DataCollector\TimeDataCollector;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
/**
* @group time-sensitive
*/
class TimeDataCollectorTest extends TestCase
{
public function testCollect()
{
$c = new TimeDataCollector();
$request = new Request();
$request->server->set('REQUEST_TIME', 1);
$c->collect($request, new Response());
$this->assertEquals(0, $c->getStartTime());
$request->server->set('REQUEST_TIME_FLOAT', 2);
$c->collect($request, new Response());
$this->assertEquals(2000, $c->getStartTime());
$request = new Request();
$c->collect($request, new Response());
$this->assertEquals(0, $c->getStartTime());
$kernel = $this->getMockBuilder('Symfony\Component\HttpKernel\KernelInterface')->getMock();
$kernel->expects($this->once())->method('getStartTime')->will($this->returnValue(123456));
$c = new TimeDataCollector($kernel);
$request = new Request();
$request->server->set('REQUEST_TIME', 1);
$c->collect($request, new Response());
$this->assertEquals(123456000, $c->getStartTime());
}
}

View File

@@ -0,0 +1,51 @@
<?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\Tests\DataCollector\Util;
use PHPUnit\Framework\TestCase;
use Symfony\Component\HttpKernel\DataCollector\Util\ValueExporter;
/**
* @group legacy
*/
class ValueExporterTest extends TestCase
{
/**
* @var ValueExporter
*/
private $valueExporter;
protected function setUp()
{
$this->valueExporter = new ValueExporter();
}
public function testDateTime()
{
$dateTime = new \DateTime('2014-06-10 07:35:40', new \DateTimeZone('UTC'));
$this->assertSame('Object(DateTime) - 2014-06-10T07:35:40+00:00', $this->valueExporter->exportValue($dateTime));
}
public function testDateTimeImmutable()
{
$dateTime = new \DateTimeImmutable('2014-06-10 07:35:40', new \DateTimeZone('UTC'));
$this->assertSame('Object(DateTimeImmutable) - 2014-06-10T07:35:40+00:00', $this->valueExporter->exportValue($dateTime));
}
public function testIncompleteClass()
{
$foo = new \__PHP_Incomplete_Class();
$array = new \ArrayObject($foo);
$array['__PHP_Incomplete_Class_Name'] = 'AppBundle/Foo';
$this->assertSame('__PHP_Incomplete_Class(AppBundle/Foo)', $this->valueExporter->exportValue($foo));
}
}

View File

@@ -0,0 +1,67 @@
<?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\Tests\Debug;
use PHPUnit\Framework\TestCase;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\HttpKernel\Debug\FileLinkFormatter;
class FileLinkFormatterTest extends TestCase
{
public function testWhenNoFileLinkFormatAndNoRequest()
{
$sut = new FileLinkFormatter();
$this->assertFalse($sut->format('/kernel/root/src/my/very/best/file.php', 3));
}
public function testWhenFileLinkFormatAndNoRequest()
{
$file = __DIR__.DIRECTORY_SEPARATOR.'file.php';
$sut = new FileLinkFormatter('debug://open?url=file://%f&line=%l', new RequestStack());
$this->assertSame("debug://open?url=file://$file&line=3", $sut->format($file, 3));
}
public function testWhenFileLinkFormatAndRequest()
{
$file = __DIR__.DIRECTORY_SEPARATOR.'file.php';
$baseDir = __DIR__;
$requestStack = new RequestStack();
$request = new Request();
$requestStack->push($request);
$sut = new FileLinkFormatter('debug://open?url=file://%f&line=%l', $requestStack, __DIR__, '/_profiler/open?file=%f&line=%l#line%l');
$this->assertSame("debug://open?url=file://$file&line=3", $sut->format($file, 3));
}
public function testWhenNoFileLinkFormatAndRequest()
{
$file = __DIR__.DIRECTORY_SEPARATOR.'file.php';
$requestStack = new RequestStack();
$request = new Request();
$requestStack->push($request);
$request->server->set('SERVER_NAME', 'www.example.org');
$request->server->set('SERVER_PORT', 80);
$request->server->set('SCRIPT_NAME', '/app.php');
$request->server->set('SCRIPT_FILENAME', '/web/app.php');
$request->server->set('REQUEST_URI', '/app.php/example');
$sut = new FileLinkFormatter(null, $requestStack, __DIR__, '/_profiler/open?file=%f&line=%l#line%l');
$this->assertSame('http://www.example.org/app.php/_profiler/open?file=file.php&line=3#line3', $sut->format($file, 3));
}
}

View File

@@ -0,0 +1,121 @@
<?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\Tests\Debug;
use PHPUnit\Framework\TestCase;
use Symfony\Component\EventDispatcher\EventDispatcher;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\HttpKernel\Debug\TraceableEventDispatcher;
use Symfony\Component\HttpKernel\HttpKernel;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Stopwatch\Stopwatch;
class TraceableEventDispatcherTest extends TestCase
{
public function testStopwatchSections()
{
$dispatcher = new TraceableEventDispatcher(new EventDispatcher(), $stopwatch = new Stopwatch());
$kernel = $this->getHttpKernel($dispatcher, function () { return new Response(); });
$request = Request::create('/');
$response = $kernel->handle($request);
$kernel->terminate($request, $response);
$events = $stopwatch->getSectionEvents($response->headers->get('X-Debug-Token'));
$this->assertEquals(array(
'__section__',
'kernel.request',
'kernel.controller',
'kernel.controller_arguments',
'controller',
'kernel.response',
'kernel.terminate',
), array_keys($events));
}
public function testStopwatchCheckControllerOnRequestEvent()
{
$stopwatch = $this->getMockBuilder('Symfony\Component\Stopwatch\Stopwatch')
->setMethods(array('isStarted'))
->getMock();
$stopwatch->expects($this->once())
->method('isStarted')
->will($this->returnValue(false));
$dispatcher = new TraceableEventDispatcher(new EventDispatcher(), $stopwatch);
$kernel = $this->getHttpKernel($dispatcher, function () { return new Response(); });
$request = Request::create('/');
$kernel->handle($request);
}
public function testStopwatchStopControllerOnRequestEvent()
{
$stopwatch = $this->getMockBuilder('Symfony\Component\Stopwatch\Stopwatch')
->setMethods(array('isStarted', 'stop', 'stopSection'))
->getMock();
$stopwatch->expects($this->once())
->method('isStarted')
->will($this->returnValue(true));
$stopwatch->expects($this->once())
->method('stop');
$stopwatch->expects($this->once())
->method('stopSection');
$dispatcher = new TraceableEventDispatcher(new EventDispatcher(), $stopwatch);
$kernel = $this->getHttpKernel($dispatcher, function () { return new Response(); });
$request = Request::create('/');
$kernel->handle($request);
}
public function testAddListenerNested()
{
$called1 = false;
$called2 = false;
$dispatcher = new TraceableEventDispatcher(new EventDispatcher(), new Stopwatch());
$dispatcher->addListener('my-event', function () use ($dispatcher, &$called1, &$called2) {
$called1 = true;
$dispatcher->addListener('my-event', function () use (&$called2) {
$called2 = true;
});
});
$dispatcher->dispatch('my-event');
$this->assertTrue($called1);
$this->assertFalse($called2);
$dispatcher->dispatch('my-event');
$this->assertTrue($called2);
}
public function testListenerCanRemoveItselfWhenExecuted()
{
$eventDispatcher = new TraceableEventDispatcher(new EventDispatcher(), new Stopwatch());
$listener1 = function () use ($eventDispatcher, &$listener1) {
$eventDispatcher->removeListener('foo', $listener1);
};
$eventDispatcher->addListener('foo', $listener1);
$eventDispatcher->addListener('foo', function () {});
$eventDispatcher->dispatch('foo');
$this->assertCount(1, $eventDispatcher->getListeners('foo'), 'expected listener1 to be removed');
}
protected function getHttpKernel($dispatcher, $controller)
{
$controllerResolver = $this->getMockBuilder('Symfony\Component\HttpKernel\Controller\ControllerResolverInterface')->getMock();
$controllerResolver->expects($this->once())->method('getController')->will($this->returnValue($controller));
$argumentResolver = $this->getMockBuilder('Symfony\Component\HttpKernel\Controller\ArgumentResolverInterface')->getMock();
$argumentResolver->expects($this->once())->method('getArguments')->will($this->returnValue(array()));
return new HttpKernel($dispatcher, $controllerResolver, new RequestStack(), $argumentResolver);
}
}

View File

@@ -0,0 +1,99 @@
<?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\Tests\DependencyInjection;
use PHPUnit\Framework\TestCase;
use Symfony\Component\HttpKernel\DependencyInjection\AddAnnotatedClassesToCachePass;
class AddAnnotatedClassesToCachePassTest extends TestCase
{
public function testExpandClasses()
{
$r = new \ReflectionClass(AddAnnotatedClassesToCachePass::class);
$pass = $r->newInstanceWithoutConstructor();
$r = new \ReflectionMethod(AddAnnotatedClassesToCachePass::class, 'expandClasses');
$r->setAccessible(true);
$expand = $r->getClosure($pass);
$this->assertSame('Foo', $expand(array('Foo'), array())[0]);
$this->assertSame('Foo', $expand(array('\\Foo'), array())[0]);
$this->assertSame('Foo', $expand(array('Foo'), array('\\Foo'))[0]);
$this->assertSame('Foo', $expand(array('Foo'), array('Foo'))[0]);
$this->assertSame('Foo', $expand(array('\\Foo'), array('\\Foo\\Bar'))[0]);
$this->assertSame('Foo', $expand(array('Foo'), array('\\Foo\\Bar'))[0]);
$this->assertSame('Foo', $expand(array('\\Foo'), array('\\Foo\\Bar\\Acme'))[0]);
$this->assertSame('Foo\\Bar', $expand(array('Foo\\'), array('\\Foo\\Bar'))[0]);
$this->assertSame('Foo\\Bar\\Acme', $expand(array('Foo\\'), array('\\Foo\\Bar\\Acme'))[0]);
$this->assertEmpty($expand(array('Foo\\'), array('\\Foo')));
$this->assertSame('Acme\\Foo\\Bar', $expand(array('**\\Foo\\'), array('\\Acme\\Foo\\Bar'))[0]);
$this->assertEmpty($expand(array('**\\Foo\\'), array('\\Foo\\Bar')));
$this->assertEmpty($expand(array('**\\Foo\\'), array('\\Acme\\Foo')));
$this->assertEmpty($expand(array('**\\Foo\\'), array('\\Foo')));
$this->assertSame('Acme\\Foo', $expand(array('**\\Foo'), array('\\Acme\\Foo'))[0]);
$this->assertEmpty($expand(array('**\\Foo'), array('\\Acme\\Foo\\AcmeBundle')));
$this->assertEmpty($expand(array('**\\Foo'), array('\\Acme\\FooBar\\AcmeBundle')));
$this->assertSame('Foo\\Acme\\Bar', $expand(array('Foo\\*\\Bar'), array('\\Foo\\Acme\\Bar'))[0]);
$this->assertEmpty($expand(array('Foo\\*\\Bar'), array('\\Foo\\Acme\\Bundle\\Bar')));
$this->assertSame('Foo\\Acme\\Bar', $expand(array('Foo\\**\\Bar'), array('\\Foo\\Acme\\Bar'))[0]);
$this->assertSame('Foo\\Acme\\Bundle\\Bar', $expand(array('Foo\\**\\Bar'), array('\\Foo\\Acme\\Bundle\\Bar'))[0]);
$this->assertSame('Acme\\Bar', $expand(array('*\\Bar'), array('\\Acme\\Bar'))[0]);
$this->assertEmpty($expand(array('*\\Bar'), array('\\Bar')));
$this->assertEmpty($expand(array('*\\Bar'), array('\\Foo\\Acme\\Bar')));
$this->assertSame('Foo\\Acme\\Bar', $expand(array('**\\Bar'), array('\\Foo\\Acme\\Bar'))[0]);
$this->assertSame('Foo\\Acme\\Bundle\\Bar', $expand(array('**\\Bar'), array('\\Foo\\Acme\\Bundle\\Bar'))[0]);
$this->assertEmpty($expand(array('**\\Bar'), array('\\Bar')));
$this->assertSame('Foo\\Bar', $expand(array('Foo\\*'), array('\\Foo\\Bar'))[0]);
$this->assertEmpty($expand(array('Foo\\*'), array('\\Foo\\Acme\\Bar')));
$this->assertSame('Foo\\Bar', $expand(array('Foo\\**'), array('\\Foo\\Bar'))[0]);
$this->assertSame('Foo\\Acme\\Bar', $expand(array('Foo\\**'), array('\\Foo\\Acme\\Bar'))[0]);
$this->assertSame(array('Foo\\Bar'), $expand(array('Foo\\*'), array('Foo\\Bar', 'Foo\\BarTest')));
$this->assertSame(array('Foo\\Bar', 'Foo\\BarTest'), $expand(array('Foo\\*', 'Foo\\*Test'), array('Foo\\Bar', 'Foo\\BarTest')));
$this->assertSame(
'Acme\\FooBundle\\Controller\\DefaultController',
$expand(array('**Bundle\\Controller\\'), array('\\Acme\\FooBundle\\Controller\\DefaultController'))[0]
);
$this->assertSame(
'FooBundle\\Controller\\DefaultController',
$expand(array('**Bundle\\Controller\\'), array('\\FooBundle\\Controller\\DefaultController'))[0]
);
$this->assertSame(
'Acme\\FooBundle\\Controller\\Bar\\DefaultController',
$expand(array('**Bundle\\Controller\\'), array('\\Acme\\FooBundle\\Controller\\Bar\\DefaultController'))[0]
);
$this->assertSame(
'Bundle\\Controller\\Bar\\DefaultController',
$expand(array('**Bundle\\Controller\\'), array('\\Bundle\\Controller\\Bar\\DefaultController'))[0]
);
$this->assertSame(
'Acme\\Bundle\\Controller\\Bar\\DefaultController',
$expand(array('**Bundle\\Controller\\'), array('\\Acme\\Bundle\\Controller\\Bar\\DefaultController'))[0]
);
$this->assertSame('Foo\\Bar', $expand(array('Foo\\Bar'), array())[0]);
$this->assertSame('Foo\\Acme\\Bar', $expand(array('Foo\\**'), array('\\Foo\\Acme\\Bar'))[0]);
}
}

View File

@@ -0,0 +1,67 @@
<?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\Tests\DependencyInjection;
use PHPUnit\Framework\TestCase;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Definition;
use Symfony\Component\DependencyInjection\Reference;
use Symfony\Component\HttpKernel\Controller\ArgumentResolver;
use Symfony\Component\HttpKernel\DependencyInjection\ControllerArgumentValueResolverPass;
class ControllerArgumentValueResolverPassTest extends TestCase
{
public function testServicesAreOrderedAccordingToPriority()
{
$services = array(
'n3' => array(array()),
'n1' => array(array('priority' => 200)),
'n2' => array(array('priority' => 100)),
);
$expected = array(
new Reference('n1'),
new Reference('n2'),
new Reference('n3'),
);
$definition = new Definition(ArgumentResolver::class, array(null, array()));
$container = new ContainerBuilder();
$container->setDefinition('argument_resolver', $definition);
foreach ($services as $id => list($tag)) {
$container->register($id)->addTag('controller.argument_value_resolver', $tag);
}
(new ControllerArgumentValueResolverPass())->process($container);
$this->assertEquals($expected, $definition->getArgument(1)->getValues());
}
public function testReturningEmptyArrayWhenNoService()
{
$definition = new Definition(ArgumentResolver::class, array(null, array()));
$container = new ContainerBuilder();
$container->setDefinition('argument_resolver', $definition);
(new ControllerArgumentValueResolverPass())->process($container);
$this->assertEquals(array(), $definition->getArgument(1)->getValues());
}
public function testNoArgumentResolver()
{
$container = new ContainerBuilder();
(new ControllerArgumentValueResolverPass())->process($container);
$this->assertFalse($container->hasDefinition('argument_resolver'));
}
}

View File

@@ -0,0 +1,105 @@
<?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\Tests\DependencyInjection;
use PHPUnit\Framework\TestCase;
use Symfony\Component\DependencyInjection\Definition;
use Symfony\Component\DependencyInjection\Reference;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\DependencyInjection\FragmentRendererPass;
use Symfony\Component\HttpKernel\Fragment\FragmentRendererInterface;
class FragmentRendererPassTest extends TestCase
{
/**
* Tests that content rendering not implementing FragmentRendererInterface
* trigger an exception.
*
* @expectedException \InvalidArgumentException
*/
public function testContentRendererWithoutInterface()
{
// one service, not implementing any interface
$services = array(
'my_content_renderer' => array(array('alias' => 'foo')),
);
$definition = $this->getMockBuilder('Symfony\Component\DependencyInjection\Definition')->getMock();
$builder = $this->getMockBuilder('Symfony\Component\DependencyInjection\ContainerBuilder')->setMethods(array('hasDefinition', 'findTaggedServiceIds', 'getDefinition'))->getMock();
$builder->expects($this->any())
->method('hasDefinition')
->will($this->returnValue(true));
// We don't test kernel.fragment_renderer here
$builder->expects($this->atLeastOnce())
->method('findTaggedServiceIds')
->will($this->returnValue($services));
$builder->expects($this->atLeastOnce())
->method('getDefinition')
->will($this->returnValue($definition));
$pass = new FragmentRendererPass();
$pass->process($builder);
}
public function testValidContentRenderer()
{
$services = array(
'my_content_renderer' => array(array('alias' => 'foo')),
);
$renderer = new Definition('', array(null));
$definition = $this->getMockBuilder('Symfony\Component\DependencyInjection\Definition')->getMock();
$definition->expects($this->atLeastOnce())
->method('getClass')
->will($this->returnValue('Symfony\Component\HttpKernel\Tests\DependencyInjection\RendererService'));
$builder = $this->getMockBuilder('Symfony\Component\DependencyInjection\ContainerBuilder')->setMethods(array('hasDefinition', 'findTaggedServiceIds', 'getDefinition', 'getReflectionClass'))->getMock();
$builder->expects($this->any())
->method('hasDefinition')
->will($this->returnValue(true));
// We don't test kernel.fragment_renderer here
$builder->expects($this->atLeastOnce())
->method('findTaggedServiceIds')
->will($this->returnValue($services));
$builder->expects($this->atLeastOnce())
->method('getDefinition')
->will($this->onConsecutiveCalls($renderer, $definition));
$builder->expects($this->atLeastOnce())
->method('getReflectionClass')
->with('Symfony\Component\HttpKernel\Tests\DependencyInjection\RendererService')
->will($this->returnValue(new \ReflectionClass('Symfony\Component\HttpKernel\Tests\DependencyInjection\RendererService')));
$pass = new FragmentRendererPass();
$pass->process($builder);
$this->assertInstanceOf(Reference::class, $renderer->getArgument(0));
}
}
class RendererService implements FragmentRendererInterface
{
public function render($uri, Request $request = null, array $options = array())
{
}
public function getName()
{
return 'test';
}
}

View File

@@ -0,0 +1,66 @@
<?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\Tests\DependencyInjection;
use PHPUnit\Framework\TestCase;
use Symfony\Component\HttpKernel\DependencyInjection\LazyLoadingFragmentHandler;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
class LazyLoadingFragmentHandlerTest extends TestCase
{
/**
* @group legacy
* @expectedDeprecation The Symfony\Component\HttpKernel\DependencyInjection\LazyLoadingFragmentHandler::addRendererService() method is deprecated since version 3.3 and will be removed in 4.0.
*/
public function testRenderWithLegacyMapping()
{
$renderer = $this->getMockBuilder('Symfony\Component\HttpKernel\Fragment\FragmentRendererInterface')->getMock();
$renderer->expects($this->once())->method('getName')->will($this->returnValue('foo'));
$renderer->expects($this->any())->method('render')->will($this->returnValue(new Response()));
$requestStack = $this->getMockBuilder('Symfony\Component\HttpFoundation\RequestStack')->getMock();
$requestStack->expects($this->any())->method('getCurrentRequest')->will($this->returnValue(Request::create('/')));
$container = $this->getMockBuilder('Symfony\Component\DependencyInjection\ContainerInterface')->getMock();
$container->expects($this->once())->method('get')->will($this->returnValue($renderer));
$handler = new LazyLoadingFragmentHandler($container, $requestStack, false);
$handler->addRendererService('foo', 'foo');
$handler->render('/foo', 'foo');
// second call should not lazy-load anymore (see once() above on the get() method)
$handler->render('/foo', 'foo');
}
public function testRender()
{
$renderer = $this->getMockBuilder('Symfony\Component\HttpKernel\Fragment\FragmentRendererInterface')->getMock();
$renderer->expects($this->once())->method('getName')->will($this->returnValue('foo'));
$renderer->expects($this->any())->method('render')->will($this->returnValue(new Response()));
$requestStack = $this->getMockBuilder('Symfony\Component\HttpFoundation\RequestStack')->getMock();
$requestStack->expects($this->any())->method('getCurrentRequest')->will($this->returnValue(Request::create('/')));
$container = $this->getMockBuilder('Psr\Container\ContainerInterface')->getMock();
$container->expects($this->once())->method('has')->with('foo')->willReturn(true);
$container->expects($this->once())->method('get')->will($this->returnValue($renderer));
$handler = new LazyLoadingFragmentHandler($container, $requestStack, false);
$handler->render('/foo', 'foo');
// second call should not lazy-load anymore (see once() above on the get() method)
$handler->render('/foo', 'foo');
}
}

View File

@@ -0,0 +1,55 @@
<?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\Tests\DependencyInjection;
use PHPUnit\Framework\TestCase;
use Symfony\Component\HttpKernel\DependencyInjection\MergeExtensionConfigurationPass;
class MergeExtensionConfigurationPassTest extends TestCase
{
public function testAutoloadMainExtension()
{
$container = $this->getMockBuilder('Symfony\\Component\\DependencyInjection\\ContainerBuilder')->setMethods(array('getExtensionConfig', 'loadFromExtension', 'getParameterBag', 'getDefinitions', 'getAliases', 'getExtensions'))->getMock();
$params = $this->getMockBuilder('Symfony\\Component\\DependencyInjection\\ParameterBag\\ParameterBag')->getMock();
$container->expects($this->at(0))
->method('getExtensionConfig')
->with('loaded')
->will($this->returnValue(array(array())));
$container->expects($this->at(1))
->method('getExtensionConfig')
->with('notloaded')
->will($this->returnValue(array()));
$container->expects($this->once())
->method('loadFromExtension')
->with('notloaded', array());
$container->expects($this->any())
->method('getParameterBag')
->will($this->returnValue($params));
$params->expects($this->any())
->method('all')
->will($this->returnValue(array()));
$container->expects($this->any())
->method('getDefinitions')
->will($this->returnValue(array()));
$container->expects($this->any())
->method('getAliases')
->will($this->returnValue(array()));
$container->expects($this->any())
->method('getExtensions')
->will($this->returnValue(array()));
$configPass = new MergeExtensionConfigurationPass(array('loaded', 'notloaded'));
$configPass->process($container);
}
}

View File

@@ -0,0 +1,344 @@
<?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\Tests\DependencyInjection;
use PHPUnit\Framework\TestCase;
use Symfony\Component\DependencyInjection\Argument\ServiceClosureArgument;
use Symfony\Component\DependencyInjection\ContainerAwareInterface;
use Symfony\Component\DependencyInjection\ContainerAwareTrait;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\DependencyInjection\ServiceLocator;
use Symfony\Component\DependencyInjection\TypedReference;
use Symfony\Component\HttpKernel\DependencyInjection\RegisterControllerArgumentLocatorsPass;
class RegisterControllerArgumentLocatorsPassTest extends TestCase
{
/**
* @expectedException \Symfony\Component\DependencyInjection\Exception\InvalidArgumentException
* @expectedExceptionMessage Class "Symfony\Component\HttpKernel\Tests\DependencyInjection\NotFound" used for service "foo" cannot be found.
*/
public function testInvalidClass()
{
$container = new ContainerBuilder();
$container->register('argument_resolver.service')->addArgument(array());
$container->register('foo', NotFound::class)
->addTag('controller.service_arguments')
;
$pass = new RegisterControllerArgumentLocatorsPass();
$pass->process($container);
}
/**
* @expectedException \Symfony\Component\DependencyInjection\Exception\InvalidArgumentException
* @expectedExceptionMessage Missing "action" attribute on tag "controller.service_arguments" {"argument":"bar"} for service "foo".
*/
public function testNoAction()
{
$container = new ContainerBuilder();
$container->register('argument_resolver.service')->addArgument(array());
$container->register('foo', RegisterTestController::class)
->addTag('controller.service_arguments', array('argument' => 'bar'))
;
$pass = new RegisterControllerArgumentLocatorsPass();
$pass->process($container);
}
/**
* @expectedException \Symfony\Component\DependencyInjection\Exception\InvalidArgumentException
* @expectedExceptionMessage Missing "argument" attribute on tag "controller.service_arguments" {"action":"fooAction"} for service "foo".
*/
public function testNoArgument()
{
$container = new ContainerBuilder();
$container->register('argument_resolver.service')->addArgument(array());
$container->register('foo', RegisterTestController::class)
->addTag('controller.service_arguments', array('action' => 'fooAction'))
;
$pass = new RegisterControllerArgumentLocatorsPass();
$pass->process($container);
}
/**
* @expectedException \Symfony\Component\DependencyInjection\Exception\InvalidArgumentException
* @expectedExceptionMessage Missing "id" attribute on tag "controller.service_arguments" {"action":"fooAction","argument":"bar"} for service "foo".
*/
public function testNoService()
{
$container = new ContainerBuilder();
$container->register('argument_resolver.service')->addArgument(array());
$container->register('foo', RegisterTestController::class)
->addTag('controller.service_arguments', array('action' => 'fooAction', 'argument' => 'bar'))
;
$pass = new RegisterControllerArgumentLocatorsPass();
$pass->process($container);
}
/**
* @expectedException \Symfony\Component\DependencyInjection\Exception\InvalidArgumentException
* @expectedExceptionMessage Invalid "action" attribute on tag "controller.service_arguments" for service "foo": no public "barAction()" method found on class "Symfony\Component\HttpKernel\Tests\DependencyInjection\RegisterTestController".
*/
public function testInvalidMethod()
{
$container = new ContainerBuilder();
$container->register('argument_resolver.service')->addArgument(array());
$container->register('foo', RegisterTestController::class)
->addTag('controller.service_arguments', array('action' => 'barAction', 'argument' => 'bar', 'id' => 'bar_service'))
;
$pass = new RegisterControllerArgumentLocatorsPass();
$pass->process($container);
}
/**
* @expectedException \Symfony\Component\DependencyInjection\Exception\InvalidArgumentException
* @expectedExceptionMessage Invalid "controller.service_arguments" tag for service "foo": method "fooAction()" has no "baz" argument on class "Symfony\Component\HttpKernel\Tests\DependencyInjection\RegisterTestController".
*/
public function testInvalidArgument()
{
$container = new ContainerBuilder();
$container->register('argument_resolver.service')->addArgument(array());
$container->register('foo', RegisterTestController::class)
->addTag('controller.service_arguments', array('action' => 'fooAction', 'argument' => 'baz', 'id' => 'bar'))
;
$pass = new RegisterControllerArgumentLocatorsPass();
$pass->process($container);
}
public function testAllActions()
{
$container = new ContainerBuilder();
$resolver = $container->register('argument_resolver.service')->addArgument(array());
$container->register('foo', RegisterTestController::class)
->addTag('controller.service_arguments')
;
$pass = new RegisterControllerArgumentLocatorsPass();
$pass->process($container);
$locator = $container->getDefinition((string) $resolver->getArgument(0))->getArgument(0);
$this->assertEquals(array('foo:fooAction'), array_keys($locator));
$this->assertInstanceof(ServiceClosureArgument::class, $locator['foo:fooAction']);
$locator = $container->getDefinition((string) $locator['foo:fooAction']->getValues()[0]);
$this->assertSame(ServiceLocator::class, $locator->getClass());
$this->assertFalse($locator->isPublic());
$expected = array('bar' => new ServiceClosureArgument(new TypedReference(ControllerDummy::class, ControllerDummy::class, RegisterTestController::class, ContainerInterface::IGNORE_ON_INVALID_REFERENCE)));
$this->assertEquals($expected, $locator->getArgument(0));
}
public function testExplicitArgument()
{
$container = new ContainerBuilder();
$resolver = $container->register('argument_resolver.service')->addArgument(array());
$container->register('foo', RegisterTestController::class)
->addTag('controller.service_arguments', array('action' => 'fooAction', 'argument' => 'bar', 'id' => 'bar'))
->addTag('controller.service_arguments', array('action' => 'fooAction', 'argument' => 'bar', 'id' => 'baz')) // should be ignored, the first wins
;
$pass = new RegisterControllerArgumentLocatorsPass();
$pass->process($container);
$locator = $container->getDefinition((string) $resolver->getArgument(0))->getArgument(0);
$locator = $container->getDefinition((string) $locator['foo:fooAction']->getValues()[0]);
$expected = array('bar' => new ServiceClosureArgument(new TypedReference('bar', ControllerDummy::class, RegisterTestController::class)));
$this->assertEquals($expected, $locator->getArgument(0));
}
public function testOptionalArgument()
{
$container = new ContainerBuilder();
$resolver = $container->register('argument_resolver.service')->addArgument(array());
$container->register('foo', RegisterTestController::class)
->addTag('controller.service_arguments', array('action' => 'fooAction', 'argument' => 'bar', 'id' => '?bar'))
;
$pass = new RegisterControllerArgumentLocatorsPass();
$pass->process($container);
$locator = $container->getDefinition((string) $resolver->getArgument(0))->getArgument(0);
$locator = $container->getDefinition((string) $locator['foo:fooAction']->getValues()[0]);
$expected = array('bar' => new ServiceClosureArgument(new TypedReference('bar', ControllerDummy::class, RegisterTestController::class, ContainerInterface::IGNORE_ON_INVALID_REFERENCE)));
$this->assertEquals($expected, $locator->getArgument(0));
}
public function testSkipSetContainer()
{
$container = new ContainerBuilder();
$resolver = $container->register('argument_resolver.service')->addArgument(array());
$container->register('foo', ContainerAwareRegisterTestController::class)
->addTag('controller.service_arguments');
$pass = new RegisterControllerArgumentLocatorsPass();
$pass->process($container);
$locator = $container->getDefinition((string) $resolver->getArgument(0))->getArgument(0);
$this->assertSame(array('foo:fooAction'), array_keys($locator));
}
/**
* @expectedException \Symfony\Component\DependencyInjection\Exception\InvalidArgumentException
* @expectedExceptionMessage Cannot determine controller argument for "Symfony\Component\HttpKernel\Tests\DependencyInjection\NonExistentClassController::fooAction()": the $nonExistent argument is type-hinted with the non-existent class or interface: "Symfony\Component\HttpKernel\Tests\DependencyInjection\NonExistentClass". Did you forget to add a use statement?
*/
public function testExceptionOnNonExistentTypeHint()
{
$container = new ContainerBuilder();
$container->register('argument_resolver.service')->addArgument(array());
$container->register('foo', NonExistentClassController::class)
->addTag('controller.service_arguments');
$pass = new RegisterControllerArgumentLocatorsPass();
$pass->process($container);
}
/**
* @expectedException \Symfony\Component\DependencyInjection\Exception\InvalidArgumentException
* @expectedExceptionMessage Cannot determine controller argument for "Symfony\Component\HttpKernel\Tests\DependencyInjection\NonExistentClassDifferentNamespaceController::fooAction()": the $nonExistent argument is type-hinted with the non-existent class or interface: "Acme\NonExistentClass".
*/
public function testExceptionOnNonExistentTypeHintDifferentNamespace()
{
$container = new ContainerBuilder();
$container->register('argument_resolver.service')->addArgument(array());
$container->register('foo', NonExistentClassDifferentNamespaceController::class)
->addTag('controller.service_arguments');
$pass = new RegisterControllerArgumentLocatorsPass();
$pass->process($container);
}
public function testNoExceptionOnNonExistentTypeHintOptionalArg()
{
$container = new ContainerBuilder();
$resolver = $container->register('argument_resolver.service')->addArgument(array());
$container->register('foo', NonExistentClassOptionalController::class)
->addTag('controller.service_arguments');
$pass = new RegisterControllerArgumentLocatorsPass();
$pass->process($container);
$locator = $container->getDefinition((string) $resolver->getArgument(0))->getArgument(0);
$this->assertSame(array('foo:barAction', 'foo:fooAction'), array_keys($locator));
}
public function testArgumentWithNoTypeHintIsOk()
{
$container = new ContainerBuilder();
$resolver = $container->register('argument_resolver.service')->addArgument(array());
$container->register('foo', ArgumentWithoutTypeController::class)
->addTag('controller.service_arguments');
$pass = new RegisterControllerArgumentLocatorsPass();
$pass->process($container);
$locator = $container->getDefinition((string) $resolver->getArgument(0))->getArgument(0);
$this->assertEmpty(array_keys($locator));
}
public function testControllersAreMadePublic()
{
$container = new ContainerBuilder();
$resolver = $container->register('argument_resolver.service')->addArgument(array());
$container->register('foo', ArgumentWithoutTypeController::class)
->setPublic(false)
->addTag('controller.service_arguments');
$pass = new RegisterControllerArgumentLocatorsPass();
$pass->process($container);
$this->assertTrue($container->getDefinition('foo')->isPublic());
}
}
class RegisterTestController
{
public function __construct(ControllerDummy $bar)
{
}
public function fooAction(ControllerDummy $bar)
{
}
protected function barAction(ControllerDummy $bar)
{
}
}
class ContainerAwareRegisterTestController implements ContainerAwareInterface
{
use ContainerAwareTrait;
public function fooAction(ControllerDummy $bar)
{
}
}
class ControllerDummy
{
}
class NonExistentClassController
{
public function fooAction(NonExistentClass $nonExistent)
{
}
}
class NonExistentClassDifferentNamespaceController
{
public function fooAction(\Acme\NonExistentClass $nonExistent)
{
}
}
class NonExistentClassOptionalController
{
public function fooAction(NonExistentClass $nonExistent = null)
{
}
public function barAction(NonExistentClass $nonExistent = null, $bar)
{
}
}
class ArgumentWithoutTypeController
{
public function fooAction($someArg)
{
}
}

View File

@@ -0,0 +1,148 @@
<?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\Tests\DependencyInjection;
use PHPUnit\Framework\TestCase;
use Symfony\Component\DependencyInjection\Compiler\ResolveInvalidReferencesPass;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Reference;
use Symfony\Component\HttpKernel\DependencyInjection\RegisterControllerArgumentLocatorsPass;
use Symfony\Component\HttpKernel\DependencyInjection\RemoveEmptyControllerArgumentLocatorsPass;
class RemoveEmptyControllerArgumentLocatorsPassTest extends TestCase
{
public function testProcess()
{
$container = new ContainerBuilder();
$resolver = $container->register('argument_resolver.service')->addArgument(array());
$container->register('stdClass', 'stdClass');
$container->register(parent::class, 'stdClass');
$container->register('c1', RemoveTestController1::class)->addTag('controller.service_arguments');
$container->register('c2', RemoveTestController2::class)->addTag('controller.service_arguments')
->addMethodCall('setTestCase', array(new Reference('c1')));
$pass = new RegisterControllerArgumentLocatorsPass();
$pass->process($container);
$controllers = $container->getDefinition((string) $resolver->getArgument(0))->getArgument(0);
$this->assertCount(2, $container->getDefinition((string) $controllers['c1:fooAction']->getValues()[0])->getArgument(0));
$this->assertCount(1, $container->getDefinition((string) $controllers['c2:setTestCase']->getValues()[0])->getArgument(0));
$this->assertCount(1, $container->getDefinition((string) $controllers['c2:fooAction']->getValues()[0])->getArgument(0));
(new ResolveInvalidReferencesPass())->process($container);
$this->assertCount(1, $container->getDefinition((string) $controllers['c2:setTestCase']->getValues()[0])->getArgument(0));
$this->assertSame(array(), $container->getDefinition((string) $controllers['c2:fooAction']->getValues()[0])->getArgument(0));
(new RemoveEmptyControllerArgumentLocatorsPass())->process($container);
$controllers = $container->getDefinition((string) $resolver->getArgument(0))->getArgument(0);
$this->assertSame(array('c1:fooAction'), array_keys($controllers));
$this->assertSame(array('bar'), array_keys($container->getDefinition((string) $controllers['c1:fooAction']->getValues()[0])->getArgument(0)));
$expectedLog = array(
'Symfony\Component\HttpKernel\DependencyInjection\RemoveEmptyControllerArgumentLocatorsPass: Removing service-argument resolver for controller "c2:fooAction": no corresponding services exist for the referenced types.',
'Symfony\Component\HttpKernel\DependencyInjection\RemoveEmptyControllerArgumentLocatorsPass: Removing method "setTestCase" of service "c2" from controller candidates: the method is called at instantiation, thus cannot be an action.',
);
$this->assertSame($expectedLog, $container->getCompiler()->getLog());
}
public function testSameIdClass()
{
$container = new ContainerBuilder();
$resolver = $container->register('argument_resolver.service')->addArgument(array());
$container->register(RegisterTestController::class, RegisterTestController::class)
->addTag('controller.service_arguments')
;
(new RegisterControllerArgumentLocatorsPass())->process($container);
(new RemoveEmptyControllerArgumentLocatorsPass())->process($container);
$expected = array(
RegisterTestController::class.':fooAction',
RegisterTestController::class.'::fooAction',
);
$this->assertEquals($expected, array_keys($container->getDefinition((string) $resolver->getArgument(0))->getArgument(0)));
}
public function testInvoke()
{
$container = new ContainerBuilder();
$resolver = $container->register('argument_resolver.service')->addArgument(array());
$container->register('invokable', InvokableRegisterTestController::class)
->addTag('controller.service_arguments')
;
(new RegisterControllerArgumentLocatorsPass())->process($container);
(new RemoveEmptyControllerArgumentLocatorsPass())->process($container);
$this->assertEquals(
array('invokable:__invoke', 'invokable'),
array_keys($container->getDefinition((string) $resolver->getArgument(0))->getArgument(0))
);
}
public function testInvokeSameIdClass()
{
$container = new ContainerBuilder();
$resolver = $container->register('argument_resolver.service')->addArgument(array());
$container->register(InvokableRegisterTestController::class, InvokableRegisterTestController::class)
->addTag('controller.service_arguments')
;
(new RegisterControllerArgumentLocatorsPass())->process($container);
(new RemoveEmptyControllerArgumentLocatorsPass())->process($container);
$expected = array(
InvokableRegisterTestController::class.':__invoke',
InvokableRegisterTestController::class.'::__invoke',
InvokableRegisterTestController::class,
);
$this->assertEquals($expected, array_keys($container->getDefinition((string) $resolver->getArgument(0))->getArgument(0)));
}
}
class RemoveTestController1
{
public function fooAction(\stdClass $bar, ClassNotInContainer $baz)
{
}
}
class RemoveTestController2
{
public function setTestCase(TestCase $test)
{
}
public function fooAction(ClassNotInContainer $bar)
{
}
}
class InvokableRegisterTestController
{
public function __invoke(\stdClass $bar)
{
}
}
class ClassNotInContainer
{
}

View File

@@ -0,0 +1,27 @@
<?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\Tests\Event;
use PHPUnit\Framework\TestCase;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Event\GetResponseForExceptionEvent;
use Symfony\Component\HttpKernel\Tests\TestHttpKernel;
class GetResponseForExceptionEventTest extends TestCase
{
public function testAllowSuccessfulResponseIsFalseByDefault()
{
$event = new GetResponseForExceptionEvent(new TestHttpKernel(), new Request(), 1, new \Exception());
$this->assertFalse($event->isAllowingCustomResponseCode());
}
}

View File

@@ -0,0 +1,84 @@
<?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\Tests\EventListener;
use PHPUnit\Framework\TestCase;
use Symfony\Component\HttpKernel\EventListener\AddRequestFormatsListener;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\KernelEvents;
/**
* Test AddRequestFormatsListener class.
*
* @author Gildas Quemener <gildas.quemener@gmail.com>
*/
class AddRequestFormatsListenerTest extends TestCase
{
/**
* @var AddRequestFormatsListener
*/
private $listener;
protected function setUp()
{
$this->listener = new AddRequestFormatsListener(array('csv' => array('text/csv', 'text/plain')));
}
protected function tearDown()
{
$this->listener = null;
}
public function testIsAnEventSubscriber()
{
$this->assertInstanceOf('Symfony\Component\EventDispatcher\EventSubscriberInterface', $this->listener);
}
public function testRegisteredEvent()
{
$this->assertEquals(
array(KernelEvents::REQUEST => array('onKernelRequest', 1)),
AddRequestFormatsListener::getSubscribedEvents()
);
}
public function testSetAdditionalFormats()
{
$request = $this->getRequestMock();
$event = $this->getGetResponseEventMock($request);
$request->expects($this->once())
->method('setFormat')
->with('csv', array('text/csv', 'text/plain'));
$this->listener->onKernelRequest($event);
}
protected function getRequestMock()
{
return $this->getMockBuilder('Symfony\Component\HttpFoundation\Request')->getMock();
}
protected function getGetResponseEventMock(Request $request)
{
$event = $this
->getMockBuilder('Symfony\Component\HttpKernel\Event\GetResponseEvent')
->disableOriginalConstructor()
->getMock();
$event->expects($this->any())
->method('getRequest')
->will($this->returnValue($request));
return $event;
}
}

View File

@@ -0,0 +1,135 @@
<?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\Tests\EventListener;
use PHPUnit\Framework\TestCase;
use Psr\Log\LogLevel;
use Symfony\Component\Console\Event\ConsoleEvent;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\ConsoleEvents;
use Symfony\Component\Console\Helper\HelperSet;
use Symfony\Component\Console\Input\ArgvInput;
use Symfony\Component\Console\Output\ConsoleOutput;
use Symfony\Component\Debug\ErrorHandler;
use Symfony\Component\Debug\ExceptionHandler;
use Symfony\Component\EventDispatcher\EventDispatcher;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Event\KernelEvent;
use Symfony\Component\HttpKernel\EventListener\DebugHandlersListener;
use Symfony\Component\HttpKernel\HttpKernelInterface;
use Symfony\Component\HttpKernel\KernelEvents;
/**
* DebugHandlersListenerTest.
*
* @author Nicolas Grekas <p@tchwork.com>
*/
class DebugHandlersListenerTest extends TestCase
{
public function testConfigure()
{
$logger = $this->getMockBuilder('Psr\Log\LoggerInterface')->getMock();
$userHandler = function () {};
$listener = new DebugHandlersListener($userHandler, $logger);
$xHandler = new ExceptionHandler();
$eHandler = new ErrorHandler();
$eHandler->setExceptionHandler(array($xHandler, 'handle'));
$exception = null;
set_error_handler(array($eHandler, 'handleError'));
set_exception_handler(array($eHandler, 'handleException'));
try {
$listener->configure();
} catch (\Exception $exception) {
}
restore_exception_handler();
restore_error_handler();
if (null !== $exception) {
throw $exception;
}
$this->assertSame($userHandler, $xHandler->setHandler('var_dump'));
$loggers = $eHandler->setLoggers(array());
$this->assertArrayHasKey(E_DEPRECATED, $loggers);
$this->assertSame(array($logger, LogLevel::INFO), $loggers[E_DEPRECATED]);
}
public function testConfigureForHttpKernelWithNoTerminateWithException()
{
$listener = new DebugHandlersListener(null);
$eHandler = new ErrorHandler();
$event = new KernelEvent(
$this->getMockBuilder('Symfony\Component\HttpKernel\HttpKernelInterface')->getMock(),
Request::create('/'),
HttpKernelInterface::MASTER_REQUEST
);
$exception = null;
$h = set_exception_handler(array($eHandler, 'handleException'));
try {
$listener->configure($event);
} catch (\Exception $exception) {
}
restore_exception_handler();
if (null !== $exception) {
throw $exception;
}
$this->assertNull($h);
}
public function testConsoleEvent()
{
$dispatcher = new EventDispatcher();
$listener = new DebugHandlersListener(null);
$app = $this->getMockBuilder('Symfony\Component\Console\Application')->getMock();
$app->expects($this->once())->method('getHelperSet')->will($this->returnValue(new HelperSet()));
$command = new Command(__FUNCTION__);
$command->setApplication($app);
$event = new ConsoleEvent($command, new ArgvInput(), new ConsoleOutput());
$dispatcher->addSubscriber($listener);
$xListeners = array(
KernelEvents::REQUEST => array(array($listener, 'configure')),
ConsoleEvents::COMMAND => array(array($listener, 'configure')),
);
$this->assertSame($xListeners, $dispatcher->getListeners());
$exception = null;
$eHandler = new ErrorHandler();
set_error_handler(array($eHandler, 'handleError'));
set_exception_handler(array($eHandler, 'handleException'));
try {
$dispatcher->dispatch(ConsoleEvents::COMMAND, $event);
} catch (\Exception $exception) {
}
restore_exception_handler();
restore_error_handler();
if (null !== $exception) {
throw $exception;
}
$xHandler = $eHandler->setExceptionHandler('var_dump');
$this->assertInstanceOf('Closure', $xHandler);
$app->expects($this->once())
->method('renderException');
$xHandler(new \Exception());
}
}

View File

@@ -0,0 +1,81 @@
<?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\Tests\EventListener;
use PHPUnit\Framework\TestCase;
use Symfony\Component\Console\ConsoleEvents;
use Symfony\Component\HttpKernel\EventListener\DumpListener;
use Symfony\Component\VarDumper\Cloner\ClonerInterface;
use Symfony\Component\VarDumper\Cloner\Data;
use Symfony\Component\VarDumper\Dumper\DataDumperInterface;
use Symfony\Component\VarDumper\VarDumper;
/**
* DumpListenerTest.
*
* @author Nicolas Grekas <p@tchwork.com>
*/
class DumpListenerTest extends TestCase
{
public function testSubscribedEvents()
{
$this->assertSame(
array(ConsoleEvents::COMMAND => array('configure', 1024)),
DumpListener::getSubscribedEvents()
);
}
public function testConfigure()
{
$prevDumper = VarDumper::setHandler('var_dump');
VarDumper::setHandler($prevDumper);
$cloner = new MockCloner();
$dumper = new MockDumper();
ob_start();
$exception = null;
$listener = new DumpListener($cloner, $dumper);
try {
$listener->configure();
VarDumper::dump('foo');
VarDumper::dump('bar');
$this->assertSame('+foo-+bar-', ob_get_clean());
} catch (\Exception $exception) {
}
VarDumper::setHandler($prevDumper);
if (null !== $exception) {
throw $exception;
}
}
}
class MockCloner implements ClonerInterface
{
public function cloneVar($var)
{
return new Data(array(array($var.'-')));
}
}
class MockDumper implements DataDumperInterface
{
public function dump(Data $data)
{
echo '+'.$data->getValue();
}
}

View File

@@ -0,0 +1,149 @@
<?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\Tests\EventListener;
use PHPUnit\Framework\TestCase;
use Symfony\Component\HttpKernel\HttpKernelInterface;
use Symfony\Component\HttpKernel\EventListener\ExceptionListener;
use Symfony\Component\HttpKernel\Log\DebugLoggerInterface;
use Symfony\Component\HttpKernel\Event\GetResponseForExceptionEvent;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Tests\Logger;
/**
* ExceptionListenerTest.
*
* @author Robert Schönthal <seroscho@googlemail.com>
*
* @group time-sensitive
*/
class ExceptionListenerTest extends TestCase
{
public function testConstruct()
{
$logger = new TestLogger();
$l = new ExceptionListener('foo', $logger);
$_logger = new \ReflectionProperty(get_class($l), 'logger');
$_logger->setAccessible(true);
$_controller = new \ReflectionProperty(get_class($l), 'controller');
$_controller->setAccessible(true);
$this->assertSame($logger, $_logger->getValue($l));
$this->assertSame('foo', $_controller->getValue($l));
}
/**
* @dataProvider provider
*/
public function testHandleWithoutLogger($event, $event2)
{
$this->iniSet('error_log', file_exists('/dev/null') ? '/dev/null' : 'nul');
$l = new ExceptionListener('foo');
$l->onKernelException($event);
$this->assertEquals(new Response('foo'), $event->getResponse());
try {
$l->onKernelException($event2);
$this->fail('RuntimeException expected');
} catch (\RuntimeException $e) {
$this->assertSame('bar', $e->getMessage());
$this->assertSame('foo', $e->getPrevious()->getMessage());
}
}
/**
* @dataProvider provider
*/
public function testHandleWithLogger($event, $event2)
{
$logger = new TestLogger();
$l = new ExceptionListener('foo', $logger);
$l->onKernelException($event);
$this->assertEquals(new Response('foo'), $event->getResponse());
try {
$l->onKernelException($event2);
$this->fail('RuntimeException expected');
} catch (\RuntimeException $e) {
$this->assertSame('bar', $e->getMessage());
$this->assertSame('foo', $e->getPrevious()->getMessage());
}
$this->assertEquals(3, $logger->countErrors());
$this->assertCount(3, $logger->getLogs('critical'));
}
public function provider()
{
if (!class_exists('Symfony\Component\HttpFoundation\Request')) {
return array(array(null, null));
}
$request = new Request();
$exception = new \Exception('foo');
$event = new GetResponseForExceptionEvent(new TestKernel(), $request, 'foo', $exception);
$event2 = new GetResponseForExceptionEvent(new TestKernelThatThrowsException(), $request, 'foo', $exception);
return array(
array($event, $event2),
);
}
public function testSubRequestFormat()
{
$listener = new ExceptionListener('foo', $this->getMockBuilder('Psr\Log\LoggerInterface')->getMock());
$kernel = $this->getMockBuilder('Symfony\Component\HttpKernel\HttpKernelInterface')->getMock();
$kernel->expects($this->once())->method('handle')->will($this->returnCallback(function (Request $request) {
return new Response($request->getRequestFormat());
}));
$request = Request::create('/');
$request->setRequestFormat('xml');
$event = new GetResponseForExceptionEvent($kernel, $request, 'foo', new \Exception('foo'));
$listener->onKernelException($event);
$response = $event->getResponse();
$this->assertEquals('xml', $response->getContent());
}
}
class TestLogger extends Logger implements DebugLoggerInterface
{
public function countErrors()
{
return count($this->logs['critical']);
}
}
class TestKernel implements HttpKernelInterface
{
public function handle(Request $request, $type = self::MASTER_REQUEST, $catch = true)
{
return new Response('foo');
}
}
class TestKernelThatThrowsException implements HttpKernelInterface
{
public function handle(Request $request, $type = self::MASTER_REQUEST, $catch = true)
{
throw new \RuntimeException('bar');
}
}

View File

@@ -0,0 +1,122 @@
<?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\Tests\EventListener;
use PHPUnit\Framework\TestCase;
use Symfony\Component\HttpKernel\EventListener\FragmentListener;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\HttpKernelInterface;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\HttpKernel\UriSigner;
class FragmentListenerTest extends TestCase
{
public function testOnlyTriggeredOnFragmentRoute()
{
$request = Request::create('http://example.com/foo?_path=foo%3Dbar%26_controller%3Dfoo');
$listener = new FragmentListener(new UriSigner('foo'));
$event = $this->createGetResponseEvent($request);
$expected = $request->attributes->all();
$listener->onKernelRequest($event);
$this->assertEquals($expected, $request->attributes->all());
$this->assertTrue($request->query->has('_path'));
}
public function testOnlyTriggeredIfControllerWasNotDefinedYet()
{
$request = Request::create('http://example.com/_fragment?_path=foo%3Dbar%26_controller%3Dfoo');
$request->attributes->set('_controller', 'bar');
$listener = new FragmentListener(new UriSigner('foo'));
$event = $this->createGetResponseEvent($request, HttpKernelInterface::SUB_REQUEST);
$expected = $request->attributes->all();
$listener->onKernelRequest($event);
$this->assertEquals($expected, $request->attributes->all());
}
/**
* @expectedException \Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException
*/
public function testAccessDeniedWithNonSafeMethods()
{
$request = Request::create('http://example.com/_fragment', 'POST');
$listener = new FragmentListener(new UriSigner('foo'));
$event = $this->createGetResponseEvent($request);
$listener->onKernelRequest($event);
}
/**
* @expectedException \Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException
*/
public function testAccessDeniedWithWrongSignature()
{
$request = Request::create('http://example.com/_fragment', 'GET', array(), array(), array(), array('REMOTE_ADDR' => '10.0.0.1'));
$listener = new FragmentListener(new UriSigner('foo'));
$event = $this->createGetResponseEvent($request);
$listener->onKernelRequest($event);
}
public function testWithSignature()
{
$signer = new UriSigner('foo');
$request = Request::create($signer->sign('http://example.com/_fragment?_path=foo%3Dbar%26_controller%3Dfoo'), 'GET', array(), array(), array(), array('REMOTE_ADDR' => '10.0.0.1'));
$listener = new FragmentListener($signer);
$event = $this->createGetResponseEvent($request);
$listener->onKernelRequest($event);
$this->assertEquals(array('foo' => 'bar', '_controller' => 'foo'), $request->attributes->get('_route_params'));
$this->assertFalse($request->query->has('_path'));
}
public function testRemovesPathWithControllerDefined()
{
$request = Request::create('http://example.com/_fragment?_path=foo%3Dbar%26_controller%3Dfoo');
$listener = new FragmentListener(new UriSigner('foo'));
$event = $this->createGetResponseEvent($request, HttpKernelInterface::SUB_REQUEST);
$listener->onKernelRequest($event);
$this->assertFalse($request->query->has('_path'));
}
public function testRemovesPathWithControllerNotDefined()
{
$signer = new UriSigner('foo');
$request = Request::create($signer->sign('http://example.com/_fragment?_path=foo%3Dbar'), 'GET', array(), array(), array(), array('REMOTE_ADDR' => '10.0.0.1'));
$listener = new FragmentListener($signer);
$event = $this->createGetResponseEvent($request);
$listener->onKernelRequest($event);
$this->assertFalse($request->query->has('_path'));
}
private function createGetResponseEvent(Request $request, $requestType = HttpKernelInterface::MASTER_REQUEST)
{
return new GetResponseEvent($this->getMockBuilder('Symfony\Component\HttpKernel\HttpKernelInterface')->getMock(), $request, $requestType);
}
}

View File

@@ -0,0 +1,103 @@
<?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\Tests\EventListener;
use PHPUnit\Framework\TestCase;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\EventListener\LocaleListener;
use Symfony\Component\HttpKernel\HttpKernelInterface;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
class LocaleListenerTest extends TestCase
{
private $requestStack;
protected function setUp()
{
$this->requestStack = $this->getMockBuilder('Symfony\Component\HttpFoundation\RequestStack')->disableOriginalConstructor()->getMock();
}
public function testDefaultLocaleWithoutSession()
{
$listener = new LocaleListener($this->requestStack, 'fr');
$event = $this->getEvent($request = Request::create('/'));
$listener->onKernelRequest($event);
$this->assertEquals('fr', $request->getLocale());
}
public function testLocaleFromRequestAttribute()
{
$request = Request::create('/');
session_name('foo');
$request->cookies->set('foo', 'value');
$request->attributes->set('_locale', 'es');
$listener = new LocaleListener($this->requestStack, 'fr');
$event = $this->getEvent($request);
$listener->onKernelRequest($event);
$this->assertEquals('es', $request->getLocale());
}
public function testLocaleSetForRoutingContext()
{
// the request context is updated
$context = $this->getMockBuilder('Symfony\Component\Routing\RequestContext')->getMock();
$context->expects($this->once())->method('setParameter')->with('_locale', 'es');
$router = $this->getMockBuilder('Symfony\Component\Routing\Router')->setMethods(array('getContext'))->disableOriginalConstructor()->getMock();
$router->expects($this->once())->method('getContext')->will($this->returnValue($context));
$request = Request::create('/');
$request->attributes->set('_locale', 'es');
$listener = new LocaleListener($this->requestStack, 'fr', $router);
$listener->onKernelRequest($this->getEvent($request));
}
public function testRouterResetWithParentRequestOnKernelFinishRequest()
{
// the request context is updated
$context = $this->getMockBuilder('Symfony\Component\Routing\RequestContext')->getMock();
$context->expects($this->once())->method('setParameter')->with('_locale', 'es');
$router = $this->getMockBuilder('Symfony\Component\Routing\Router')->setMethods(array('getContext'))->disableOriginalConstructor()->getMock();
$router->expects($this->once())->method('getContext')->will($this->returnValue($context));
$parentRequest = Request::create('/');
$parentRequest->setLocale('es');
$this->requestStack->expects($this->once())->method('getParentRequest')->will($this->returnValue($parentRequest));
$event = $this->getMockBuilder('Symfony\Component\HttpKernel\Event\FinishRequestEvent')->disableOriginalConstructor()->getMock();
$listener = new LocaleListener($this->requestStack, 'fr', $router);
$listener->onKernelFinishRequest($event);
}
public function testRequestLocaleIsNotOverridden()
{
$request = Request::create('/');
$request->setLocale('de');
$listener = new LocaleListener($this->requestStack, 'fr');
$event = $this->getEvent($request);
$listener->onKernelRequest($event);
$this->assertEquals('de', $request->getLocale());
}
private function getEvent(Request $request)
{
return new GetResponseEvent($this->getMockBuilder('Symfony\Component\HttpKernel\HttpKernelInterface')->getMock(), $request, HttpKernelInterface::MASTER_REQUEST);
}
}

View File

@@ -0,0 +1,71 @@
<?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\Tests\EventListener;
use PHPUnit\Framework\TestCase;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\HttpKernel\EventListener\ProfilerListener;
use Symfony\Component\HttpKernel\Event\FilterResponseEvent;
use Symfony\Component\HttpKernel\Event\GetResponseForExceptionEvent;
use Symfony\Component\HttpKernel\Event\PostResponseEvent;
use Symfony\Component\HttpKernel\Exception\HttpException;
use Symfony\Component\HttpKernel\Kernel;
class ProfilerListenerTest extends TestCase
{
/**
* Test a master and sub request with an exception and `onlyException` profiler option enabled.
*/
public function testKernelTerminate()
{
$profile = $this->getMockBuilder('Symfony\Component\HttpKernel\Profiler\Profile')
->disableOriginalConstructor()
->getMock();
$profiler = $this->getMockBuilder('Symfony\Component\HttpKernel\Profiler\Profiler')
->disableOriginalConstructor()
->getMock();
$profiler->expects($this->once())
->method('collect')
->will($this->returnValue($profile));
$kernel = $this->getMockBuilder('Symfony\Component\HttpKernel\HttpKernelInterface')->getMock();
$masterRequest = $this->getMockBuilder('Symfony\Component\HttpFoundation\Request')
->disableOriginalConstructor()
->getMock();
$subRequest = $this->getMockBuilder('Symfony\Component\HttpFoundation\Request')
->disableOriginalConstructor()
->getMock();
$response = $this->getMockBuilder('Symfony\Component\HttpFoundation\Response')
->disableOriginalConstructor()
->getMock();
$requestStack = new RequestStack();
$requestStack->push($masterRequest);
$onlyException = true;
$listener = new ProfilerListener($profiler, $requestStack, null, $onlyException);
// master request
$listener->onKernelResponse(new FilterResponseEvent($kernel, $masterRequest, Kernel::MASTER_REQUEST, $response));
// sub request
$listener->onKernelException(new GetResponseForExceptionEvent($kernel, $subRequest, Kernel::SUB_REQUEST, new HttpException(404)));
$listener->onKernelResponse(new FilterResponseEvent($kernel, $subRequest, Kernel::SUB_REQUEST, $response));
$listener->onKernelTerminate(new PostResponseEvent($kernel, $masterRequest, $response));
}
}

View File

@@ -0,0 +1,95 @@
<?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\Tests\EventListener;
use PHPUnit\Framework\TestCase;
use Symfony\Component\HttpKernel\EventListener\ResponseListener;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\HttpKernelInterface;
use Symfony\Component\HttpKernel\Event\FilterResponseEvent;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\EventDispatcher\EventDispatcher;
class ResponseListenerTest extends TestCase
{
private $dispatcher;
private $kernel;
protected function setUp()
{
$this->dispatcher = new EventDispatcher();
$listener = new ResponseListener('UTF-8');
$this->dispatcher->addListener(KernelEvents::RESPONSE, array($listener, 'onKernelResponse'));
$this->kernel = $this->getMockBuilder('Symfony\Component\HttpKernel\HttpKernelInterface')->getMock();
}
protected function tearDown()
{
$this->dispatcher = null;
$this->kernel = null;
}
public function testFilterDoesNothingForSubRequests()
{
$response = new Response('foo');
$event = new FilterResponseEvent($this->kernel, new Request(), HttpKernelInterface::SUB_REQUEST, $response);
$this->dispatcher->dispatch(KernelEvents::RESPONSE, $event);
$this->assertEquals('', $event->getResponse()->headers->get('content-type'));
}
public function testFilterSetsNonDefaultCharsetIfNotOverridden()
{
$listener = new ResponseListener('ISO-8859-15');
$this->dispatcher->addListener(KernelEvents::RESPONSE, array($listener, 'onKernelResponse'), 1);
$response = new Response('foo');
$event = new FilterResponseEvent($this->kernel, Request::create('/'), HttpKernelInterface::MASTER_REQUEST, $response);
$this->dispatcher->dispatch(KernelEvents::RESPONSE, $event);
$this->assertEquals('ISO-8859-15', $response->getCharset());
}
public function testFilterDoesNothingIfCharsetIsOverridden()
{
$listener = new ResponseListener('ISO-8859-15');
$this->dispatcher->addListener(KernelEvents::RESPONSE, array($listener, 'onKernelResponse'), 1);
$response = new Response('foo');
$response->setCharset('ISO-8859-1');
$event = new FilterResponseEvent($this->kernel, Request::create('/'), HttpKernelInterface::MASTER_REQUEST, $response);
$this->dispatcher->dispatch(KernelEvents::RESPONSE, $event);
$this->assertEquals('ISO-8859-1', $response->getCharset());
}
public function testFiltersSetsNonDefaultCharsetIfNotOverriddenOnNonTextContentType()
{
$listener = new ResponseListener('ISO-8859-15');
$this->dispatcher->addListener(KernelEvents::RESPONSE, array($listener, 'onKernelResponse'), 1);
$response = new Response('foo');
$request = Request::create('/');
$request->setRequestFormat('application/json');
$event = new FilterResponseEvent($this->kernel, $request, HttpKernelInterface::MASTER_REQUEST, $response);
$this->dispatcher->dispatch(KernelEvents::RESPONSE, $event);
$this->assertEquals('ISO-8859-15', $response->getCharset());
}
}

View File

@@ -0,0 +1,188 @@
<?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\Tests\EventListener;
use PHPUnit\Framework\TestCase;
use Symfony\Component\EventDispatcher\EventDispatcher;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Controller\ArgumentResolver;
use Symfony\Component\HttpKernel\Controller\ControllerResolver;
use Symfony\Component\HttpKernel\EventListener\ExceptionListener;
use Symfony\Component\HttpKernel\EventListener\RouterListener;
use Symfony\Component\HttpKernel\EventListener\ValidateRequestListener;
use Symfony\Component\HttpKernel\HttpKernelInterface;
use Symfony\Component\HttpKernel\HttpKernel;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\Routing\RequestContext;
class RouterListenerTest extends TestCase
{
private $requestStack;
protected function setUp()
{
$this->requestStack = $this->getMockBuilder('Symfony\Component\HttpFoundation\RequestStack')->disableOriginalConstructor()->getMock();
}
/**
* @dataProvider getPortData
*/
public function testPort($defaultHttpPort, $defaultHttpsPort, $uri, $expectedHttpPort, $expectedHttpsPort)
{
$urlMatcher = $this->getMockBuilder('Symfony\Component\Routing\Matcher\UrlMatcherInterface')
->disableOriginalConstructor()
->getMock();
$context = new RequestContext();
$context->setHttpPort($defaultHttpPort);
$context->setHttpsPort($defaultHttpsPort);
$urlMatcher->expects($this->any())
->method('getContext')
->will($this->returnValue($context));
$listener = new RouterListener($urlMatcher, $this->requestStack);
$event = $this->createGetResponseEventForUri($uri);
$listener->onKernelRequest($event);
$this->assertEquals($expectedHttpPort, $context->getHttpPort());
$this->assertEquals($expectedHttpsPort, $context->getHttpsPort());
$this->assertEquals(0 === strpos($uri, 'https') ? 'https' : 'http', $context->getScheme());
}
public function getPortData()
{
return array(
array(80, 443, 'http://localhost/', 80, 443),
array(80, 443, 'http://localhost:90/', 90, 443),
array(80, 443, 'https://localhost/', 80, 443),
array(80, 443, 'https://localhost:90/', 80, 90),
);
}
/**
* @param string $uri
*
* @return GetResponseEvent
*/
private function createGetResponseEventForUri($uri)
{
$kernel = $this->getMockBuilder('Symfony\Component\HttpKernel\HttpKernelInterface')->getMock();
$request = Request::create($uri);
$request->attributes->set('_controller', null); // Prevents going in to routing process
return new GetResponseEvent($kernel, $request, HttpKernelInterface::MASTER_REQUEST);
}
/**
* @expectedException \InvalidArgumentException
*/
public function testInvalidMatcher()
{
new RouterListener(new \stdClass(), $this->requestStack);
}
public function testRequestMatcher()
{
$kernel = $this->getMockBuilder('Symfony\Component\HttpKernel\HttpKernelInterface')->getMock();
$request = Request::create('http://localhost/');
$event = new GetResponseEvent($kernel, $request, HttpKernelInterface::MASTER_REQUEST);
$requestMatcher = $this->getMockBuilder('Symfony\Component\Routing\Matcher\RequestMatcherInterface')->getMock();
$requestMatcher->expects($this->once())
->method('matchRequest')
->with($this->isInstanceOf('Symfony\Component\HttpFoundation\Request'))
->will($this->returnValue(array()));
$listener = new RouterListener($requestMatcher, $this->requestStack, new RequestContext());
$listener->onKernelRequest($event);
}
public function testSubRequestWithDifferentMethod()
{
$kernel = $this->getMockBuilder('Symfony\Component\HttpKernel\HttpKernelInterface')->getMock();
$request = Request::create('http://localhost/', 'post');
$event = new GetResponseEvent($kernel, $request, HttpKernelInterface::MASTER_REQUEST);
$requestMatcher = $this->getMockBuilder('Symfony\Component\Routing\Matcher\RequestMatcherInterface')->getMock();
$requestMatcher->expects($this->any())
->method('matchRequest')
->with($this->isInstanceOf('Symfony\Component\HttpFoundation\Request'))
->will($this->returnValue(array()));
$context = new RequestContext();
$listener = new RouterListener($requestMatcher, $this->requestStack, new RequestContext());
$listener->onKernelRequest($event);
// sub-request with another HTTP method
$kernel = $this->getMockBuilder('Symfony\Component\HttpKernel\HttpKernelInterface')->getMock();
$request = Request::create('http://localhost/', 'get');
$event = new GetResponseEvent($kernel, $request, HttpKernelInterface::SUB_REQUEST);
$listener->onKernelRequest($event);
$this->assertEquals('GET', $context->getMethod());
}
/**
* @dataProvider getLoggingParameterData
*/
public function testLoggingParameter($parameter, $log, $parameters)
{
$requestMatcher = $this->getMockBuilder('Symfony\Component\Routing\Matcher\RequestMatcherInterface')->getMock();
$requestMatcher->expects($this->once())
->method('matchRequest')
->will($this->returnValue($parameter));
$logger = $this->getMockBuilder('Psr\Log\LoggerInterface')->getMock();
$logger->expects($this->once())
->method('info')
->with($this->equalTo($log), $this->equalTo($parameters));
$kernel = $this->getMockBuilder('Symfony\Component\HttpKernel\HttpKernelInterface')->getMock();
$request = Request::create('http://localhost/');
$listener = new RouterListener($requestMatcher, $this->requestStack, new RequestContext(), $logger);
$listener->onKernelRequest(new GetResponseEvent($kernel, $request, HttpKernelInterface::MASTER_REQUEST));
}
public function getLoggingParameterData()
{
return array(
array(array('_route' => 'foo'), 'Matched route "{route}".', array('route' => 'foo', 'route_parameters' => array('_route' => 'foo'), 'request_uri' => 'http://localhost/', 'method' => 'GET')),
array(array(), 'Matched route "{route}".', array('route' => 'n/a', 'route_parameters' => array(), 'request_uri' => 'http://localhost/', 'method' => 'GET')),
);
}
public function testWithBadRequest()
{
$requestStack = new RequestStack();
$requestMatcher = $this->getMockBuilder('Symfony\Component\Routing\Matcher\RequestMatcherInterface')->getMock();
$requestMatcher->expects($this->never())->method('matchRequest');
$dispatcher = new EventDispatcher();
$dispatcher->addSubscriber(new ValidateRequestListener());
$dispatcher->addSubscriber(new RouterListener($requestMatcher, $requestStack, new RequestContext()));
$dispatcher->addSubscriber(new ExceptionListener(function () {
return new Response('Exception handled', 400);
}));
$kernel = new HttpKernel($dispatcher, new ControllerResolver(), $requestStack, new ArgumentResolver());
$request = Request::create('http://localhost/');
$request->headers->set('host', '###');
$response = $kernel->handle($request);
$this->assertSame(400, $response->getStatusCode());
}
}

View File

@@ -0,0 +1,67 @@
<?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\Tests\EventListener;
use PHPUnit\Framework\TestCase;
use Symfony\Component\HttpKernel\HttpCache\Esi;
use Symfony\Component\HttpKernel\EventListener\SurrogateListener;
use Symfony\Component\HttpKernel\Event\FilterResponseEvent;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\HttpKernel\HttpKernelInterface;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\EventDispatcher\EventDispatcher;
class SurrogateListenerTest extends TestCase
{
public function testFilterDoesNothingForSubRequests()
{
$dispatcher = new EventDispatcher();
$kernel = $this->getMockBuilder('Symfony\Component\HttpKernel\HttpKernelInterface')->getMock();
$response = new Response('foo <esi:include src="" />');
$listener = new SurrogateListener(new Esi());
$dispatcher->addListener(KernelEvents::RESPONSE, array($listener, 'onKernelResponse'));
$event = new FilterResponseEvent($kernel, new Request(), HttpKernelInterface::SUB_REQUEST, $response);
$dispatcher->dispatch(KernelEvents::RESPONSE, $event);
$this->assertEquals('', $event->getResponse()->headers->get('Surrogate-Control'));
}
public function testFilterWhenThereIsSomeEsiIncludes()
{
$dispatcher = new EventDispatcher();
$kernel = $this->getMockBuilder('Symfony\Component\HttpKernel\HttpKernelInterface')->getMock();
$response = new Response('foo <esi:include src="" />');
$listener = new SurrogateListener(new Esi());
$dispatcher->addListener(KernelEvents::RESPONSE, array($listener, 'onKernelResponse'));
$event = new FilterResponseEvent($kernel, new Request(), HttpKernelInterface::MASTER_REQUEST, $response);
$dispatcher->dispatch(KernelEvents::RESPONSE, $event);
$this->assertEquals('content="ESI/1.0"', $event->getResponse()->headers->get('Surrogate-Control'));
}
public function testFilterWhenThereIsNoEsiIncludes()
{
$dispatcher = new EventDispatcher();
$kernel = $this->getMockBuilder('Symfony\Component\HttpKernel\HttpKernelInterface')->getMock();
$response = new Response('foo');
$listener = new SurrogateListener(new Esi());
$dispatcher->addListener(KernelEvents::RESPONSE, array($listener, 'onKernelResponse'));
$event = new FilterResponseEvent($kernel, new Request(), HttpKernelInterface::MASTER_REQUEST, $response);
$dispatcher->dispatch(KernelEvents::RESPONSE, $event);
$this->assertEquals('', $event->getResponse()->headers->get('Surrogate-Control'));
}
}

View File

@@ -0,0 +1,145 @@
<?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\Tests\EventListener;
use PHPUnit\Framework\TestCase;
use Symfony\Component\DependencyInjection\ServiceSubscriberInterface;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\HttpKernelInterface;
use Symfony\Component\HttpKernel\Event\FilterResponseEvent;
use Symfony\Component\HttpKernel\EventListener\SessionListener;
use Symfony\Component\HttpKernel\EventListener\TestSessionListener;
use Symfony\Component\HttpFoundation\Session\SessionInterface;
/**
* SessionListenerTest.
*
* Tests SessionListener.
*
* @author Bulat Shakirzyanov <mallluhuct@gmail.com>
*/
class TestSessionListenerTest extends TestCase
{
/**
* @var TestSessionListener
*/
private $listener;
/**
* @var SessionInterface
*/
private $session;
protected function setUp()
{
$this->listener = $this->getMockForAbstractClass('Symfony\Component\HttpKernel\EventListener\AbstractTestSessionListener');
$this->session = $this->getSession();
}
public function testShouldSaveMasterRequestSession()
{
$this->sessionHasBeenStarted();
$this->sessionMustBeSaved();
$this->filterResponse(new Request());
}
public function testShouldNotSaveSubRequestSession()
{
$this->sessionMustNotBeSaved();
$this->filterResponse(new Request(), HttpKernelInterface::SUB_REQUEST);
}
public function testDoesNotDeleteCookieIfUsingSessionLifetime()
{
$this->sessionHasBeenStarted();
$params = session_get_cookie_params();
session_set_cookie_params(0, $params['path'], $params['domain'], $params['secure'], $params['httponly']);
$response = $this->filterResponse(new Request(), HttpKernelInterface::MASTER_REQUEST);
$cookies = $response->headers->getCookies();
$this->assertEquals(0, reset($cookies)->getExpiresTime());
}
public function testUnstartedSessionIsNotSave()
{
$this->sessionHasNotBeenStarted();
$this->sessionMustNotBeSaved();
$this->filterResponse(new Request());
}
public function testDoesNotImplementServiceSubscriberInterface()
{
$this->assertTrue(interface_exists(ServiceSubscriberInterface::class));
$this->assertTrue(class_exists(SessionListener::class));
$this->assertTrue(class_exists(TestSessionListener::class));
$this->assertFalse(is_subclass_of(SessionListener::class, ServiceSubscriberInterface::class), 'Implementing ServiceSubscriberInterface would create a dep on the DI component, which eg Silex cannot afford');
$this->assertFalse(is_subclass_of(TestSessionListener::class, ServiceSubscriberInterface::class, 'Implementing ServiceSubscriberInterface would create a dep on the DI component, which eg Silex cannot afford'));
}
private function filterResponse(Request $request, $type = HttpKernelInterface::MASTER_REQUEST)
{
$request->setSession($this->session);
$response = new Response();
$kernel = $this->getMockBuilder('Symfony\Component\HttpKernel\HttpKernelInterface')->getMock();
$event = new FilterResponseEvent($kernel, $request, $type, $response);
$this->listener->onKernelResponse($event);
$this->assertSame($response, $event->getResponse());
return $response;
}
private function sessionMustNotBeSaved()
{
$this->session->expects($this->never())
->method('save');
}
private function sessionMustBeSaved()
{
$this->session->expects($this->once())
->method('save');
}
private function sessionHasBeenStarted()
{
$this->session->expects($this->once())
->method('isStarted')
->will($this->returnValue(true));
}
private function sessionHasNotBeenStarted()
{
$this->session->expects($this->once())
->method('isStarted')
->will($this->returnValue(false));
}
private function getSession()
{
$mock = $this->getMockBuilder('Symfony\Component\HttpFoundation\Session\Session')
->disableOriginalConstructor()
->getMock();
// set return value for getName()
$mock->expects($this->any())->method('getName')->will($this->returnValue('MOCKSESSID'));
return $mock;
}
}

View File

@@ -0,0 +1,118 @@
<?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\Tests\EventListener;
use PHPUnit\Framework\TestCase;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Event\FinishRequestEvent;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\HttpKernel\EventListener\TranslatorListener;
use Symfony\Component\HttpKernel\HttpKernelInterface;
class TranslatorListenerTest extends TestCase
{
private $listener;
private $translator;
private $requestStack;
protected function setUp()
{
$this->translator = $this->getMockBuilder('Symfony\Component\Translation\TranslatorInterface')->getMock();
$this->requestStack = $this->getMockBuilder('Symfony\Component\HttpFoundation\RequestStack')->getMock();
$this->listener = new TranslatorListener($this->translator, $this->requestStack);
}
public function testLocaleIsSetInOnKernelRequest()
{
$this->translator
->expects($this->once())
->method('setLocale')
->with($this->equalTo('fr'));
$event = new GetResponseEvent($this->createHttpKernel(), $this->createRequest('fr'), HttpKernelInterface::MASTER_REQUEST);
$this->listener->onKernelRequest($event);
}
public function testDefaultLocaleIsUsedOnExceptionsInOnKernelRequest()
{
$this->translator
->expects($this->at(0))
->method('setLocale')
->will($this->throwException(new \InvalidArgumentException()));
$this->translator
->expects($this->at(1))
->method('setLocale')
->with($this->equalTo('en'));
$event = new GetResponseEvent($this->createHttpKernel(), $this->createRequest('fr'), HttpKernelInterface::MASTER_REQUEST);
$this->listener->onKernelRequest($event);
}
public function testLocaleIsSetInOnKernelFinishRequestWhenParentRequestExists()
{
$this->translator
->expects($this->once())
->method('setLocale')
->with($this->equalTo('fr'));
$this->setMasterRequest($this->createRequest('fr'));
$event = new FinishRequestEvent($this->createHttpKernel(), $this->createRequest('de'), HttpKernelInterface::SUB_REQUEST);
$this->listener->onKernelFinishRequest($event);
}
public function testLocaleIsNotSetInOnKernelFinishRequestWhenParentRequestDoesNotExist()
{
$this->translator
->expects($this->never())
->method('setLocale');
$event = new FinishRequestEvent($this->createHttpKernel(), $this->createRequest('de'), HttpKernelInterface::SUB_REQUEST);
$this->listener->onKernelFinishRequest($event);
}
public function testDefaultLocaleIsUsedOnExceptionsInOnKernelFinishRequest()
{
$this->translator
->expects($this->at(0))
->method('setLocale')
->will($this->throwException(new \InvalidArgumentException()));
$this->translator
->expects($this->at(1))
->method('setLocale')
->with($this->equalTo('en'));
$this->setMasterRequest($this->createRequest('fr'));
$event = new FinishRequestEvent($this->createHttpKernel(), $this->createRequest('de'), HttpKernelInterface::SUB_REQUEST);
$this->listener->onKernelFinishRequest($event);
}
private function createHttpKernel()
{
return $this->getMockBuilder('Symfony\Component\HttpKernel\HttpKernelInterface')->getMock();
}
private function createRequest($locale)
{
$request = new Request();
$request->setLocale($locale);
return $request;
}
private function setMasterRequest($request)
{
$this->requestStack
->expects($this->any())
->method('getParentRequest')
->will($this->returnValue($request));
}
}

View File

@@ -0,0 +1,43 @@
<?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\Tests\EventListener;
use PHPUnit\Framework\TestCase;
use Symfony\Component\EventDispatcher\EventDispatcher;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\EventListener\ValidateRequestListener;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\HttpKernel\HttpKernelInterface;
use Symfony\Component\HttpKernel\KernelEvents;
class ValidateRequestListenerTest extends TestCase
{
/**
* @expectedException \Symfony\Component\HttpFoundation\Exception\ConflictingHeadersException
*/
public function testListenerThrowsWhenMasterRequestHasInconsistentClientIps()
{
$dispatcher = new EventDispatcher();
$kernel = $this->getMockBuilder('Symfony\Component\HttpKernel\HttpKernelInterface')->getMock();
$request = new Request();
$request->setTrustedProxies(array('1.1.1.1'), Request::HEADER_X_FORWARDED_FOR | Request::HEADER_FORWARDED);
$request->server->set('REMOTE_ADDR', '1.1.1.1');
$request->headers->set('FORWARDED', 'for=2.2.2.2');
$request->headers->set('X_FORWARDED_FOR', '3.3.3.3');
$dispatcher->addListener(KernelEvents::REQUEST, array(new ValidateRequestListener(), 'onKernelRequest'));
$event = new GetResponseEvent($kernel, $request, HttpKernelInterface::MASTER_REQUEST);
$dispatcher->dispatch(KernelEvents::REQUEST, $event);
}
}

View File

@@ -0,0 +1,13 @@
<?php
namespace Symfony\Component\HttpKernel\Tests\Exception;
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
class AccessDeniedHttpExceptionTest extends HttpExceptionTest
{
protected function createException()
{
return new AccessDeniedHttpException();
}
}

View File

@@ -0,0 +1,13 @@
<?php
namespace Symfony\Component\HttpKernel\Tests\Exception;
use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
class BadRequestHttpExceptionTest extends HttpExceptionTest
{
protected function createException()
{
return new BadRequestHttpException();
}
}

View File

@@ -0,0 +1,13 @@
<?php
namespace Symfony\Component\HttpKernel\Tests\Exception;
use Symfony\Component\HttpKernel\Exception\ConflictHttpException;
class ConflictHttpExceptionTest extends HttpExceptionTest
{
protected function createException()
{
return new ConflictHttpException();
}
}

View File

@@ -0,0 +1,13 @@
<?php
namespace Symfony\Component\HttpKernel\Tests\Exception;
use Symfony\Component\HttpKernel\Exception\GoneHttpException;
class GoneHttpExceptionTest extends HttpExceptionTest
{
protected function createException()
{
return new GoneHttpException();
}
}

View File

@@ -0,0 +1,53 @@
<?php
namespace Symfony\Component\HttpKernel\Tests\Exception;
use PHPUnit\Framework\TestCase;
use Symfony\Component\HttpKernel\Exception\HttpException;
class HttpExceptionTest extends TestCase
{
public function headerDataProvider()
{
return array(
array(array('X-Test' => 'Test')),
array(array('X-Test' => 1)),
array(
array(
array('X-Test' => 'Test'),
array('X-Test-2' => 'Test-2'),
),
),
);
}
public function testHeadersDefault()
{
$exception = $this->createException();
$this->assertSame(array(), $exception->getHeaders());
}
/**
* @dataProvider headerDataProvider
*/
public function testHeadersConstructor($headers)
{
$exception = new HttpException(200, null, null, $headers);
$this->assertSame($headers, $exception->getHeaders());
}
/**
* @dataProvider headerDataProvider
*/
public function testHeadersSetter($headers)
{
$exception = $this->createException();
$exception->setHeaders($headers);
$this->assertSame($headers, $exception->getHeaders());
}
protected function createException()
{
return new HttpException(200);
}
}

View File

@@ -0,0 +1,13 @@
<?php
namespace Symfony\Component\HttpKernel\Tests\Exception;
use Symfony\Component\HttpKernel\Exception\LengthRequiredHttpException;
class LengthRequiredHttpExceptionTest extends HttpExceptionTest
{
protected function createException()
{
return new LengthRequiredHttpException();
}
}

View File

@@ -0,0 +1,24 @@
<?php
namespace Symfony\Component\HttpKernel\Tests\Exception;
use Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpException;
class MethodNotAllowedHttpExceptionTest extends HttpExceptionTest
{
public function testHeadersDefault()
{
$exception = new MethodNotAllowedHttpException(array('GET', 'PUT'));
$this->assertSame(array('Allow' => 'GET, PUT'), $exception->getHeaders());
}
/**
* @dataProvider headerDataProvider
*/
public function testHeadersSetter($headers)
{
$exception = new MethodNotAllowedHttpException(array('GET'));
$exception->setHeaders($headers);
$this->assertSame($headers, $exception->getHeaders());
}
}

View File

@@ -0,0 +1,13 @@
<?php
namespace Symfony\Component\HttpKernel\Tests\Exception;
use Symfony\Component\HttpKernel\Exception\NotAcceptableHttpException;
class NotAcceptableHttpExceptionTest extends HttpExceptionTest
{
protected function createException()
{
return new NotAcceptableHttpException();
}
}

View File

@@ -0,0 +1,13 @@
<?php
namespace Symfony\Component\HttpKernel\Tests\Exception;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
class NotFoundHttpExceptionTest extends HttpExceptionTest
{
protected function createException()
{
return new NotFoundHttpException();
}
}

View File

@@ -0,0 +1,13 @@
<?php
namespace Symfony\Component\HttpKernel\Tests\Exception;
use Symfony\Component\HttpKernel\Exception\PreconditionFailedHttpException;
class PreconditionFailedHttpExceptionTest extends HttpExceptionTest
{
protected function createException()
{
return new PreconditionFailedHttpException();
}
}

View File

@@ -0,0 +1,13 @@
<?php
namespace Symfony\Component\HttpKernel\Tests\Exception;
use Symfony\Component\HttpKernel\Exception\PreconditionRequiredHttpException;
class PreconditionRequiredHttpExceptionTest extends HttpExceptionTest
{
protected function createException()
{
return new PreconditionRequiredHttpException();
}
}

View File

@@ -0,0 +1,29 @@
<?php
namespace Symfony\Component\HttpKernel\Tests\Exception;
use Symfony\Component\HttpKernel\Exception\ServiceUnavailableHttpException;
class ServiceUnavailableHttpExceptionTest extends HttpExceptionTest
{
public function testHeadersDefaultRetryAfter()
{
$exception = new ServiceUnavailableHttpException(10);
$this->assertSame(array('Retry-After' => 10), $exception->getHeaders());
}
/**
* @dataProvider headerDataProvider
*/
public function testHeadersSetter($headers)
{
$exception = new ServiceUnavailableHttpException(10);
$exception->setHeaders($headers);
$this->assertSame($headers, $exception->getHeaders());
}
protected function createException()
{
return new ServiceUnavailableHttpException();
}
}

View File

@@ -0,0 +1,29 @@
<?php
namespace Symfony\Component\HttpKernel\Tests\Exception;
use Symfony\Component\HttpKernel\Exception\TooManyRequestsHttpException;
class TooManyRequestsHttpExceptionTest extends HttpExceptionTest
{
public function testHeadersDefaultRertyAfter()
{
$exception = new TooManyRequestsHttpException(10);
$this->assertSame(array('Retry-After' => 10), $exception->getHeaders());
}
/**
* @dataProvider headerDataProvider
*/
public function testHeadersSetter($headers)
{
$exception = new TooManyRequestsHttpException(10);
$exception->setHeaders($headers);
$this->assertSame($headers, $exception->getHeaders());
}
protected function createException()
{
return new TooManyRequestsHttpException();
}
}

View File

@@ -0,0 +1,24 @@
<?php
namespace Symfony\Component\HttpKernel\Tests\Exception;
use Symfony\Component\HttpKernel\Exception\UnauthorizedHttpException;
class UnauthorizedHttpExceptionTest extends HttpExceptionTest
{
public function testHeadersDefault()
{
$exception = new UnauthorizedHttpException('Challenge');
$this->assertSame(array('WWW-Authenticate' => 'Challenge'), $exception->getHeaders());
}
/**
* @dataProvider headerDataProvider
*/
public function testHeadersSetter($headers)
{
$exception = new UnauthorizedHttpException('Challenge');
$exception->setHeaders($headers);
$this->assertSame($headers, $exception->getHeaders());
}
}

View File

@@ -0,0 +1,28 @@
<?php
namespace Symfony\Component\HttpKernel\Tests\Exception;
use Symfony\Component\HttpKernel\Exception\UnprocessableEntityHttpException;
class UnprocessableEntityHttpExceptionTest extends HttpExceptionTest
{
/**
* Test that setting the headers using the setter function
* is working as expected.
*
* @param array $headers The headers to set
*
* @dataProvider headerDataProvider
*/
public function testHeadersSetter($headers)
{
$exception = new UnprocessableEntityHttpException(10);
$exception->setHeaders($headers);
$this->assertSame($headers, $exception->getHeaders());
}
protected function createException()
{
return new UnprocessableEntityHttpException();
}
}

View File

@@ -0,0 +1,23 @@
<?php
namespace Symfony\Component\HttpKernel\Tests\Exception;
use Symfony\Component\HttpKernel\Exception\UnsupportedMediaTypeHttpException;
class UnsupportedMediaTypeHttpExceptionTest extends HttpExceptionTest
{
/**
* @dataProvider headerDataProvider
*/
public function testHeadersSetter($headers)
{
$exception = new UnsupportedMediaTypeHttpException(10);
$exception->setHeaders($headers);
$this->assertSame($headers, $exception->getHeaders());
}
protected function createException($headers = array())
{
return new UnsupportedMediaTypeHttpException();
}
}

View File

@@ -0,0 +1,37 @@
<?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\Tests\Fixtures\_123;
use Symfony\Component\HttpKernel\Kernel;
use Symfony\Component\Config\Loader\LoaderInterface;
class Kernel123 extends Kernel
{
public function registerBundles()
{
return array();
}
public function registerContainerConfiguration(LoaderInterface $loader)
{
}
public function getCacheDir()
{
return sys_get_temp_dir().'/'.Kernel::VERSION.'/kernel123/cache/'.$this->environment;
}
public function getLogDir()
{
return sys_get_temp_dir().'/'.Kernel::VERSION.'/kernel123/logs';
}
}

View File

@@ -0,0 +1,19 @@
<?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\Tests\Fixtures\Controller;
class BasicTypesController
{
public function action(string $foo, int $bar, float $baz)
{
}
}

View File

@@ -0,0 +1,18 @@
<?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\Tests\Fixtures\Controller;
use Symfony\Component\HttpFoundation\Request;
class ExtendingRequest extends Request
{
}

View File

@@ -0,0 +1,18 @@
<?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\Tests\Fixtures\Controller;
use Symfony\Component\HttpFoundation\Session\Session;
class ExtendingSession extends Session
{
}

View File

@@ -0,0 +1,19 @@
<?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\Tests\Fixtures\Controller;
class NullableController
{
public function action(?string $foo, ?\stdClass $bar, ?string $baz = 'value', $mandatory)
{
}
}

View File

@@ -0,0 +1,19 @@
<?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\Tests\Fixtures\Controller;
class VariadicController
{
public function action($foo, ...$bar)
{
}
}

View File

@@ -0,0 +1,41 @@
<?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\Tests\Fixtures\DataCollector;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\DataCollector\DataCollector;
class CloneVarDataCollector extends DataCollector
{
private $varToClone;
public function __construct($varToClone)
{
$this->varToClone = $varToClone;
}
public function collect(Request $request, Response $response, \Exception $exception = null)
{
$this->data = $this->cloneVar($this->varToClone);
}
public function getData()
{
return $this->data;
}
public function getName()
{
return 'clone_var';
}
}

View File

@@ -0,0 +1,18 @@
<?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\Tests\Fixtures\ExtensionAbsentBundle;
use Symfony\Component\HttpKernel\Bundle\Bundle;
class ExtensionAbsentBundle extends Bundle
{
}

View File

@@ -0,0 +1,22 @@
<?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\Tests\Fixtures\ExtensionLoadedBundle\DependencyInjection;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Extension\Extension;
class ExtensionLoadedExtension extends Extension
{
public function load(array $configs, ContainerBuilder $container)
{
}
}

View File

@@ -0,0 +1,18 @@
<?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\Tests\Fixtures\ExtensionLoadedBundle;
use Symfony\Component\HttpKernel\Bundle\Bundle;
class ExtensionLoadedBundle extends Bundle
{
}

View File

@@ -0,0 +1,20 @@
<?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\Tests\Fixtures\ExtensionNotValidBundle\DependencyInjection;
class ExtensionNotValidExtension
{
public function getAlias()
{
return 'extension_not_valid';
}
}

View File

@@ -0,0 +1,18 @@
<?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\Tests\Fixtures\ExtensionNotValidBundle;
use Symfony\Component\HttpKernel\Bundle\Bundle;
class ExtensionNotValidBundle extends Bundle
{
}

View File

@@ -0,0 +1,17 @@
<?php
namespace Symfony\Component\HttpKernel\Tests\Fixtures\ExtensionPresentBundle\Command;
use Symfony\Component\Console\Command\Command;
/**
* This command has a required parameter on the constructor and will be ignored by the default Bundle implementation.
*
* @see Bundle::registerCommands()
*/
class BarCommand extends Command
{
public function __construct($example, $name = 'bar')
{
}
}

View File

@@ -0,0 +1,22 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien.potencier@symfony-project.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\HttpKernel\Tests\Fixtures\ExtensionPresentBundle\Command;
use Symfony\Component\Console\Command\Command;
class FooCommand extends Command
{
protected function configure()
{
$this->setName('foo');
}
}

View File

@@ -0,0 +1,22 @@
<?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\Tests\Fixtures\ExtensionPresentBundle\DependencyInjection;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Extension\Extension;
class ExtensionPresentExtension extends Extension
{
public function load(array $configs, ContainerBuilder $container)
{
}
}

View File

@@ -0,0 +1,18 @@
<?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\Tests\Fixtures\ExtensionPresentBundle;
use Symfony\Component\HttpKernel\Bundle\Bundle;
class ExtensionPresentBundle extends Bundle
{
}

View File

@@ -0,0 +1,28 @@
<?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\Tests\Fixtures;
use Symfony\Component\HttpKernel\Kernel;
use Symfony\Component\Config\Loader\LoaderInterface;
class KernelForOverrideName extends Kernel
{
protected $name = 'overridden';
public function registerBundles()
{
}
public function registerContainerConfiguration(LoaderInterface $loader)
{
}
}

View File

@@ -0,0 +1,37 @@
<?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\Tests\Fixtures;
use Symfony\Component\HttpKernel\Kernel;
use Symfony\Component\Config\Loader\LoaderInterface;
class KernelForTest extends Kernel
{
public function getBundleMap()
{
return $this->bundleMap;
}
public function registerBundles()
{
return array();
}
public function registerContainerConfiguration(LoaderInterface $loader)
{
}
public function isBooted()
{
return $this->booted;
}
}

View File

@@ -0,0 +1,33 @@
<?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\Tests\Fixtures;
use Symfony\Component\Config\Loader\LoaderInterface;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\HttpKernel\Kernel;
class KernelWithoutBundles extends Kernel
{
public function registerBundles()
{
return array();
}
public function registerContainerConfiguration(LoaderInterface $loader)
{
}
protected function build(ContainerBuilder $container)
{
$container->setParameter('test_executed', true);
}
}

View File

@@ -0,0 +1,31 @@
<?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\Tests\Fixtures;
use Symfony\Component\HttpKernel\Client;
class TestClient extends Client
{
protected function getScript($request)
{
$script = parent::getScript($request);
$autoload = file_exists(__DIR__.'/../../vendor/autoload.php')
? __DIR__.'/../../vendor/autoload.php'
: __DIR__.'/../../../../../../vendor/autoload.php'
;
$script = preg_replace('/(\->register\(\);)/', "$0\nrequire_once '$autoload';\n", $script);
return $script;
}
}

View File

@@ -0,0 +1,28 @@
<?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\Tests\Fixtures;
use Symfony\Component\EventDispatcher\Debug\TraceableEventDispatcherInterface;
use Symfony\Component\EventDispatcher\EventDispatcher;
class TestEventDispatcher extends EventDispatcher implements TraceableEventDispatcherInterface
{
public function getCalledListeners()
{
return array('foo');
}
public function getNotCalledListeners()
{
return array('bar');
}
}

View File

@@ -0,0 +1,110 @@
<?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\Tests\Fragment;
use PHPUnit\Framework\TestCase;
use Symfony\Component\HttpKernel\Controller\ControllerReference;
use Symfony\Component\HttpKernel\Fragment\EsiFragmentRenderer;
use Symfony\Component\HttpKernel\HttpCache\Esi;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\UriSigner;
class EsiFragmentRendererTest extends TestCase
{
public function testRenderFallbackToInlineStrategyIfEsiNotSupported()
{
$strategy = new EsiFragmentRenderer(new Esi(), $this->getInlineStrategy(true));
$strategy->render('/', Request::create('/'));
}
/**
* @group legacy
* @expectedDeprecation Passing non-scalar values as part of URI attributes to the ESI and SSI rendering strategies is deprecated %s.
*/
public function testRenderFallbackWithObjectAttributesIsDeprecated()
{
$strategy = new EsiFragmentRenderer(new Esi(), $this->getInlineStrategy(true), new UriSigner('foo'));
$request = Request::create('/');
$reference = new ControllerReference('main_controller', array('foo' => array('a' => array(), 'b' => new \stdClass())), array());
$strategy->render($reference, $request);
}
public function testRender()
{
$strategy = new EsiFragmentRenderer(new Esi(), $this->getInlineStrategy());
$request = Request::create('/');
$request->setLocale('fr');
$request->headers->set('Surrogate-Capability', 'ESI/1.0');
$this->assertEquals('<esi:include src="/" />', $strategy->render('/', $request)->getContent());
$this->assertEquals("<esi:comment text=\"This is a comment\" />\n<esi:include src=\"/\" />", $strategy->render('/', $request, array('comment' => 'This is a comment'))->getContent());
$this->assertEquals('<esi:include src="/" alt="foo" />', $strategy->render('/', $request, array('alt' => 'foo'))->getContent());
}
public function testRenderControllerReference()
{
$signer = new UriSigner('foo');
$strategy = new EsiFragmentRenderer(new Esi(), $this->getInlineStrategy(), $signer);
$request = Request::create('/');
$request->setLocale('fr');
$request->headers->set('Surrogate-Capability', 'ESI/1.0');
$reference = new ControllerReference('main_controller', array(), array());
$altReference = new ControllerReference('alt_controller', array(), array());
$this->assertEquals(
'<esi:include src="/_fragment?_path=_format%3Dhtml%26_locale%3Dfr%26_controller%3Dmain_controller&_hash=Jz1P8NErmhKTeI6onI1EdAXTB85359MY3RIk5mSJ60w%3D" alt="/_fragment?_path=_format%3Dhtml%26_locale%3Dfr%26_controller%3Dalt_controller&_hash=iPJEdRoUpGrM1ztqByiorpfMPtiW%2FOWwdH1DBUXHhEc%3D" />',
$strategy->render($reference, $request, array('alt' => $altReference))->getContent()
);
}
/**
* @expectedException \LogicException
*/
public function testRenderControllerReferenceWithoutSignerThrowsException()
{
$strategy = new EsiFragmentRenderer(new Esi(), $this->getInlineStrategy());
$request = Request::create('/');
$request->setLocale('fr');
$request->headers->set('Surrogate-Capability', 'ESI/1.0');
$strategy->render(new ControllerReference('main_controller'), $request);
}
/**
* @expectedException \LogicException
*/
public function testRenderAltControllerReferenceWithoutSignerThrowsException()
{
$strategy = new EsiFragmentRenderer(new Esi(), $this->getInlineStrategy());
$request = Request::create('/');
$request->setLocale('fr');
$request->headers->set('Surrogate-Capability', 'ESI/1.0');
$strategy->render('/', $request, array('alt' => new ControllerReference('alt_controller')));
}
private function getInlineStrategy($called = false)
{
$inline = $this->getMockBuilder('Symfony\Component\HttpKernel\Fragment\InlineFragmentRenderer')->disableOriginalConstructor()->getMock();
if ($called) {
$inline->expects($this->once())->method('render');
}
return $inline;
}
}

View File

@@ -0,0 +1,99 @@
<?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\Tests\Fragment;
use PHPUnit\Framework\TestCase;
use Symfony\Component\HttpKernel\Fragment\FragmentHandler;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
/**
* @group time-sensitive
*/
class FragmentHandlerTest extends TestCase
{
private $requestStack;
protected function setUp()
{
$this->requestStack = $this->getMockBuilder('Symfony\\Component\\HttpFoundation\\RequestStack')
->disableOriginalConstructor()
->getMock()
;
$this->requestStack
->expects($this->any())
->method('getCurrentRequest')
->will($this->returnValue(Request::create('/')))
;
}
/**
* @expectedException \InvalidArgumentException
*/
public function testRenderWhenRendererDoesNotExist()
{
$handler = new FragmentHandler($this->requestStack);
$handler->render('/', 'foo');
}
/**
* @expectedException \InvalidArgumentException
*/
public function testRenderWithUnknownRenderer()
{
$handler = $this->getHandler($this->returnValue(new Response('foo')));
$handler->render('/', 'bar');
}
/**
* @expectedException \RuntimeException
* @expectedExceptionMessage Error when rendering "http://localhost/" (Status code is 404).
*/
public function testDeliverWithUnsuccessfulResponse()
{
$handler = $this->getHandler($this->returnValue(new Response('foo', 404)));
$handler->render('/', 'foo');
}
public function testRender()
{
$handler = $this->getHandler($this->returnValue(new Response('foo')), array('/', Request::create('/'), array('foo' => 'foo', 'ignore_errors' => true)));
$this->assertEquals('foo', $handler->render('/', 'foo', array('foo' => 'foo')));
}
protected function getHandler($returnValue, $arguments = array())
{
$renderer = $this->getMockBuilder('Symfony\Component\HttpKernel\Fragment\FragmentRendererInterface')->getMock();
$renderer
->expects($this->any())
->method('getName')
->will($this->returnValue('foo'))
;
$e = $renderer
->expects($this->any())
->method('render')
->will($returnValue)
;
if ($arguments) {
call_user_func_array(array($e, 'with'), $arguments);
}
$handler = new FragmentHandler($this->requestStack);
$handler->addRenderer($renderer);
return $handler;
}
}

View File

@@ -0,0 +1,89 @@
<?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\Tests\Fragment;
use PHPUnit\Framework\TestCase;
use Symfony\Component\HttpKernel\Controller\ControllerReference;
use Symfony\Component\HttpKernel\Fragment\HIncludeFragmentRenderer;
use Symfony\Component\HttpKernel\UriSigner;
use Symfony\Component\HttpFoundation\Request;
class HIncludeFragmentRendererTest extends TestCase
{
/**
* @expectedException \LogicException
*/
public function testRenderExceptionWhenControllerAndNoSigner()
{
$strategy = new HIncludeFragmentRenderer();
$strategy->render(new ControllerReference('main_controller', array(), array()), Request::create('/'));
}
public function testRenderWithControllerAndSigner()
{
$strategy = new HIncludeFragmentRenderer(null, new UriSigner('foo'));
$this->assertEquals('<hx:include src="/_fragment?_path=_format%3Dhtml%26_locale%3Den%26_controller%3Dmain_controller&amp;_hash=BP%2BOzCD5MRUI%2BHJpgPDOmoju00FnzLhP3TGcSHbbBLs%3D"></hx:include>', $strategy->render(new ControllerReference('main_controller', array(), array()), Request::create('/'))->getContent());
}
public function testRenderWithUri()
{
$strategy = new HIncludeFragmentRenderer();
$this->assertEquals('<hx:include src="/foo"></hx:include>', $strategy->render('/foo', Request::create('/'))->getContent());
$strategy = new HIncludeFragmentRenderer(null, new UriSigner('foo'));
$this->assertEquals('<hx:include src="/foo"></hx:include>', $strategy->render('/foo', Request::create('/'))->getContent());
}
public function testRenderWithDefault()
{
// only default
$strategy = new HIncludeFragmentRenderer();
$this->assertEquals('<hx:include src="/foo">default</hx:include>', $strategy->render('/foo', Request::create('/'), array('default' => 'default'))->getContent());
// only global default
$strategy = new HIncludeFragmentRenderer(null, null, 'global_default');
$this->assertEquals('<hx:include src="/foo">global_default</hx:include>', $strategy->render('/foo', Request::create('/'), array())->getContent());
// global default and default
$strategy = new HIncludeFragmentRenderer(null, null, 'global_default');
$this->assertEquals('<hx:include src="/foo">default</hx:include>', $strategy->render('/foo', Request::create('/'), array('default' => 'default'))->getContent());
}
public function testRenderWithAttributesOptions()
{
// with id
$strategy = new HIncludeFragmentRenderer();
$this->assertEquals('<hx:include src="/foo" id="bar">default</hx:include>', $strategy->render('/foo', Request::create('/'), array('default' => 'default', 'id' => 'bar'))->getContent());
// with attributes
$strategy = new HIncludeFragmentRenderer();
$this->assertEquals('<hx:include src="/foo" p1="v1" p2="v2">default</hx:include>', $strategy->render('/foo', Request::create('/'), array('default' => 'default', 'attributes' => array('p1' => 'v1', 'p2' => 'v2')))->getContent());
// with id & attributes
$strategy = new HIncludeFragmentRenderer();
$this->assertEquals('<hx:include src="/foo" p1="v1" p2="v2" id="bar">default</hx:include>', $strategy->render('/foo', Request::create('/'), array('default' => 'default', 'id' => 'bar', 'attributes' => array('p1' => 'v1', 'p2' => 'v2')))->getContent());
}
public function testRenderWithDefaultText()
{
$engine = $this->getMockBuilder('Symfony\\Component\\Templating\\EngineInterface')->getMock();
$engine->expects($this->once())
->method('exists')
->with('default')
->will($this->throwException(new \InvalidArgumentException()));
// only default
$strategy = new HIncludeFragmentRenderer($engine);
$this->assertEquals('<hx:include src="/foo">default</hx:include>', $strategy->render('/foo', Request::create('/'), array('default' => 'default'))->getContent());
}
}

View File

@@ -0,0 +1,250 @@
<?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\Tests\Fragment;
use PHPUnit\Framework\TestCase;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\HttpKernel\Controller\ArgumentResolver;
use Symfony\Component\HttpKernel\Controller\ControllerResolverInterface;
use Symfony\Component\HttpKernel\Controller\ControllerReference;
use Symfony\Component\HttpKernel\HttpKernel;
use Symfony\Component\HttpKernel\Fragment\InlineFragmentRenderer;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\EventDispatcher\EventDispatcher;
class InlineFragmentRendererTest extends TestCase
{
public function testRender()
{
$strategy = new InlineFragmentRenderer($this->getKernel($this->returnValue(new Response('foo'))));
$this->assertEquals('foo', $strategy->render('/', Request::create('/'))->getContent());
}
public function testRenderWithControllerReference()
{
$strategy = new InlineFragmentRenderer($this->getKernel($this->returnValue(new Response('foo'))));
$this->assertEquals('foo', $strategy->render(new ControllerReference('main_controller', array(), array()), Request::create('/'))->getContent());
}
public function testRenderWithObjectsAsAttributes()
{
$object = new \stdClass();
$subRequest = Request::create('/_fragment?_path=_format%3Dhtml%26_locale%3Den%26_controller%3Dmain_controller');
$subRequest->attributes->replace(array('object' => $object, '_format' => 'html', '_controller' => 'main_controller', '_locale' => 'en'));
$subRequest->headers->set('x-forwarded-for', array('127.0.0.1'));
$subRequest->server->set('HTTP_X_FORWARDED_FOR', '127.0.0.1');
$strategy = new InlineFragmentRenderer($this->getKernelExpectingRequest($subRequest));
$this->assertSame('foo', $strategy->render(new ControllerReference('main_controller', array('object' => $object), array()), Request::create('/'))->getContent());
}
/**
* @group legacy
*/
public function testRenderWithObjectsAsAttributesPassedAsObjectsInTheControllerLegacy()
{
$resolver = $this->getMockBuilder('Symfony\\Component\\HttpKernel\\Controller\\ControllerResolver')->setMethods(array('getController'))->getMock();
$resolver
->expects($this->once())
->method('getController')
->will($this->returnValue(function (\stdClass $object, Bar $object1) {
return new Response($object1->getBar());
}))
;
$kernel = new HttpKernel(new EventDispatcher(), $resolver, new RequestStack());
$renderer = new InlineFragmentRenderer($kernel);
$response = $renderer->render(new ControllerReference('main_controller', array('object' => new \stdClass(), 'object1' => new Bar()), array()), Request::create('/'));
$this->assertEquals('bar', $response->getContent());
}
/**
* @group legacy
*/
public function testRenderWithObjectsAsAttributesPassedAsObjectsInTheController()
{
$resolver = $this->getMockBuilder(ControllerResolverInterface::class)->getMock();
$resolver
->expects($this->once())
->method('getController')
->will($this->returnValue(function (\stdClass $object, Bar $object1) {
return new Response($object1->getBar());
}))
;
$kernel = new HttpKernel(new EventDispatcher(), $resolver, new RequestStack(), new ArgumentResolver());
$renderer = new InlineFragmentRenderer($kernel);
$response = $renderer->render(new ControllerReference('main_controller', array('object' => new \stdClass(), 'object1' => new Bar()), array()), Request::create('/'));
$this->assertEquals('bar', $response->getContent());
}
public function testRenderWithTrustedHeaderDisabled()
{
Request::setTrustedProxies(array(), 0);
$strategy = new InlineFragmentRenderer($this->getKernelExpectingRequest(Request::create('/')));
$this->assertSame('foo', $strategy->render('/', Request::create('/'))->getContent());
Request::setTrustedProxies(array(), -1);
}
/**
* @expectedException \RuntimeException
*/
public function testRenderExceptionNoIgnoreErrors()
{
$dispatcher = $this->getMockBuilder('Symfony\Component\EventDispatcher\EventDispatcherInterface')->getMock();
$dispatcher->expects($this->never())->method('dispatch');
$strategy = new InlineFragmentRenderer($this->getKernel($this->throwException(new \RuntimeException('foo'))), $dispatcher);
$this->assertEquals('foo', $strategy->render('/', Request::create('/'))->getContent());
}
public function testRenderExceptionIgnoreErrors()
{
$dispatcher = $this->getMockBuilder('Symfony\Component\EventDispatcher\EventDispatcherInterface')->getMock();
$dispatcher->expects($this->once())->method('dispatch')->with(KernelEvents::EXCEPTION);
$strategy = new InlineFragmentRenderer($this->getKernel($this->throwException(new \RuntimeException('foo'))), $dispatcher);
$this->assertEmpty($strategy->render('/', Request::create('/'), array('ignore_errors' => true))->getContent());
}
public function testRenderExceptionIgnoreErrorsWithAlt()
{
$strategy = new InlineFragmentRenderer($this->getKernel($this->onConsecutiveCalls(
$this->throwException(new \RuntimeException('foo')),
$this->returnValue(new Response('bar'))
)));
$this->assertEquals('bar', $strategy->render('/', Request::create('/'), array('ignore_errors' => true, 'alt' => '/foo'))->getContent());
}
private function getKernel($returnValue)
{
$kernel = $this->getMockBuilder('Symfony\Component\HttpKernel\HttpKernelInterface')->getMock();
$kernel
->expects($this->any())
->method('handle')
->will($returnValue)
;
return $kernel;
}
public function testExceptionInSubRequestsDoesNotMangleOutputBuffers()
{
$controllerResolver = $this->getMockBuilder('Symfony\\Component\\HttpKernel\\Controller\\ControllerResolverInterface')->getMock();
$controllerResolver
->expects($this->once())
->method('getController')
->will($this->returnValue(function () {
ob_start();
echo 'bar';
throw new \RuntimeException();
}))
;
$argumentResolver = $this->getMockBuilder('Symfony\\Component\\HttpKernel\\Controller\\ArgumentResolverInterface')->getMock();
$argumentResolver
->expects($this->once())
->method('getArguments')
->will($this->returnValue(array()))
;
$kernel = new HttpKernel(new EventDispatcher(), $controllerResolver, new RequestStack(), $argumentResolver);
$renderer = new InlineFragmentRenderer($kernel);
// simulate a main request with output buffering
ob_start();
echo 'Foo';
// simulate a sub-request with output buffering and an exception
$renderer->render('/', Request::create('/'), array('ignore_errors' => true));
$this->assertEquals('Foo', ob_get_clean());
}
public function testESIHeaderIsKeptInSubrequest()
{
$expectedSubRequest = Request::create('/');
$expectedSubRequest->headers->set('Surrogate-Capability', 'abc="ESI/1.0"');
if (Request::HEADER_X_FORWARDED_FOR & Request::getTrustedHeaderSet()) {
$expectedSubRequest->headers->set('x-forwarded-for', array('127.0.0.1'));
$expectedSubRequest->server->set('HTTP_X_FORWARDED_FOR', '127.0.0.1');
}
$strategy = new InlineFragmentRenderer($this->getKernelExpectingRequest($expectedSubRequest));
$request = Request::create('/');
$request->headers->set('Surrogate-Capability', 'abc="ESI/1.0"');
$strategy->render('/', $request);
}
public function testESIHeaderIsKeptInSubrequestWithTrustedHeaderDisabled()
{
Request::setTrustedProxies(array(), 0);
$this->testESIHeaderIsKeptInSubrequest();
Request::setTrustedProxies(array(), -1);
}
public function testHeadersPossiblyResultingIn304AreNotAssignedToSubrequest()
{
$expectedSubRequest = Request::create('/');
if (Request::HEADER_X_FORWARDED_FOR & Request::getTrustedHeaderSet()) {
$expectedSubRequest->headers->set('x-forwarded-for', array('127.0.0.1'));
$expectedSubRequest->server->set('HTTP_X_FORWARDED_FOR', '127.0.0.1');
}
$strategy = new InlineFragmentRenderer($this->getKernelExpectingRequest($expectedSubRequest));
$request = Request::create('/', 'GET', array(), array(), array(), array('HTTP_IF_MODIFIED_SINCE' => 'Fri, 01 Jan 2016 00:00:00 GMT', 'HTTP_IF_NONE_MATCH' => '*'));
$strategy->render('/', $request);
}
/**
* Creates a Kernel expecting a request equals to $request
* Allows delta in comparison in case REQUEST_TIME changed by 1 second.
*/
private function getKernelExpectingRequest(Request $request, $strict = false)
{
$kernel = $this->getMockBuilder('Symfony\Component\HttpKernel\HttpKernelInterface')->getMock();
$kernel
->expects($this->once())
->method('handle')
->with($this->equalTo($request, 1))
->willReturn(new Response('foo'));
return $kernel;
}
}
class Bar
{
public $bar = 'bar';
public function getBar()
{
return $this->bar;
}
}

View File

@@ -0,0 +1,94 @@
<?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\Tests\Fragment;
use PHPUnit\Framework\TestCase;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Controller\ControllerReference;
class RoutableFragmentRendererTest extends TestCase
{
/**
* @dataProvider getGenerateFragmentUriData
*/
public function testGenerateFragmentUri($uri, $controller)
{
$this->assertEquals($uri, $this->callGenerateFragmentUriMethod($controller, Request::create('/')));
}
/**
* @dataProvider getGenerateFragmentUriData
*/
public function testGenerateAbsoluteFragmentUri($uri, $controller)
{
$this->assertEquals('http://localhost'.$uri, $this->callGenerateFragmentUriMethod($controller, Request::create('/'), true));
}
public function getGenerateFragmentUriData()
{
return array(
array('/_fragment?_path=_format%3Dhtml%26_locale%3Den%26_controller%3Dcontroller', new ControllerReference('controller', array(), array())),
array('/_fragment?_path=_format%3Dxml%26_locale%3Den%26_controller%3Dcontroller', new ControllerReference('controller', array('_format' => 'xml'), array())),
array('/_fragment?_path=foo%3Dfoo%26_format%3Djson%26_locale%3Den%26_controller%3Dcontroller', new ControllerReference('controller', array('foo' => 'foo', '_format' => 'json'), array())),
array('/_fragment?bar=bar&_path=foo%3Dfoo%26_format%3Dhtml%26_locale%3Den%26_controller%3Dcontroller', new ControllerReference('controller', array('foo' => 'foo'), array('bar' => 'bar'))),
array('/_fragment?foo=foo&_path=_format%3Dhtml%26_locale%3Den%26_controller%3Dcontroller', new ControllerReference('controller', array(), array('foo' => 'foo'))),
array('/_fragment?_path=foo%255B0%255D%3Dfoo%26foo%255B1%255D%3Dbar%26_format%3Dhtml%26_locale%3Den%26_controller%3Dcontroller', new ControllerReference('controller', array('foo' => array('foo', 'bar')), array())),
);
}
public function testGenerateFragmentUriWithARequest()
{
$request = Request::create('/');
$request->attributes->set('_format', 'json');
$request->setLocale('fr');
$controller = new ControllerReference('controller', array(), array());
$this->assertEquals('/_fragment?_path=_format%3Djson%26_locale%3Dfr%26_controller%3Dcontroller', $this->callGenerateFragmentUriMethod($controller, $request));
}
/**
* @expectedException \LogicException
* @dataProvider getGenerateFragmentUriDataWithNonScalar
*/
public function testGenerateFragmentUriWithNonScalar($controller)
{
$this->callGenerateFragmentUriMethod($controller, Request::create('/'));
}
public function getGenerateFragmentUriDataWithNonScalar()
{
return array(
array(new ControllerReference('controller', array('foo' => new Foo(), 'bar' => 'bar'), array())),
array(new ControllerReference('controller', array('foo' => array('foo' => 'foo'), 'bar' => array('bar' => new Foo())), array())),
);
}
private function callGenerateFragmentUriMethod(ControllerReference $reference, Request $request, $absolute = false)
{
$renderer = $this->getMockForAbstractClass('Symfony\Component\HttpKernel\Fragment\RoutableFragmentRenderer');
$r = new \ReflectionObject($renderer);
$m = $r->getMethod('generateFragmentUri');
$m->setAccessible(true);
return $m->invoke($renderer, $reference, $request, $absolute);
}
}
class Foo
{
public $foo;
public function getFoo()
{
return $this->foo;
}
}

Some files were not shown because too many files have changed in this diff Show More