N°2651 rollback gitignore for lib tests dirs

Too dangerous ! We'll work properly on this but for 2.8
This commit is contained in:
Pierre Goiffon
2020-01-10 15:15:15 +01:00
parent 881fc2a1de
commit ad821e7d9c
2086 changed files with 151849 additions and 6 deletions

View File

@@ -0,0 +1,152 @@
<?php
namespace Symfony\Bundle\FrameworkBundle\Tests\CacheWarmer;
use Doctrine\Common\Annotations\AnnotationReader;
use Doctrine\Common\Annotations\CachedReader;
use Doctrine\Common\Annotations\Reader;
use PHPUnit\Framework\MockObject\MockObject;
use Symfony\Bundle\FrameworkBundle\CacheWarmer\AnnotationsCacheWarmer;
use Symfony\Bundle\FrameworkBundle\Tests\TestCase;
use Symfony\Component\Cache\Adapter\ArrayAdapter;
use Symfony\Component\Cache\Adapter\NullAdapter;
use Symfony\Component\Cache\Adapter\PhpArrayAdapter;
use Symfony\Component\Cache\DoctrineProvider;
use Symfony\Component\Filesystem\Filesystem;
class AnnotationsCacheWarmerTest extends TestCase
{
private $cacheDir;
protected function setUp()
{
$this->cacheDir = sys_get_temp_dir().'/'.uniqid();
$fs = new Filesystem();
$fs->mkdir($this->cacheDir);
parent::setUp();
}
protected function tearDown()
{
$fs = new Filesystem();
$fs->remove($this->cacheDir);
parent::tearDown();
}
public function testAnnotationsCacheWarmerWithDebugDisabled()
{
file_put_contents($this->cacheDir.'/annotations.map', sprintf('<?php return %s;', var_export([__CLASS__], true)));
$cacheFile = tempnam($this->cacheDir, __FUNCTION__);
$reader = new AnnotationReader();
$fallbackPool = new ArrayAdapter();
$warmer = new AnnotationsCacheWarmer(
$reader,
$cacheFile,
$fallbackPool,
null
);
$warmer->warmUp($this->cacheDir);
$this->assertFileExists($cacheFile);
// Assert cache is valid
$reader = new CachedReader(
$this->getReadOnlyReader(),
new DoctrineProvider(new PhpArrayAdapter($cacheFile, new NullAdapter()))
);
$refClass = new \ReflectionClass($this);
$reader->getClassAnnotations($refClass);
$reader->getMethodAnnotations($refClass->getMethod(__FUNCTION__));
$reader->getPropertyAnnotations($refClass->getProperty('cacheDir'));
}
public function testAnnotationsCacheWarmerWithDebugEnabled()
{
file_put_contents($this->cacheDir.'/annotations.map', sprintf('<?php return %s;', var_export([__CLASS__], true)));
$cacheFile = tempnam($this->cacheDir, __FUNCTION__);
$reader = new AnnotationReader();
$fallbackPool = new ArrayAdapter();
$warmer = new AnnotationsCacheWarmer(
$reader,
$cacheFile,
$fallbackPool,
null,
true
);
$warmer->warmUp($this->cacheDir);
$this->assertFileExists($cacheFile);
// Assert cache is valid
$reader = new CachedReader(
$this->getReadOnlyReader(),
new DoctrineProvider(new PhpArrayAdapter($cacheFile, new NullAdapter())),
true
);
$refClass = new \ReflectionClass($this);
$reader->getClassAnnotations($refClass);
$reader->getMethodAnnotations($refClass->getMethod(__FUNCTION__));
$reader->getPropertyAnnotations($refClass->getProperty('cacheDir'));
}
/**
* Test that the cache warming process is not broken if a class loader
* throws an exception (on class / file not found for example).
*/
public function testClassAutoloadException()
{
$this->assertFalse(class_exists($annotatedClass = 'C\C\C', false));
file_put_contents($this->cacheDir.'/annotations.map', sprintf('<?php return %s;', var_export([$annotatedClass], true)));
$warmer = new AnnotationsCacheWarmer(new AnnotationReader(), tempnam($this->cacheDir, __FUNCTION__), new ArrayAdapter());
spl_autoload_register($classLoader = function ($class) use ($annotatedClass) {
if ($class === $annotatedClass) {
throw new \DomainException('This exception should be caught by the warmer.');
}
}, true, true);
$warmer->warmUp($this->cacheDir);
spl_autoload_unregister($classLoader);
}
/**
* Test that the cache warming process is broken if a class loader throws an
* exception but that is unrelated to the class load.
*/
public function testClassAutoloadExceptionWithUnrelatedException()
{
$this->expectException(\DomainException::class);
$this->expectExceptionMessage('This exception should not be caught by the warmer.');
$this->assertFalse(class_exists($annotatedClass = 'AClassThatDoesNotExist_FWB_CacheWarmer_AnnotationsCacheWarmerTest', false));
file_put_contents($this->cacheDir.'/annotations.map', sprintf('<?php return %s;', var_export([$annotatedClass], true)));
$warmer = new AnnotationsCacheWarmer(new AnnotationReader(), tempnam($this->cacheDir, __FUNCTION__), new ArrayAdapter());
spl_autoload_register($classLoader = function ($class) use ($annotatedClass) {
if ($class === $annotatedClass) {
eval('class '.$annotatedClass.'{}');
throw new \DomainException('This exception should not be caught by the warmer.');
}
}, true, true);
$warmer->warmUp($this->cacheDir);
spl_autoload_unregister($classLoader);
}
/**
* @return MockObject|Reader
*/
private function getReadOnlyReader()
{
$readerMock = $this->getMockBuilder('Doctrine\Common\Annotations\Reader')->getMock();
$readerMock->expects($this->exactly(0))->method('getClassAnnotations');
$readerMock->expects($this->exactly(0))->method('getClassAnnotation');
$readerMock->expects($this->exactly(0))->method('getMethodAnnotations');
$readerMock->expects($this->exactly(0))->method('getMethodAnnotation');
$readerMock->expects($this->exactly(0))->method('getPropertyAnnotations');
$readerMock->expects($this->exactly(0))->method('getPropertyAnnotation');
return $readerMock;
}
}

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\Bundle\FrameworkBundle\Tests\CacheWarmer;
use Symfony\Bundle\FrameworkBundle\CacheWarmer\ClassCacheCacheWarmer;
use Symfony\Bundle\FrameworkBundle\Tests\Fixtures\DeclaredClass;
use Symfony\Bundle\FrameworkBundle\Tests\Fixtures\WarmedClass;
use Symfony\Bundle\FrameworkBundle\Tests\TestCase;
/**
* @group legacy
*/
class ClassCacheCacheWarmerTest extends TestCase
{
public function testWithDeclaredClasses()
{
$this->assertTrue(class_exists(WarmedClass::class, true));
$dir = sys_get_temp_dir();
@unlink($dir.'/classes.php');
file_put_contents($dir.'/classes.map', sprintf('<?php return %s;', var_export([WarmedClass::class], true)));
$warmer = new ClassCacheCacheWarmer([DeclaredClass::class]);
$warmer->warmUp($dir);
$this->assertSame(<<<'EOTXT'
<?php
namespace Symfony\Bundle\FrameworkBundle\Tests\Fixtures
{
class WarmedClass extends DeclaredClass
{
}
}
EOTXT
, file_get_contents($dir.'/classes.php')
);
@unlink($dir.'/classes.map');
@unlink($dir.'/classes.php');
}
}

View File

@@ -0,0 +1,134 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Bundle\FrameworkBundle\Tests\CacheWarmer;
use Symfony\Bundle\FrameworkBundle\CacheWarmer\SerializerCacheWarmer;
use Symfony\Bundle\FrameworkBundle\Tests\TestCase;
use Symfony\Component\Cache\Adapter\ArrayAdapter;
use Symfony\Component\Cache\Adapter\NullAdapter;
use Symfony\Component\Cache\Adapter\PhpArrayAdapter;
use Symfony\Component\Serializer\Mapping\Factory\CacheClassMetadataFactory;
use Symfony\Component\Serializer\Mapping\Loader\XmlFileLoader;
use Symfony\Component\Serializer\Mapping\Loader\YamlFileLoader;
class SerializerCacheWarmerTest extends TestCase
{
public function testWarmUp()
{
if (!class_exists(CacheClassMetadataFactory::class) || !method_exists(XmlFileLoader::class, 'getMappedClasses') || !method_exists(YamlFileLoader::class, 'getMappedClasses')) {
$this->markTestSkipped('The Serializer default cache warmer has been introduced in the Serializer Component version 3.2.');
}
$loaders = [
new XmlFileLoader(__DIR__.'/../Fixtures/Serialization/Resources/person.xml'),
new YamlFileLoader(__DIR__.'/../Fixtures/Serialization/Resources/author.yml'),
];
$file = sys_get_temp_dir().'/cache-serializer.php';
@unlink($file);
$fallbackPool = new ArrayAdapter();
$warmer = new SerializerCacheWarmer($loaders, $file, $fallbackPool);
$warmer->warmUp(\dirname($file));
$this->assertFileExists($file);
$arrayPool = new PhpArrayAdapter($file, new NullAdapter());
$this->assertTrue($arrayPool->getItem('Symfony_Bundle_FrameworkBundle_Tests_Fixtures_Serialization_Person')->isHit());
$this->assertTrue($arrayPool->getItem('Symfony_Bundle_FrameworkBundle_Tests_Fixtures_Serialization_Author')->isHit());
$values = $fallbackPool->getValues();
$this->assertIsArray($values);
$this->assertCount(2, $values);
$this->assertArrayHasKey('Symfony_Bundle_FrameworkBundle_Tests_Fixtures_Serialization_Person', $values);
$this->assertArrayHasKey('Symfony_Bundle_FrameworkBundle_Tests_Fixtures_Serialization_Author', $values);
}
public function testWarmUpWithoutLoader()
{
if (!class_exists(CacheClassMetadataFactory::class) || !method_exists(XmlFileLoader::class, 'getMappedClasses') || !method_exists(YamlFileLoader::class, 'getMappedClasses')) {
$this->markTestSkipped('The Serializer default cache warmer has been introduced in the Serializer Component version 3.2.');
}
$file = sys_get_temp_dir().'/cache-serializer-without-loader.php';
@unlink($file);
$fallbackPool = new ArrayAdapter();
$warmer = new SerializerCacheWarmer([], $file, $fallbackPool);
$warmer->warmUp(\dirname($file));
$this->assertFileExists($file);
$values = $fallbackPool->getValues();
$this->assertIsArray($values);
$this->assertCount(0, $values);
}
/**
* Test that the cache warming process is not broken if a class loader
* throws an exception (on class / file not found for example).
*/
public function testClassAutoloadException()
{
if (!class_exists(CacheClassMetadataFactory::class) || !method_exists(XmlFileLoader::class, 'getMappedClasses') || !method_exists(YamlFileLoader::class, 'getMappedClasses')) {
$this->markTestSkipped('The Serializer default cache warmer has been introduced in the Serializer Component version 3.2.');
}
$this->assertFalse(class_exists($mappedClass = 'AClassThatDoesNotExist_FWB_CacheWarmer_SerializerCacheWarmerTest', false));
$warmer = new SerializerCacheWarmer([new YamlFileLoader(__DIR__.'/../Fixtures/Serialization/Resources/does_not_exist.yaml')], tempnam(sys_get_temp_dir(), __FUNCTION__), new ArrayAdapter());
spl_autoload_register($classLoader = function ($class) use ($mappedClass) {
if ($class === $mappedClass) {
throw new \DomainException('This exception should be caught by the warmer.');
}
}, true, true);
$warmer->warmUp('foo');
spl_autoload_unregister($classLoader);
}
/**
* Test that the cache warming process is broken if a class loader throws an
* exception but that is unrelated to the class load.
*/
public function testClassAutoloadExceptionWithUnrelatedException()
{
$this->expectException(\DomainException::class);
$this->expectExceptionMessage('This exception should not be caught by the warmer.');
if (!class_exists(CacheClassMetadataFactory::class) || !method_exists(XmlFileLoader::class, 'getMappedClasses') || !method_exists(YamlFileLoader::class, 'getMappedClasses')) {
$this->markTestSkipped('The Serializer default cache warmer has been introduced in the Serializer Component version 3.2.');
}
$this->assertFalse(class_exists($mappedClass = 'AClassThatDoesNotExist_FWB_CacheWarmer_SerializerCacheWarmerTest', false));
$warmer = new SerializerCacheWarmer([new YamlFileLoader(__DIR__.'/../Fixtures/Serialization/Resources/does_not_exist.yaml')], tempnam(sys_get_temp_dir(), __FUNCTION__), new ArrayAdapter());
spl_autoload_register($classLoader = function ($class) use ($mappedClass) {
if ($class === $mappedClass) {
eval('class '.$mappedClass.'{}');
throw new \DomainException('This exception should not be caught by the warmer.');
}
}, true, true);
$warmer->warmUp('foo');
spl_autoload_unregister($classLoader);
}
}

View File

@@ -0,0 +1,57 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Bundle\FrameworkBundle\Tests\CacheWarmer;
use Symfony\Bundle\FrameworkBundle\CacheWarmer\TemplateFinder;
use Symfony\Bundle\FrameworkBundle\Templating\TemplateFilenameParser;
use Symfony\Bundle\FrameworkBundle\Tests\Fixtures\BaseBundle\BaseBundle;
use Symfony\Bundle\FrameworkBundle\Tests\TestCase;
class TemplateFinderTest extends TestCase
{
public function testFindAllTemplates()
{
$kernel = $this
->getMockBuilder('Symfony\Component\HttpKernel\Kernel')
->disableOriginalConstructor()
->getMock()
;
$kernel
->expects($this->any())
->method('getBundle')
;
$kernel
->expects($this->once())
->method('getBundles')
->willReturn(['BaseBundle' => new BaseBundle()])
;
$parser = new TemplateFilenameParser();
$finder = new TemplateFinder($kernel, $parser, __DIR__.'/../Fixtures/Resources');
$templates = array_map(
function ($template) { return $template->getLogicalName(); },
$finder->findAllTemplates()
);
$this->assertCount(7, $templates, '->findAllTemplates() find all templates in the bundles and global folders');
$this->assertContains('BaseBundle::base.format.engine', $templates);
$this->assertContains('BaseBundle::this.is.a.template.format.engine', $templates);
$this->assertContains('BaseBundle:controller:base.format.engine', $templates);
$this->assertContains('BaseBundle:controller:custom.format.engine', $templates);
$this->assertContains('::this.is.a.template.format.engine', $templates);
$this->assertContains('::resource.format.engine', $templates);
}
}

View File

@@ -0,0 +1,102 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Bundle\FrameworkBundle\Tests\CacheWarmer;
use Symfony\Bundle\FrameworkBundle\CacheWarmer\TemplateFinderInterface;
use Symfony\Bundle\FrameworkBundle\CacheWarmer\TemplatePathsCacheWarmer;
use Symfony\Bundle\FrameworkBundle\Templating\Loader\TemplateLocator;
use Symfony\Bundle\FrameworkBundle\Templating\TemplateReference;
use Symfony\Bundle\FrameworkBundle\Tests\TestCase;
use Symfony\Component\Config\FileLocator;
use Symfony\Component\Filesystem\Filesystem;
class TemplatePathsCacheWarmerTest extends TestCase
{
/** @var Filesystem */
private $filesystem;
/** @var TemplateFinderInterface */
private $templateFinder;
/** @var FileLocator */
private $fileLocator;
/** @var TemplateLocator */
private $templateLocator;
private $tmpDir;
protected function setUp()
{
$this->templateFinder = $this
->getMockBuilder(TemplateFinderInterface::class)
->setMethods(['findAllTemplates'])
->getMock();
$this->fileLocator = $this
->getMockBuilder(FileLocator::class)
->setMethods(['locate'])
->setConstructorArgs(['/path/to/fallback'])
->getMock();
$this->templateLocator = new TemplateLocator($this->fileLocator);
$this->tmpDir = sys_get_temp_dir().\DIRECTORY_SEPARATOR.uniqid('cache_template_paths_', true);
$this->filesystem = new Filesystem();
$this->filesystem->mkdir($this->tmpDir);
}
protected function tearDown()
{
$this->filesystem->remove($this->tmpDir);
}
public function testWarmUp()
{
$template = new TemplateReference('bundle', 'controller', 'name', 'format', 'engine');
$this->templateFinder
->expects($this->once())
->method('findAllTemplates')
->willReturn([$template]);
$this->fileLocator
->expects($this->once())
->method('locate')
->with($template->getPath())
->willReturn(\dirname($this->tmpDir).'/path/to/template.html.twig');
$warmer = new TemplatePathsCacheWarmer($this->templateFinder, $this->templateLocator);
$warmer->warmUp($this->tmpDir);
$this->assertFileEquals(__DIR__.'/../Fixtures/TemplatePathsCache/templates.php', $this->tmpDir.'/templates.php');
}
public function testWarmUpEmpty()
{
$this->templateFinder
->expects($this->once())
->method('findAllTemplates')
->willReturn([]);
$this->fileLocator
->expects($this->never())
->method('locate');
$warmer = new TemplatePathsCacheWarmer($this->templateFinder, $this->templateLocator);
$warmer->warmUp($this->tmpDir);
$this->assertFileExists($this->tmpDir.'/templates.php');
$this->assertSame(file_get_contents(__DIR__.'/../Fixtures/TemplatePathsCache/templates-empty.php'), file_get_contents($this->tmpDir.'/templates.php'));
}
}

View File

@@ -0,0 +1,155 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Bundle\FrameworkBundle\Tests\CacheWarmer;
use Symfony\Bundle\FrameworkBundle\CacheWarmer\ValidatorCacheWarmer;
use Symfony\Bundle\FrameworkBundle\Tests\TestCase;
use Symfony\Component\Cache\Adapter\ArrayAdapter;
use Symfony\Component\Cache\Adapter\NullAdapter;
use Symfony\Component\Cache\Adapter\PhpArrayAdapter;
use Symfony\Component\Validator\Mapping\ClassMetadata;
use Symfony\Component\Validator\ValidatorBuilder;
class ValidatorCacheWarmerTest extends TestCase
{
public function testWarmUp()
{
$validatorBuilder = new ValidatorBuilder();
$validatorBuilder->addXmlMapping(__DIR__.'/../Fixtures/Validation/Resources/person.xml');
$validatorBuilder->addYamlMapping(__DIR__.'/../Fixtures/Validation/Resources/author.yml');
$validatorBuilder->addMethodMapping('loadValidatorMetadata');
$validatorBuilder->enableAnnotationMapping();
$file = sys_get_temp_dir().'/cache-validator.php';
@unlink($file);
$fallbackPool = new ArrayAdapter();
$warmer = new ValidatorCacheWarmer($validatorBuilder, $file, $fallbackPool);
$warmer->warmUp(\dirname($file));
$this->assertFileExists($file);
$arrayPool = new PhpArrayAdapter($file, new NullAdapter());
$this->assertTrue($arrayPool->getItem('Symfony.Bundle.FrameworkBundle.Tests.Fixtures.Validation.Person')->isHit());
$this->assertTrue($arrayPool->getItem('Symfony.Bundle.FrameworkBundle.Tests.Fixtures.Validation.Author')->isHit());
$values = $fallbackPool->getValues();
$this->assertIsArray($values);
$this->assertCount(2, $values);
$this->assertArrayHasKey('Symfony.Bundle.FrameworkBundle.Tests.Fixtures.Validation.Person', $values);
$this->assertArrayHasKey('Symfony.Bundle.FrameworkBundle.Tests.Fixtures.Validation.Author', $values);
}
public function testWarmUpWithAnnotations()
{
$validatorBuilder = new ValidatorBuilder();
$validatorBuilder->addYamlMapping(__DIR__.'/../Fixtures/Validation/Resources/categories.yml');
$validatorBuilder->enableAnnotationMapping();
$file = sys_get_temp_dir().'/cache-validator-with-annotations.php';
@unlink($file);
$fallbackPool = new ArrayAdapter();
$warmer = new ValidatorCacheWarmer($validatorBuilder, $file, $fallbackPool);
$warmer->warmUp(\dirname($file));
$this->assertFileExists($file);
$arrayPool = new PhpArrayAdapter($file, new NullAdapter());
$item = $arrayPool->getItem('Symfony.Bundle.FrameworkBundle.Tests.Fixtures.Validation.Category');
$this->assertTrue($item->isHit());
$this->assertInstanceOf(ClassMetadata::class, $item->get());
$values = $fallbackPool->getValues();
$this->assertIsArray($values);
$this->assertCount(2, $values);
$this->assertArrayHasKey('Symfony.Bundle.FrameworkBundle.Tests.Fixtures.Validation.Category', $values);
$this->assertArrayHasKey('Symfony.Bundle.FrameworkBundle.Tests.Fixtures.Validation.SubCategory', $values);
}
public function testWarmUpWithoutLoader()
{
$validatorBuilder = new ValidatorBuilder();
$file = sys_get_temp_dir().'/cache-validator-without-loaders.php';
@unlink($file);
$fallbackPool = new ArrayAdapter();
$warmer = new ValidatorCacheWarmer($validatorBuilder, $file, $fallbackPool);
$warmer->warmUp(\dirname($file));
$this->assertFileExists($file);
$values = $fallbackPool->getValues();
$this->assertIsArray($values);
$this->assertCount(0, $values);
}
/**
* Test that the cache warming process is not broken if a class loader
* throws an exception (on class / file not found for example).
*/
public function testClassAutoloadException()
{
$this->assertFalse(class_exists($mappedClass = 'AClassThatDoesNotExist_FWB_CacheWarmer_ValidatorCacheWarmerTest', false));
$validatorBuilder = new ValidatorBuilder();
$validatorBuilder->addYamlMapping(__DIR__.'/../Fixtures/Validation/Resources/does_not_exist.yaml');
$warmer = new ValidatorCacheWarmer($validatorBuilder, tempnam(sys_get_temp_dir(), __FUNCTION__), new ArrayAdapter());
spl_autoload_register($classloader = function ($class) use ($mappedClass) {
if ($class === $mappedClass) {
throw new \DomainException('This exception should be caught by the warmer.');
}
}, true, true);
$warmer->warmUp('foo');
spl_autoload_unregister($classloader);
}
/**
* Test that the cache warming process is broken if a class loader throws an
* exception but that is unrelated to the class load.
*/
public function testClassAutoloadExceptionWithUnrelatedException()
{
$this->expectException(\DomainException::class);
$this->expectExceptionMessage('This exception should not be caught by the warmer.');
$this->assertFalse(class_exists($mappedClass = 'AClassThatDoesNotExist_FWB_CacheWarmer_ValidatorCacheWarmerTest', false));
$validatorBuilder = new ValidatorBuilder();
$validatorBuilder->addYamlMapping(__DIR__.'/../Fixtures/Validation/Resources/does_not_exist.yaml');
$warmer = new ValidatorCacheWarmer($validatorBuilder, tempnam(sys_get_temp_dir(), __FUNCTION__), new ArrayAdapter());
spl_autoload_register($classLoader = function ($class) use ($mappedClass) {
if ($class === $mappedClass) {
eval('class '.$mappedClass.'{}');
throw new \DomainException('This exception should not be caught by the warmer.');
}
}, true, true);
$warmer->warmUp('foo');
spl_autoload_unregister($classLoader);
}
}

View File

@@ -0,0 +1,65 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Bundle\FrameworkBundle\Tests;
use Symfony\Bundle\FrameworkBundle\Client;
use Symfony\Bundle\FrameworkBundle\Tests\Functional\AbstractWebTestCase;
use Symfony\Component\HttpFoundation\Response;
class ClientTest extends AbstractWebTestCase
{
public function testRebootKernelBetweenRequests()
{
$mock = $this->getKernelMock();
$mock->expects($this->once())->method('shutdown');
$client = new Client($mock);
$client->request('GET', '/');
$client->request('GET', '/');
}
public function testDisabledRebootKernel()
{
$mock = $this->getKernelMock();
$mock->expects($this->never())->method('shutdown');
$client = new Client($mock);
$client->disableReboot();
$client->request('GET', '/');
$client->request('GET', '/');
}
public function testEnableRebootKernel()
{
$mock = $this->getKernelMock();
$mock->expects($this->once())->method('shutdown');
$client = new Client($mock);
$client->disableReboot();
$client->request('GET', '/');
$client->request('GET', '/');
$client->enableReboot();
$client->request('GET', '/');
}
private function getKernelMock()
{
$mock = $this->getMockBuilder($this->getKernelClass())
->setMethods(['shutdown', 'boot', 'handle'])
->disableOriginalConstructor()
->getMock();
$mock->expects($this->any())->method('handle')->willReturn(new Response('foo'));
return $mock;
}
}

View File

@@ -0,0 +1,92 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Bundle\FrameworkBundle\Tests\Command\CacheClearCommand;
use Symfony\Bundle\FrameworkBundle\Console\Application;
use Symfony\Bundle\FrameworkBundle\Tests\Command\CacheClearCommand\Fixture\TestAppKernel;
use Symfony\Bundle\FrameworkBundle\Tests\TestCase;
use Symfony\Component\Config\ConfigCacheFactory;
use Symfony\Component\Config\Resource\ResourceInterface;
use Symfony\Component\Console\Input\ArrayInput;
use Symfony\Component\Console\Output\NullOutput;
use Symfony\Component\Filesystem\Filesystem;
use Symfony\Component\Finder\Finder;
class CacheClearCommandTest extends TestCase
{
/** @var TestAppKernel */
private $kernel;
/** @var Filesystem */
private $fs;
private $rootDir;
protected function setUp()
{
$this->fs = new Filesystem();
$this->kernel = new TestAppKernel('test', true);
$this->rootDir = sys_get_temp_dir().\DIRECTORY_SEPARATOR.uniqid('sf2_cache_', true);
$this->kernel->setRootDir($this->rootDir);
$this->fs->mkdir($this->rootDir);
}
protected function tearDown()
{
$this->fs->remove($this->rootDir);
}
public function testCacheIsFreshAfterCacheClearedWithWarmup()
{
$input = new ArrayInput(['cache:clear']);
$application = new Application($this->kernel);
$application->setCatchExceptions(false);
$application->doRun($input, new NullOutput());
// Ensure that all *.meta files are fresh
$finder = new Finder();
$metaFiles = $finder->files()->in($this->kernel->getCacheDir())->name('*.php.meta');
// check that cache is warmed up
$this->assertNotEmpty($metaFiles);
$configCacheFactory = new ConfigCacheFactory(true);
foreach ($metaFiles as $file) {
$configCacheFactory->cache(substr($file, 0, -5), function () use ($file) {
$this->fail(sprintf('Meta file "%s" is not fresh', (string) $file));
});
}
// check that app kernel file present in meta file of container's cache
$containerClass = $this->kernel->getContainer()->getParameter('kernel.container_class');
$containerRef = new \ReflectionClass($containerClass);
$containerFile = \dirname(\dirname($containerRef->getFileName())).'/'.$containerClass.'.php';
$containerMetaFile = $containerFile.'.meta';
$kernelRef = new \ReflectionObject($this->kernel);
$kernelFile = $kernelRef->getFileName();
/** @var ResourceInterface[] $meta */
$meta = unserialize(file_get_contents($containerMetaFile));
$found = false;
foreach ($meta as $resource) {
if ((string) $resource === $kernelFile) {
$found = true;
break;
}
}
$this->assertTrue($found, 'Kernel file should present as resource');
if (\defined('HHVM_VERSION')) {
return;
}
$containerRef = new \ReflectionClass(require $containerFile);
$containerFile = str_replace('tes_'.\DIRECTORY_SEPARATOR, 'test'.\DIRECTORY_SEPARATOR, $containerRef->getFileName());
$this->assertRegExp(sprintf('/\'kernel.container_class\'\s*=>\s*\'%s\'/', $containerClass), file_get_contents($containerFile), 'kernel.container_class is properly set on the dumped container');
}
}

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\Bundle\FrameworkBundle\Tests\Command\CacheClearCommand\Fixture;
use Psr\Log\NullLogger;
use Symfony\Bundle\FrameworkBundle\FrameworkBundle;
use Symfony\Component\Config\Loader\LoaderInterface;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\HttpKernel\Kernel;
class TestAppKernel extends Kernel
{
public function registerBundles()
{
return [
new FrameworkBundle(),
];
}
public function setRootDir($rootDir)
{
$this->rootDir = $rootDir;
}
public function registerContainerConfiguration(LoaderInterface $loader)
{
$loader->load(__DIR__.\DIRECTORY_SEPARATOR.'config.yml');
}
protected function build(ContainerBuilder $container)
{
$container->register('logger', NullLogger::class);
}
}

View File

@@ -0,0 +1,2 @@
framework:
secret: test

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\Bundle\FrameworkBundle\Tests\Command;
use PHPUnit\Framework\MockObject\MockObject;
use Symfony\Bundle\FrameworkBundle\Command\CachePoolPruneCommand;
use Symfony\Bundle\FrameworkBundle\Console\Application;
use Symfony\Bundle\FrameworkBundle\Tests\TestCase;
use Symfony\Component\Cache\PruneableInterface;
use Symfony\Component\Console\Tester\CommandTester;
use Symfony\Component\DependencyInjection\Argument\RewindableGenerator;
use Symfony\Component\HttpKernel\KernelInterface;
class CachePruneCommandTest extends TestCase
{
public function testCommandWithPools()
{
$tester = $this->getCommandTester($this->getKernel(), $this->getRewindableGenerator());
$tester->execute([]);
}
public function testCommandWithNoPools()
{
$tester = $this->getCommandTester($this->getKernel(), $this->getEmptyRewindableGenerator());
$tester->execute([]);
}
/**
* @return RewindableGenerator
*/
private function getRewindableGenerator()
{
return new RewindableGenerator(function () {
yield 'foo_pool' => $this->getPruneableInterfaceMock();
yield 'bar_pool' => $this->getPruneableInterfaceMock();
}, 2);
}
/**
* @return RewindableGenerator
*/
private function getEmptyRewindableGenerator()
{
return new RewindableGenerator(function () {
return new \ArrayIterator([]);
}, 0);
}
/**
* @return MockObject|KernelInterface
*/
private function getKernel()
{
$container = $this
->getMockBuilder('Symfony\Component\DependencyInjection\ContainerInterface')
->getMock();
$kernel = $this
->getMockBuilder(KernelInterface::class)
->getMock();
$kernel
->expects($this->any())
->method('getContainer')
->willReturn($container);
$kernel
->expects($this->once())
->method('getBundles')
->willReturn([]);
return $kernel;
}
/**
* @return MockObject|PruneableInterface
*/
private function getPruneableInterfaceMock()
{
$pruneable = $this
->getMockBuilder(PruneableInterface::class)
->getMock();
$pruneable
->expects($this->atLeastOnce())
->method('prune');
return $pruneable;
}
/**
* @return CommandTester
*/
private function getCommandTester(KernelInterface $kernel, RewindableGenerator $generator)
{
$application = new Application($kernel);
$application->add(new CachePoolPruneCommand($generator));
return new CommandTester($application->find('cache:pool:prune'));
}
}

View File

@@ -0,0 +1,123 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Bundle\FrameworkBundle\Tests\Command;
use PHPUnit\Framework\TestCase;
use Symfony\Bundle\FrameworkBundle\Command\RouterDebugCommand;
use Symfony\Bundle\FrameworkBundle\Console\Application;
use Symfony\Component\Console\Tester\CommandTester;
use Symfony\Component\HttpKernel\KernelInterface;
use Symfony\Component\Routing\Route;
use Symfony\Component\Routing\RouteCollection;
class RouterDebugCommandTest extends TestCase
{
public function testDebugAllRoutes()
{
$tester = $this->createCommandTester();
$ret = $tester->execute(['name' => null], ['decorated' => false]);
$this->assertEquals(0, $ret, 'Returns 0 in case of success');
$this->assertStringContainsString('Name Method Scheme Host Path', $tester->getDisplay());
}
public function testDebugSingleRoute()
{
$tester = $this->createCommandTester();
$ret = $tester->execute(['name' => 'foo'], ['decorated' => false]);
$this->assertEquals(0, $ret, 'Returns 0 in case of success');
$this->assertStringContainsString('Route Name | foo', $tester->getDisplay());
}
public function testDebugInvalidRoute()
{
$this->expectException('InvalidArgumentException');
$this->createCommandTester()->execute(['name' => 'test']);
}
/**
* @group legacy
* @expectedDeprecation Symfony\Bundle\FrameworkBundle\Command\RouterDebugCommand::__construct() expects an instance of "Symfony\Component\Routing\RouterInterface" as first argument since Symfony 3.4. Not passing it is deprecated and will throw a TypeError in 4.0.
*/
public function testLegacyDebugCommand()
{
$application = new Application($this->getKernel());
$application->add(new RouterDebugCommand());
$tester = new CommandTester($application->find('debug:router'));
$tester->execute([]);
$this->assertRegExp('/foo\s+ANY\s+ANY\s+ANY\s+\\/foo/', $tester->getDisplay());
}
/**
* @return CommandTester
*/
private function createCommandTester()
{
$application = new Application($this->getKernel());
$application->add(new RouterDebugCommand($this->getRouter()));
return new CommandTester($application->find('debug:router'));
}
private function getRouter()
{
$routeCollection = new RouteCollection();
$routeCollection->add('foo', new Route('foo'));
$router = $this->getMockBuilder('Symfony\Component\Routing\RouterInterface')->getMock();
$router
->expects($this->any())
->method('getRouteCollection')
->willReturn($routeCollection);
return $router;
}
private function getKernel()
{
$container = $this->getMockBuilder('Symfony\Component\DependencyInjection\ContainerInterface')->getMock();
$container
->expects($this->atLeastOnce())
->method('has')
->willReturnCallback(function ($id) {
if ('console.command_loader' === $id) {
return false;
}
return true;
})
;
$container
->expects($this->any())
->method('get')
->with('router')
->willReturn($this->getRouter())
;
$kernel = $this->getMockBuilder(KernelInterface::class)->getMock();
$kernel
->expects($this->any())
->method('getContainer')
->willReturn($container)
;
$kernel
->expects($this->once())
->method('getBundles')
->willReturn([])
;
return $kernel;
}
}

View File

@@ -0,0 +1,123 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Bundle\FrameworkBundle\Tests\Command;
use PHPUnit\Framework\TestCase;
use Symfony\Bundle\FrameworkBundle\Command\RouterDebugCommand;
use Symfony\Bundle\FrameworkBundle\Command\RouterMatchCommand;
use Symfony\Bundle\FrameworkBundle\Console\Application;
use Symfony\Component\Console\Tester\CommandTester;
use Symfony\Component\HttpKernel\KernelInterface;
use Symfony\Component\Routing\RequestContext;
use Symfony\Component\Routing\Route;
use Symfony\Component\Routing\RouteCollection;
class RouterMatchCommandTest extends TestCase
{
public function testWithMatchPath()
{
$tester = $this->createCommandTester();
$ret = $tester->execute(['path_info' => '/foo', 'foo'], ['decorated' => false]);
$this->assertEquals(0, $ret, 'Returns 0 in case of success');
$this->assertStringContainsString('Route Name | foo', $tester->getDisplay());
}
public function testWithNotMatchPath()
{
$tester = $this->createCommandTester();
$ret = $tester->execute(['path_info' => '/test', 'foo'], ['decorated' => false]);
$this->assertEquals(1, $ret, 'Returns 1 in case of failure');
$this->assertStringContainsString('None of the routes match the path "/test"', $tester->getDisplay());
}
/**
* @group legacy
* @expectedDeprecation Symfony\Bundle\FrameworkBundle\Command\RouterMatchCommand::__construct() expects an instance of "Symfony\Component\Routing\RouterInterface" as first argument since Symfony 3.4. Not passing it is deprecated and will throw a TypeError in 4.0.
* @expectedDeprecation Symfony\Bundle\FrameworkBundle\Command\RouterDebugCommand::__construct() expects an instance of "Symfony\Component\Routing\RouterInterface" as first argument since Symfony 3.4. Not passing it is deprecated and will throw a TypeError in 4.0.
*/
public function testLegacyMatchCommand()
{
$application = new Application($this->getKernel());
$application->add(new RouterMatchCommand());
$application->add(new RouterDebugCommand());
$tester = new CommandTester($application->find('router:match'));
$tester->execute(['path_info' => '/']);
$this->assertStringContainsString('None of the routes match the path "/"', $tester->getDisplay());
}
/**
* @return CommandTester
*/
private function createCommandTester()
{
$application = new Application($this->getKernel());
$application->add(new RouterMatchCommand($this->getRouter()));
$application->add(new RouterDebugCommand($this->getRouter()));
return new CommandTester($application->find('router:match'));
}
private function getRouter()
{
$routeCollection = new RouteCollection();
$routeCollection->add('foo', new Route('foo'));
$requestContext = new RequestContext();
$router = $this->getMockBuilder('Symfony\Component\Routing\RouterInterface')->getMock();
$router
->expects($this->any())
->method('getRouteCollection')
->willReturn($routeCollection);
$router
->expects($this->any())
->method('getContext')
->willReturn($requestContext);
return $router;
}
private function getKernel()
{
$container = $this->getMockBuilder('Symfony\Component\DependencyInjection\ContainerInterface')->getMock();
$container
->expects($this->atLeastOnce())
->method('has')
->willReturnCallback(function ($id) {
return 'console.command_loader' !== $id;
})
;
$container
->expects($this->any())
->method('get')
->with('router')
->willReturn($this->getRouter())
;
$kernel = $this->getMockBuilder(KernelInterface::class)->getMock();
$kernel
->expects($this->any())
->method('getContainer')
->willReturn($container)
;
$kernel
->expects($this->once())
->method('getBundles')
->willReturn([])
;
return $kernel;
}
}

View File

@@ -0,0 +1,256 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Bundle\FrameworkBundle\Tests\Command;
use PHPUnit\Framework\TestCase;
use Symfony\Bundle\FrameworkBundle\Command\TranslationDebugCommand;
use Symfony\Bundle\FrameworkBundle\Console\Application;
use Symfony\Component\Console\Tester\CommandTester;
use Symfony\Component\Filesystem\Filesystem;
use Symfony\Component\HttpKernel;
class TranslationDebugCommandTest extends TestCase
{
private $fs;
private $translationDir;
public function testDebugMissingMessages()
{
$tester = $this->createCommandTester(['foo' => 'foo']);
$tester->execute(['locale' => 'en', 'bundle' => 'foo']);
$this->assertRegExp('/missing/', $tester->getDisplay());
}
public function testDebugUnusedMessages()
{
$tester = $this->createCommandTester([], ['foo' => 'foo']);
$tester->execute(['locale' => 'en', 'bundle' => 'foo']);
$this->assertRegExp('/unused/', $tester->getDisplay());
}
public function testDebugFallbackMessages()
{
$tester = $this->createCommandTester([], ['foo' => 'foo']);
$tester->execute(['locale' => 'fr', 'bundle' => 'foo']);
$this->assertRegExp('/fallback/', $tester->getDisplay());
}
public function testNoDefinedMessages()
{
$tester = $this->createCommandTester();
$tester->execute(['locale' => 'fr', 'bundle' => 'test']);
$this->assertRegExp('/No defined or extracted messages for locale "fr"/', $tester->getDisplay());
}
public function testDebugDefaultDirectory()
{
$tester = $this->createCommandTester(['foo' => 'foo'], ['bar' => 'bar']);
$tester->execute(['locale' => 'en']);
$this->assertRegExp('/missing/', $tester->getDisplay());
$this->assertRegExp('/unused/', $tester->getDisplay());
}
public function testDebugDefaultRootDirectory()
{
$this->fs->remove($this->translationDir);
$this->fs = new Filesystem();
$this->translationDir = sys_get_temp_dir().'/'.uniqid('sf2_translation', true);
$this->fs->mkdir($this->translationDir.'/translations');
$this->fs->mkdir($this->translationDir.'/templates');
$tester = $this->createCommandTester(['foo' => 'foo'], ['bar' => 'bar']);
$tester->execute(['locale' => 'en']);
$this->assertRegExp('/missing/', $tester->getDisplay());
$this->assertRegExp('/unused/', $tester->getDisplay());
}
public function testDebugCustomDirectory()
{
$kernel = $this->getMockBuilder('Symfony\Component\HttpKernel\KernelInterface')->getMock();
$kernel->expects($this->once())
->method('getBundle')
->with($this->equalTo($this->translationDir))
->willThrowException(new \InvalidArgumentException());
$tester = $this->createCommandTester(['foo' => 'foo'], ['bar' => 'bar'], $kernel);
$tester->execute(['locale' => 'en', 'bundle' => $this->translationDir]);
$this->assertRegExp('/missing/', $tester->getDisplay());
$this->assertRegExp('/unused/', $tester->getDisplay());
}
public function testDebugInvalidDirectory()
{
$this->expectException('InvalidArgumentException');
$kernel = $this->getMockBuilder('Symfony\Component\HttpKernel\KernelInterface')->getMock();
$kernel->expects($this->once())
->method('getBundle')
->with($this->equalTo('dir'))
->willThrowException(new \InvalidArgumentException());
$tester = $this->createCommandTester([], [], $kernel);
$tester->execute(['locale' => 'en', 'bundle' => 'dir']);
}
protected function setUp()
{
$this->fs = new Filesystem();
$this->translationDir = sys_get_temp_dir().'/'.uniqid('sf2_translation', true);
$this->fs->mkdir($this->translationDir.'/Resources/translations');
$this->fs->mkdir($this->translationDir.'/Resources/views');
$this->fs->mkdir($this->translationDir.'/translations');
$this->fs->mkdir($this->translationDir.'/templates');
}
protected function tearDown()
{
$this->fs->remove($this->translationDir);
}
/**
* @return CommandTester
*/
private function createCommandTester($extractedMessages = [], $loadedMessages = [], $kernel = null)
{
$translator = $this->getMockBuilder('Symfony\Component\Translation\Translator')
->disableOriginalConstructor()
->getMock();
$translator
->expects($this->any())
->method('getFallbackLocales')
->willReturn(['en']);
$extractor = $this->getMockBuilder('Symfony\Component\Translation\Extractor\ExtractorInterface')->getMock();
$extractor
->expects($this->any())
->method('extract')
->willReturnCallback(
function ($path, $catalogue) use ($extractedMessages) {
$catalogue->add($extractedMessages);
}
);
$loader = $this->getMockBuilder('Symfony\Component\Translation\Reader\TranslationReader')->getMock();
$loader
->expects($this->any())
->method('read')
->willReturnCallback(
function ($path, $catalogue) use ($loadedMessages) {
$catalogue->add($loadedMessages);
}
);
if (null === $kernel) {
$returnValues = [
['foo', $this->getBundle($this->translationDir)],
['test', $this->getBundle('test')],
];
if (HttpKernel\Kernel::VERSION_ID < 40000) {
$returnValues = [
['foo', true, $this->getBundle($this->translationDir)],
['test', true, $this->getBundle('test')],
];
}
$kernel = $this->getMockBuilder('Symfony\Component\HttpKernel\KernelInterface')->getMock();
$kernel
->expects($this->any())
->method('getBundle')
->willReturnMap($returnValues);
}
$kernel
->expects($this->any())
->method('getRootDir')
->willReturn($this->translationDir);
$kernel
->expects($this->any())
->method('getBundles')
->willReturn([]);
$kernel
->expects($this->any())
->method('getContainer')
->willReturn($this->getMockBuilder('Symfony\Component\DependencyInjection\ContainerInterface')->getMock());
$command = new TranslationDebugCommand($translator, $loader, $extractor, $this->translationDir.'/translations', $this->translationDir.'/templates');
$application = new Application($kernel);
$application->add($command);
return new CommandTester($application->find('debug:translation'));
}
/**
* @group legacy
* @expectedDeprecation Symfony\Bundle\FrameworkBundle\Command\TranslationDebugCommand::__construct() expects an instance of "Symfony\Component\Translation\TranslatorInterface" as first argument since Symfony 3.4. Not passing it is deprecated and will throw a TypeError in 4.0.
*/
public function testLegacyDebugCommand()
{
$translator = $this->getMockBuilder('Symfony\Component\Translation\Translator')
->disableOriginalConstructor()
->getMock();
$extractor = $this->getMockBuilder('Symfony\Component\Translation\Extractor\ExtractorInterface')->getMock();
$loader = $this->getMockBuilder('Symfony\Bundle\FrameworkBundle\Translation\TranslationLoader')->getMock();
$kernel = $this->getMockBuilder('Symfony\Component\HttpKernel\KernelInterface')->getMock();
$kernel
->expects($this->any())
->method('getBundles')
->willReturn([]);
$container = $this->getMockBuilder('Symfony\Component\DependencyInjection\ContainerInterface')->getMock();
$container
->expects($this->any())
->method('get')
->willReturnMap([
['translation.extractor', 1, $extractor],
['translation.reader', 1, $loader],
['translator', 1, $translator],
['kernel', 1, $kernel],
]);
$kernel
->expects($this->any())
->method('getContainer')
->willReturn($container);
$command = new TranslationDebugCommand();
$command->setContainer($container);
$application = new Application($kernel);
$application->add($command);
$tester = new CommandTester($application->find('debug:translation'));
$tester->execute(['locale' => 'en']);
$this->assertStringContainsString('No defined or extracted', $tester->getDisplay());
}
private function getBundle($path)
{
$bundle = $this->getMockBuilder('Symfony\Component\HttpKernel\Bundle\BundleInterface')->getMock();
$bundle
->expects($this->any())
->method('getPath')
->willReturn($path)
;
return $bundle;
}
}

View File

@@ -0,0 +1,248 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Bundle\FrameworkBundle\Tests\Command;
use PHPUnit\Framework\TestCase;
use Symfony\Bundle\FrameworkBundle\Command\TranslationUpdateCommand;
use Symfony\Bundle\FrameworkBundle\Console\Application;
use Symfony\Component\Console\Tester\CommandTester;
use Symfony\Component\Filesystem\Filesystem;
use Symfony\Component\HttpKernel;
class TranslationUpdateCommandTest extends TestCase
{
private $fs;
private $translationDir;
public function testDumpMessagesAndClean()
{
$tester = $this->createCommandTester(['messages' => ['foo' => 'foo']]);
$tester->execute(['command' => 'translation:update', 'locale' => 'en', 'bundle' => 'foo', '--dump-messages' => true, '--clean' => true]);
$this->assertRegExp('/foo/', $tester->getDisplay());
$this->assertRegExp('/1 message was successfully extracted/', $tester->getDisplay());
}
public function testDumpMessagesAndCleanInRootDirectory()
{
$this->fs->remove($this->translationDir);
$this->translationDir = sys_get_temp_dir().'/'.uniqid('sf2_translation', true);
$this->fs->mkdir($this->translationDir.'/translations');
$this->fs->mkdir($this->translationDir.'/templates');
$tester = $this->createCommandTester(['messages' => ['foo' => 'foo']]);
$tester->execute(['command' => 'translation:update', 'locale' => 'en', '--dump-messages' => true, '--clean' => true]);
$this->assertRegExp('/foo/', $tester->getDisplay());
$this->assertRegExp('/1 message was successfully extracted/', $tester->getDisplay());
}
public function testDumpTwoMessagesAndClean()
{
$tester = $this->createCommandTester(['messages' => ['foo' => 'foo', 'bar' => 'bar']]);
$tester->execute(['command' => 'translation:update', 'locale' => 'en', 'bundle' => 'foo', '--dump-messages' => true, '--clean' => true]);
$this->assertRegExp('/foo/', $tester->getDisplay());
$this->assertRegExp('/bar/', $tester->getDisplay());
$this->assertRegExp('/2 messages were successfully extracted/', $tester->getDisplay());
}
public function testDumpMessagesForSpecificDomain()
{
$tester = $this->createCommandTester(['messages' => ['foo' => 'foo'], 'mydomain' => ['bar' => 'bar']]);
$tester->execute(['command' => 'translation:update', 'locale' => 'en', 'bundle' => 'foo', '--dump-messages' => true, '--clean' => true, '--domain' => 'mydomain']);
$this->assertRegExp('/bar/', $tester->getDisplay());
$this->assertRegExp('/1 message was successfully extracted/', $tester->getDisplay());
}
public function testWriteMessages()
{
$tester = $this->createCommandTester(['messages' => ['foo' => 'foo']]);
$tester->execute(['command' => 'translation:update', 'locale' => 'en', 'bundle' => 'foo', '--force' => true]);
$this->assertRegExp('/Translation files were successfully updated./', $tester->getDisplay());
}
public function testWriteMessagesInRootDirectory()
{
$this->fs->remove($this->translationDir);
$this->translationDir = sys_get_temp_dir().'/'.uniqid('sf2_translation', true);
$this->fs->mkdir($this->translationDir.'/translations');
$this->fs->mkdir($this->translationDir.'/templates');
$tester = $this->createCommandTester(['messages' => ['foo' => 'foo']]);
$tester->execute(['command' => 'translation:update', 'locale' => 'en', '--force' => true]);
$this->assertRegExp('/Translation files were successfully updated./', $tester->getDisplay());
}
public function testWriteMessagesForSpecificDomain()
{
$tester = $this->createCommandTester(['messages' => ['foo' => 'foo'], 'mydomain' => ['bar' => 'bar']]);
$tester->execute(['command' => 'translation:update', 'locale' => 'en', 'bundle' => 'foo', '--force' => true, '--domain' => 'mydomain']);
$this->assertRegExp('/Translation files were successfully updated./', $tester->getDisplay());
}
protected function setUp()
{
$this->fs = new Filesystem();
$this->translationDir = sys_get_temp_dir().'/'.uniqid('sf2_translation', true);
$this->fs->mkdir($this->translationDir.'/Resources/translations');
$this->fs->mkdir($this->translationDir.'/Resources/views');
$this->fs->mkdir($this->translationDir.'/translations');
$this->fs->mkdir($this->translationDir.'/templates');
}
protected function tearDown()
{
$this->fs->remove($this->translationDir);
}
/**
* @return CommandTester
*/
private function createCommandTester($extractedMessages = [], $loadedMessages = [], HttpKernel\KernelInterface $kernel = null)
{
$translator = $this->getMockBuilder('Symfony\Component\Translation\Translator')
->disableOriginalConstructor()
->getMock();
$translator
->expects($this->any())
->method('getFallbackLocales')
->willReturn(['en']);
$extractor = $this->getMockBuilder('Symfony\Component\Translation\Extractor\ExtractorInterface')->getMock();
$extractor
->expects($this->any())
->method('extract')
->willReturnCallback(
function ($path, $catalogue) use ($extractedMessages) {
foreach ($extractedMessages as $domain => $messages) {
$catalogue->add($messages, $domain);
}
}
);
$loader = $this->getMockBuilder('Symfony\Component\Translation\Reader\TranslationReader')->getMock();
$loader
->expects($this->any())
->method('read')
->willReturnCallback(
function ($path, $catalogue) use ($loadedMessages) {
$catalogue->add($loadedMessages);
}
);
$writer = $this->getMockBuilder('Symfony\Component\Translation\Writer\TranslationWriter')->getMock();
$writer
->expects($this->any())
->method('getFormats')
->willReturn(
['xlf', 'yml', 'yaml']
);
if (null === $kernel) {
$returnValues = [
['foo', $this->getBundle($this->translationDir)],
['test', $this->getBundle('test')],
];
if (HttpKernel\Kernel::VERSION_ID < 40000) {
$returnValues = [
['foo', true, $this->getBundle($this->translationDir)],
['test', true, $this->getBundle('test')],
];
}
$kernel = $this->getMockBuilder('Symfony\Component\HttpKernel\KernelInterface')->getMock();
$kernel
->expects($this->any())
->method('getBundle')
->willReturnMap($returnValues);
}
$kernel
->expects($this->any())
->method('getRootDir')
->willReturn($this->translationDir);
$kernel
->expects($this->any())
->method('getBundles')
->willReturn([]);
$kernel
->expects($this->any())
->method('getContainer')
->willReturn($this->getMockBuilder('Symfony\Component\DependencyInjection\ContainerInterface')->getMock());
$command = new TranslationUpdateCommand($writer, $loader, $extractor, 'en', $this->translationDir.'/translations', $this->translationDir.'/templates');
$application = new Application($kernel);
$application->add($command);
return new CommandTester($application->find('translation:update'));
}
/**
* @group legacy
* @expectedDeprecation Symfony\Bundle\FrameworkBundle\Command\TranslationUpdateCommand::__construct() expects an instance of "Symfony\Component\Translation\Writer\TranslationWriterInterface" as first argument since Symfony 3.4. Not passing it is deprecated and will throw a TypeError in 4.0.
*/
public function testLegacyUpdateCommand()
{
$translator = $this->getMockBuilder('Symfony\Component\Translation\Translator')
->disableOriginalConstructor()
->getMock();
$extractor = $this->getMockBuilder('Symfony\Component\Translation\Extractor\ExtractorInterface')->getMock();
$loader = $this->getMockBuilder('Symfony\Bundle\FrameworkBundle\Translation\TranslationLoader')->getMock();
$writer = $this->getMockBuilder('Symfony\Component\Translation\Writer\TranslationWriter')->getMock();
$kernel = $this->getMockBuilder('Symfony\Component\HttpKernel\KernelInterface')->getMock();
$kernel
->expects($this->any())
->method('getBundles')
->willReturn([]);
$container = $this->getMockBuilder('Symfony\Component\DependencyInjection\ContainerInterface')->getMock();
$container
->expects($this->any())
->method('get')
->willReturnMap([
['translation.extractor', 1, $extractor],
['translation.reader', 1, $loader],
['translation.writer', 1, $writer],
['translator', 1, $translator],
['kernel', 1, $kernel],
]);
$kernel
->expects($this->any())
->method('getContainer')
->willReturn($container);
$command = new TranslationUpdateCommand();
$command->setContainer($container);
$application = new Application($kernel);
$application->add($command);
$tester = new CommandTester($application->find('translation:update'));
$tester->execute(['locale' => 'en']);
$this->assertStringContainsString('You must choose one of --force or --dump-messages', $tester->getDisplay());
}
private function getBundle($path)
{
$bundle = $this->getMockBuilder('Symfony\Component\HttpKernel\Bundle\BundleInterface')->getMock();
$bundle
->expects($this->any())
->method('getPath')
->willReturn($path)
;
return $bundle;
}
}

View File

@@ -0,0 +1,182 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Bundle\FrameworkBundle\Tests\Command;
use PHPUnit\Framework\TestCase;
use Symfony\Bundle\FrameworkBundle\Command\YamlLintCommand;
use Symfony\Bundle\FrameworkBundle\Console\Application;
use Symfony\Component\Console\Application as BaseApplication;
use Symfony\Component\Console\Helper\HelperSet;
use Symfony\Component\Console\Input\InputDefinition;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Tester\CommandTester;
use Symfony\Component\HttpKernel\KernelInterface;
/**
* Tests the YamlLintCommand.
*
* @author Robin Chalas <robin.chalas@gmail.com>
*/
class YamlLintCommandTest extends TestCase
{
private $files;
public function testLintCorrectFile()
{
$tester = $this->createCommandTester();
$filename = $this->createFile('foo: bar');
$tester->execute(
['filename' => $filename],
['verbosity' => OutputInterface::VERBOSITY_VERBOSE, 'decorated' => false]
);
$this->assertEquals(0, $tester->getStatusCode(), 'Returns 0 in case of success');
$this->assertStringContainsString('OK', trim($tester->getDisplay()));
}
public function testLintIncorrectFile()
{
$incorrectContent = '
foo:
bar';
$tester = $this->createCommandTester();
$filename = $this->createFile($incorrectContent);
$tester->execute(['filename' => $filename], ['decorated' => false]);
$this->assertEquals(1, $tester->getStatusCode(), 'Returns 1 in case of error');
$this->assertStringContainsString('Unable to parse at line 3 (near "bar").', trim($tester->getDisplay()));
}
public function testLintFileNotReadable()
{
$this->expectException('RuntimeException');
$tester = $this->createCommandTester();
$filename = $this->createFile('');
unlink($filename);
$tester->execute(['filename' => $filename], ['decorated' => false]);
}
public function testGetHelp()
{
$command = new YamlLintCommand();
$expected = <<<EOF
Or find all files in a bundle:
<info>php %command.full_name% @AcmeDemoBundle</info>
EOF;
$this->assertStringContainsString($expected, $command->getHelp());
}
public function testLintFilesFromBundleDirectory()
{
$tester = $this->createCommandTester($this->getKernelAwareApplicationMock());
$tester->execute(
['filename' => '@AppBundle/Resources'],
['verbosity' => OutputInterface::VERBOSITY_VERBOSE, 'decorated' => false]
);
$this->assertEquals(0, $tester->getStatusCode(), 'Returns 0 in case of success');
$this->assertStringContainsString('[OK] All 0 YAML files contain valid syntax', trim($tester->getDisplay()));
}
/**
* @return string Path to the new file
*/
private function createFile($content)
{
$filename = tempnam(sys_get_temp_dir().'/yml-lint-test', 'sf-');
file_put_contents($filename, $content);
$this->files[] = $filename;
return $filename;
}
/**
* @return CommandTester
*/
private function createCommandTester($application = null)
{
if (!$application) {
$application = new BaseApplication();
$application->add(new YamlLintCommand());
}
$command = $application->find('lint:yaml');
if ($application) {
$command->setApplication($application);
}
return new CommandTester($command);
}
private function getKernelAwareApplicationMock()
{
$kernel = $this->getMockBuilder(KernelInterface::class)
->disableOriginalConstructor()
->getMock();
$kernel
->expects($this->once())
->method('locateResource')
->with('@AppBundle/Resources')
->willReturn(sys_get_temp_dir().'/yml-lint-test');
$application = $this->getMockBuilder(Application::class)
->disableOriginalConstructor()
->getMock();
$application
->expects($this->once())
->method('getKernel')
->willReturn($kernel);
$application
->expects($this->once())
->method('getHelperSet')
->willReturn(new HelperSet());
$application
->expects($this->any())
->method('getDefinition')
->willReturn(new InputDefinition());
$application
->expects($this->once())
->method('find')
->with('lint:yaml')
->willReturn(new YamlLintCommand());
return $application;
}
protected function setUp()
{
@mkdir(sys_get_temp_dir().'/yml-lint-test');
$this->files = [];
}
protected function tearDown()
{
foreach ($this->files as $file) {
if (file_exists($file)) {
unlink($file);
}
}
rmdir(sys_get_temp_dir().'/yml-lint-test');
}
}

View File

@@ -0,0 +1,261 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Bundle\FrameworkBundle\Tests\Console;
use Symfony\Bundle\FrameworkBundle\Console\Application;
use Symfony\Bundle\FrameworkBundle\Tests\TestCase;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\ArrayInput;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\NullOutput;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Tester\ApplicationTester;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\EventDispatcher\EventDispatcher;
use Symfony\Component\HttpKernel\KernelInterface;
class ApplicationTest extends TestCase
{
public function testBundleInterfaceImplementation()
{
$bundle = $this->getMockBuilder('Symfony\Component\HttpKernel\Bundle\BundleInterface')->getMock();
$kernel = $this->getKernel([$bundle], true);
$application = new Application($kernel);
$application->doRun(new ArrayInput(['list']), new NullOutput());
}
public function testBundleCommandsAreRegistered()
{
$bundle = $this->createBundleMock([]);
$kernel = $this->getKernel([$bundle], true);
$application = new Application($kernel);
$application->doRun(new ArrayInput(['list']), new NullOutput());
// Calling twice: registration should only be done once.
$application->doRun(new ArrayInput(['list']), new NullOutput());
}
public function testBundleCommandsAreRetrievable()
{
$bundle = $this->createBundleMock([]);
$kernel = $this->getKernel([$bundle]);
$application = new Application($kernel);
$application->all();
// Calling twice: registration should only be done once.
$application->all();
}
public function testBundleSingleCommandIsRetrievable()
{
$command = new Command('example');
$bundle = $this->createBundleMock([$command]);
$kernel = $this->getKernel([$bundle]);
$application = new Application($kernel);
$this->assertSame($command, $application->get('example'));
}
public function testBundleCommandCanBeFound()
{
$command = new Command('example');
$bundle = $this->createBundleMock([$command]);
$kernel = $this->getKernel([$bundle]);
$application = new Application($kernel);
$this->assertSame($command, $application->find('example'));
}
public function testBundleCommandCanBeFoundByAlias()
{
$command = new Command('example');
$command->setAliases(['alias']);
$bundle = $this->createBundleMock([$command]);
$kernel = $this->getKernel([$bundle]);
$application = new Application($kernel);
$this->assertSame($command, $application->find('alias'));
}
public function testBundleCommandsHaveRightContainer()
{
$command = $this->getMockForAbstractClass('Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand', ['foo'], '', true, true, true, ['setContainer']);
$command->setCode(function () {});
$command->expects($this->exactly(2))->method('setContainer');
$application = new Application($this->getKernel([], true));
$application->setAutoExit(false);
$application->setCatchExceptions(false);
$application->add($command);
$tester = new ApplicationTester($application);
// set container is called here
$tester->run(['command' => 'foo']);
// as the container might have change between two runs, setContainer must called again
$tester->run(['command' => 'foo']);
}
public function testBundleCommandCanOverriddeAPreExistingCommandWithTheSameName()
{
$command = new Command('example');
$bundle = $this->createBundleMock([$command]);
$kernel = $this->getKernel([$bundle]);
$application = new Application($kernel);
$newCommand = new Command('example');
$application->add($newCommand);
$this->assertSame($newCommand, $application->get('example'));
}
public function testRunOnlyWarnsOnUnregistrableCommand()
{
$container = new ContainerBuilder();
$container->register('event_dispatcher', EventDispatcher::class);
$container->register(ThrowingCommand::class, ThrowingCommand::class);
$container->setParameter('console.command.ids', [ThrowingCommand::class => ThrowingCommand::class]);
$kernel = $this->getMockBuilder(KernelInterface::class)->getMock();
$kernel
->method('getBundles')
->willReturn([$this->createBundleMock(
[(new Command('fine'))->setCode(function (InputInterface $input, OutputInterface $output) { $output->write('fine'); })]
)]);
$kernel
->method('getContainer')
->willReturn($container);
$application = new Application($kernel);
$application->setAutoExit(false);
$tester = new ApplicationTester($application);
$tester->run(['command' => 'fine']);
$output = $tester->getDisplay();
$this->assertSame(0, $tester->getStatusCode());
$this->assertStringContainsString('Some commands could not be registered:', $output);
$this->assertStringContainsString('throwing', $output);
$this->assertStringContainsString('fine', $output);
}
public function testRegistrationErrorsAreDisplayedOnCommandNotFound()
{
$container = new ContainerBuilder();
$container->register('event_dispatcher', EventDispatcher::class);
$kernel = $this->getMockBuilder(KernelInterface::class)->getMock();
$kernel
->method('getBundles')
->willReturn([$this->createBundleMock(
[(new Command(null))->setCode(function (InputInterface $input, OutputInterface $output) { $output->write('fine'); })]
)]);
$kernel
->method('getContainer')
->willReturn($container);
$application = new Application($kernel);
$application->setAutoExit(false);
$tester = new ApplicationTester($application);
$tester->run(['command' => 'fine']);
$output = $tester->getDisplay();
$this->assertSame(1, $tester->getStatusCode());
$this->assertStringContainsString('Some commands could not be registered:', $output);
$this->assertStringContainsString('Command "fine" is not defined.', $output);
}
private function getKernel(array $bundles, $useDispatcher = false)
{
$container = $this->getMockBuilder('Symfony\Component\DependencyInjection\ContainerInterface')->getMock();
if ($useDispatcher) {
$dispatcher = $this->getMockBuilder('Symfony\Component\EventDispatcher\EventDispatcherInterface')->getMock();
$dispatcher
->expects($this->atLeastOnce())
->method('dispatch')
;
$container
->expects($this->atLeastOnce())
->method('get')
->with($this->equalTo('event_dispatcher'))
->willReturn($dispatcher);
}
$container
->expects($this->exactly(2))
->method('hasParameter')
->withConsecutive(['console.command.ids'], ['console.lazy_command.ids'])
->willReturnOnConsecutiveCalls(true, true)
;
$container
->expects($this->exactly(2))
->method('getParameter')
->withConsecutive(['console.lazy_command.ids'], ['console.command.ids'])
->willReturnOnConsecutiveCalls([], [])
;
$kernel = $this->getMockBuilder('Symfony\Component\HttpKernel\KernelInterface')->getMock();
$kernel
->expects($this->any())
->method('getBundles')
->willReturn($bundles)
;
$kernel
->expects($this->any())
->method('getContainer')
->willReturn($container)
;
return $kernel;
}
private function createBundleMock(array $commands)
{
$bundle = $this->getMockBuilder('Symfony\Component\HttpKernel\Bundle\Bundle')->getMock();
$bundle
->expects($this->once())
->method('registerCommands')
->willReturnCallback(function (Application $application) use ($commands) {
$application->addCommands($commands);
})
;
return $bundle;
}
}
class ThrowingCommand extends Command
{
public function __construct()
{
throw new \Exception('throwing');
}
}

View File

@@ -0,0 +1,252 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Bundle\FrameworkBundle\Tests\Console\Descriptor;
use PHPUnit\Framework\TestCase;
use Symfony\Component\Console\Input\ArrayInput;
use Symfony\Component\Console\Output\BufferedOutput;
use Symfony\Component\Console\Style\SymfonyStyle;
use Symfony\Component\DependencyInjection\Alias;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Definition;
use Symfony\Component\DependencyInjection\ParameterBag\ParameterBag;
use Symfony\Component\EventDispatcher\EventDispatcher;
use Symfony\Component\Routing\Route;
use Symfony\Component\Routing\RouteCollection;
abstract class AbstractDescriptorTest extends TestCase
{
/** @dataProvider getDescribeRouteCollectionTestData */
public function testDescribeRouteCollection(RouteCollection $routes, $expectedDescription)
{
$this->assertDescription($expectedDescription, $routes);
}
public function getDescribeRouteCollectionTestData()
{
return $this->getDescriptionTestData(ObjectsProvider::getRouteCollections());
}
/** @dataProvider getDescribeRouteTestData */
public function testDescribeRoute(Route $route, $expectedDescription)
{
$this->assertDescription($expectedDescription, $route);
}
public function getDescribeRouteTestData()
{
return $this->getDescriptionTestData(ObjectsProvider::getRoutes());
}
/** @dataProvider getDescribeContainerParametersTestData */
public function testDescribeContainerParameters(ParameterBag $parameters, $expectedDescription)
{
$this->assertDescription($expectedDescription, $parameters);
}
public function getDescribeContainerParametersTestData()
{
return $this->getDescriptionTestData(ObjectsProvider::getContainerParameters());
}
/** @dataProvider getDescribeContainerBuilderTestData */
public function testDescribeContainerBuilder(ContainerBuilder $builder, $expectedDescription, array $options)
{
$this->assertDescription($expectedDescription, $builder, $options);
}
public function getDescribeContainerBuilderTestData()
{
return $this->getContainerBuilderDescriptionTestData(ObjectsProvider::getContainerBuilders());
}
/** @dataProvider getDescribeContainerDefinitionTestData */
public function testDescribeContainerDefinition(Definition $definition, $expectedDescription)
{
$this->assertDescription($expectedDescription, $definition);
}
public function getDescribeContainerDefinitionTestData()
{
return $this->getDescriptionTestData(ObjectsProvider::getContainerDefinitions());
}
/** @dataProvider getDescribeContainerDefinitionWithArgumentsShownTestData */
public function testDescribeContainerDefinitionWithArgumentsShown(Definition $definition, $expectedDescription)
{
$this->assertDescription($expectedDescription, $definition, ['show_arguments' => true]);
}
public function getDescribeContainerDefinitionWithArgumentsShownTestData()
{
$definitions = ObjectsProvider::getContainerDefinitions();
$definitionsWithArgs = [];
foreach ($definitions as $key => $definition) {
$definitionsWithArgs[str_replace('definition_', 'definition_arguments_', $key)] = $definition;
}
return $this->getDescriptionTestData($definitionsWithArgs);
}
/** @dataProvider getDescribeContainerAliasTestData */
public function testDescribeContainerAlias(Alias $alias, $expectedDescription)
{
$this->assertDescription($expectedDescription, $alias);
}
public function getDescribeContainerAliasTestData()
{
return $this->getDescriptionTestData(ObjectsProvider::getContainerAliases());
}
/** @dataProvider getDescribeContainerDefinitionWhichIsAnAliasTestData */
public function testDescribeContainerDefinitionWhichIsAnAlias(Alias $alias, $expectedDescription, ContainerBuilder $builder, $options = [])
{
$this->assertDescription($expectedDescription, $builder, $options);
}
public function getDescribeContainerDefinitionWhichIsAnAliasTestData()
{
$builder = current(ObjectsProvider::getContainerBuilders());
$builder->setDefinition('service_1', $builder->getDefinition('definition_1'));
$builder->setDefinition('service_2', $builder->getDefinition('definition_2'));
$aliases = ObjectsProvider::getContainerAliases();
$aliasesWithDefinitions = [];
foreach ($aliases as $name => $alias) {
$aliasesWithDefinitions[str_replace('alias_', 'alias_with_definition_', $name)] = $alias;
}
$i = 0;
$data = $this->getDescriptionTestData($aliasesWithDefinitions);
foreach ($aliases as $name => $alias) {
$data[$i][] = $builder;
$data[$i][] = ['id' => $name];
++$i;
}
return $data;
}
/** @dataProvider getDescribeContainerParameterTestData */
public function testDescribeContainerParameter($parameter, $expectedDescription, array $options)
{
$this->assertDescription($expectedDescription, $parameter, $options);
}
public function getDescribeContainerParameterTestData()
{
$data = $this->getDescriptionTestData(ObjectsProvider::getContainerParameter());
$data[0][] = ['parameter' => 'database_name'];
$data[1][] = ['parameter' => 'twig.form.resources'];
return $data;
}
/** @dataProvider getDescribeEventDispatcherTestData */
public function testDescribeEventDispatcher(EventDispatcher $eventDispatcher, $expectedDescription, array $options)
{
$this->assertDescription($expectedDescription, $eventDispatcher, $options);
}
public function getDescribeEventDispatcherTestData()
{
return $this->getEventDispatcherDescriptionTestData(ObjectsProvider::getEventDispatchers());
}
/** @dataProvider getDescribeCallableTestData */
public function testDescribeCallable($callable, $expectedDescription)
{
$this->assertDescription($expectedDescription, $callable);
}
public function getDescribeCallableTestData()
{
return $this->getDescriptionTestData(ObjectsProvider::getCallables());
}
abstract protected function getDescriptor();
abstract protected function getFormat();
private function assertDescription($expectedDescription, $describedObject, array $options = [])
{
$options['is_debug'] = false;
$options['raw_output'] = true;
$options['raw_text'] = true;
$output = new BufferedOutput(BufferedOutput::VERBOSITY_NORMAL, true);
if ('txt' === $this->getFormat()) {
$options['output'] = new SymfonyStyle(new ArrayInput([]), $output);
}
$this->getDescriptor()->describe($output, $describedObject, $options);
if ('json' === $this->getFormat()) {
$this->assertEquals(json_encode(json_decode($expectedDescription), JSON_PRETTY_PRINT), json_encode(json_decode($output->fetch()), JSON_PRETTY_PRINT));
} else {
$this->assertEquals(trim($expectedDescription), trim(str_replace(PHP_EOL, "\n", $output->fetch())));
}
}
private function getDescriptionTestData(array $objects)
{
$data = [];
foreach ($objects as $name => $object) {
$description = file_get_contents(sprintf('%s/../../Fixtures/Descriptor/%s.%s', __DIR__, $name, $this->getFormat()));
$data[] = [$object, $description];
}
return $data;
}
private function getContainerBuilderDescriptionTestData(array $objects)
{
$variations = [
'services' => ['show_private' => true],
'public' => ['show_private' => false],
'tag1' => ['show_private' => true, 'tag' => 'tag1'],
'tags' => ['group_by' => 'tags', 'show_private' => true],
'arguments' => ['show_private' => false, 'show_arguments' => true],
];
$data = [];
foreach ($objects as $name => $object) {
foreach ($variations as $suffix => $options) {
$description = file_get_contents(sprintf('%s/../../Fixtures/Descriptor/%s_%s.%s', __DIR__, $name, $suffix, $this->getFormat()));
$data[] = [$object, $description, $options];
}
}
return $data;
}
private function getEventDispatcherDescriptionTestData(array $objects)
{
$variations = [
'events' => [],
'event1' => ['event' => 'event1'],
];
$data = [];
foreach ($objects as $name => $object) {
foreach ($variations as $suffix => $options) {
$description = file_get_contents(sprintf('%s/../../Fixtures/Descriptor/%s_%s.%s', __DIR__, $name, $suffix, $this->getFormat()));
$data[] = [$object, $description, $options];
}
}
return $data;
}
}

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\Bundle\FrameworkBundle\Tests\Console\Descriptor;
use Symfony\Bundle\FrameworkBundle\Console\Descriptor\JsonDescriptor;
class JsonDescriptorTest extends AbstractDescriptorTest
{
protected function getDescriptor()
{
return new JsonDescriptor();
}
protected function getFormat()
{
return 'json';
}
}

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\Bundle\FrameworkBundle\Tests\Console\Descriptor;
use Symfony\Bundle\FrameworkBundle\Console\Descriptor\MarkdownDescriptor;
class MarkdownDescriptorTest extends AbstractDescriptorTest
{
protected function getDescriptor()
{
return new MarkdownDescriptor();
}
protected function getFormat()
{
return 'md';
}
}

View File

@@ -0,0 +1,204 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Bundle\FrameworkBundle\Tests\Console\Descriptor;
use Symfony\Component\DependencyInjection\Alias;
use Symfony\Component\DependencyInjection\Argument\IteratorArgument;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Definition;
use Symfony\Component\DependencyInjection\ParameterBag\ParameterBag;
use Symfony\Component\DependencyInjection\Reference;
use Symfony\Component\EventDispatcher\EventDispatcher;
use Symfony\Component\Routing\CompiledRoute;
use Symfony\Component\Routing\Route;
use Symfony\Component\Routing\RouteCollection;
class ObjectsProvider
{
public static function getRouteCollections()
{
$collection1 = new RouteCollection();
foreach (self::getRoutes() as $name => $route) {
$collection1->add($name, $route);
}
return ['route_collection_1' => $collection1];
}
public static function getRoutes()
{
return [
'route_1' => new RouteStub(
'/hello/{name}',
['name' => 'Joseph'],
['name' => '[a-z]+'],
['opt1' => 'val1', 'opt2' => 'val2'],
'localhost',
['http', 'https'],
['get', 'head']
),
'route_2' => new RouteStub(
'/name/add',
[],
[],
['opt1' => 'val1', 'opt2' => 'val2'],
'localhost',
['http', 'https'],
['put', 'post']
),
];
}
public static function getContainerParameters()
{
return [
'parameters_1' => new ParameterBag([
'integer' => 12,
'string' => 'Hello world!',
'boolean' => true,
'array' => [12, 'Hello world!', true],
]),
];
}
public static function getContainerParameter()
{
$builder = new ContainerBuilder();
$builder->setParameter('database_name', 'symfony');
$builder->setParameter('twig.form.resources', [
'bootstrap_3_horizontal_layout.html.twig',
'bootstrap_3_layout.html.twig',
'form_div_layout.html.twig',
'form_table_layout.html.twig',
]);
return [
'parameter' => $builder,
'array_parameter' => $builder,
];
}
public static function getContainerBuilders()
{
$builder1 = new ContainerBuilder();
$builder1->setDefinitions(self::getContainerDefinitions());
$builder1->setAliases(self::getContainerAliases());
return ['builder_1' => $builder1];
}
public static function getContainerDefinitions()
{
$definition1 = new Definition('Full\\Qualified\\Class1');
$definition2 = new Definition('Full\\Qualified\\Class2');
return [
'definition_1' => $definition1
->setPublic(true)
->setSynthetic(false)
->setLazy(true)
->setAbstract(true)
->addArgument(new Reference('definition2'))
->addArgument('%parameter%')
->addArgument(new Definition('inline_service', ['arg1', 'arg2']))
->addArgument([
'foo',
new Reference('definition2'),
new Definition('inline_service'),
])
->addArgument(new IteratorArgument([
new Reference('definition_1'),
new Reference('definition_2'),
]))
->setFactory(['Full\\Qualified\\FactoryClass', 'get']),
'definition_2' => $definition2
->setPublic(false)
->setSynthetic(true)
->setFile('/path/to/file')
->setLazy(false)
->setAbstract(false)
->addTag('tag1', ['attr1' => 'val1', 'attr2' => 'val2'])
->addTag('tag1', ['attr3' => 'val3'])
->addTag('tag2')
->addMethodCall('setMailer', [new Reference('mailer')])
->setFactory([new Reference('factory.service'), 'get']),
];
}
public static function getContainerAliases()
{
return [
'alias_1' => new Alias('service_1', true),
'alias_2' => new Alias('service_2', false),
];
}
public static function getEventDispatchers()
{
$eventDispatcher = new EventDispatcher();
$eventDispatcher->addListener('event1', 'global_function', 255);
$eventDispatcher->addListener('event1', function () { return 'Closure'; }, -1);
$eventDispatcher->addListener('event2', new CallableClass());
return ['event_dispatcher_1' => $eventDispatcher];
}
public static function getCallables()
{
$callables = [
'callable_1' => 'array_key_exists',
'callable_2' => ['Symfony\\Bundle\\FrameworkBundle\\Tests\\Console\\Descriptor\\CallableClass', 'staticMethod'],
'callable_3' => [new CallableClass(), 'method'],
'callable_4' => 'Symfony\\Bundle\\FrameworkBundle\\Tests\\Console\\Descriptor\\CallableClass::staticMethod',
'callable_5' => ['Symfony\\Bundle\\FrameworkBundle\\Tests\\Console\\Descriptor\\ExtendedCallableClass', 'parent::staticMethod'],
'callable_6' => function () { return 'Closure'; },
'callable_7' => new CallableClass(),
];
if (\PHP_VERSION_ID >= 70100) {
$callables['callable_from_callable'] = \Closure::fromCallable(new CallableClass());
}
return $callables;
}
}
class CallableClass
{
public function __invoke()
{
}
public static function staticMethod()
{
}
public function method()
{
}
}
class ExtendedCallableClass extends CallableClass
{
public static function staticMethod()
{
}
}
class RouteStub extends Route
{
public function compile()
{
return new CompiledRoute('', '#PATH_REGEX#', [], [], '#HOST_REGEX#');
}
}

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\Bundle\FrameworkBundle\Tests\Console\Descriptor;
use Symfony\Bundle\FrameworkBundle\Console\Descriptor\TextDescriptor;
class TextDescriptorTest extends AbstractDescriptorTest
{
protected function setUp()
{
putenv('COLUMNS=121');
}
protected function tearDown()
{
putenv('COLUMNS');
}
protected function getDescriptor()
{
return new TextDescriptor();
}
protected function getFormat()
{
return 'txt';
}
}

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\Bundle\FrameworkBundle\Tests\Console\Descriptor;
use Symfony\Bundle\FrameworkBundle\Console\Descriptor\XmlDescriptor;
class XmlDescriptorTest extends AbstractDescriptorTest
{
protected function getDescriptor()
{
return new XmlDescriptor();
}
protected function getFormat()
{
return 'xml';
}
}

View File

@@ -0,0 +1,63 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Bundle\FrameworkBundle\Tests\Controller;
use Psr\Container\ContainerInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
class AbstractControllerTest extends ControllerTraitTest
{
protected function createController()
{
return new TestAbstractController();
}
}
class TestAbstractController extends AbstractController
{
use TestControllerTrait;
private $throwOnUnexpectedService;
public function __construct($throwOnUnexpectedService = true)
{
$this->throwOnUnexpectedService = $throwOnUnexpectedService;
}
public function setContainer(ContainerInterface $container)
{
if (!$this->throwOnUnexpectedService) {
return parent::setContainer($container);
}
$expected = self::getSubscribedServices();
foreach ($container->getServiceIds() as $id) {
if ('service_container' === $id) {
continue;
}
if (!isset($expected[$id])) {
throw new \UnexpectedValueException(sprintf('Service "%s" is not expected, as declared by %s::getSubscribedServices()', $id, AbstractController::class));
}
$type = substr($expected[$id], 1);
if (!$container->get($id) instanceof $type) {
throw new \UnexpectedValueException(sprintf('Service "%s" is expected to be an instance of "%s", as declared by %s::getSubscribedServices()', $id, $type, AbstractController::class));
}
}
return parent::setContainer($container);
}
public function fooAction()
{
}
}

View File

@@ -0,0 +1,192 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Bundle\FrameworkBundle\Tests\Controller;
use Composer\Autoload\ClassLoader;
use Symfony\Bundle\FrameworkBundle\Controller\ControllerNameParser;
use Symfony\Bundle\FrameworkBundle\Tests\TestCase;
use Symfony\Component\HttpKernel\Kernel;
class ControllerNameParserTest extends TestCase
{
protected $loader;
protected function setUp()
{
$this->loader = new ClassLoader();
$this->loader->add('TestBundle', __DIR__.'/../Fixtures');
$this->loader->add('TestApplication', __DIR__.'/../Fixtures');
$this->loader->register();
}
protected function tearDown()
{
$this->loader->unregister();
$this->loader = null;
}
public function testParse()
{
$parser = $this->createParser();
$this->assertEquals('TestBundle\FooBundle\Controller\DefaultController::indexAction', $parser->parse('FooBundle:Default:index'), '->parse() converts a short a:b:c notation string to a class::method string');
$this->assertEquals('TestBundle\FooBundle\Controller\Sub\DefaultController::indexAction', $parser->parse('FooBundle:Sub\Default:index'), '->parse() converts a short a:b:c notation string to a class::method string');
$this->assertEquals('TestBundle\Fabpot\FooBundle\Controller\DefaultController::indexAction', $parser->parse('SensioFooBundle:Default:index'), '->parse() converts a short a:b:c notation string to a class::method string');
$this->assertEquals('TestBundle\Sensio\Cms\FooBundle\Controller\DefaultController::indexAction', $parser->parse('SensioCmsFooBundle:Default:index'), '->parse() converts a short a:b:c notation string to a class::method string');
$this->assertEquals('TestBundle\FooBundle\Controller\Test\DefaultController::indexAction', $parser->parse('FooBundle:Test\\Default:index'), '->parse() converts a short a:b:c notation string to a class::method string');
$this->assertEquals('TestBundle\FooBundle\Controller\Test\DefaultController::indexAction', $parser->parse('FooBundle:Test/Default:index'), '->parse() converts a short a:b:c notation string to a class::method string');
try {
$parser->parse('foo:');
$this->fail('->parse() throws an \InvalidArgumentException if the controller is not an a:b:c string');
} catch (\Exception $e) {
$this->assertInstanceOf('\InvalidArgumentException', $e, '->parse() throws an \InvalidArgumentException if the controller is not an a:b:c string');
}
}
public function testBuild()
{
$parser = $this->createParser();
$this->assertEquals('FoooooBundle:Default:index', $parser->build('TestBundle\FooBundle\Controller\DefaultController::indexAction'), '->parse() converts a class::method string to a short a:b:c notation string');
$this->assertEquals('FoooooBundle:Sub\Default:index', $parser->build('TestBundle\FooBundle\Controller\Sub\DefaultController::indexAction'), '->parse() converts a class::method string to a short a:b:c notation string');
try {
$parser->build('TestBundle\FooBundle\Controller\DefaultController::index');
$this->fail('->parse() throws an \InvalidArgumentException if the controller is not an aController::cAction string');
} catch (\Exception $e) {
$this->assertInstanceOf('\InvalidArgumentException', $e, '->parse() throws an \InvalidArgumentException if the controller is not an aController::cAction string');
}
try {
$parser->build('TestBundle\FooBundle\Controller\Default::indexAction');
$this->fail('->parse() throws an \InvalidArgumentException if the controller is not an aController::cAction string');
} catch (\Exception $e) {
$this->assertInstanceOf('\InvalidArgumentException', $e, '->parse() throws an \InvalidArgumentException if the controller is not an aController::cAction string');
}
try {
$parser->build('Foo\Controller\DefaultController::indexAction');
$this->fail('->parse() throws an \InvalidArgumentException if the controller is not an aController::cAction string');
} catch (\Exception $e) {
$this->assertInstanceOf('\InvalidArgumentException', $e, '->parse() throws an \InvalidArgumentException if the controller is not an aController::cAction string');
}
}
/**
* @dataProvider getMissingControllersTest
*/
public function testMissingControllers($name)
{
$parser = $this->createParser();
try {
$parser->parse($name);
$this->fail('->parse() throws a \InvalidArgumentException if the class is found but does not exist');
} catch (\Exception $e) {
$this->assertInstanceOf('\InvalidArgumentException', $e, '->parse() throws a \InvalidArgumentException if the class is found but does not exist');
}
}
public function getMissingControllersTest()
{
// a normal bundle
$bundles = [
['FooBundle:Fake:index'],
];
// a bundle with children
if (Kernel::VERSION_ID < 40000) {
$bundles[] = ['SensioFooBundle:Fake:index'];
}
return $bundles;
}
/**
* @dataProvider getInvalidBundleNameTests
*/
public function testInvalidBundleName($bundleName, $suggestedBundleName)
{
$parser = $this->createParser();
try {
$parser->parse($bundleName);
$this->fail('->parse() throws a \InvalidArgumentException if the bundle does not exist');
} catch (\Exception $e) {
$this->assertInstanceOf('\InvalidArgumentException', $e, '->parse() throws a \InvalidArgumentException if the bundle does not exist');
if (false === $suggestedBundleName) {
// make sure we don't have a suggestion
$this->assertStringNotContainsString('Did you mean', $e->getMessage());
} else {
$this->assertStringContainsString(sprintf('Did you mean "%s"', $suggestedBundleName), $e->getMessage());
}
}
}
public function getInvalidBundleNameTests()
{
return [
'Alternative will be found using levenshtein' => ['FoodBundle:Default:index', 'FooBundle:Default:index'],
'Alternative will be found using partial match' => ['FabpotFooBund:Default:index', 'FabpotFooBundle:Default:index'],
'Bundle does not exist at all' => ['CrazyBundle:Default:index', false],
];
}
private function createParser()
{
$bundles = [
'SensioFooBundle' => [$this->getBundle('TestBundle\Fabpot\FooBundle', 'FabpotFooBundle'), $this->getBundle('TestBundle\Sensio\FooBundle', 'SensioFooBundle')],
'SensioCmsFooBundle' => [$this->getBundle('TestBundle\Sensio\Cms\FooBundle', 'SensioCmsFooBundle')],
'FooBundle' => [$this->getBundle('TestBundle\FooBundle', 'FooBundle')],
'FabpotFooBundle' => [$this->getBundle('TestBundle\Fabpot\FooBundle', 'FabpotFooBundle'), $this->getBundle('TestBundle\Sensio\FooBundle', 'SensioFooBundle')],
];
$kernel = $this->getMockBuilder('Symfony\Component\HttpKernel\KernelInterface')->getMock();
$kernel
->expects($this->any())
->method('getBundle')
->willReturnCallback(function ($bundle) use ($bundles) {
if (!isset($bundles[$bundle])) {
throw new \InvalidArgumentException(sprintf('Invalid bundle name "%s"', $bundle));
}
return $bundles[$bundle];
})
;
$bundles = [
'SensioFooBundle' => $this->getBundle('TestBundle\Fabpot\FooBundle', 'FabpotFooBundle'),
'SensioCmsFooBundle' => $this->getBundle('TestBundle\Sensio\Cms\FooBundle', 'SensioCmsFooBundle'),
'FoooooBundle' => $this->getBundle('TestBundle\FooBundle', 'FoooooBundle'),
'FooBundle' => $this->getBundle('TestBundle\FooBundle', 'FooBundle'),
'FabpotFooBundle' => $this->getBundle('TestBundle\Fabpot\FooBundle', 'FabpotFooBundle'),
];
$kernel
->expects($this->any())
->method('getBundles')
->willReturn($bundles)
;
return new ControllerNameParser($kernel);
}
private function getBundle($namespace, $name)
{
$bundle = $this->getMockBuilder('Symfony\Component\HttpKernel\Bundle\BundleInterface')->getMock();
$bundle->expects($this->any())->method('getName')->willReturn($name);
$bundle->expects($this->any())->method('getNamespace')->willReturn($namespace);
return $bundle;
}
}

View File

@@ -0,0 +1,223 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Bundle\FrameworkBundle\Tests\Controller;
use Psr\Container\ContainerInterface as Psr11ContainerInterface;
use Psr\Log\LoggerInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Bundle\FrameworkBundle\Controller\ControllerNameParser;
use Symfony\Bundle\FrameworkBundle\Controller\ControllerResolver;
use Symfony\Component\DependencyInjection\Container;
use Symfony\Component\DependencyInjection\ContainerAwareInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Tests\Controller\ContainerControllerResolverTest;
class ControllerResolverTest extends ContainerControllerResolverTest
{
public function testGetControllerOnContainerAware()
{
$resolver = $this->createControllerResolver();
$request = Request::create('/');
$request->attributes->set('_controller', 'Symfony\Bundle\FrameworkBundle\Tests\Controller\ContainerAwareController::testAction');
$controller = $resolver->getController($request);
$this->assertInstanceOf('Symfony\Component\DependencyInjection\ContainerInterface', $controller[0]->getContainer());
$this->assertSame('testAction', $controller[1]);
}
public function testGetControllerOnContainerAwareInvokable()
{
$resolver = $this->createControllerResolver();
$request = Request::create('/');
$request->attributes->set('_controller', 'Symfony\Bundle\FrameworkBundle\Tests\Controller\ContainerAwareController');
$controller = $resolver->getController($request);
$this->assertInstanceOf('Symfony\Bundle\FrameworkBundle\Tests\Controller\ContainerAwareController', $controller);
$this->assertInstanceOf('Symfony\Component\DependencyInjection\ContainerInterface', $controller->getContainer());
}
public function testGetControllerWithBundleNotation()
{
$shortName = 'FooBundle:Default:test';
$parser = $this->createMockParser();
$parser->expects($this->once())
->method('parse')
->with($shortName)
->willReturn('Symfony\Bundle\FrameworkBundle\Tests\Controller\ContainerAwareController::testAction')
;
$resolver = $this->createControllerResolver(null, null, $parser);
$request = Request::create('/');
$request->attributes->set('_controller', $shortName);
$controller = $resolver->getController($request);
$this->assertInstanceOf('Symfony\Bundle\FrameworkBundle\Tests\Controller\ContainerAwareController', $controller[0]);
$this->assertInstanceOf('Symfony\Component\DependencyInjection\ContainerInterface', $controller[0]->getContainer());
$this->assertSame('testAction', $controller[1]);
}
public function testContainerAwareControllerGetsContainerWhenNotSet()
{
class_exists(AbstractControllerTest::class);
$controller = new ContainerAwareController();
$container = new Container();
$container->set(TestAbstractController::class, $controller);
$resolver = $this->createControllerResolver(null, $container);
$request = Request::create('/');
$request->attributes->set('_controller', TestAbstractController::class.':testAction');
$this->assertSame([$controller, 'testAction'], $resolver->getController($request));
$this->assertSame($container, $controller->getContainer());
}
public function testAbstractControllerGetsContainerWhenNotSet()
{
class_exists(AbstractControllerTest::class);
$controller = new TestAbstractController(false);
$container = new Container();
$container->set(TestAbstractController::class, $controller);
$resolver = $this->createControllerResolver(null, $container);
$request = Request::create('/');
$request->attributes->set('_controller', TestAbstractController::class.'::fooAction');
$this->assertSame([$controller, 'fooAction'], $resolver->getController($request));
$this->assertSame($container, $controller->setContainer($container));
}
public function testAbstractControllerServiceWithFcqnIdGetsContainerWhenNotSet()
{
class_exists(AbstractControllerTest::class);
$controller = new DummyController();
$container = new Container();
$container->set(DummyController::class, $controller);
$resolver = $this->createControllerResolver(null, $container);
$request = Request::create('/');
$request->attributes->set('_controller', DummyController::class.':fooAction');
$this->assertSame([$controller, 'fooAction'], $resolver->getController($request));
$this->assertSame($container, $controller->getContainer());
}
public function testAbstractControllerGetsNoContainerWhenSet()
{
class_exists(AbstractControllerTest::class);
$controller = new TestAbstractController(false);
$controllerContainer = new Container();
$controller->setContainer($controllerContainer);
$container = new Container();
$container->set(TestAbstractController::class, $controller);
$resolver = $this->createControllerResolver(null, $container);
$request = Request::create('/');
$request->attributes->set('_controller', TestAbstractController::class.'::fooAction');
$this->assertSame([$controller, 'fooAction'], $resolver->getController($request));
$this->assertSame($controllerContainer, $controller->setContainer($container));
}
public function testAbstractControllerServiceWithFcqnIdGetsNoContainerWhenSet()
{
class_exists(AbstractControllerTest::class);
$controller = new DummyController();
$controllerContainer = new Container();
$controller->setContainer($controllerContainer);
$container = new Container();
$container->set(DummyController::class, $controller);
$resolver = $this->createControllerResolver(null, $container);
$request = Request::create('/');
$request->attributes->set('_controller', DummyController::class.':fooAction');
$this->assertSame([$controller, 'fooAction'], $resolver->getController($request));
$this->assertSame($controllerContainer, $controller->getContainer());
}
protected function createControllerResolver(LoggerInterface $logger = null, Psr11ContainerInterface $container = null, ControllerNameParser $parser = null)
{
if (!$parser) {
$parser = $this->createMockParser();
}
if (!$container) {
$container = $this->createMockContainer();
}
return new ControllerResolver($container, $parser, $logger);
}
protected function createMockParser()
{
return $this->getMockBuilder('Symfony\Bundle\FrameworkBundle\Controller\ControllerNameParser')->disableOriginalConstructor()->getMock();
}
protected function createMockContainer()
{
return $this->getMockBuilder('Symfony\Component\DependencyInjection\ContainerInterface')->getMock();
}
}
class ContainerAwareController implements ContainerAwareInterface
{
private $container;
public function setContainer(ContainerInterface $container = null)
{
$this->container = $container;
}
public function getContainer()
{
return $this->container;
}
public function testAction()
{
}
public function __invoke()
{
}
}
class DummyController extends AbstractController
{
public function getContainer()
{
return $this->container;
}
public function fooAction()
{
}
}

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\Bundle\FrameworkBundle\Tests\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
class ControllerTest extends ControllerTraitTest
{
protected function createController()
{
return new TestController();
}
}
class TestController extends Controller
{
use TestControllerTrait;
}

View File

@@ -0,0 +1,551 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Bundle\FrameworkBundle\Tests\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\ControllerTrait;
use Symfony\Bundle\FrameworkBundle\Tests\TestCase;
use Symfony\Component\DependencyInjection\Container;
use Symfony\Component\Form\Form;
use Symfony\Component\Form\FormConfigInterface;
use Symfony\Component\HttpFoundation\BinaryFileResponse;
use Symfony\Component\HttpFoundation\File\File;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\ResponseHeaderBag;
use Symfony\Component\HttpFoundation\Session\Flash\FlashBag;
use Symfony\Component\Security\Core\Authentication\Token\AnonymousToken;
use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken;
use Symfony\Component\Security\Core\User\User;
use Symfony\Component\Serializer\SerializerInterface;
abstract class ControllerTraitTest extends TestCase
{
abstract protected function createController();
public function testForward()
{
$request = Request::create('/');
$request->setLocale('fr');
$request->setRequestFormat('xml');
$requestStack = new RequestStack();
$requestStack->push($request);
$kernel = $this->getMockBuilder('Symfony\Component\HttpKernel\HttpKernelInterface')->getMock();
$kernel->expects($this->once())->method('handle')->willReturnCallback(function (Request $request) {
return new Response($request->getRequestFormat().'--'.$request->getLocale());
});
$container = new Container();
$container->set('request_stack', $requestStack);
$container->set('http_kernel', $kernel);
$controller = $this->createController();
$controller->setContainer($container);
$response = $controller->forward('a_controller');
$this->assertEquals('xml--fr', $response->getContent());
}
public function testGetUser()
{
$user = new User('user', 'pass');
$token = new UsernamePasswordToken($user, 'pass', 'default', ['ROLE_USER']);
$controller = $this->createController();
$controller->setContainer($this->getContainerWithTokenStorage($token));
$this->assertSame($controller->getUser(), $user);
}
public function testGetUserAnonymousUserConvertedToNull()
{
$token = new AnonymousToken('default', 'anon.');
$controller = $this->createController();
$controller->setContainer($this->getContainerWithTokenStorage($token));
$this->assertNull($controller->getUser());
}
public function testGetUserWithEmptyTokenStorage()
{
$controller = $this->createController();
$controller->setContainer($this->getContainerWithTokenStorage(null));
$this->assertNull($controller->getUser());
}
public function testGetUserWithEmptyContainer()
{
$this->expectException('LogicException');
$this->expectExceptionMessage('The SecurityBundle is not registered in your application.');
$controller = $this->createController();
$controller->setContainer(new Container());
$controller->getUser();
}
/**
* @param $token
*
* @return Container
*/
private function getContainerWithTokenStorage($token = null)
{
$tokenStorage = $this->getMockBuilder('Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorage')->getMock();
$tokenStorage
->expects($this->once())
->method('getToken')
->willReturn($token);
$container = new Container();
$container->set('security.token_storage', $tokenStorage);
return $container;
}
public function testJson()
{
$controller = $this->createController();
$controller->setContainer(new Container());
$response = $controller->json([]);
$this->assertInstanceOf(JsonResponse::class, $response);
$this->assertEquals('[]', $response->getContent());
}
public function testJsonWithSerializer()
{
$container = new Container();
$serializer = $this->getMockBuilder(SerializerInterface::class)->getMock();
$serializer
->expects($this->once())
->method('serialize')
->with([], 'json', ['json_encode_options' => JsonResponse::DEFAULT_ENCODING_OPTIONS])
->willReturn('[]');
$container->set('serializer', $serializer);
$controller = $this->createController();
$controller->setContainer($container);
$response = $controller->json([]);
$this->assertInstanceOf(JsonResponse::class, $response);
$this->assertEquals('[]', $response->getContent());
}
public function testJsonWithSerializerContextOverride()
{
$container = new Container();
$serializer = $this->getMockBuilder(SerializerInterface::class)->getMock();
$serializer
->expects($this->once())
->method('serialize')
->with([], 'json', ['json_encode_options' => 0, 'other' => 'context'])
->willReturn('[]');
$container->set('serializer', $serializer);
$controller = $this->createController();
$controller->setContainer($container);
$response = $controller->json([], 200, [], ['json_encode_options' => 0, 'other' => 'context']);
$this->assertInstanceOf(JsonResponse::class, $response);
$this->assertEquals('[]', $response->getContent());
$response->setEncodingOptions(JSON_FORCE_OBJECT);
$this->assertEquals('{}', $response->getContent());
}
public function testFile()
{
$container = new Container();
$kernel = $this->getMockBuilder('Symfony\Component\HttpKernel\HttpKernelInterface')->getMock();
$container->set('http_kernel', $kernel);
$controller = $this->createController();
$controller->setContainer($container);
/* @var BinaryFileResponse $response */
$response = $controller->file(new File(__FILE__));
$this->assertInstanceOf(BinaryFileResponse::class, $response);
$this->assertSame(200, $response->getStatusCode());
if ($response->headers->get('content-type')) {
$this->assertSame('text/x-php', $response->headers->get('content-type'));
}
$this->assertStringContainsString(ResponseHeaderBag::DISPOSITION_ATTACHMENT, $response->headers->get('content-disposition'));
$this->assertStringContainsString(basename(__FILE__), $response->headers->get('content-disposition'));
}
public function testFileAsInline()
{
$controller = $this->createController();
/* @var BinaryFileResponse $response */
$response = $controller->file(new File(__FILE__), null, ResponseHeaderBag::DISPOSITION_INLINE);
$this->assertInstanceOf(BinaryFileResponse::class, $response);
$this->assertSame(200, $response->getStatusCode());
if ($response->headers->get('content-type')) {
$this->assertSame('text/x-php', $response->headers->get('content-type'));
}
$this->assertStringContainsString(ResponseHeaderBag::DISPOSITION_INLINE, $response->headers->get('content-disposition'));
$this->assertStringContainsString(basename(__FILE__), $response->headers->get('content-disposition'));
}
public function testFileWithOwnFileName()
{
$controller = $this->createController();
/* @var BinaryFileResponse $response */
$fileName = 'test.php';
$response = $controller->file(new File(__FILE__), $fileName);
$this->assertInstanceOf(BinaryFileResponse::class, $response);
$this->assertSame(200, $response->getStatusCode());
if ($response->headers->get('content-type')) {
$this->assertSame('text/x-php', $response->headers->get('content-type'));
}
$this->assertStringContainsString(ResponseHeaderBag::DISPOSITION_ATTACHMENT, $response->headers->get('content-disposition'));
$this->assertStringContainsString($fileName, $response->headers->get('content-disposition'));
}
public function testFileWithOwnFileNameAsInline()
{
$controller = $this->createController();
/* @var BinaryFileResponse $response */
$fileName = 'test.php';
$response = $controller->file(new File(__FILE__), $fileName, ResponseHeaderBag::DISPOSITION_INLINE);
$this->assertInstanceOf(BinaryFileResponse::class, $response);
$this->assertSame(200, $response->getStatusCode());
if ($response->headers->get('content-type')) {
$this->assertSame('text/x-php', $response->headers->get('content-type'));
}
$this->assertStringContainsString(ResponseHeaderBag::DISPOSITION_INLINE, $response->headers->get('content-disposition'));
$this->assertStringContainsString($fileName, $response->headers->get('content-disposition'));
}
public function testFileFromPath()
{
$controller = $this->createController();
/* @var BinaryFileResponse $response */
$response = $controller->file(__FILE__);
$this->assertInstanceOf(BinaryFileResponse::class, $response);
$this->assertSame(200, $response->getStatusCode());
if ($response->headers->get('content-type')) {
$this->assertSame('text/x-php', $response->headers->get('content-type'));
}
$this->assertStringContainsString(ResponseHeaderBag::DISPOSITION_ATTACHMENT, $response->headers->get('content-disposition'));
$this->assertStringContainsString(basename(__FILE__), $response->headers->get('content-disposition'));
}
public function testFileFromPathWithCustomizedFileName()
{
$controller = $this->createController();
/* @var BinaryFileResponse $response */
$response = $controller->file(__FILE__, 'test.php');
$this->assertInstanceOf(BinaryFileResponse::class, $response);
$this->assertSame(200, $response->getStatusCode());
if ($response->headers->get('content-type')) {
$this->assertSame('text/x-php', $response->headers->get('content-type'));
}
$this->assertStringContainsString(ResponseHeaderBag::DISPOSITION_ATTACHMENT, $response->headers->get('content-disposition'));
$this->assertStringContainsString('test.php', $response->headers->get('content-disposition'));
}
public function testFileWhichDoesNotExist()
{
$this->expectException('Symfony\Component\HttpFoundation\File\Exception\FileNotFoundException');
$controller = $this->createController();
$controller->file('some-file.txt', 'test.php');
}
public function testIsGranted()
{
$authorizationChecker = $this->getMockBuilder('Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface')->getMock();
$authorizationChecker->expects($this->once())->method('isGranted')->willReturn(true);
$container = new Container();
$container->set('security.authorization_checker', $authorizationChecker);
$controller = $this->createController();
$controller->setContainer($container);
$this->assertTrue($controller->isGranted('foo'));
}
public function testdenyAccessUnlessGranted()
{
$this->expectException('Symfony\Component\Security\Core\Exception\AccessDeniedException');
$authorizationChecker = $this->getMockBuilder('Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface')->getMock();
$authorizationChecker->expects($this->once())->method('isGranted')->willReturn(false);
$container = new Container();
$container->set('security.authorization_checker', $authorizationChecker);
$controller = $this->createController();
$controller->setContainer($container);
$controller->denyAccessUnlessGranted('foo');
}
public function testRenderViewTwig()
{
$twig = $this->getMockBuilder('Twig\Environment')->disableOriginalConstructor()->getMock();
$twig->expects($this->once())->method('render')->willReturn('bar');
$container = new Container();
$container->set('twig', $twig);
$controller = $this->createController();
$controller->setContainer($container);
$this->assertEquals('bar', $controller->renderView('foo'));
}
public function testRenderTwig()
{
$twig = $this->getMockBuilder('Twig\Environment')->disableOriginalConstructor()->getMock();
$twig->expects($this->once())->method('render')->willReturn('bar');
$container = new Container();
$container->set('twig', $twig);
$controller = $this->createController();
$controller->setContainer($container);
$this->assertEquals('bar', $controller->render('foo')->getContent());
}
public function testStreamTwig()
{
$twig = $this->getMockBuilder('Twig\Environment')->disableOriginalConstructor()->getMock();
$container = new Container();
$container->set('twig', $twig);
$controller = $this->createController();
$controller->setContainer($container);
$this->assertInstanceOf('Symfony\Component\HttpFoundation\StreamedResponse', $controller->stream('foo'));
}
public function testRedirectToRoute()
{
$router = $this->getMockBuilder('Symfony\Component\Routing\RouterInterface')->getMock();
$router->expects($this->once())->method('generate')->willReturn('/foo');
$container = new Container();
$container->set('router', $router);
$controller = $this->createController();
$controller->setContainer($container);
$response = $controller->redirectToRoute('foo');
$this->assertInstanceOf('Symfony\Component\HttpFoundation\RedirectResponse', $response);
$this->assertSame('/foo', $response->getTargetUrl());
$this->assertSame(302, $response->getStatusCode());
}
/**
* @runInSeparateProcess
*/
public function testAddFlash()
{
$flashBag = new FlashBag();
$session = $this->getMockBuilder('Symfony\Component\HttpFoundation\Session\Session')->disableOriginalConstructor()->getMock();
$session->expects($this->once())->method('getFlashBag')->willReturn($flashBag);
$container = new Container();
$container->set('session', $session);
$controller = $this->createController();
$controller->setContainer($container);
$controller->addFlash('foo', 'bar');
$this->assertSame(['bar'], $flashBag->get('foo'));
}
public function testCreateAccessDeniedException()
{
$controller = $this->createController();
$this->assertInstanceOf('Symfony\Component\Security\Core\Exception\AccessDeniedException', $controller->createAccessDeniedException());
}
public function testIsCsrfTokenValid()
{
$tokenManager = $this->getMockBuilder('Symfony\Component\Security\Csrf\CsrfTokenManagerInterface')->getMock();
$tokenManager->expects($this->once())->method('isTokenValid')->willReturn(true);
$container = new Container();
$container->set('security.csrf.token_manager', $tokenManager);
$controller = $this->createController();
$controller->setContainer($container);
$this->assertTrue($controller->isCsrfTokenValid('foo', 'bar'));
}
public function testGenerateUrl()
{
$router = $this->getMockBuilder('Symfony\Component\Routing\RouterInterface')->getMock();
$router->expects($this->once())->method('generate')->willReturn('/foo');
$container = new Container();
$container->set('router', $router);
$controller = $this->createController();
$controller->setContainer($container);
$this->assertEquals('/foo', $controller->generateUrl('foo'));
}
public function testRedirect()
{
$controller = $this->createController();
$response = $controller->redirect('https://dunglas.fr', 301);
$this->assertInstanceOf('Symfony\Component\HttpFoundation\RedirectResponse', $response);
$this->assertSame('https://dunglas.fr', $response->getTargetUrl());
$this->assertSame(301, $response->getStatusCode());
}
public function testRenderViewTemplating()
{
$templating = $this->getMockBuilder('Symfony\Bundle\FrameworkBundle\Templating\EngineInterface')->getMock();
$templating->expects($this->once())->method('render')->willReturn('bar');
$container = new Container();
$container->set('templating', $templating);
$controller = $this->createController();
$controller->setContainer($container);
$this->assertEquals('bar', $controller->renderView('foo'));
}
public function testRenderTemplating()
{
$templating = $this->getMockBuilder('Symfony\Bundle\FrameworkBundle\Templating\EngineInterface')->getMock();
$templating->expects($this->once())->method('render')->willReturn('bar');
$container = new Container();
$container->set('templating', $templating);
$controller = $this->createController();
$controller->setContainer($container);
$this->assertEquals('bar', $controller->render('foo')->getContent());
}
public function testStreamTemplating()
{
$templating = $this->getMockBuilder('Symfony\Bundle\FrameworkBundle\Templating\EngineInterface')->getMock();
$container = new Container();
$container->set('templating', $templating);
$controller = $this->createController();
$controller->setContainer($container);
$this->assertInstanceOf('Symfony\Component\HttpFoundation\StreamedResponse', $controller->stream('foo'));
}
public function testCreateNotFoundException()
{
$controller = $this->createController();
$this->assertInstanceOf('Symfony\Component\HttpKernel\Exception\NotFoundHttpException', $controller->createNotFoundException());
}
public function testCreateForm()
{
$form = new Form($this->getMockBuilder(FormConfigInterface::class)->getMock());
$formFactory = $this->getMockBuilder('Symfony\Component\Form\FormFactoryInterface')->getMock();
$formFactory->expects($this->once())->method('create')->willReturn($form);
$container = new Container();
$container->set('form.factory', $formFactory);
$controller = $this->createController();
$controller->setContainer($container);
$this->assertEquals($form, $controller->createForm('foo'));
}
public function testCreateFormBuilder()
{
$formBuilder = $this->getMockBuilder('Symfony\Component\Form\FormBuilderInterface')->getMock();
$formFactory = $this->getMockBuilder('Symfony\Component\Form\FormFactoryInterface')->getMock();
$formFactory->expects($this->once())->method('createBuilder')->willReturn($formBuilder);
$container = new Container();
$container->set('form.factory', $formFactory);
$controller = $this->createController();
$controller->setContainer($container);
$this->assertEquals($formBuilder, $controller->createFormBuilder('foo'));
}
public function testGetDoctrine()
{
$doctrine = $this->getMockBuilder('Doctrine\Common\Persistence\ManagerRegistry')->getMock();
$container = new Container();
$container->set('doctrine', $doctrine);
$controller = $this->createController();
$controller->setContainer($container);
$this->assertEquals($doctrine, $controller->getDoctrine());
}
}
trait TestControllerTrait
{
use ControllerTrait {
generateUrl as public;
redirect as public;
forward as public;
getUser as public;
json as public;
file as public;
isGranted as public;
denyAccessUnlessGranted as public;
redirectToRoute as public;
addFlash as public;
isCsrfTokenValid as public;
renderView as public;
render as public;
stream as public;
createNotFoundException as public;
createAccessDeniedException as public;
createForm as public;
createFormBuilder as public;
getDoctrine as public;
}
}

View File

@@ -0,0 +1,321 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Bundle\FrameworkBundle\Tests\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\RedirectController;
use Symfony\Bundle\FrameworkBundle\Tests\TestCase;
use Symfony\Component\HttpFoundation\ParameterBag;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Exception\HttpException;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
/**
* @author Marcin Sikon <marcin.sikon@gmail.com>
*/
class RedirectControllerTest extends TestCase
{
public function testEmptyRoute()
{
$request = new Request();
$controller = new RedirectController();
try {
$controller->redirectAction($request, '', true);
$this->fail('Expected Symfony\Component\HttpKernel\Exception\HttpException to be thrown');
} catch (HttpException $e) {
$this->assertSame(410, $e->getStatusCode());
}
try {
$controller->redirectAction($request, '', false);
$this->fail('Expected Symfony\Component\HttpKernel\Exception\HttpException to be thrown');
} catch (HttpException $e) {
$this->assertSame(404, $e->getStatusCode());
}
}
/**
* @dataProvider provider
*/
public function testRoute($permanent, $ignoreAttributes, $expectedCode, $expectedAttributes)
{
$request = new Request();
$route = 'new-route';
$url = '/redirect-url';
$attributes = [
'route' => $route,
'permanent' => $permanent,
'_route' => 'current-route',
'_route_params' => [
'route' => $route,
'permanent' => $permanent,
'additional-parameter' => 'value',
'ignoreAttributes' => $ignoreAttributes,
],
];
$request->attributes = new ParameterBag($attributes);
$router = $this->getMockBuilder(UrlGeneratorInterface::class)->getMock();
$router
->expects($this->once())
->method('generate')
->with($this->equalTo($route), $this->equalTo($expectedAttributes))
->willReturn($url);
$controller = new RedirectController($router);
$returnResponse = $controller->redirectAction($request, $route, $permanent, $ignoreAttributes);
$this->assertRedirectUrl($returnResponse, $url);
$this->assertEquals($expectedCode, $returnResponse->getStatusCode());
}
public function provider()
{
return [
[true, false, 301, ['additional-parameter' => 'value']],
[false, false, 302, ['additional-parameter' => 'value']],
[false, true, 302, []],
[false, ['additional-parameter'], 302, []],
];
}
public function testEmptyPath()
{
$request = new Request();
$controller = new RedirectController();
try {
$controller->urlRedirectAction($request, '', true);
$this->fail('Expected Symfony\Component\HttpKernel\Exception\HttpException to be thrown');
} catch (HttpException $e) {
$this->assertSame(410, $e->getStatusCode());
}
try {
$controller->urlRedirectAction($request, '', false);
$this->fail('Expected Symfony\Component\HttpKernel\Exception\HttpException to be thrown');
} catch (HttpException $e) {
$this->assertSame(404, $e->getStatusCode());
}
}
public function testFullURL()
{
$request = new Request();
$controller = new RedirectController();
$returnResponse = $controller->urlRedirectAction($request, 'http://foo.bar/');
$this->assertRedirectUrl($returnResponse, 'http://foo.bar/');
$this->assertEquals(302, $returnResponse->getStatusCode());
}
public function testUrlRedirectDefaultPorts()
{
$host = 'www.example.com';
$baseUrl = '/base';
$path = '/redirect-path';
$httpPort = 1080;
$httpsPort = 1443;
$expectedUrl = "https://$host:$httpsPort$baseUrl$path";
$request = $this->createRequestObject('http', $host, $httpPort, $baseUrl);
$controller = $this->createRedirectController(null, $httpsPort);
$returnValue = $controller->urlRedirectAction($request, $path, false, 'https');
$this->assertRedirectUrl($returnValue, $expectedUrl);
$expectedUrl = "http://$host:$httpPort$baseUrl$path";
$request = $this->createRequestObject('https', $host, $httpPort, $baseUrl);
$controller = $this->createRedirectController($httpPort);
$returnValue = $controller->urlRedirectAction($request, $path, false, 'http');
$this->assertRedirectUrl($returnValue, $expectedUrl);
}
/**
* @group legacy
*/
public function testUrlRedirectDefaultPortParameters()
{
$host = 'www.example.com';
$baseUrl = '/base';
$path = '/redirect-path';
$httpPort = 1080;
$httpsPort = 1443;
$expectedUrl = "https://$host:$httpsPort$baseUrl$path";
$request = $this->createRequestObject('http', $host, $httpPort, $baseUrl);
$controller = $this->createLegacyRedirectController(null, $httpsPort);
$returnValue = $controller->urlRedirectAction($request, $path, false, 'https');
$this->assertRedirectUrl($returnValue, $expectedUrl);
$expectedUrl = "http://$host:$httpPort$baseUrl$path";
$request = $this->createRequestObject('https', $host, $httpPort, $baseUrl);
$controller = $this->createLegacyRedirectController($httpPort);
$returnValue = $controller->urlRedirectAction($request, $path, false, 'http');
$this->assertRedirectUrl($returnValue, $expectedUrl);
}
public function urlRedirectProvider()
{
return [
// Standard ports
['http', null, null, 'http', 80, ''],
['http', 80, null, 'http', 80, ''],
['https', null, null, 'http', 80, ''],
['https', 80, null, 'http', 80, ''],
['http', null, null, 'https', 443, ''],
['http', null, 443, 'https', 443, ''],
['https', null, null, 'https', 443, ''],
['https', null, 443, 'https', 443, ''],
// Non-standard ports
['http', null, null, 'http', 8080, ':8080'],
['http', 4080, null, 'http', 8080, ':4080'],
['http', 80, null, 'http', 8080, ''],
['https', null, null, 'http', 8080, ''],
['https', null, 8443, 'http', 8080, ':8443'],
['https', null, 443, 'http', 8080, ''],
['https', null, null, 'https', 8443, ':8443'],
['https', null, 4443, 'https', 8443, ':4443'],
['https', null, 443, 'https', 8443, ''],
['http', null, null, 'https', 8443, ''],
['http', 8080, 4443, 'https', 8443, ':8080'],
['http', 80, 4443, 'https', 8443, ''],
];
}
/**
* @dataProvider urlRedirectProvider
*/
public function testUrlRedirect($scheme, $httpPort, $httpsPort, $requestScheme, $requestPort, $expectedPort)
{
$host = 'www.example.com';
$baseUrl = '/base';
$path = '/redirect-path';
$expectedUrl = "$scheme://$host$expectedPort$baseUrl$path";
$request = $this->createRequestObject($requestScheme, $host, $requestPort, $baseUrl);
$controller = $this->createRedirectController();
$returnValue = $controller->urlRedirectAction($request, $path, false, $scheme, $httpPort, $httpsPort);
$this->assertRedirectUrl($returnValue, $expectedUrl);
}
public function pathQueryParamsProvider()
{
return [
['http://www.example.com/base/redirect-path', '/redirect-path', ''],
['http://www.example.com/base/redirect-path?foo=bar', '/redirect-path?foo=bar', ''],
['http://www.example.com/base/redirect-path?foo=bar', '/redirect-path', 'foo=bar'],
['http://www.example.com/base/redirect-path?foo=bar&abc=example', '/redirect-path?foo=bar', 'abc=example'],
['http://www.example.com/base/redirect-path?foo=bar&abc=example&baz=def', '/redirect-path?foo=bar', 'abc=example&baz=def'],
];
}
/**
* @dataProvider pathQueryParamsProvider
*/
public function testPathQueryParams($expectedUrl, $path, $queryString)
{
$scheme = 'http';
$host = 'www.example.com';
$baseUrl = '/base';
$port = 80;
$request = $this->createRequestObject($scheme, $host, $port, $baseUrl, $queryString);
$controller = $this->createRedirectController();
$returnValue = $controller->urlRedirectAction($request, $path, false, $scheme, $port, null);
$this->assertRedirectUrl($returnValue, $expectedUrl);
}
private function createRequestObject($scheme, $host, $port, $baseUrl, $queryString = '')
{
$request = $this->getMockBuilder('Symfony\Component\HttpFoundation\Request')->getMock();
$request
->expects($this->any())
->method('getScheme')
->willReturn($scheme);
$request
->expects($this->any())
->method('getHost')
->willReturn($host);
$request
->expects($this->any())
->method('getPort')
->willReturn($port);
$request
->expects($this->any())
->method('getBaseUrl')
->willReturn($baseUrl);
$request
->expects($this->any())
->method('getQueryString')
->willReturn($queryString);
return $request;
}
private function createRedirectController($httpPort = null, $httpsPort = null)
{
return new RedirectController(null, $httpPort, $httpsPort);
}
/**
* @deprecated
*/
private function createLegacyRedirectController($httpPort = null, $httpsPort = null)
{
$container = $this->getMockBuilder('Symfony\Component\DependencyInjection\ContainerInterface')->getMock();
if (null !== $httpPort) {
$container
->expects($this->once())
->method('hasParameter')
->with($this->equalTo('request_listener.http_port'))
->willReturn(true);
$container
->expects($this->once())
->method('getParameter')
->with($this->equalTo('request_listener.http_port'))
->willReturn($httpPort);
}
if (null !== $httpsPort) {
$container
->expects($this->once())
->method('hasParameter')
->with($this->equalTo('request_listener.https_port'))
->willReturn(true);
$container
->expects($this->once())
->method('getParameter')
->with($this->equalTo('request_listener.https_port'))
->willReturn($httpsPort);
}
$controller = new RedirectController();
$controller->setContainer($container);
return $controller;
}
private function assertRedirectUrl(Response $returnResponse, $expectedUrl)
{
$this->assertTrue($returnResponse->isRedirect($expectedUrl), "Expected: $expectedUrl\nGot: ".$returnResponse->headers->get('Location'));
}
}

View File

@@ -0,0 +1,88 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Bundle\FrameworkBundle\Tests\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\TemplateController;
use Symfony\Bundle\FrameworkBundle\Templating\EngineInterface;
use Symfony\Bundle\FrameworkBundle\Tests\TestCase;
/**
* @author Kévin Dunglas <dunglas@gmail.com>
*/
class TemplateControllerTest extends TestCase
{
public function testTwig()
{
$twig = $this->getMockBuilder('Twig\Environment')->disableOriginalConstructor()->getMock();
$twig->expects($this->once())->method('render')->willReturn('bar');
$controller = new TemplateController($twig);
$this->assertEquals('bar', $controller->templateAction('mytemplate')->getContent());
}
public function testTemplating()
{
$templating = $this->getMockBuilder(EngineInterface::class)->getMock();
$templating->expects($this->once())->method('render')->willReturn('bar');
$controller = new TemplateController(null, $templating);
$this->assertEquals('bar', $controller->templateAction('mytemplate')->getContent());
}
/**
* @group legacy
*/
public function testLegacyTwig()
{
$twig = $this->getMockBuilder('Twig\Environment')->disableOriginalConstructor()->getMock();
$twig->expects($this->once())->method('render')->willReturn('bar');
$container = $this->getMockBuilder('Symfony\Component\DependencyInjection\ContainerInterface')->getMock();
$container->expects($this->at(0))->method('has')->willReturn(false);
$container->expects($this->at(1))->method('has')->willReturn(true);
$container->expects($this->at(2))->method('get')->willReturn($twig);
$controller = new TemplateController();
$controller->setContainer($container);
$this->assertEquals('bar', $controller->templateAction('mytemplate')->getContent());
}
/**
* @group legacy
*/
public function testLegacyTemplating()
{
$templating = $this->getMockBuilder('Symfony\Bundle\FrameworkBundle\Templating\EngineInterface')->getMock();
$templating->expects($this->once())->method('render')->willReturn('bar');
$container = $this->getMockBuilder('Symfony\Component\DependencyInjection\ContainerInterface')->getMock();
$container->expects($this->at(0))->method('has')->willReturn(true);
$container->expects($this->at(1))->method('get')->willReturn($templating);
$controller = new TemplateController();
$controller->setContainer($container);
$this->assertEquals('bar', $controller->templateAction('mytemplate')->getContent());
}
public function testNoTwigNorTemplating()
{
$this->expectException('LogicException');
$this->expectExceptionMessage('You can not use the TemplateController if the Templating Component or the Twig Bundle are not available.');
$controller = new TemplateController();
$controller->templateAction('mytemplate')->getContent();
}
}

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\Bundle\FrameworkBundle\Tests\DependencyInjection\Compiler;
use PHPUnit\Framework\TestCase;
use Symfony\Bundle\FrameworkBundle\DependencyInjection\Compiler\AddCacheWarmerPass;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Reference;
/**
* @group legacy
*/
class AddCacheWarmerPassTest extends TestCase
{
public function testThatCacheWarmersAreProcessedInPriorityOrder()
{
$container = new ContainerBuilder();
$cacheWarmerDefinition = $container->register('cache_warmer')->addArgument([]);
$container->register('my_cache_warmer_service1')->addTag('kernel.cache_warmer', ['priority' => 100]);
$container->register('my_cache_warmer_service2')->addTag('kernel.cache_warmer', ['priority' => 200]);
$container->register('my_cache_warmer_service3')->addTag('kernel.cache_warmer');
$addCacheWarmerPass = new AddCacheWarmerPass();
$addCacheWarmerPass->process($container);
$this->assertEquals(
[
new Reference('my_cache_warmer_service2'),
new Reference('my_cache_warmer_service1'),
new Reference('my_cache_warmer_service3'),
],
$cacheWarmerDefinition->getArgument(0)
);
}
public function testThatCompilerPassIsIgnoredIfThereIsNoCacheWarmerDefinition()
{
$container = new ContainerBuilder();
$addCacheWarmerPass = new AddCacheWarmerPass();
$addCacheWarmerPass->process($container);
// we just check that the pass does not break if no cache warmer is registered
$this->addToAssertionCount(1);
}
public function testThatCacheWarmersMightBeNotDefined()
{
$container = new ContainerBuilder();
$cacheWarmerDefinition = $container->register('cache_warmer')->addArgument([]);
$addCacheWarmerPass = new AddCacheWarmerPass();
$addCacheWarmerPass->process($container);
$this->assertSame([], $cacheWarmerDefinition->getArgument(0));
}
}

View File

@@ -0,0 +1,120 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Bundle\FrameworkBundle\Tests\DependencyInjection\Compiler;
use PHPUnit\Framework\TestCase;
use Symfony\Bundle\FrameworkBundle\DependencyInjection\Compiler\AddConsoleCommandPass;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Definition;
/**
* @group legacy
*/
class AddConsoleCommandPassTest extends TestCase
{
/**
* @dataProvider visibilityProvider
*/
public function testProcess($public)
{
$container = new ContainerBuilder();
$container->addCompilerPass(new AddConsoleCommandPass());
$container->setParameter('my-command.class', 'Symfony\Bundle\FrameworkBundle\Tests\DependencyInjection\Compiler\MyCommand');
$definition = new Definition('%my-command.class%');
$definition->setPublic($public);
$definition->addTag('console.command');
$container->setDefinition('my-command', $definition);
$container->compile();
$alias = 'console.command.symfony_bundle_frameworkbundle_tests_dependencyinjection_compiler_mycommand';
if ($public) {
$this->assertFalse($container->hasAlias($alias));
$id = 'my-command';
} else {
$id = $alias;
// The alias is replaced by a Definition by the ReplaceAliasByActualDefinitionPass
// in case the original service is private
$this->assertFalse($container->hasDefinition('my-command'));
$this->assertTrue($container->hasDefinition($alias));
}
$this->assertTrue($container->hasParameter('console.command.ids'));
$this->assertSame([$alias => $id], $container->getParameter('console.command.ids'));
}
public function visibilityProvider()
{
return [
[true],
[false],
];
}
public function testProcessThrowAnExceptionIfTheServiceIsAbstract()
{
$this->expectException('InvalidArgumentException');
$this->expectExceptionMessage('The service "my-command" tagged "console.command" must not be abstract.');
$container = new ContainerBuilder();
$container->addCompilerPass(new AddConsoleCommandPass());
$definition = new Definition('Symfony\Bundle\FrameworkBundle\Tests\DependencyInjection\Compiler\MyCommand');
$definition->addTag('console.command');
$definition->setAbstract(true);
$container->setDefinition('my-command', $definition);
$container->compile();
}
public function testProcessThrowAnExceptionIfTheServiceIsNotASubclassOfCommand()
{
$this->expectException('InvalidArgumentException');
$this->expectExceptionMessage('The service "my-command" tagged "console.command" must be a subclass of "Symfony\Component\Console\Command\Command".');
$container = new ContainerBuilder();
$container->addCompilerPass(new AddConsoleCommandPass());
$definition = new Definition('SplObjectStorage');
$definition->addTag('console.command');
$container->setDefinition('my-command', $definition);
$container->compile();
}
public function testProcessPrivateServicesWithSameCommand()
{
$container = new ContainerBuilder();
$className = 'Symfony\Bundle\FrameworkBundle\Tests\DependencyInjection\Compiler\MyCommand';
$definition1 = new Definition($className);
$definition1->addTag('console.command')->setPublic(false);
$definition2 = new Definition($className);
$definition2->addTag('console.command')->setPublic(false);
$container->setDefinition('my-command1', $definition1);
$container->setDefinition('my-command2', $definition2);
(new AddConsoleCommandPass())->process($container);
$alias1 = 'console.command.symfony_bundle_frameworkbundle_tests_dependencyinjection_compiler_mycommand';
$alias2 = $alias1.'_my-command2';
$this->assertTrue($container->hasAlias($alias1));
$this->assertTrue($container->hasAlias($alias2));
}
}
class MyCommand extends Command
{
}

View File

@@ -0,0 +1,73 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Bundle\FrameworkBundle\Tests\DependencyInjection\Compiler;
use PHPUnit\Framework\TestCase;
use Symfony\Bundle\FrameworkBundle\DependencyInjection\Compiler\AddConstraintValidatorsPass;
use Symfony\Component\DependencyInjection\Argument\ServiceClosureArgument;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Definition;
use Symfony\Component\DependencyInjection\Reference;
use Symfony\Component\DependencyInjection\ServiceLocator;
/**
* @group legacy
*/
class AddConstraintValidatorsPassTest extends TestCase
{
public function testThatConstraintValidatorServicesAreProcessed()
{
$container = new ContainerBuilder();
$validatorFactory = $container->register('validator.validator_factory')
->addArgument([]);
$container->register('my_constraint_validator_service1', Validator1::class)
->addTag('validator.constraint_validator', ['alias' => 'my_constraint_validator_alias1']);
$container->register('my_constraint_validator_service2', Validator2::class)
->addTag('validator.constraint_validator');
$addConstraintValidatorsPass = new AddConstraintValidatorsPass();
$addConstraintValidatorsPass->process($container);
$expected = (new Definition(ServiceLocator::class, [[
Validator1::class => new ServiceClosureArgument(new Reference('my_constraint_validator_service1')),
'my_constraint_validator_alias1' => new ServiceClosureArgument(new Reference('my_constraint_validator_service1')),
Validator2::class => new ServiceClosureArgument(new Reference('my_constraint_validator_service2')),
]]))->addTag('container.service_locator')->setPublic(false);
$this->assertEquals($expected, $container->getDefinition((string) $validatorFactory->getArgument(0)));
}
public function testAbstractConstraintValidator()
{
$this->expectException('InvalidArgumentException');
$this->expectExceptionMessage('The service "my_abstract_constraint_validator" tagged "validator.constraint_validator" must not be abstract.');
$container = new ContainerBuilder();
$container->register('validator.validator_factory')
->addArgument([]);
$container->register('my_abstract_constraint_validator')
->setAbstract(true)
->addTag('validator.constraint_validator');
$addConstraintValidatorsPass = new AddConstraintValidatorsPass();
$addConstraintValidatorsPass->process($container);
}
public function testThatCompilerPassIsIgnoredIfThereIsNoConstraintValidatorFactoryDefinition()
{
$addConstraintValidatorsPass = new AddConstraintValidatorsPass();
$addConstraintValidatorsPass->process(new ContainerBuilder());
// we just check that the pass does not fail if no constraint validator factory is registered
$this->addToAssertionCount(1);
}
}

View File

@@ -0,0 +1,97 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Bundle\FrameworkBundle\Tests\DependencyInjection\Compiler;
use PHPUnit\Framework\TestCase;
use Symfony\Bundle\FrameworkBundle\DependencyInjection\Compiler\AddExpressionLanguageProvidersPass;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Definition;
use Symfony\Component\DependencyInjection\Reference;
class AddExpressionLanguageProvidersPassTest extends TestCase
{
public function testProcessForRouter()
{
$container = new ContainerBuilder();
$container->addCompilerPass(new AddExpressionLanguageProvidersPass());
$definition = new Definition('\stdClass');
$definition->addTag('routing.expression_language_provider');
$container->setDefinition('some_routing_provider', $definition->setPublic(true));
$container->register('router', '\stdClass')->setPublic(true);
$container->compile();
$router = $container->getDefinition('router');
$calls = $router->getMethodCalls();
$this->assertCount(1, $calls);
$this->assertEquals('addExpressionLanguageProvider', $calls[0][0]);
$this->assertEquals(new Reference('some_routing_provider'), $calls[0][1][0]);
}
public function testProcessForRouterAlias()
{
$container = new ContainerBuilder();
$container->addCompilerPass(new AddExpressionLanguageProvidersPass());
$definition = new Definition('\stdClass');
$definition->addTag('routing.expression_language_provider');
$container->setDefinition('some_routing_provider', $definition->setPublic(true));
$container->register('my_router', '\stdClass')->setPublic(true);
$container->setAlias('router', 'my_router');
$container->compile();
$router = $container->getDefinition('my_router');
$calls = $router->getMethodCalls();
$this->assertCount(1, $calls);
$this->assertEquals('addExpressionLanguageProvider', $calls[0][0]);
$this->assertEquals(new Reference('some_routing_provider'), $calls[0][1][0]);
}
public function testProcessForSecurity()
{
$container = new ContainerBuilder();
$container->addCompilerPass(new AddExpressionLanguageProvidersPass());
$definition = new Definition('\stdClass');
$definition->addTag('security.expression_language_provider');
$container->setDefinition('some_security_provider', $definition->setPublic(true));
$container->register('security.expression_language', '\stdClass')->setPublic(true);
$container->compile();
$calls = $container->getDefinition('security.expression_language')->getMethodCalls();
$this->assertCount(1, $calls);
$this->assertEquals('registerProvider', $calls[0][0]);
$this->assertEquals(new Reference('some_security_provider'), $calls[0][1][0]);
}
public function testProcessForSecurityAlias()
{
$container = new ContainerBuilder();
$container->addCompilerPass(new AddExpressionLanguageProvidersPass());
$definition = new Definition('\stdClass');
$definition->addTag('security.expression_language_provider');
$container->setDefinition('some_security_provider', $definition->setPublic(true));
$container->register('my_security.expression_language', '\stdClass')->setPublic(true);
$container->setAlias('security.expression_language', 'my_security.expression_language');
$container->compile();
$calls = $container->getDefinition('my_security.expression_language')->getMethodCalls();
$this->assertCount(1, $calls);
$this->assertEquals('registerProvider', $calls[0][0]);
$this->assertEquals(new Reference('some_security_provider'), $calls[0][1][0]);
}
}

View File

@@ -0,0 +1,49 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Bundle\FrameworkBundle\Tests\DependencyInjection\Compiler;
use PHPUnit\Framework\TestCase;
use Symfony\Bundle\FrameworkBundle\DependencyInjection\Compiler\CacheCollectorPass;
use Symfony\Component\Cache\Adapter\FilesystemAdapter;
use Symfony\Component\Cache\Adapter\TagAwareAdapter;
use Symfony\Component\Cache\Adapter\TraceableAdapter;
use Symfony\Component\Cache\Adapter\TraceableTagAwareAdapter;
use Symfony\Component\Cache\DataCollector\CacheDataCollector;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Reference;
class CacheCollectorPassTest extends TestCase
{
public function testProcess()
{
$container = new ContainerBuilder();
$container
->register('fs', FilesystemAdapter::class)
->addTag('cache.pool');
$container
->register('tagged_fs', TagAwareAdapter::class)
->addArgument(new Reference('fs'))
->addTag('cache.pool');
$collector = $container->register('data_collector.cache', CacheDataCollector::class);
(new CacheCollectorPass())->process($container);
$this->assertEquals([
['addInstance', ['fs', new Reference('fs')]],
['addInstance', ['tagged_fs', new Reference('tagged_fs')]],
], $collector->getMethodCalls());
$this->assertSame(TraceableAdapter::class, $container->findDefinition('fs')->getClass());
$this->assertSame(TraceableTagAwareAdapter::class, $container->getDefinition('tagged_fs')->getClass());
$this->assertFalse($collector->isPublic(), 'The "data_collector.cache" should be private after processing');
}
}

View File

@@ -0,0 +1,61 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Bundle\FrameworkBundle\Tests\DependencyInjection\Compiler;
use PHPUnit\Framework\TestCase;
use Symfony\Bundle\FrameworkBundle\DependencyInjection\Compiler\CachePoolClearerPass;
use Symfony\Bundle\FrameworkBundle\DependencyInjection\Compiler\CachePoolPass;
use Symfony\Component\DependencyInjection\Compiler\RemoveUnusedDefinitionsPass;
use Symfony\Component\DependencyInjection\Compiler\RepeatedPass;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Definition;
use Symfony\Component\DependencyInjection\Reference;
use Symfony\Component\HttpKernel\CacheClearer\Psr6CacheClearer;
class CachePoolClearerPassTest extends TestCase
{
public function testPoolRefsAreWeak()
{
$container = new ContainerBuilder();
$container->setParameter('kernel.debug', false);
$container->setParameter('kernel.name', 'app');
$container->setParameter('kernel.environment', 'prod');
$container->setParameter('kernel.root_dir', 'foo');
$globalClearer = new Definition(Psr6CacheClearer::class);
$container->setDefinition('cache.global_clearer', $globalClearer);
$publicPool = new Definition();
$publicPool->addArgument('namespace');
$publicPool->addTag('cache.pool', ['clearer' => 'clearer_alias']);
$container->setDefinition('public.pool', $publicPool);
$privatePool = new Definition();
$privatePool->setPublic(false);
$privatePool->addArgument('namespace');
$privatePool->addTag('cache.pool', ['clearer' => 'clearer_alias']);
$container->setDefinition('private.pool', $privatePool);
$clearer = new Definition();
$container->setDefinition('clearer', $clearer);
$container->setAlias('clearer_alias', 'clearer');
$pass = new RemoveUnusedDefinitionsPass();
$pass->setRepeatedPass(new RepeatedPass([$pass]));
foreach ([new CachePoolPass(), $pass, new CachePoolClearerPass()] as $pass) {
$pass->process($container);
}
$this->assertEquals([['public.pool' => new Reference('public.pool')]], $clearer->getArguments());
$this->assertEquals([['public.pool' => new Reference('public.pool')]], $globalClearer->getArguments());
}
}

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\Bundle\FrameworkBundle\Tests\DependencyInjection\Compiler;
use PHPUnit\Framework\TestCase;
use Symfony\Bundle\FrameworkBundle\DependencyInjection\Compiler\CachePoolPass;
use Symfony\Component\Cache\Adapter\ArrayAdapter;
use Symfony\Component\DependencyInjection\ChildDefinition;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Definition;
use Symfony\Component\DependencyInjection\Reference;
class CachePoolPassTest extends TestCase
{
private $cachePoolPass;
protected function setUp()
{
$this->cachePoolPass = new CachePoolPass();
}
public function testNamespaceArgumentIsReplaced()
{
$container = new ContainerBuilder();
$container->setParameter('kernel.debug', false);
$container->setParameter('kernel.name', 'app');
$container->setParameter('kernel.environment', 'prod');
$container->setParameter('kernel.root_dir', 'foo');
$adapter = new Definition();
$adapter->setAbstract(true);
$adapter->addTag('cache.pool');
$container->setDefinition('app.cache_adapter', $adapter);
$container->setAlias('app.cache_adapter_alias', 'app.cache_adapter');
$cachePool = new ChildDefinition('app.cache_adapter_alias');
$cachePool->addArgument(null);
$cachePool->addTag('cache.pool');
$container->setDefinition('app.cache_pool', $cachePool);
$this->cachePoolPass->process($container);
$this->assertSame('D07rhFx97S', $cachePool->getArgument(0));
}
public function testNamespaceArgumentIsNotReplacedIfArrayAdapterIsUsed()
{
$container = new ContainerBuilder();
$container->setParameter('kernel.environment', 'prod');
$container->setParameter('kernel.name', 'app');
$container->setParameter('kernel.root_dir', 'foo');
$container->register('cache.adapter.array', ArrayAdapter::class)->addArgument(0);
$cachePool = new ChildDefinition('cache.adapter.array');
$cachePool->addTag('cache.pool');
$container->setDefinition('app.cache_pool', $cachePool);
$this->cachePoolPass->process($container);
$this->assertCount(0, $container->getDefinition('app.cache_pool')->getArguments());
}
public function testArgsAreReplaced()
{
$container = new ContainerBuilder();
$container->setParameter('kernel.debug', false);
$container->setParameter('kernel.name', 'app');
$container->setParameter('kernel.environment', 'prod');
$container->setParameter('cache.prefix.seed', 'foo');
$cachePool = new Definition();
$cachePool->addTag('cache.pool', [
'provider' => 'foobar',
'default_lifetime' => 3,
]);
$cachePool->addArgument(null);
$cachePool->addArgument(null);
$cachePool->addArgument(null);
$container->setDefinition('app.cache_pool', $cachePool);
$this->cachePoolPass->process($container);
$this->assertInstanceOf(Reference::class, $cachePool->getArgument(0));
$this->assertSame('foobar', (string) $cachePool->getArgument(0));
$this->assertSame('itantF+pIq', $cachePool->getArgument(1));
$this->assertSame(3, $cachePool->getArgument(2));
}
public function testThrowsExceptionWhenCachePoolTagHasUnknownAttributes()
{
$this->expectException('InvalidArgumentException');
$this->expectExceptionMessage('Invalid "cache.pool" tag for service "app.cache_pool": accepted attributes are');
$container = new ContainerBuilder();
$container->setParameter('kernel.debug', false);
$container->setParameter('kernel.name', 'app');
$container->setParameter('kernel.environment', 'prod');
$container->setParameter('kernel.root_dir', 'foo');
$adapter = new Definition();
$adapter->setAbstract(true);
$adapter->addTag('cache.pool');
$container->setDefinition('app.cache_adapter', $adapter);
$cachePool = new ChildDefinition('app.cache_adapter');
$cachePool->addTag('cache.pool', ['foobar' => 123]);
$container->setDefinition('app.cache_pool', $cachePool);
$this->cachePoolPass->process($container);
}
}

View File

@@ -0,0 +1,70 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Bundle\FrameworkBundle\Tests\DependencyInjection\Compiler;
use PHPUnit\Framework\TestCase;
use Symfony\Bundle\FrameworkBundle\DependencyInjection\Compiler\CachePoolPrunerPass;
use Symfony\Component\Cache\Adapter\FilesystemAdapter;
use Symfony\Component\Cache\Adapter\PhpFilesAdapter;
use Symfony\Component\DependencyInjection\Argument\IteratorArgument;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Reference;
class CachePoolPrunerPassTest extends TestCase
{
public function testCompilerPassReplacesCommandArgument()
{
$container = new ContainerBuilder();
$container->register('console.command.cache_pool_prune')->addArgument([]);
$container->register('pool.foo', FilesystemAdapter::class)->addTag('cache.pool');
$container->register('pool.bar', PhpFilesAdapter::class)->addTag('cache.pool');
$pass = new CachePoolPrunerPass();
$pass->process($container);
$expected = [
'pool.foo' => new Reference('pool.foo'),
'pool.bar' => new Reference('pool.bar'),
];
$argument = $container->getDefinition('console.command.cache_pool_prune')->getArgument(0);
$this->assertInstanceOf(IteratorArgument::class, $argument);
$this->assertEquals($expected, $argument->getValues());
}
public function testCompilePassIsIgnoredIfCommandDoesNotExist()
{
$container = new ContainerBuilder();
$definitionsBefore = \count($container->getDefinitions());
$aliasesBefore = \count($container->getAliases());
$pass = new CachePoolPrunerPass();
$pass->process($container);
// the container is untouched (i.e. no new definitions or aliases)
$this->assertCount($definitionsBefore, $container->getDefinitions());
$this->assertCount($aliasesBefore, $container->getAliases());
}
public function testCompilerPassThrowsOnInvalidDefinitionClass()
{
$this->expectException('Symfony\Component\DependencyInjection\Exception\InvalidArgumentException');
$this->expectExceptionMessage('Class "Symfony\Bundle\FrameworkBundle\Tests\DependencyInjection\Compiler\NotFound" used for service "pool.not-found" cannot be found.');
$container = new ContainerBuilder();
$container->register('console.command.cache_pool_prune')->addArgument([]);
$container->register('pool.not-found', NotFound::class)->addTag('cache.pool');
$pass = new CachePoolPrunerPass();
$pass->process($container);
}
}

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\Bundle\FrameworkBundle\Tests\DependencyInjection\Compiler;
use PHPUnit\Framework\TestCase;
use Symfony\Bundle\FrameworkBundle\DependencyInjection\Compiler\ConfigCachePass;
use Symfony\Component\DependencyInjection\Argument\IteratorArgument;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Reference;
/**
* @group legacy
*/
class ConfigCachePassTest extends TestCase
{
public function testThatCheckersAreProcessedInPriorityOrder()
{
$container = new ContainerBuilder();
$definition = $container->register('config_cache_factory')->addArgument(null);
$container->register('checker_2')->addTag('config_cache.resource_checker', ['priority' => 100]);
$container->register('checker_1')->addTag('config_cache.resource_checker', ['priority' => 200]);
$container->register('checker_3')->addTag('config_cache.resource_checker');
$pass = new ConfigCachePass();
$pass->process($container);
$expected = new IteratorArgument([
new Reference('checker_1'),
new Reference('checker_2'),
new Reference('checker_3'),
]);
$this->assertEquals($expected, $definition->getArgument(0));
}
public function testThatCheckersCanBeMissing()
{
$container = new ContainerBuilder();
$definitionsBefore = \count($container->getDefinitions());
$aliasesBefore = \count($container->getAliases());
$pass = new ConfigCachePass();
$pass->process($container);
// the container is untouched (i.e. no new definitions or aliases)
$this->assertCount($definitionsBefore, $container->getDefinitions());
$this->assertCount($aliasesBefore, $container->getAliases());
}
}

View File

@@ -0,0 +1,70 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Bundle\FrameworkBundle\Tests\DependencyInjection\Compiler;
use PHPUnit\Framework\TestCase;
use Symfony\Bundle\FrameworkBundle\DependencyInjection\Compiler\ControllerArgumentValueResolverPass;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Definition;
use Symfony\Component\DependencyInjection\Reference;
use Symfony\Component\HttpKernel\Controller\ArgumentResolver;
/**
* @group legacy
*/
class ControllerArgumentValueResolverPassTest extends TestCase
{
public function testServicesAreOrderedAccordingToPriority()
{
$services = [
'n3' => [[]],
'n1' => [['priority' => 200]],
'n2' => [['priority' => 100]],
];
$expected = [
new Reference('n1'),
new Reference('n2'),
new Reference('n3'),
];
$definition = new Definition(ArgumentResolver::class, [null, []]);
$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, [null, []]);
$container = new ContainerBuilder();
$container->setDefinition('argument_resolver', $definition);
(new ControllerArgumentValueResolverPass())->process($container);
$this->assertEquals([], $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,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\Bundle\FrameworkBundle\Tests\DependencyInjection\Compiler;
use PHPUnit\Framework\TestCase;
use Symfony\Bundle\FrameworkBundle\DependencyInjection\Compiler\DataCollectorTranslatorPass;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Reference;
use Symfony\Component\Translation\TranslatorInterface;
class DataCollectorTranslatorPassTest extends TestCase
{
private $container;
private $dataCollectorTranslatorPass;
protected function setUp()
{
$this->container = new ContainerBuilder();
$this->dataCollectorTranslatorPass = new DataCollectorTranslatorPass();
$this->container->setParameter('translator_implementing_bag', 'Symfony\Component\Translation\Translator');
$this->container->setParameter('translator_not_implementing_bag', 'Symfony\Bundle\FrameworkBundle\Tests\DependencyInjection\Compiler\TranslatorWithTranslatorBag');
$this->container->register('translator.data_collector', 'Symfony\Component\Translation\DataCollectorTranslator')
->setPublic(false)
->setDecoratedService('translator')
->setArguments([new Reference('translator.data_collector.inner')])
;
$this->container->register('data_collector.translation', 'Symfony\Component\Translation\DataCollector\TranslationDataCollector')
->setArguments([new Reference('translator.data_collector')])
;
}
/**
* @dataProvider getImplementingTranslatorBagInterfaceTranslatorClassNames
*/
public function testProcessKeepsDataCollectorTranslatorIfItImplementsTranslatorBagInterface($class)
{
$this->container->register('translator', $class);
$this->dataCollectorTranslatorPass->process($this->container);
$this->assertTrue($this->container->hasDefinition('translator.data_collector'));
}
/**
* @dataProvider getImplementingTranslatorBagInterfaceTranslatorClassNames
*/
public function testProcessKeepsDataCollectorIfTranslatorImplementsTranslatorBagInterface($class)
{
$this->container->register('translator', $class);
$this->dataCollectorTranslatorPass->process($this->container);
$this->assertTrue($this->container->hasDefinition('data_collector.translation'));
}
public function getImplementingTranslatorBagInterfaceTranslatorClassNames()
{
return [
['Symfony\Component\Translation\Translator'],
['%translator_implementing_bag%'],
];
}
/**
* @dataProvider getNotImplementingTranslatorBagInterfaceTranslatorClassNames
*/
public function testProcessRemovesDataCollectorTranslatorIfItDoesNotImplementTranslatorBagInterface($class)
{
$this->container->register('translator', $class);
$this->dataCollectorTranslatorPass->process($this->container);
$this->assertFalse($this->container->hasDefinition('translator.data_collector'));
}
/**
* @dataProvider getNotImplementingTranslatorBagInterfaceTranslatorClassNames
*/
public function testProcessRemovesDataCollectorIfTranslatorDoesNotImplementTranslatorBagInterface($class)
{
$this->container->register('translator', $class);
$this->dataCollectorTranslatorPass->process($this->container);
$this->assertFalse($this->container->hasDefinition('data_collector.translation'));
}
public function getNotImplementingTranslatorBagInterfaceTranslatorClassNames()
{
return [
['Symfony\Bundle\FrameworkBundle\Tests\DependencyInjection\Compiler\TranslatorWithTranslatorBag'],
['%translator_not_implementing_bag%'],
];
}
}
class TranslatorWithTranslatorBag implements TranslatorInterface
{
public function trans($id, array $parameters = [], $domain = null, $locale = null)
{
}
public function transChoice($id, $number, array $parameters = [], $domain = null, $locale = null)
{
}
public function setLocale($locale)
{
}
public function getLocale()
{
}
}

View File

@@ -0,0 +1,213 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Bundle\FrameworkBundle\Tests\DependencyInjection\Compiler;
use PHPUnit\Framework\TestCase;
use Symfony\Bundle\FrameworkBundle\DependencyInjection\Compiler\FormPass;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Definition;
use Symfony\Component\DependencyInjection\Reference;
/**
* @group legacy
*
* @author Bernhard Schussek <bschussek@gmail.com>
*/
class FormPassTest extends TestCase
{
public function testDoNothingIfFormExtensionNotLoaded()
{
$container = new ContainerBuilder();
$container->addCompilerPass(new FormPass());
$container->compile();
$this->assertFalse($container->hasDefinition('form.extension'));
}
public function testAddTaggedTypes()
{
$container = new ContainerBuilder();
$container->addCompilerPass(new FormPass());
$extDefinition = new Definition('Symfony\Component\Form\Extension\DependencyInjection\DependencyInjectionExtension');
$extDefinition->setPublic(true);
$extDefinition->setArguments([
new Reference('service_container'),
[],
[],
[],
]);
$container->setDefinition('form.extension', $extDefinition);
$container->register('my.type1', __CLASS__.'_Type1')->addTag('form.type')->setPublic(true);
$container->register('my.type2', __CLASS__.'_Type2')->addTag('form.type')->setPublic(true);
$container->compile();
$extDefinition = $container->getDefinition('form.extension');
$this->assertEquals([
__CLASS__.'_Type1' => 'my.type1',
__CLASS__.'_Type2' => 'my.type2',
], $extDefinition->getArgument(1));
}
/**
* @dataProvider addTaggedTypeExtensionsDataProvider
*/
public function testAddTaggedTypeExtensions(array $extensions, array $expectedRegisteredExtensions)
{
$container = new ContainerBuilder();
$container->addCompilerPass(new FormPass());
$extDefinition = new Definition('Symfony\Component\Form\Extension\DependencyInjection\DependencyInjectionExtension', [
new Reference('service_container'),
[],
[],
[],
]);
$extDefinition->setPublic(true);
$container->setDefinition('form.extension', $extDefinition);
foreach ($extensions as $serviceId => $tag) {
$container->register($serviceId, 'stdClass')->addTag('form.type_extension', $tag);
}
$container->compile();
$extDefinition = $container->getDefinition('form.extension');
$this->assertSame($expectedRegisteredExtensions, $extDefinition->getArgument(2));
}
/**
* @return array
*/
public function addTaggedTypeExtensionsDataProvider()
{
return [
[
[
'my.type_extension1' => ['extended_type' => 'type1'],
'my.type_extension2' => ['extended_type' => 'type1'],
'my.type_extension3' => ['extended_type' => 'type2'],
],
[
'type1' => ['my.type_extension1', 'my.type_extension2'],
'type2' => ['my.type_extension3'],
],
],
[
[
'my.type_extension1' => ['extended_type' => 'type1', 'priority' => 1],
'my.type_extension2' => ['extended_type' => 'type1', 'priority' => 2],
'my.type_extension3' => ['extended_type' => 'type1', 'priority' => -1],
'my.type_extension4' => ['extended_type' => 'type2', 'priority' => 2],
'my.type_extension5' => ['extended_type' => 'type2', 'priority' => 1],
'my.type_extension6' => ['extended_type' => 'type2', 'priority' => 1],
],
[
'type1' => ['my.type_extension2', 'my.type_extension1', 'my.type_extension3'],
'type2' => ['my.type_extension4', 'my.type_extension5', 'my.type_extension6'],
],
],
];
}
public function testAddTaggedFormTypeExtensionWithoutExtendedTypeAttribute()
{
$this->expectException('InvalidArgumentException');
$this->expectExceptionMessage('extended-type attribute, none was configured for the "my.type_extension" service');
$container = new ContainerBuilder();
$container->addCompilerPass(new FormPass());
$extDefinition = new Definition('Symfony\Component\Form\Extension\DependencyInjection\DependencyInjectionExtension', [
new Reference('service_container'),
[],
[],
[],
]);
$extDefinition->setPublic(true);
$container->setDefinition('form.extension', $extDefinition);
$container->register('my.type_extension', 'stdClass')
->addTag('form.type_extension');
$container->compile();
}
public function testAddTaggedGuessers()
{
$container = new ContainerBuilder();
$container->addCompilerPass(new FormPass());
$extDefinition = new Definition('Symfony\Component\Form\Extension\DependencyInjection\DependencyInjectionExtension');
$extDefinition->setPublic(true);
$extDefinition->setArguments([
new Reference('service_container'),
[],
[],
[],
]);
$definition1 = new Definition('stdClass');
$definition1->addTag('form.type_guesser');
$definition2 = new Definition('stdClass');
$definition2->addTag('form.type_guesser');
$container->setDefinition('form.extension', $extDefinition);
$container->setDefinition('my.guesser1', $definition1);
$container->setDefinition('my.guesser2', $definition2);
$container->compile();
$extDefinition = $container->getDefinition('form.extension');
$this->assertSame([
'my.guesser1',
'my.guesser2',
], $extDefinition->getArgument(3));
}
/**
* @dataProvider privateTaggedServicesProvider
*/
public function testPrivateTaggedServices($id, $tagName)
{
$container = new ContainerBuilder();
$container->addCompilerPass(new FormPass());
$extDefinition = new Definition('Symfony\Component\Form\Extension\DependencyInjection\DependencyInjectionExtension');
$extDefinition->setArguments([
new Reference('service_container'),
[],
[],
[],
]);
$container->setDefinition('form.extension', $extDefinition);
$container->register($id, 'stdClass')->setPublic(false)->addTag($tagName, ['extended_type' => 'Foo']);
$container->compile();
$this->assertTrue($container->getDefinition($id)->isPublic());
}
public function privateTaggedServicesProvider()
{
return [
['my.type', 'form.type'],
['my.type_extension', 'form.type_extension'],
['my.guesser', 'form.type_guesser'],
];
}
}

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\Bundle\FrameworkBundle\Tests\DependencyInjection\Compiler;
use PHPUnit\Framework\TestCase;
use Symfony\Bundle\FrameworkBundle\DependencyInjection\Compiler\LoggingTranslatorPass;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Reference;
class LoggingTranslatorPassTest extends TestCase
{
public function testProcess()
{
$container = new ContainerBuilder();
$container->setParameter('translator.logging', true);
$container->setParameter('translator.class', 'Symfony\Component\Translation\Translator');
$container->register('monolog.logger');
$container->setAlias('logger', 'monolog.logger');
$container->register('translator.default', '%translator.class%');
$container->register('translator.logging', '%translator.class%');
$container->setAlias('translator', 'translator.default');
$translationWarmerDefinition = $container->register('translation.warmer')
->addArgument(new Reference('translator'))
->addTag('container.service_subscriber', ['id' => 'translator'])
->addTag('container.service_subscriber', ['id' => 'foo']);
$pass = new LoggingTranslatorPass();
$pass->process($container);
$this->assertEquals(
['container.service_subscriber' => [
['id' => 'foo'],
['key' => 'translator', 'id' => 'translator.logging.inner'],
]],
$translationWarmerDefinition->getTags()
);
}
public function testThatCompilerPassIsIgnoredIfThereIsNotLoggerDefinition()
{
$container = new ContainerBuilder();
$container->register('identity_translator');
$container->setAlias('translator', 'identity_translator');
$definitionsBefore = \count($container->getDefinitions());
$aliasesBefore = \count($container->getAliases());
$pass = new LoggingTranslatorPass();
$pass->process($container);
// the container is untouched (i.e. no new definitions or aliases)
$this->assertCount($definitionsBefore, $container->getDefinitions());
$this->assertCount($aliasesBefore, $container->getAliases());
}
public function testThatCompilerPassIsIgnoredIfThereIsNotTranslatorDefinition()
{
$container = new ContainerBuilder();
$container->register('monolog.logger');
$container->setAlias('logger', 'monolog.logger');
$definitionsBefore = \count($container->getDefinitions());
$aliasesBefore = \count($container->getAliases());
$pass = new LoggingTranslatorPass();
$pass->process($container);
// the container is untouched (i.e. no new definitions or aliases)
$this->assertCount($definitionsBefore, $container->getDefinitions());
$this->assertCount($aliasesBefore, $container->getAliases());
}
}

View File

@@ -0,0 +1,57 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Bundle\FrameworkBundle\Tests\DependencyInjection\Compiler;
use PHPUnit\Framework\TestCase;
use Symfony\Bundle\FrameworkBundle\DependencyInjection\Compiler\ProfilerPass;
use Symfony\Component\DependencyInjection\ContainerBuilder;
class ProfilerPassTest extends TestCase
{
/**
* Tests that collectors that specify a template but no "id" will throw
* an exception (both are needed if the template is specified).
*
* Thus, a fully-valid tag looks something like this:
*
* <tag name="data_collector" template="YourBundle:Collector:templatename" id="your_collector_name" />
*/
public function testTemplateNoIdThrowsException()
{
$this->expectException('InvalidArgumentException');
$builder = new ContainerBuilder();
$builder->register('profiler', 'ProfilerClass');
$builder->register('my_collector_service')
->addTag('data_collector', ['template' => 'foo']);
$profilerPass = new ProfilerPass();
$profilerPass->process($builder);
}
public function testValidCollector()
{
$container = new ContainerBuilder();
$profilerDefinition = $container->register('profiler', 'ProfilerClass');
$container->register('my_collector_service')
->addTag('data_collector', ['template' => 'foo', 'id' => 'my_collector']);
$profilerPass = new ProfilerPass();
$profilerPass->process($container);
$this->assertSame(['my_collector_service' => ['my_collector', 'foo']], $container->getParameter('data_collector.templates'));
// grab the method calls off of the "profiler" definition
$methodCalls = $profilerDefinition->getMethodCalls();
$this->assertCount(1, $methodCalls);
$this->assertEquals('add', $methodCalls[0][0]); // grab the method part of the first call
}
}

View File

@@ -0,0 +1,72 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Bundle\FrameworkBundle\Tests\DependencyInjection\Compiler;
use PHPUnit\Framework\TestCase;
use Symfony\Bundle\FrameworkBundle\DependencyInjection\Compiler\PropertyInfoPass;
use Symfony\Component\DependencyInjection\Argument\IteratorArgument;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Reference;
/**
* @group legacy
*/
class PropertyInfoPassTest extends TestCase
{
/**
* @dataProvider provideTags
*/
public function testServicesAreOrderedAccordingToPriority($index, $tag)
{
$container = new ContainerBuilder();
$definition = $container->register('property_info')->setArguments([null, null, null, null]);
$container->register('n2')->addTag($tag, ['priority' => 100]);
$container->register('n1')->addTag($tag, ['priority' => 200]);
$container->register('n3')->addTag($tag);
$propertyInfoPass = new PropertyInfoPass();
$propertyInfoPass->process($container);
$expected = new IteratorArgument([
new Reference('n1'),
new Reference('n2'),
new Reference('n3'),
]);
$this->assertEquals($expected, $definition->getArgument($index));
}
public function provideTags()
{
return [
[0, 'property_info.list_extractor'],
[1, 'property_info.type_extractor'],
[2, 'property_info.description_extractor'],
[3, 'property_info.access_extractor'],
];
}
public function testReturningEmptyArrayWhenNoService()
{
$container = new ContainerBuilder();
$propertyInfoExtractorDefinition = $container->register('property_info')
->setArguments([[], [], [], []]);
$propertyInfoPass = new PropertyInfoPass();
$propertyInfoPass->process($container);
$this->assertEquals(new IteratorArgument([]), $propertyInfoExtractorDefinition->getArgument(0));
$this->assertEquals(new IteratorArgument([]), $propertyInfoExtractorDefinition->getArgument(1));
$this->assertEquals(new IteratorArgument([]), $propertyInfoExtractorDefinition->getArgument(2));
$this->assertEquals(new IteratorArgument([]), $propertyInfoExtractorDefinition->getArgument(3));
}
}

View File

@@ -0,0 +1,73 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Bundle\FrameworkBundle\Tests\DependencyInjection\Compiler;
use PHPUnit\Framework\TestCase;
use Symfony\Bundle\FrameworkBundle\DependencyInjection\Compiler\SerializerPass;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Reference;
/**
* Tests for the SerializerPass class.
*
* @group legacy
*
* @author Javier Lopez <f12loalf@gmail.com>
*/
class SerializerPassTest extends TestCase
{
public function testThrowExceptionWhenNoNormalizers()
{
$this->expectException('RuntimeException');
$this->expectExceptionMessage('You must tag at least one service as "serializer.normalizer" to use the "serializer" service');
$container = new ContainerBuilder();
$container->register('serializer');
$serializerPass = new SerializerPass();
$serializerPass->process($container);
}
public function testThrowExceptionWhenNoEncoders()
{
$this->expectException('RuntimeException');
$this->expectExceptionMessage('You must tag at least one service as "serializer.encoder" to use the "serializer" service');
$container = new ContainerBuilder();
$container->register('serializer')
->addArgument([])
->addArgument([]);
$container->register('normalizer')->addTag('serializer.normalizer');
$serializerPass = new SerializerPass();
$serializerPass->process($container);
}
public function testServicesAreOrderedAccordingToPriority()
{
$container = new ContainerBuilder();
$definition = $container->register('serializer')->setArguments([null, null]);
$container->register('n2')->addTag('serializer.normalizer', ['priority' => 100])->addTag('serializer.encoder', ['priority' => 100]);
$container->register('n1')->addTag('serializer.normalizer', ['priority' => 200])->addTag('serializer.encoder', ['priority' => 200]);
$container->register('n3')->addTag('serializer.normalizer')->addTag('serializer.encoder');
$serializerPass = new SerializerPass();
$serializerPass->process($container);
$expected = [
new Reference('n1'),
new Reference('n2'),
new Reference('n3'),
];
$this->assertEquals($expected, $definition->getArgument(0));
$this->assertEquals($expected, $definition->getArgument(1));
}
}

View File

@@ -0,0 +1,53 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Bundle\FrameworkBundle\Tests\DependencyInjection\Compiler;
use PHPUnit\Framework\TestCase;
use Symfony\Bundle\FrameworkBundle\DependencyInjection\Compiler\TranslatorPass;
use Symfony\Component\DependencyInjection\Argument\ServiceClosureArgument;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Definition;
use Symfony\Component\DependencyInjection\Reference;
/**
* @group legacy
*/
class TranslatorPassTest extends TestCase
{
public function testValidCollector()
{
$loader = (new Definition())
->addTag('translation.loader', ['alias' => 'xliff', 'legacy-alias' => 'xlf']);
$translator = (new Definition())
->setArguments([null, null, null, null]);
$container = new ContainerBuilder();
$container->setDefinition('translator.default', $translator);
$container->setDefinition('translation.loader', $loader);
$pass = new TranslatorPass();
$pass->process($container);
$expected = (new Definition())
->addTag('translation.loader', ['alias' => 'xliff', 'legacy-alias' => 'xlf'])
->addMethodCall('addLoader', ['xliff', new Reference('translation.loader')])
->addMethodCall('addLoader', ['xlf', new Reference('translation.loader')])
;
$this->assertEquals($expected, $loader);
$this->assertSame(['translation.loader' => ['xliff', 'xlf']], $translator->getArgument(3));
$expected = ['translation.loader' => new ServiceClosureArgument(new Reference('translation.loader'))];
$this->assertEquals($expected, $container->getDefinition((string) $translator->getArgument(0))->getArgument(0));
}
}

View File

@@ -0,0 +1,34 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Bundle\FrameworkBundle\Tests\DependencyInjection\Compiler;
use PHPUnit\Framework\TestCase;
use Symfony\Bundle\FrameworkBundle\DependencyInjection\Compiler\UnusedTagsPass;
use Symfony\Component\DependencyInjection\ContainerBuilder;
class UnusedTagsPassTest extends TestCase
{
public function testProcess()
{
$pass = new UnusedTagsPass();
$container = new ContainerBuilder();
$container->register('foo')
->addTag('kenrel.event_subscriber');
$container->register('bar')
->addTag('kenrel.event_subscriber');
$pass->process($container);
$this->assertSame([sprintf('%s: Tag "kenrel.event_subscriber" was defined on service(s) "foo", "bar", but was never used. Did you mean "kernel.event_subscriber"?', UnusedTagsPass::class)], $container->getCompiler()->getLog());
}
}

View File

@@ -0,0 +1,102 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Bundle\FrameworkBundle\Tests\DependencyInjection\Compiler;
use PHPUnit\Framework\TestCase;
use Symfony\Bundle\FrameworkBundle\DependencyInjection\Compiler\WorkflowGuardListenerPass;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\Security\Core\Authentication\AuthenticationTrustResolverInterface;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
use Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface;
use Symfony\Component\Security\Core\Role\RoleHierarchy;
use Symfony\Component\Validator\Validator\ValidatorInterface;
class WorkflowGuardListenerPassTest extends TestCase
{
private $container;
private $compilerPass;
protected function setUp()
{
$this->container = new ContainerBuilder();
$this->compilerPass = new WorkflowGuardListenerPass();
}
public function testNoExeptionIfParameterIsNotSet()
{
$this->compilerPass->process($this->container);
$this->assertFalse($this->container->hasParameter('workflow.has_guard_listeners'));
}
public function testNoExeptionIfAllDependenciesArePresent()
{
$this->container->setParameter('workflow.has_guard_listeners', true);
$this->container->register('security.token_storage', TokenStorageInterface::class);
$this->container->register('security.authorization_checker', AuthorizationCheckerInterface::class);
$this->container->register('security.authentication.trust_resolver', AuthenticationTrustResolverInterface::class);
$this->container->register('security.role_hierarchy', RoleHierarchy::class);
$this->container->register('validator', ValidatorInterface::class);
$this->compilerPass->process($this->container);
$this->assertFalse($this->container->hasParameter('workflow.has_guard_listeners'));
}
public function testExceptionIfTheTokenStorageServiceIsNotPresent()
{
$this->expectException('Symfony\Component\DependencyInjection\Exception\LogicException');
$this->expectExceptionMessage('The "security.token_storage" service is needed to be able to use the workflow guard listener.');
$this->container->setParameter('workflow.has_guard_listeners', true);
$this->container->register('security.authorization_checker', AuthorizationCheckerInterface::class);
$this->container->register('security.authentication.trust_resolver', AuthenticationTrustResolverInterface::class);
$this->container->register('security.role_hierarchy', RoleHierarchy::class);
$this->compilerPass->process($this->container);
}
public function testExceptionIfTheAuthorizationCheckerServiceIsNotPresent()
{
$this->expectException('Symfony\Component\DependencyInjection\Exception\LogicException');
$this->expectExceptionMessage('The "security.authorization_checker" service is needed to be able to use the workflow guard listener.');
$this->container->setParameter('workflow.has_guard_listeners', true);
$this->container->register('security.token_storage', TokenStorageInterface::class);
$this->container->register('security.authentication.trust_resolver', AuthenticationTrustResolverInterface::class);
$this->container->register('security.role_hierarchy', RoleHierarchy::class);
$this->compilerPass->process($this->container);
}
public function testExceptionIfTheAuthenticationTrustResolverServiceIsNotPresent()
{
$this->expectException('Symfony\Component\DependencyInjection\Exception\LogicException');
$this->expectExceptionMessage('The "security.authentication.trust_resolver" service is needed to be able to use the workflow guard listener.');
$this->container->setParameter('workflow.has_guard_listeners', true);
$this->container->register('security.token_storage', TokenStorageInterface::class);
$this->container->register('security.authorization_checker', AuthorizationCheckerInterface::class);
$this->container->register('security.role_hierarchy', RoleHierarchy::class);
$this->compilerPass->process($this->container);
}
public function testExceptionIfTheRoleHierarchyServiceIsNotPresent()
{
$this->expectException('Symfony\Component\DependencyInjection\Exception\LogicException');
$this->expectExceptionMessage('The "security.role_hierarchy" service is needed to be able to use the workflow guard listener.');
$this->container->setParameter('workflow.has_guard_listeners', true);
$this->container->register('security.token_storage', TokenStorageInterface::class);
$this->container->register('security.authorization_checker', AuthorizationCheckerInterface::class);
$this->container->register('security.authentication.trust_resolver', AuthenticationTrustResolverInterface::class);
$this->compilerPass->process($this->container);
}
}

View File

@@ -0,0 +1,496 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Bundle\FrameworkBundle\Tests\DependencyInjection;
use PHPUnit\Framework\TestCase;
use Symfony\Bundle\FrameworkBundle\DependencyInjection\Configuration;
use Symfony\Bundle\FullStack;
use Symfony\Component\Config\Definition\Exception\InvalidConfigurationException;
use Symfony\Component\Config\Definition\Processor;
use Symfony\Component\Lock\Store\SemaphoreStore;
class ConfigurationTest extends TestCase
{
public function testDefaultConfig()
{
$processor = new Processor();
$config = $processor->processConfiguration(new Configuration(true), [['secret' => 's3cr3t']]);
$this->assertEquals(
array_merge(['secret' => 's3cr3t', 'trusted_hosts' => []], self::getBundleDefaultConfig()),
$config
);
}
public function testDoNoDuplicateDefaultFormResources()
{
$input = ['templating' => [
'form' => ['resources' => ['FrameworkBundle:Form']],
'engines' => ['php'],
]];
$processor = new Processor();
$config = $processor->processConfiguration(new Configuration(true), [$input]);
$this->assertEquals(['FrameworkBundle:Form'], $config['templating']['form']['resources']);
}
/**
* @group legacy
* @expectedDeprecation The "framework.trusted_proxies" configuration key has been deprecated in Symfony 3.3. Use the Request::setTrustedProxies() method in your front controller instead.
*/
public function testTrustedProxiesSetToNullIsDeprecated()
{
$processor = new Processor();
$configuration = new Configuration(true);
$processor->processConfiguration($configuration, [['trusted_proxies' => null]]);
}
/**
* @group legacy
* @expectedDeprecation The "framework.trusted_proxies" configuration key has been deprecated in Symfony 3.3. Use the Request::setTrustedProxies() method in your front controller instead.
*/
public function testTrustedProxiesSetToEmptyArrayIsDeprecated()
{
$processor = new Processor();
$configuration = new Configuration(true);
$processor->processConfiguration($configuration, [['trusted_proxies' => []]]);
}
/**
* @group legacy
* @expectedDeprecation The "framework.trusted_proxies" configuration key has been deprecated in Symfony 3.3. Use the Request::setTrustedProxies() method in your front controller instead.
*/
public function testTrustedProxiesSetToNonEmptyArrayIsInvalid()
{
$processor = new Processor();
$configuration = new Configuration(true);
$processor->processConfiguration($configuration, [['trusted_proxies' => ['127.0.0.1']]]);
}
/**
* @group legacy
* @dataProvider getTestValidSessionName
*/
public function testValidSessionName($sessionName)
{
$processor = new Processor();
$config = $processor->processConfiguration(
new Configuration(true),
[['session' => ['name' => $sessionName]]]
);
$this->assertEquals($sessionName, $config['session']['name']);
}
public function getTestValidSessionName()
{
return [
[null],
['PHPSESSID'],
['a&b'],
[',_-!@#$%^*(){}:<>/?'],
];
}
/**
* @dataProvider getTestInvalidSessionName
*/
public function testInvalidSessionName($sessionName)
{
$this->expectException('Symfony\Component\Config\Definition\Exception\InvalidConfigurationException');
$processor = new Processor();
$processor->processConfiguration(
new Configuration(true),
[['session' => ['name' => $sessionName]]]
);
}
public function getTestInvalidSessionName()
{
return [
['a.b'],
['a['],
['a[]'],
['a[b]'],
['a=b'],
['a+b'],
];
}
/**
* @dataProvider getTestValidTrustedProxiesData
* @group legacy
*/
public function testValidTrustedProxies($trustedProxies, $processedProxies)
{
$processor = new Processor();
$configuration = new Configuration(true);
$config = $processor->processConfiguration($configuration, [[
'secret' => 's3cr3t',
'trusted_proxies' => $trustedProxies,
]]);
$this->assertEquals($processedProxies, $config['trusted_proxies']);
}
public function getTestValidTrustedProxiesData()
{
return [
[['127.0.0.1'], ['127.0.0.1']],
[['::1'], ['::1']],
[['127.0.0.1', '::1'], ['127.0.0.1', '::1']],
[null, []],
[false, []],
[[], []],
[['10.0.0.0/8'], ['10.0.0.0/8']],
[['::ffff:0:0/96'], ['::ffff:0:0/96']],
[['0.0.0.0/0'], ['0.0.0.0/0']],
];
}
/**
* @group legacy
*/
public function testInvalidTypeTrustedProxies()
{
$this->expectException('Symfony\Component\Config\Definition\Exception\InvalidConfigurationException');
$processor = new Processor();
$configuration = new Configuration(true);
$processor->processConfiguration($configuration, [
[
'secret' => 's3cr3t',
'trusted_proxies' => 'Not an IP address',
],
]);
}
/**
* @group legacy
*/
public function testInvalidValueTrustedProxies()
{
$this->expectException('Symfony\Component\Config\Definition\Exception\InvalidConfigurationException');
$processor = new Processor();
$configuration = new Configuration(true);
$processor->processConfiguration($configuration, [
[
'secret' => 's3cr3t',
'trusted_proxies' => ['Not an IP address'],
],
]);
}
public function testAssetsCanBeEnabled()
{
$processor = new Processor();
$configuration = new Configuration(true);
$config = $processor->processConfiguration($configuration, [['assets' => null]]);
$defaultConfig = [
'enabled' => true,
'version_strategy' => null,
'version' => null,
'version_format' => '%%s?%%s',
'base_path' => '',
'base_urls' => [],
'packages' => [],
'json_manifest_path' => null,
];
$this->assertEquals($defaultConfig, $config['assets']);
}
/**
* @dataProvider provideValidAssetsPackageNameConfigurationTests
*/
public function testValidAssetsPackageNameConfiguration($packageName)
{
$processor = new Processor();
$configuration = new Configuration(true);
$config = $processor->processConfiguration($configuration, [
[
'assets' => [
'packages' => [
$packageName => [],
],
],
],
]);
$this->assertArrayHasKey($packageName, $config['assets']['packages']);
}
public function provideValidAssetsPackageNameConfigurationTests()
{
return [
['foobar'],
['foo-bar'],
['foo_bar'],
];
}
/**
* @dataProvider provideInvalidAssetConfigurationTests
*/
public function testInvalidAssetsConfiguration(array $assetConfig, $expectedMessage)
{
$this->expectException(InvalidConfigurationException::class);
$this->expectExceptionMessage($expectedMessage);
$processor = new Processor();
$configuration = new Configuration(true);
$processor->processConfiguration($configuration, [
[
'assets' => $assetConfig,
],
]);
}
public function provideInvalidAssetConfigurationTests()
{
// helper to turn config into embedded package config
$createPackageConfig = function (array $packageConfig) {
return [
'base_urls' => '//example.com',
'version' => 1,
'packages' => [
'foo' => $packageConfig,
],
];
};
$config = [
'version' => 1,
'version_strategy' => 'foo',
];
yield [$config, 'You cannot use both "version_strategy" and "version" at the same time under "assets".'];
yield [$createPackageConfig($config), 'You cannot use both "version_strategy" and "version" at the same time under "assets" packages.'];
$config = [
'json_manifest_path' => '/foo.json',
'version_strategy' => 'foo',
];
yield [$config, 'You cannot use both "version_strategy" and "json_manifest_path" at the same time under "assets".'];
yield [$createPackageConfig($config), 'You cannot use both "version_strategy" and "json_manifest_path" at the same time under "assets" packages.'];
$config = [
'json_manifest_path' => '/foo.json',
'version' => '1',
];
yield [$config, 'You cannot use both "version" and "json_manifest_path" at the same time under "assets".'];
yield [$createPackageConfig($config), 'You cannot use both "version" and "json_manifest_path" at the same time under "assets" packages.'];
}
/**
* @dataProvider provideValidLockConfigurationTests
*/
public function testValidLockConfiguration($lockConfig, $processedConfig)
{
$processor = new Processor();
$configuration = new Configuration(true);
$config = $processor->processConfiguration($configuration, [
[
'lock' => $lockConfig,
],
]);
$this->assertArrayHasKey('lock', $config);
$this->assertEquals($processedConfig, $config['lock']);
}
public function provideValidLockConfigurationTests()
{
yield [null, ['enabled' => true, 'resources' => ['default' => [class_exists(SemaphoreStore::class) && SemaphoreStore::isSupported() ? 'semaphore' : 'flock']]]];
yield ['flock', ['enabled' => true, 'resources' => ['default' => ['flock']]]];
yield [['flock', 'semaphore'], ['enabled' => true, 'resources' => ['default' => ['flock', 'semaphore']]]];
yield [['foo' => 'flock', 'bar' => 'semaphore'], ['enabled' => true, 'resources' => ['foo' => ['flock'], 'bar' => ['semaphore']]]];
yield [['foo' => ['flock', 'semaphore'], 'bar' => 'semaphore'], ['enabled' => true, 'resources' => ['foo' => ['flock', 'semaphore'], 'bar' => ['semaphore']]]];
yield [['default' => 'flock'], ['enabled' => true, 'resources' => ['default' => ['flock']]]];
yield [['enabled' => false, 'flock'], ['enabled' => false, 'resources' => ['default' => ['flock']]]];
yield [['enabled' => false, ['flock', 'semaphore']], ['enabled' => false, 'resources' => ['default' => ['flock', 'semaphore']]]];
yield [['enabled' => false, 'foo' => 'flock', 'bar' => 'semaphore'], ['enabled' => false, 'resources' => ['foo' => ['flock'], 'bar' => ['semaphore']]]];
yield [['enabled' => false, 'foo' => ['flock', 'semaphore']], ['enabled' => false, 'resources' => ['foo' => ['flock', 'semaphore']]]];
yield [['enabled' => false, 'default' => 'flock'], ['enabled' => false, 'resources' => ['default' => ['flock']]]];
yield [['resources' => 'flock'], ['enabled' => true, 'resources' => ['default' => ['flock']]]];
yield [['resources' => ['flock', 'semaphore']], ['enabled' => true, 'resources' => ['default' => ['flock', 'semaphore']]]];
yield [['resources' => ['foo' => 'flock', 'bar' => 'semaphore']], ['enabled' => true, 'resources' => ['foo' => ['flock'], 'bar' => ['semaphore']]]];
yield [['resources' => ['foo' => ['flock', 'semaphore'], 'bar' => 'semaphore']], ['enabled' => true, 'resources' => ['foo' => ['flock', 'semaphore'], 'bar' => ['semaphore']]]];
yield [['resources' => ['default' => 'flock']], ['enabled' => true, 'resources' => ['default' => ['flock']]]];
yield [['enabled' => false, 'resources' => 'flock'], ['enabled' => false, 'resources' => ['default' => ['flock']]]];
yield [['enabled' => false, 'resources' => ['flock', 'semaphore']], ['enabled' => false, 'resources' => ['default' => ['flock', 'semaphore']]]];
yield [['enabled' => false, 'resources' => ['foo' => 'flock', 'bar' => 'semaphore']], ['enabled' => false, 'resources' => ['foo' => ['flock'], 'bar' => ['semaphore']]]];
yield [['enabled' => false, 'resources' => ['foo' => ['flock', 'semaphore'], 'bar' => 'semaphore']], ['enabled' => false, 'resources' => ['foo' => ['flock', 'semaphore'], 'bar' => ['semaphore']]]];
yield [['enabled' => false, 'resources' => ['default' => 'flock']], ['enabled' => false, 'resources' => ['default' => ['flock']]]];
// xml
yield [['resource' => ['flock']], ['enabled' => true, 'resources' => ['default' => ['flock']]]];
yield [['resource' => ['flock', ['name' => 'foo', 'value' => 'semaphore']]], ['enabled' => true, 'resources' => ['default' => ['flock'], 'foo' => ['semaphore']]]];
yield [['resource' => [['name' => 'foo', 'value' => 'flock']]], ['enabled' => true, 'resources' => ['foo' => ['flock']]]];
yield [['resource' => [['name' => 'foo', 'value' => 'flock'], ['name' => 'foo', 'value' => 'semaphore']]], ['enabled' => true, 'resources' => ['foo' => ['flock', 'semaphore']]]];
yield [['resource' => [['name' => 'foo', 'value' => 'flock'], ['name' => 'bar', 'value' => 'semaphore']]], ['enabled' => true, 'resources' => ['foo' => ['flock'], 'bar' => ['semaphore']]]];
yield [['resource' => [['name' => 'foo', 'value' => 'flock'], ['name' => 'foo', 'value' => 'semaphore'], ['name' => 'bar', 'value' => 'semaphore']]], ['enabled' => true, 'resources' => ['foo' => ['flock', 'semaphore'], 'bar' => ['semaphore']]]];
yield [['enabled' => false, 'resource' => ['flock']], ['enabled' => false, 'resources' => ['default' => ['flock']]]];
yield [['enabled' => false, 'resource' => ['flock', ['name' => 'foo', 'value' => 'semaphore']]], ['enabled' => false, 'resources' => ['default' => ['flock'], 'foo' => ['semaphore']]]];
yield [['enabled' => false, 'resource' => [['name' => 'foo', 'value' => 'flock']]], ['enabled' => false, 'resources' => ['foo' => ['flock']]]];
yield [['enabled' => false, 'resource' => [['name' => 'foo', 'value' => 'flock'], ['name' => 'foo', 'value' => 'semaphore']]], ['enabled' => false, 'resources' => ['foo' => ['flock', 'semaphore']]]];
yield [['enabled' => false, 'resource' => [['name' => 'foo', 'value' => 'flock'], ['name' => 'bar', 'value' => 'semaphore']]], ['enabled' => false, 'resources' => ['foo' => ['flock'], 'bar' => ['semaphore']]]];
yield [['enabled' => false, 'resource' => [['name' => 'foo', 'value' => 'flock'], ['name' => 'foo', 'value' => 'semaphore'], ['name' => 'bar', 'value' => 'semaphore']]], ['enabled' => false, 'resources' => ['foo' => ['flock', 'semaphore'], 'bar' => ['semaphore']]]];
}
protected static function getBundleDefaultConfig()
{
return [
'http_method_override' => true,
'trusted_proxies' => [],
'ide' => null,
'default_locale' => 'en',
'csrf_protection' => [
'enabled' => false,
],
'form' => [
'enabled' => !class_exists(FullStack::class),
'csrf_protection' => [
'enabled' => null, // defaults to csrf_protection.enabled
'field_name' => '_token',
],
],
'esi' => ['enabled' => false],
'ssi' => ['enabled' => false],
'fragments' => [
'enabled' => false,
'path' => '/_fragment',
],
'profiler' => [
'enabled' => false,
'only_exceptions' => false,
'only_master_requests' => false,
'dsn' => 'file:%kernel.cache_dir%/profiler',
'collect' => true,
'matcher' => [
'enabled' => false,
'ips' => [],
],
],
'translator' => [
'enabled' => !class_exists(FullStack::class),
'fallbacks' => ['en'],
'logging' => true,
'formatter' => 'translator.formatter.default',
'paths' => [],
'default_path' => '%kernel.project_dir%/translations',
],
'validation' => [
'enabled' => !class_exists(FullStack::class),
'enable_annotations' => !class_exists(FullStack::class),
'static_method' => ['loadValidatorMetadata'],
'translation_domain' => 'validators',
'strict_email' => false,
'mapping' => [
'paths' => [],
],
],
'annotations' => [
'cache' => 'php_array',
'file_cache_dir' => '%kernel.cache_dir%/annotations',
'debug' => true,
'enabled' => true,
],
'serializer' => [
'enabled' => !class_exists(FullStack::class),
'enable_annotations' => !class_exists(FullStack::class),
'mapping' => ['paths' => []],
],
'property_access' => [
'magic_call' => false,
'throw_exception_on_invalid_index' => false,
],
'property_info' => [
'enabled' => !class_exists(FullStack::class),
],
'router' => [
'enabled' => false,
'http_port' => 80,
'https_port' => 443,
'strict_requirements' => true,
],
'session' => [
'enabled' => false,
'storage_id' => 'session.storage.native',
'handler_id' => 'session.handler.native_file',
'cookie_httponly' => true,
'gc_probability' => 1,
'save_path' => '%kernel.cache_dir%/sessions',
'metadata_update_threshold' => '0',
'use_strict_mode' => true,
],
'request' => [
'enabled' => false,
'formats' => [],
],
'templating' => [
'enabled' => false,
'hinclude_default_template' => null,
'form' => [
'resources' => ['FrameworkBundle:Form'],
],
'engines' => [],
'loaders' => [],
],
'assets' => [
'enabled' => !class_exists(FullStack::class),
'version_strategy' => null,
'version' => null,
'version_format' => '%%s?%%s',
'base_path' => '',
'base_urls' => [],
'packages' => [],
'json_manifest_path' => null,
],
'cache' => [
'pools' => [],
'app' => 'cache.adapter.filesystem',
'system' => 'cache.adapter.system',
'directory' => '%kernel.cache_dir%/pools',
'default_redis_provider' => 'redis://localhost',
'default_memcached_provider' => 'memcached://localhost',
],
'workflows' => [
'enabled' => false,
'workflows' => [],
],
'php_errors' => [
'log' => true,
'throw' => true,
],
'web_link' => [
'enabled' => !class_exists(FullStack::class),
],
'lock' => [
'enabled' => !class_exists(FullStack::class),
'resources' => [
'default' => [
class_exists(SemaphoreStore::class) && SemaphoreStore::isSupported() ? 'semaphore' : 'flock',
],
],
],
];
}
}

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\Bundle\FrameworkBundle\Tests;
use Symfony\Component\HttpKernel\Bundle\Bundle;
class CustomPathBundle extends Bundle
{
public function getPath()
{
return __DIR__.'/..';
}
}

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\Bundle\FrameworkBundle\Tests;
use Symfony\Component\HttpKernel\Bundle\Bundle;
class TestBundle extends Bundle
{
}

View File

@@ -0,0 +1,32 @@
<?php
$container->loadFromExtension('framework', [
'assets' => [
'version' => 'SomeVersionScheme',
'base_urls' => 'http://cdn.example.com',
'version_format' => '%%s?version=%%s',
'packages' => [
'images_path' => [
'base_path' => '/foo',
],
'images' => [
'version' => '1.0.0',
'base_urls' => ['http://images1.example.com', 'http://images2.example.com'],
],
'foo' => [
'version' => '1.0.0',
'version_format' => '%%s-%%s',
],
'bar' => [
'base_urls' => ['https://bar2.example.com'],
],
'bar_version_strategy' => [
'base_urls' => ['https://bar2.example.com'],
'version_strategy' => 'assets.custom_version_strategy',
],
'json_manifest_strategy' => [
'json_manifest_path' => '/path/to/manifest.json',
],
],
],
]);

View File

@@ -0,0 +1,7 @@
<?php
$container->loadFromExtension('framework', [
'assets' => [
'enabled' => false,
],
]);

View File

@@ -0,0 +1,8 @@
<?php
$container->loadFromExtension('framework', [
'assets' => [
'version_strategy' => 'assets.custom_version_strategy',
'base_urls' => 'http://cdn.example.com',
],
]);

View File

@@ -0,0 +1,29 @@
<?php
$container->loadFromExtension('framework', [
'cache' => [
'pools' => [
'cache.foo' => [
'adapter' => 'cache.adapter.apcu',
'default_lifetime' => 30,
],
'cache.bar' => [
'adapter' => 'cache.adapter.doctrine',
'default_lifetime' => 5,
'provider' => 'app.doctrine_cache_provider',
],
'cache.baz' => [
'adapter' => 'cache.adapter.filesystem',
'default_lifetime' => 7,
],
'cache.foobar' => [
'adapter' => 'cache.adapter.psr6',
'default_lifetime' => 10,
'provider' => 'app.cache_pool',
],
'cache.def' => [
'default_lifetime' => 11,
],
],
],
]);

View File

@@ -0,0 +1,9 @@
<?php
$container->setParameter('env(REDIS_URL)', 'redis://paas.com');
$container->loadFromExtension('framework', [
'cache' => [
'default_redis_provider' => '%env(REDIS_URL)%',
],
]);

View File

@@ -0,0 +1,9 @@
<?php
$container->loadFromExtension('framework', [
'csrf_protection' => true,
'form' => true,
'session' => [
'handler_id' => null,
],
]);

View File

@@ -0,0 +1,7 @@
<?php
$container->loadFromExtension('framework', [
'csrf_protection' => [
'enabled' => true,
],
]);

View File

@@ -0,0 +1,3 @@
<?php
$container->loadFromExtension('framework', []);

View File

@@ -0,0 +1,13 @@
<?php
$container->loadFromExtension('framework', [
'fragments' => [
'enabled' => false,
],
'esi' => [
'enabled' => true,
],
'ssi' => [
'enabled' => true,
],
]);

View File

@@ -0,0 +1,7 @@
<?php
$container->loadFromExtension('framework', [
'esi' => [
'enabled' => false,
],
]);

View File

@@ -0,0 +1,9 @@
<?php
$container->loadFromExtension('framework', [
'form' => [
'csrf_protection' => [
'enabled' => false,
],
],
]);

View File

@@ -0,0 +1,84 @@
<?php
$container->loadFromExtension('framework', [
'secret' => 's3cr3t',
'default_locale' => 'fr',
'csrf_protection' => true,
'form' => [
'csrf_protection' => [
'field_name' => '_csrf',
],
],
'http_method_override' => false,
'esi' => [
'enabled' => true,
],
'ssi' => [
'enabled' => true,
],
'profiler' => [
'only_exceptions' => true,
'enabled' => false,
],
'router' => [
'resource' => '%kernel.project_dir%/config/routing.xml',
'type' => 'xml',
],
'session' => [
'storage_id' => 'session.storage.native',
'handler_id' => 'session.handler.native_file',
'name' => '_SYMFONY',
'cookie_lifetime' => 86400,
'cookie_path' => '/',
'cookie_domain' => 'example.com',
'cookie_secure' => true,
'cookie_httponly' => false,
'use_cookies' => true,
'gc_maxlifetime' => 90000,
'gc_divisor' => 108,
'gc_probability' => 1,
'save_path' => '/path/to/sessions',
],
'templating' => [
'cache' => '/path/to/cache',
'engines' => ['php', 'twig'],
'loader' => ['loader.foo', 'loader.bar'],
'form' => [
'resources' => ['theme1', 'theme2'],
],
'hinclude_default_template' => 'global_hinclude_template',
],
'assets' => [
'version' => 'v1',
],
'translator' => [
'enabled' => true,
'fallback' => 'fr',
'paths' => ['%kernel.project_dir%/Fixtures/translations'],
],
'validation' => [
'enabled' => true,
],
'annotations' => [
'cache' => 'file',
'debug' => true,
'file_cache_dir' => '%kernel.cache_dir%/annotations',
],
'serializer' => [
'enabled' => true,
'enable_annotations' => true,
'name_converter' => 'serializer.name_converter.camel_case_to_snake_case',
'circular_reference_handler' => 'my.circular.reference.handler',
],
'property_info' => true,
'ide' => 'file%%link%%format',
'request' => [
'formats' => [
'csv' => [
'text/csv',
'text/plain',
],
'pdf' => 'application/pdf',
],
],
]);

View File

@@ -0,0 +1,8 @@
<?php
$container->loadFromExtension('framework', [
'php_errors' => [
'log' => false,
'throw' => false,
],
]);

View File

@@ -0,0 +1,8 @@
<?php
$container->loadFromExtension('framework', [
'php_errors' => [
'log' => true,
'throw' => true,
],
]);

View File

@@ -0,0 +1,7 @@
<?php
$container->loadFromExtension('framework', [
'profiler' => [
'enabled' => true,
],
]);

View File

@@ -0,0 +1,8 @@
<?php
$container->loadFromExtension('framework', [
'property_access' => [
'magic_call' => true,
'throw_exception_on_invalid_index' => true,
],
]);

View File

@@ -0,0 +1,7 @@
<?php
$container->loadFromExtension('framework', [
'property_info' => [
'enabled' => true,
],
]);

View File

@@ -0,0 +1,7 @@
<?php
$container->loadFromExtension('framework', [
'request' => [
'formats' => [],
],
]);

View File

@@ -0,0 +1,7 @@
<?php
$container->loadFromExtension('framework', [
'serializer' => [
'enabled' => false,
],
]);

View File

@@ -0,0 +1,7 @@
<?php
$container->loadFromExtension('framework', [
'serializer' => [
'enabled' => true,
],
]);

View File

@@ -0,0 +1,8 @@
<?php
$container->loadFromExtension('framework', [
'serializer' => [
'enabled' => true,
'cache' => 'foo',
],
]);

View File

@@ -0,0 +1,15 @@
<?php
$container->loadFromExtension('framework', [
'annotations' => ['enabled' => true],
'serializer' => [
'enable_annotations' => true,
'mapping' => [
'paths' => [
'%kernel.project_dir%/Fixtures/TestBundle/Resources/config/serializer_mapping/files',
'%kernel.project_dir%/Fixtures/TestBundle/Resources/config/serializer_mapping/serialization.yml',
'%kernel.project_dir%/Fixtures/TestBundle/Resources/config/serializer_mapping/serialization.yaml',
],
],
],
]);

View File

@@ -0,0 +1,7 @@
<?php
$container->loadFromExtension('framework', [
'session' => [
'handler_id' => null,
],
]);

View File

@@ -0,0 +1,7 @@
<?php
$container->loadFromExtension('framework', [
'ssi' => [
'enabled' => false,
],
]);

View File

@@ -0,0 +1,5 @@
<?php
$container->loadFromExtension('framework', [
'templating' => false,
]);

View File

@@ -0,0 +1,7 @@
<?php
$container->loadFromExtension('framework', [
'templating' => [
'engines' => ['php', 'twig'],
],
]);

View File

@@ -0,0 +1,8 @@
<?php
$container->loadFromExtension('framework', [
'assets' => false,
'templating' => [
'engines' => ['php'],
],
]);

View File

@@ -0,0 +1,8 @@
<?php
$container->loadFromExtension('framework', [
'translator' => false,
'templating' => [
'engines' => ['php'],
],
]);

View File

@@ -0,0 +1,8 @@
<?php
$container->loadFromExtension('framework', [
'translator' => true,
'templating' => [
'engines' => ['php'],
],
]);

View File

@@ -0,0 +1,7 @@
<?php
$container->loadFromExtension('framework', [
'translator' => [
'fallbacks' => ['en', 'fr'],
],
]);

View File

@@ -0,0 +1,9 @@
<?php
$container->loadFromExtension('framework', [
'secret' => 's3cr3t',
'validation' => [
'enabled' => true,
'enable_annotations' => true,
],
]);

View File

@@ -0,0 +1,13 @@
<?php
$container->loadFromExtension('framework', [
'validation' => [
'mapping' => [
'paths' => [
'%kernel.project_dir%/Fixtures/TestBundle/Resources/config/validation_mapping/files',
'%kernel.project_dir%/Fixtures/TestBundle/Resources/config/validation_mapping/validation.yml',
'%kernel.project_dir%/Fixtures/TestBundle/Resources/config/validation_mapping/validation.yaml',
],
],
],
]);

View File

@@ -0,0 +1,9 @@
<?php
$container->loadFromExtension('framework', [
'secret' => 's3cr3t',
'validation' => [
'enabled' => true,
'static_method' => ['loadFoo', 'loadBar'],
],
]);

View File

@@ -0,0 +1,9 @@
<?php
$container->loadFromExtension('framework', [
'secret' => 's3cr3t',
'validation' => [
'enabled' => true,
'static_method' => false,
],
]);

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