Actualización

This commit is contained in:
Xes
2025-04-10 12:24:57 +02:00
parent 8969cc929d
commit 45420b6f0d
39760 changed files with 4303286 additions and 0 deletions

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\Tests\TestCase;
use Symfony\Bundle\FrameworkBundle\Templating\TemplateFilenameParser;
use Symfony\Bundle\FrameworkBundle\CacheWarmer\TemplateFinder;
use Symfony\Bundle\FrameworkBundle\Tests\Fixtures\BaseBundle\BaseBundle;
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')
->will($this->returnValue(array('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,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\WebTestCase;
use Symfony\Component\HttpFoundation\Response;
class ClientTest extends WebTestCase
{
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(array('shutdown', 'boot', 'handle'))
->disableOriginalConstructor()
->getMock();
$mock->expects($this->any())->method('handle')->willReturn(new Response('foo'));
return $mock;
}
}

View File

@@ -0,0 +1,86 @@
<?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(array('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');
// simply check that cache is warmed up
$this->assertGreaterThanOrEqual(1, count($metaFiles));
$configCacheFactory = new ConfigCacheFactory(true);
$that = $this;
foreach ($metaFiles as $file) {
$configCacheFactory->cache(substr($file, 0, -5), function () use ($that, $file) {
$that->fail(sprintf('Meta file "%s" is not fresh', (string) $file));
});
}
// check that app kernel file present in meta file of container's cache
$containerRef = new \ReflectionObject($this->kernel->getContainer());
$containerFile = $containerRef->getFileName();
$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');
$this->assertRegExp(sprintf('/\'kernel.name\'\s*=>\s*\'%s\'/', $this->kernel->getName()), file_get_contents($containerFile), 'kernel.name is properly set on the dumped container');
}
}

View File

@@ -0,0 +1,36 @@
<?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 Symfony\Bundle\FrameworkBundle\FrameworkBundle;
use Symfony\Component\Config\Loader\LoaderInterface;
use Symfony\Component\HttpKernel\Kernel;
class TestAppKernel extends Kernel
{
public function registerBundles()
{
return array(
new FrameworkBundle(),
);
}
public function setRootDir($rootDir)
{
$this->rootDir = $rootDir;
}
public function registerContainerConfiguration(LoaderInterface $loader)
{
$loader->load(__DIR__.DIRECTORY_SEPARATOR.'config.yml');
}
}

View File

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

View File

@@ -0,0 +1,94 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Bundle\FrameworkBundle\Tests\Command;
use Symfony\Component\Console\Application;
use Symfony\Component\Console\Tester\CommandTester;
use Symfony\Bundle\FrameworkBundle\Command\RouterDebugCommand;
use Symfony\Component\Routing\Route;
use Symfony\Component\Routing\RouteCollection;
class RouterDebugCommandTest extends \PHPUnit_Framework_TestCase
{
public function testDebugAllRoutes()
{
$tester = $this->createCommandTester();
$ret = $tester->execute(array('name' => null), array('decorated' => false));
$this->assertEquals(0, $ret, 'Returns 0 in case of success');
$this->assertContains('Name Method Scheme Host Path', $tester->getDisplay());
}
public function testDebugSingleRoute()
{
$tester = $this->createCommandTester();
$ret = $tester->execute(array('name' => 'foo'), array('decorated' => false));
$this->assertEquals(0, $ret, 'Returns 0 in case of success');
$this->assertContains('Route Name | foo', $tester->getDisplay());
}
/**
* @expectedException \InvalidArgumentException
*/
public function testDebugInvalidRoute()
{
$this->createCommandTester()->execute(array('name' => 'test'));
}
/**
* @return CommandTester
*/
private function createCommandTester()
{
$application = new Application();
$command = new RouterDebugCommand();
$command->setContainer($this->getContainer());
$application->add($command);
return new CommandTester($application->find('debug:router'));
}
private function getContainer()
{
$routeCollection = new RouteCollection();
$routeCollection->add('foo', new Route('foo'));
$router = $this->getMock('Symfony\Component\Routing\RouterInterface');
$router
->expects($this->any())
->method('getRouteCollection')
->will($this->returnValue($routeCollection))
;
$loader = $this->getMockBuilder('Symfony\Bundle\FrameworkBundle\Routing\DelegatingLoader')
->disableOriginalConstructor()
->getMock();
$container = $this->getMock('Symfony\Component\DependencyInjection\ContainerInterface');
$container
->expects($this->once())
->method('has')
->with('router')
->will($this->returnValue(true))
;
$container
->method('get')
->will($this->returnValueMap(array(
array('router', 1, $router),
array('controller_name_converter', 1, $loader),
)));
return $container;
}
}

View File

@@ -0,0 +1,96 @@
<?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 Symfony\Component\Console\Application;
use Symfony\Component\Console\Tester\CommandTester;
use Symfony\Bundle\FrameworkBundle\Command\RouterMatchCommand;
use Symfony\Bundle\FrameworkBundle\Command\RouterDebugCommand;
use Symfony\Component\Routing\Route;
use Symfony\Component\Routing\RouteCollection;
use Symfony\Component\Routing\RequestContext;
class RouterMatchCommandTest extends \PHPUnit_Framework_TestCase
{
public function testWithMatchPath()
{
$tester = $this->createCommandTester();
$ret = $tester->execute(array('path_info' => '/foo', 'foo'), array('decorated' => false));
$this->assertEquals(0, $ret, 'Returns 0 in case of success');
$this->assertContains('Route Name | foo', $tester->getDisplay());
}
public function testWithNotMatchPath()
{
$tester = $this->createCommandTester();
$ret = $tester->execute(array('path_info' => '/test', 'foo'), array('decorated' => false));
$this->assertEquals(1, $ret, 'Returns 1 in case of failure');
$this->assertContains('None of the routes match the path "/test"', $tester->getDisplay());
}
/**
* @return CommandTester
*/
private function createCommandTester()
{
$application = new Application();
$command = new RouterMatchCommand();
$command->setContainer($this->getContainer());
$application->add($command);
$command = new RouterDebugCommand();
$command->setContainer($this->getContainer());
$application->add($command);
return new CommandTester($application->find('router:match'));
}
private function getContainer()
{
$routeCollection = new RouteCollection();
$routeCollection->add('foo', new Route('foo'));
$requestContext = new RequestContext();
$router = $this->getMock('Symfony\Component\Routing\RouterInterface');
$router
->expects($this->any())
->method('getRouteCollection')
->will($this->returnValue($routeCollection))
;
$router
->expects($this->any())
->method('getContext')
->will($this->returnValue($requestContext))
;
$loader = $this->getMockBuilder('Symfony\Bundle\FrameworkBundle\Routing\DelegatingLoader')
->disableOriginalConstructor()
->getMock();
$container = $this->getMock('Symfony\Component\DependencyInjection\ContainerInterface');
$container
->expects($this->once())
->method('has')
->with('router')
->will($this->returnValue(true));
$container->method('get')
->will($this->returnValueMap(array(
array('router', 1, $router),
array('controller_name_converter', 1, $loader),
)));
return $container;
}
}

View File

@@ -0,0 +1,194 @@
<?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 Symfony\Component\Console\Application;
use Symfony\Component\Console\Tester\CommandTester;
use Symfony\Bundle\FrameworkBundle\Command\TranslationDebugCommand;
use Symfony\Component\Filesystem\Filesystem;
class TranslationDebugCommandTest extends \PHPUnit_Framework_TestCase
{
private $fs;
private $translationDir;
public function testDebugMissingMessages()
{
$tester = $this->createCommandTester($this->getContainer(array('foo' => 'foo')));
$tester->execute(array('locale' => 'en', 'bundle' => 'foo'));
$this->assertRegExp('/missing/', $tester->getDisplay());
}
public function testDebugUnusedMessages()
{
$tester = $this->createCommandTester($this->getContainer(array(), array('foo' => 'foo')));
$tester->execute(array('locale' => 'en', 'bundle' => 'foo'));
$this->assertRegExp('/unused/', $tester->getDisplay());
}
public function testDebugFallbackMessages()
{
$tester = $this->createCommandTester($this->getContainer(array(), array('foo' => 'foo')));
$tester->execute(array('locale' => 'fr', 'bundle' => 'foo'));
$this->assertRegExp('/fallback/', $tester->getDisplay());
}
public function testNoDefinedMessages()
{
$tester = $this->createCommandTester($this->getContainer());
$tester->execute(array('locale' => 'fr', 'bundle' => 'test'));
$this->assertRegExp('/No defined or extracted messages for locale "fr"/', $tester->getDisplay());
}
public function testDebugDefaultDirectory()
{
$tester = $this->createCommandTester($this->getContainer(array('foo' => 'foo'), array('bar' => 'bar')));
$tester->execute(array('locale' => 'en'));
$this->assertRegExp('/missing/', $tester->getDisplay());
$this->assertRegExp('/unused/', $tester->getDisplay());
}
public function testDebugCustomDirectory()
{
$kernel = $this->getMock('Symfony\Component\HttpKernel\KernelInterface');
$kernel->expects($this->once())
->method('getBundle')
->with($this->equalTo($this->translationDir))
->willThrowException(new \InvalidArgumentException());
$tester = $this->createCommandTester($this->getContainer(array('foo' => 'foo'), array('bar' => 'bar'), $kernel));
$tester->execute(array('locale' => 'en', 'bundle' => $this->translationDir));
$this->assertRegExp('/missing/', $tester->getDisplay());
$this->assertRegExp('/unused/', $tester->getDisplay());
}
/**
* @expectedException \InvalidArgumentException
*/
public function testDebugInvalidDirectory()
{
$kernel = $this->getMock('Symfony\Component\HttpKernel\KernelInterface');
$kernel->expects($this->once())
->method('getBundle')
->with($this->equalTo('dir'))
->will($this->throwException(new \InvalidArgumentException()));
$tester = $this->createCommandTester($this->getContainer(array(), array(), $kernel));
$tester->execute(array('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');
}
protected function tearDown()
{
$this->fs->remove($this->translationDir);
}
/**
* @return CommandTester
*/
private function createCommandTester($container)
{
$command = new TranslationDebugCommand();
$command->setContainer($container);
$application = new Application();
$application->add($command);
return new CommandTester($application->find('debug:translation'));
}
private function getContainer($extractedMessages = array(), $loadedMessages = array(), $kernel = null)
{
$translator = $this->getMockBuilder('Symfony\Component\Translation\Translator')
->disableOriginalConstructor()
->getMock();
$translator
->expects($this->any())
->method('getFallbackLocales')
->will($this->returnValue(array('en')));
$extractor = $this->getMock('Symfony\Component\Translation\Extractor\ExtractorInterface');
$extractor
->expects($this->any())
->method('extract')
->will(
$this->returnCallback(function ($path, $catalogue) use ($extractedMessages) {
$catalogue->add($extractedMessages);
})
);
$loader = $this->getMock('Symfony\Bundle\FrameworkBundle\Translation\TranslationLoader');
$loader
->expects($this->any())
->method('loadMessages')
->will(
$this->returnCallback(function ($path, $catalogue) use ($loadedMessages) {
$catalogue->add($loadedMessages);
})
);
if (null === $kernel) {
$kernel = $this->getMock('Symfony\Component\HttpKernel\KernelInterface');
$kernel
->expects($this->any())
->method('getBundle')
->will($this->returnValueMap(array(
array('foo', true, $this->getBundle($this->translationDir)),
array('test', true, $this->getBundle('test')),
)));
}
$kernel
->expects($this->any())
->method('getRootDir')
->will($this->returnValue($this->translationDir));
$container = $this->getMock('Symfony\Component\DependencyInjection\ContainerInterface');
$container
->expects($this->any())
->method('get')
->will($this->returnValueMap(array(
array('translation.extractor', 1, $extractor),
array('translation.loader', 1, $loader),
array('translator', 1, $translator),
array('kernel', 1, $kernel),
)));
return $container;
}
private function getBundle($path)
{
$bundle = $this->getMock('Symfony\Component\HttpKernel\Bundle\BundleInterface');
$bundle
->expects($this->any())
->method('getPath')
->will($this->returnValue($path))
;
return $bundle;
}
}

View File

@@ -0,0 +1,149 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Bundle\FrameworkBundle\Tests\Command;
use Symfony\Component\Console\Application;
use Symfony\Component\Console\Tester\CommandTester;
use Symfony\Bundle\FrameworkBundle\Command\TranslationUpdateCommand;
use Symfony\Component\Filesystem\Filesystem;
use Symfony\Component\DependencyInjection;
use Symfony\Component\HttpKernel;
class TranslationUpdateCommandTest extends \PHPUnit_Framework_TestCase
{
private $fs;
private $translationDir;
public function testDumpMessagesAndClean()
{
$tester = $this->createCommandTester($this->getContainer(array('foo' => 'foo')));
$tester->execute(array('command' => 'translation:update', 'locale' => 'en', 'bundle' => 'foo', '--dump-messages' => true, '--clean' => true));
$this->assertRegExp('/foo/', $tester->getDisplay());
$this->assertRegExp('/2 messages were successfully extracted/', $tester->getDisplay());
}
public function testWriteMessages()
{
$tester = $this->createCommandTester($this->getContainer(array('foo' => 'foo')));
$tester->execute(array('command' => 'translation:update', 'locale' => 'en', 'bundle' => 'foo', '--force' => true));
$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');
}
protected function tearDown()
{
$this->fs->remove($this->translationDir);
}
/**
* @return CommandTester
*/
private function createCommandTester(DependencyInjection\ContainerInterface $container)
{
$command = new TranslationUpdateCommand();
$command->setContainer($container);
$application = new Application();
$application->add($command);
return new CommandTester($application->find('translation:update'));
}
private function getContainer($extractedMessages = array(), $loadedMessages = array(), HttpKernel\KernelInterface $kernel = null)
{
$translator = $this->getMockBuilder('Symfony\Component\Translation\Translator')
->disableOriginalConstructor()
->getMock();
$translator
->expects($this->any())
->method('getFallbackLocales')
->will($this->returnValue(array('en')));
$extractor = $this->getMock('Symfony\Component\Translation\Extractor\ExtractorInterface');
$extractor
->expects($this->any())
->method('extract')
->will(
$this->returnCallback(function ($path, $catalogue) use ($extractedMessages) {
$catalogue->add($extractedMessages);
})
);
$loader = $this->getMock('Symfony\Bundle\FrameworkBundle\Translation\TranslationLoader');
$loader
->expects($this->any())
->method('loadMessages')
->will(
$this->returnCallback(function ($path, $catalogue) use ($loadedMessages) {
$catalogue->add($loadedMessages);
})
);
$writer = $this->getMock('Symfony\Component\Translation\Writer\TranslationWriter');
$writer
->expects($this->any())
->method('getFormats')
->will(
$this->returnValue(array('xlf', 'yml'))
);
if (null === $kernel) {
$kernel = $this->getMock('Symfony\Component\HttpKernel\KernelInterface');
$kernel
->expects($this->any())
->method('getBundle')
->will($this->returnValueMap(array(
array('foo', true, $this->getBundle($this->translationDir)),
array('test', true, $this->getBundle('test')),
)));
}
$kernel
->expects($this->any())
->method('getRootDir')
->will($this->returnValue($this->translationDir));
$container = $this->getMock('Symfony\Component\DependencyInjection\ContainerInterface');
$container
->expects($this->any())
->method('get')
->will($this->returnValueMap(array(
array('translation.extractor', 1, $extractor),
array('translation.loader', 1, $loader),
array('translation.writer', 1, $writer),
array('translator', 1, $translator),
array('kernel', 1, $kernel),
)));
return $container;
}
private function getBundle($path)
{
$bundle = $this->getMock('Symfony\Component\HttpKernel\Bundle\BundleInterface');
$bundle
->expects($this->any())
->method('getPath')
->will($this->returnValue($path))
;
return $bundle;
}
}

View File

@@ -0,0 +1,170 @@
<?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\Output\NullOutput;
use Symfony\Component\Console\Tester\ApplicationTester;
class ApplicationTest extends TestCase
{
public function testBundleInterfaceImplementation()
{
$bundle = $this->getMock('Symfony\Component\HttpKernel\Bundle\BundleInterface');
$kernel = $this->getKernel(array($bundle), true);
$application = new Application($kernel);
$application->doRun(new ArrayInput(array('list')), new NullOutput());
}
public function testBundleCommandsAreRegistered()
{
$bundle = $this->getMock('Symfony\Component\HttpKernel\Bundle\Bundle');
$bundle->expects($this->once())->method('registerCommands');
$kernel = $this->getKernel(array($bundle), true);
$application = new Application($kernel);
$application->doRun(new ArrayInput(array('list')), new NullOutput());
// Calling twice: registration should only be done once.
$application->doRun(new ArrayInput(array('list')), new NullOutput());
}
public function testBundleCommandsAreRetrievable()
{
$bundle = $this->getMock('Symfony\Component\HttpKernel\Bundle\Bundle');
$bundle->expects($this->once())->method('registerCommands');
$kernel = $this->getKernel(array($bundle));
$application = new Application($kernel);
$application->all();
// Calling twice: registration should only be done once.
$application->all();
}
public function testBundleSingleCommandIsRetrievable()
{
$bundle = $this->getMock('Symfony\Component\HttpKernel\Bundle\Bundle');
$bundle->expects($this->once())->method('registerCommands');
$kernel = $this->getKernel(array($bundle));
$application = new Application($kernel);
$command = new Command('example');
$application->add($command);
$this->assertSame($command, $application->get('example'));
}
public function testBundleCommandCanBeFound()
{
$bundle = $this->getMock('Symfony\Component\HttpKernel\Bundle\Bundle');
$bundle->expects($this->once())->method('registerCommands');
$kernel = $this->getKernel(array($bundle));
$application = new Application($kernel);
$command = new Command('example');
$application->add($command);
$this->assertSame($command, $application->find('example'));
}
public function testBundleCommandCanBeFoundByAlias()
{
$bundle = $this->getMock('Symfony\Component\HttpKernel\Bundle\Bundle');
$bundle->expects($this->once())->method('registerCommands');
$kernel = $this->getKernel(array($bundle));
$application = new Application($kernel);
$command = new Command('example');
$command->setAliases(array('alias'));
$application->add($command);
$this->assertSame($command, $application->find('alias'));
}
public function testBundleCommandsHaveRightContainer()
{
$command = $this->getMockForAbstractClass('Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand', array('foo'), '', true, true, true, array('setContainer'));
$command->setCode(function () {});
$command->expects($this->exactly(2))->method('setContainer');
$application = new Application($this->getKernel(array(), true));
$application->setAutoExit(false);
$application->setCatchExceptions(false);
$application->add($command);
$tester = new ApplicationTester($application);
// set container is called here
$tester->run(array('command' => 'foo'));
// as the container might have change between two runs, setContainer must called again
$tester->run(array('command' => 'foo'));
}
private function getKernel(array $bundles, $useDispatcher = false)
{
$container = $this->getMock('Symfony\Component\DependencyInjection\ContainerInterface');
if ($useDispatcher) {
$dispatcher = $this->getMock('Symfony\Component\EventDispatcher\EventDispatcherInterface');
$dispatcher
->expects($this->atLeastOnce())
->method('dispatch')
;
$container
->expects($this->atLeastOnce())
->method('get')
->with($this->equalTo('event_dispatcher'))
->will($this->returnValue($dispatcher));
}
$container
->expects($this->once())
->method('hasParameter')
->with($this->equalTo('console.command.ids'))
->will($this->returnValue(true))
;
$container
->expects($this->once())
->method('getParameter')
->with($this->equalTo('console.command.ids'))
->will($this->returnValue(array()))
;
$kernel = $this->getMock('Symfony\Component\HttpKernel\KernelInterface');
$kernel
->expects($this->any())
->method('getBundles')
->will($this->returnValue($bundles))
;
$kernel
->expects($this->any())
->method('getContainer')
->will($this->returnValue($container))
;
return $kernel;
}
}

View File

@@ -0,0 +1,200 @@
<?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\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 \PHPUnit_Framework_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 getDescribeContainerAliasTestData */
public function testDescribeContainerAlias(Alias $alias, $expectedDescription)
{
$this->assertDescription($expectedDescription, $alias);
}
public function getDescribeContainerAliasTestData()
{
return $this->getDescriptionTestData(ObjectsProvider::getContainerAliases());
}
/** @dataProvider getDescribeContainerParameterTestData */
public function testDescribeContainerParameter($parameter, $expectedDescription, array $options)
{
$this->assertDescription($expectedDescription, $parameter, $options);
}
public function getDescribeContainerParameterTestData()
{
$data = $this->getDescriptionTestData(ObjectsProvider::getContainerParameter());
$data[0][] = array('parameter' => 'database_name');
$data[1][] = array('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 = array())
{
$options['raw_output'] = true;
$output = new BufferedOutput(BufferedOutput::VERBOSITY_NORMAL, true);
if ('txt' === $this->getFormat()) {
$options['output'] = new SymfonyStyle(new ArrayInput(array()), $output);
}
$this->getDescriptor()->describe($output, $describedObject, $options);
if ('json' === $this->getFormat()) {
$this->assertEquals(json_decode($expectedDescription), json_decode($output->fetch()));
} else {
$this->assertEquals(trim($expectedDescription), trim(str_replace(PHP_EOL, "\n", $output->fetch())));
}
}
private function getDescriptionTestData(array $objects)
{
$data = array();
foreach ($objects as $name => $object) {
$description = file_get_contents(sprintf('%s/../../Fixtures/Descriptor/%s.%s', __DIR__, $name, $this->getFormat()));
$data[] = array($object, $description);
}
return $data;
}
private function getContainerBuilderDescriptionTestData(array $objects)
{
$variations = array(
'services' => array('show_private' => true),
'public' => array('show_private' => false),
'tag1' => array('show_private' => true, 'tag' => 'tag1'),
'tags' => array('group_by' => 'tags', 'show_private' => true),
);
$data = array();
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[] = array($object, $description, $options);
}
}
return $data;
}
private function getEventDispatcherDescriptionTestData(array $objects)
{
$variations = array(
'events' => array(),
'event1' => array('event' => 'event1'),
);
$data = array();
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[] = array($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,173 @@
<?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\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\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 array('route_collection_1' => $collection1);
}
public static function getRoutes()
{
return array(
'route_1' => new Route(
'/hello/{name}',
array('name' => 'Joseph'),
array('name' => '[a-z]+'),
array('opt1' => 'val1', 'opt2' => 'val2'),
'localhost',
array('http', 'https'),
array('get', 'head')
),
'route_2' => new Route(
'/name/add',
array(),
array(),
array('opt1' => 'val1', 'opt2' => 'val2'),
'localhost',
array('http', 'https'),
array('put', 'post')
),
);
}
public static function getContainerParameters()
{
return array(
'parameters_1' => new ParameterBag(array(
'integer' => 12,
'string' => 'Hello world!',
'boolean' => true,
'array' => array(12, 'Hello world!', true),
)),
);
}
public static function getContainerParameter()
{
$builder = new ContainerBuilder();
$builder->setParameter('database_name', 'symfony');
$builder->setParameter('twig.form.resources', array(
'bootstrap_3_horizontal_layout.html.twig',
'bootstrap_3_layout.html.twig',
'form_div_layout.html.twig',
'form_table_layout.html.twig',
));
return array(
'parameter' => $builder,
'array_parameter' => $builder,
);
}
public static function getContainerBuilders()
{
$builder1 = new ContainerBuilder();
$builder1->setDefinitions(self::getContainerDefinitions());
$builder1->setAliases(self::getContainerAliases());
return array('builder_1' => $builder1);
}
public static function getContainerDefinitions()
{
$definition1 = new Definition('Full\\Qualified\\Class1');
$definition2 = new Definition('Full\\Qualified\\Class2');
return array(
'definition_1' => $definition1
->setPublic(true)
->setSynthetic(false)
->setLazy(true)
->setAbstract(true)
->setFactory(array('Full\\Qualified\\FactoryClass', 'get')),
'definition_2' => $definition2
->setPublic(false)
->setSynthetic(true)
->setFile('/path/to/file')
->setLazy(false)
->setAbstract(false)
->addTag('tag1', array('attr1' => 'val1', 'attr2' => 'val2'))
->addTag('tag1', array('attr3' => 'val3'))
->addTag('tag2')
->setFactory(array(new Reference('factory.service'), 'get')),
);
}
public static function getContainerAliases()
{
return array(
'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 array('event_dispatcher_1' => $eventDispatcher);
}
public static function getCallables()
{
return array(
'callable_1' => 'array_key_exists',
'callable_2' => array('Symfony\\Bundle\\FrameworkBundle\\Tests\\Console\\Descriptor\\CallableClass', 'staticMethod'),
'callable_3' => array(new CallableClass(), 'method'),
'callable_4' => 'Symfony\\Bundle\\FrameworkBundle\\Tests\\Console\\Descriptor\\CallableClass::staticMethod',
'callable_5' => array('Symfony\\Bundle\\FrameworkBundle\\Tests\\Console\\Descriptor\\ExtendedCallableClass', 'parent::staticMethod'),
'callable_6' => function () { return 'Closure'; },
'callable_7' => new CallableClass(),
);
}
}
class CallableClass
{
public function __invoke()
{
}
public static function staticMethod()
{
}
public function method()
{
}
}
class ExtendedCallableClass extends CallableClass
{
public static function staticMethod()
{
}
}

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\TextDescriptor;
class TextDescriptorTest extends AbstractDescriptorTest
{
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,187 @@
<?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\Tests\TestCase;
use Symfony\Bundle\FrameworkBundle\Controller\ControllerNameParser;
use Symfony\Component\ClassLoader\ClassLoader;
class ControllerNameParserTest extends TestCase
{
protected $loader;
protected function setUp()
{
$this->loader = new ClassLoader();
$this->loader->addPrefixes(array(
'TestBundle' => __DIR__.'/../Fixtures',
'TestApplication' => __DIR__.'/../Fixtures',
));
$this->loader->register();
}
protected function tearDown()
{
spl_autoload_unregister(array($this->loader, 'loadClass'));
$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 string is in the valid format, but not matching class can be found');
} catch (\Exception $e) {
$this->assertInstanceOf('\InvalidArgumentException', $e, '->parse() throws a \InvalidArgumentException if the class is found but does not exist');
}
}
public function getMissingControllersTest()
{
return array(
array('FooBundle:Fake:index'), // a normal bundle
array('SensioFooBundle:Fake:index'), // a bundle with children
);
}
/**
* @expectedException
* @dataProvider getInvalidBundleNameTests
*/
public function testInvalidBundleName($bundleName, $suggestedBundleName)
{
$parser = $this->createParser();
try {
$parser->parse($bundleName);
} 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->assertNotContains('Did you mean', $e->getMessage());
} else {
$this->assertContains(sprintf('Did you mean "%s"', $suggestedBundleName), $e->getMessage());
}
}
}
public function getInvalidBundleNameTests()
{
return array(
'Alternative will be found using levenshtein' => array('FoodBundle:Default:index', 'FooBundle:Default:index'),
'Alternative will be found using partial match' => array('FabpotFooBund:Default:index', 'FabpotFooBundle:Default:index'),
'Bundle does not exist at all' => array('CrazyBundle:Default:index', false),
);
}
private function createParser()
{
$bundles = array(
'SensioFooBundle' => array($this->getBundle('TestBundle\Fabpot\FooBundle', 'FabpotFooBundle'), $this->getBundle('TestBundle\Sensio\FooBundle', 'SensioFooBundle')),
'SensioCmsFooBundle' => array($this->getBundle('TestBundle\Sensio\Cms\FooBundle', 'SensioCmsFooBundle')),
'FooBundle' => array($this->getBundle('TestBundle\FooBundle', 'FooBundle')),
'FabpotFooBundle' => array($this->getBundle('TestBundle\Fabpot\FooBundle', 'FabpotFooBundle'), $this->getBundle('TestBundle\Sensio\FooBundle', 'SensioFooBundle')),
);
$kernel = $this->getMock('Symfony\Component\HttpKernel\KernelInterface');
$kernel
->expects($this->any())
->method('getBundle')
->will($this->returnCallback(function ($bundle) use ($bundles) {
if (!isset($bundles[$bundle])) {
throw new \InvalidArgumentException(sprintf('Invalid bundle name "%s"', $bundle));
}
return $bundles[$bundle];
}))
;
$bundles = array(
'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')
->will($this->returnValue($bundles))
;
return new ControllerNameParser($kernel);
}
private function getBundle($namespace, $name)
{
$bundle = $this->getMock('Symfony\Component\HttpKernel\Bundle\BundleInterface');
$bundle->expects($this->any())->method('getName')->will($this->returnValue($name));
$bundle->expects($this->any())->method('getNamespace')->will($this->returnValue($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\Log\LoggerInterface;
use Symfony\Bundle\FrameworkBundle\Controller\ControllerNameParser;
use Symfony\Bundle\FrameworkBundle\Controller\ControllerResolver;
use Symfony\Component\DependencyInjection\ContainerAwareInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Tests\Controller\ControllerResolverTest as BaseControllerResolverTest;
class ControllerResolverTest extends BaseControllerResolverTest
{
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)
->will($this->returnValue('Symfony\Bundle\FrameworkBundle\Tests\Controller\ContainerAwareController::testAction'))
;
$resolver = $this->createControllerResolver(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 testGetControllerService()
{
$container = $this->createMockContainer();
$container->expects($this->once())
->method('get')
->with('foo')
->will($this->returnValue($this))
;
$resolver = $this->createControllerResolver(null, null, $container);
$request = Request::create('/');
$request->attributes->set('_controller', 'foo:controllerMethod1');
$controller = $resolver->getController($request);
$this->assertInstanceOf(get_class($this), $controller[0]);
$this->assertSame('controllerMethod1', $controller[1]);
}
public function testGetControllerInvokableService()
{
$invokableController = new InvokableController('bar');
$container = $this->createMockContainer();
$container->expects($this->once())
->method('has')
->with('foo')
->will($this->returnValue(true))
;
$container->expects($this->once())
->method('get')
->with('foo')
->will($this->returnValue($invokableController))
;
$resolver = $this->createControllerResolver(null, null, $container);
$request = Request::create('/');
$request->attributes->set('_controller', 'foo');
$controller = $resolver->getController($request);
$this->assertEquals($invokableController, $controller);
}
public function testGetControllerInvokableServiceWithClassNameAsName()
{
$invokableController = new InvokableController('bar');
$className = __NAMESPACE__.'\InvokableController';
$container = $this->createMockContainer();
$container->expects($this->once())
->method('has')
->with($className)
->will($this->returnValue(true))
;
$container->expects($this->once())
->method('get')
->with($className)
->will($this->returnValue($invokableController))
;
$resolver = $this->createControllerResolver(null, null, $container);
$request = Request::create('/');
$request->attributes->set('_controller', $className);
$controller = $resolver->getController($request);
$this->assertEquals($invokableController, $controller);
}
/**
* @dataProvider getUndefinedControllers
*/
public function testGetControllerOnNonUndefinedFunction($controller, $exceptionName = null, $exceptionMessage = null)
{
// All this logic needs to be duplicated, since calling parent::testGetControllerOnNonUndefinedFunction will override the expected excetion and not use the regex
$resolver = $this->createControllerResolver();
$this->setExpectedExceptionRegExp($exceptionName, $exceptionMessage);
$request = Request::create('/');
$request->attributes->set('_controller', $controller);
$resolver->getController($request);
}
public function getUndefinedControllers()
{
return array(
array('foo', '\LogicException', '/Unable to parse the controller name "foo"\./'),
array('oof::bar', '\InvalidArgumentException', '/Class "oof" does not exist\./'),
array('stdClass', '\LogicException', '/Unable to parse the controller name "stdClass"\./'),
array(
'Symfony\Component\HttpKernel\Tests\Controller\ControllerResolverTest::bar',
'\InvalidArgumentException',
'/.?[cC]ontroller(.*?) for URI "\/" is not callable\.( Expected method(.*) Available methods)?/',
),
);
}
protected function createControllerResolver(LoggerInterface $logger = null, ControllerNameParser $parser = null, ContainerInterface $container = null)
{
if (!$parser) {
$parser = $this->createMockParser();
}
if (!$container) {
$container = $this->createMockContainer();
}
return new ControllerResolver($container, $parser, $logger);
}
protected function createMockParser()
{
return $this->getMock('Symfony\Bundle\FrameworkBundle\Controller\ControllerNameParser', array(), array(), '', false);
}
protected function createMockContainer()
{
return $this->getMock('Symfony\Component\DependencyInjection\ContainerInterface');
}
}
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 InvokableController
{
public function __construct($bar) // mandatory argument to prevent automatic instantiation
{
}
public function __invoke()
{
}
}

View File

@@ -0,0 +1,475 @@
<?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\Tests\TestCase;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Session\Flash\FlashBag;
use Symfony\Component\HttpFoundation\StreamedResponse;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
use Symfony\Component\Security\Core\Authentication\Token\AnonymousToken;
use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken;
use Symfony\Component\Security\Core\User\User;
class ControllerTest extends TestCase
{
public function testForward()
{
$request = Request::create('/');
$request->setLocale('fr');
$request->setRequestFormat('xml');
$requestStack = new RequestStack();
$requestStack->push($request);
$kernel = $this->getMock('Symfony\Component\HttpKernel\HttpKernelInterface');
$kernel->expects($this->once())->method('handle')->will($this->returnCallback(function (Request $request) {
return new Response($request->getRequestFormat().'--'.$request->getLocale());
}));
$container = $this->getMock('Symfony\Component\DependencyInjection\ContainerInterface');
$container->expects($this->at(0))->method('get')->will($this->returnValue($requestStack));
$container->expects($this->at(1))->method('get')->will($this->returnValue($kernel));
$controller = new TestController();
$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', array('ROLE_USER'));
$controller = new TestController();
$controller->setContainer($this->getContainerWithTokenStorage($token));
$this->assertSame($controller->getUser(), $user);
}
public function testGetUserAnonymousUserConvertedToNull()
{
$token = new AnonymousToken('default', 'anon.');
$controller = new TestController();
$controller->setContainer($this->getContainerWithTokenStorage($token));
$this->assertNull($controller->getUser());
}
public function testGetUserWithEmptyTokenStorage()
{
$controller = new TestController();
$controller->setContainer($this->getContainerWithTokenStorage(null));
$this->assertNull($controller->getUser());
}
/**
* @expectedException \LogicException
* @expectedExceptionMessage The SecurityBundle is not registered in your application.
*/
public function testGetUserWithEmptyContainer()
{
$container = $this->getMock('Symfony\Component\DependencyInjection\ContainerInterface');
$container
->expects($this->once())
->method('has')
->with('security.token_storage')
->will($this->returnValue(false));
$controller = new TestController();
$controller->setContainer($container);
$controller->getUser();
}
/**
* @param $token
*
* @return ContainerInterface
*/
private function getContainerWithTokenStorage($token = null)
{
$tokenStorage = $this->getMock('Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorage');
$tokenStorage
->expects($this->once())
->method('getToken')
->will($this->returnValue($token));
$container = $this->getMock('Symfony\Component\DependencyInjection\ContainerInterface');
$container
->expects($this->once())
->method('has')
->with('security.token_storage')
->will($this->returnValue(true));
$container
->expects($this->once())
->method('get')
->with('security.token_storage')
->will($this->returnValue($tokenStorage));
return $container;
}
public function testIsGranted()
{
$authorizationChecker = $this->getMock('Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface');
$authorizationChecker->expects($this->once())->method('isGranted')->willReturn(true);
$container = $this->getMock('Symfony\Component\DependencyInjection\ContainerInterface');
$container->expects($this->at(0))->method('has')->will($this->returnValue(true));
$container->expects($this->at(1))->method('get')->will($this->returnValue($authorizationChecker));
$controller = new TestController();
$controller->setContainer($container);
$this->assertTrue($controller->isGranted('foo'));
}
/**
* @expectedException \Symfony\Component\Security\Core\Exception\AccessDeniedException
*/
public function testdenyAccessUnlessGranted()
{
$authorizationChecker = $this->getMock('Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface');
$authorizationChecker->expects($this->once())->method('isGranted')->willReturn(false);
$container = $this->getMock('Symfony\Component\DependencyInjection\ContainerInterface');
$container->expects($this->at(0))->method('has')->will($this->returnValue(true));
$container->expects($this->at(1))->method('get')->will($this->returnValue($authorizationChecker));
$controller = new TestController();
$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 = $this->getMock('Symfony\Component\DependencyInjection\ContainerInterface');
$container->expects($this->at(0))->method('has')->will($this->returnValue(false));
$container->expects($this->at(1))->method('has')->will($this->returnValue(true));
$container->expects($this->at(2))->method('get')->will($this->returnValue($twig));
$controller = new TestController();
$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 = $this->getMock('Symfony\Component\DependencyInjection\ContainerInterface');
$container->expects($this->at(0))->method('has')->will($this->returnValue(false));
$container->expects($this->at(1))->method('has')->will($this->returnValue(true));
$container->expects($this->at(2))->method('get')->will($this->returnValue($twig));
$controller = new TestController();
$controller->setContainer($container);
$this->assertEquals('bar', $controller->render('foo')->getContent());
}
public function testStreamTwig()
{
$twig = $this->getMockBuilder('\Twig_Environment')->disableOriginalConstructor()->getMock();
$container = $this->getMock('Symfony\Component\DependencyInjection\ContainerInterface');
$container->expects($this->at(0))->method('has')->will($this->returnValue(false));
$container->expects($this->at(1))->method('has')->will($this->returnValue(true));
$container->expects($this->at(2))->method('get')->will($this->returnValue($twig));
$controller = new TestController();
$controller->setContainer($container);
$this->assertInstanceOf('Symfony\Component\HttpFoundation\StreamedResponse', $controller->stream('foo'));
}
public function testRedirectToRoute()
{
$router = $this->getMock('Symfony\Component\Routing\RouterInterface');
$router->expects($this->once())->method('generate')->willReturn('/foo');
$container = $this->getMock('Symfony\Component\DependencyInjection\ContainerInterface');
$container->expects($this->at(0))->method('get')->will($this->returnValue($router));
$controller = new TestController();
$controller->setContainer($container);
$response = $controller->redirectToRoute('foo');
$this->assertInstanceOf('Symfony\Component\HttpFoundation\RedirectResponse', $response);
$this->assertSame('/foo', $response->getTargetUrl());
$this->assertSame(302, $response->getStatusCode());
}
public function testAddFlash()
{
$flashBag = new FlashBag();
$session = $this->getMock('Symfony\Component\HttpFoundation\Session\Session');
$session->expects($this->once())->method('getFlashBag')->willReturn($flashBag);
$container = $this->getMock('Symfony\Component\DependencyInjection\ContainerInterface');
$container->expects($this->at(0))->method('has')->will($this->returnValue(true));
$container->expects($this->at(1))->method('get')->will($this->returnValue($session));
$controller = new TestController();
$controller->setContainer($container);
$controller->addFlash('foo', 'bar');
$this->assertSame(array('bar'), $flashBag->get('foo'));
}
public function testCreateAccessDeniedException()
{
$controller = new TestController();
$this->assertInstanceOf('Symfony\Component\Security\Core\Exception\AccessDeniedException', $controller->createAccessDeniedException());
}
public function testIsCsrfTokenValid()
{
$tokenManager = $this->getMock('Symfony\Component\Security\Csrf\CsrfTokenManagerInterface');
$tokenManager->expects($this->once())->method('isTokenValid')->willReturn(true);
$container = $this->getMock('Symfony\Component\DependencyInjection\ContainerInterface');
$container->expects($this->at(0))->method('has')->will($this->returnValue(true));
$container->expects($this->at(1))->method('get')->will($this->returnValue($tokenManager));
$controller = new TestController();
$controller->setContainer($container);
$this->assertTrue($controller->isCsrfTokenValid('foo', 'bar'));
}
public function testGenerateUrl()
{
$router = $this->getMock('Symfony\Component\Routing\RouterInterface');
$router->expects($this->once())->method('generate')->willReturn('/foo');
$container = $this->getMock('Symfony\Component\DependencyInjection\ContainerInterface');
$container->expects($this->at(0))->method('get')->will($this->returnValue($router));
$controller = new TestController();
$controller->setContainer($container);
$this->assertEquals('/foo', $controller->generateUrl('foo'));
}
public function testRedirect()
{
$controller = new TestController();
$response = $controller->redirect('http://dunglas.fr', 301);
$this->assertInstanceOf('Symfony\Component\HttpFoundation\RedirectResponse', $response);
$this->assertSame('http://dunglas.fr', $response->getTargetUrl());
$this->assertSame(301, $response->getStatusCode());
}
public function testRenderViewTemplating()
{
$templating = $this->getMock('Symfony\Bundle\FrameworkBundle\Templating\EngineInterface');
$templating->expects($this->once())->method('render')->willReturn('bar');
$container = $this->getMock('Symfony\Component\DependencyInjection\ContainerInterface');
$container->expects($this->at(0))->method('has')->willReturn(true);
$container->expects($this->at(1))->method('get')->will($this->returnValue($templating));
$controller = new TestController();
$controller->setContainer($container);
$this->assertEquals('bar', $controller->renderView('foo'));
}
public function testRenderTemplating()
{
$templating = $this->getMock('Symfony\Bundle\FrameworkBundle\Templating\EngineInterface');
$templating->expects($this->once())->method('renderResponse')->willReturn(new Response('bar'));
$container = $this->getMock('Symfony\Component\DependencyInjection\ContainerInterface');
$container->expects($this->at(0))->method('has')->willReturn(true);
$container->expects($this->at(1))->method('get')->will($this->returnValue($templating));
$controller = new TestController();
$controller->setContainer($container);
$this->assertEquals('bar', $controller->render('foo')->getContent());
}
public function testStreamTemplating()
{
$templating = $this->getMock('Symfony\Component\Routing\RouterInterface');
$container = $this->getMock('Symfony\Component\DependencyInjection\ContainerInterface');
$container->expects($this->at(0))->method('has')->willReturn(true);
$container->expects($this->at(1))->method('get')->will($this->returnValue($templating));
$controller = new TestController();
$controller->setContainer($container);
$this->assertInstanceOf('Symfony\Component\HttpFoundation\StreamedResponse', $controller->stream('foo'));
}
public function testCreateNotFoundException()
{
$controller = new TestController();
$this->assertInstanceOf('Symfony\Component\HttpKernel\Exception\NotFoundHttpException', $controller->createNotFoundException());
}
public function testCreateForm()
{
$form = $this->getMock('Symfony\Component\Form\FormInterface');
$formFactory = $this->getMock('Symfony\Component\Form\FormFactoryInterface');
$formFactory->expects($this->once())->method('create')->willReturn($form);
$container = $this->getMock('Symfony\Component\DependencyInjection\ContainerInterface');
$container->expects($this->at(0))->method('get')->will($this->returnValue($formFactory));
$controller = new TestController();
$controller->setContainer($container);
$this->assertEquals($form, $controller->createForm('foo'));
}
public function testCreateFormBuilder()
{
$formBuilder = $this->getMock('Symfony\Component\Form\FormBuilderInterface');
$formFactory = $this->getMock('Symfony\Component\Form\FormFactoryInterface');
$formFactory->expects($this->once())->method('createBuilder')->willReturn($formBuilder);
$container = $this->getMock('Symfony\Component\DependencyInjection\ContainerInterface');
$container->expects($this->at(0))->method('get')->will($this->returnValue($formFactory));
$controller = new TestController();
$controller->setContainer($container);
$this->assertEquals($formBuilder, $controller->createFormBuilder('foo'));
}
public function testGetDoctrine()
{
$doctrine = $this->getMock('Doctrine\Common\Persistence\ManagerRegistry');
$container = $this->getMock('Symfony\Component\DependencyInjection\ContainerInterface');
$container->expects($this->at(0))->method('has')->will($this->returnValue(true));
$container->expects($this->at(1))->method('get')->will($this->returnValue($doctrine));
$controller = new TestController();
$controller->setContainer($container);
$this->assertEquals($doctrine, $controller->getDoctrine());
}
}
class TestController extends Controller
{
public function generateUrl($route, $parameters = array(), $referenceType = UrlGeneratorInterface::ABSOLUTE_PATH)
{
return parent::generateUrl($route, $parameters, $referenceType);
}
public function redirect($url, $status = 302)
{
return parent::redirect($url, $status);
}
public function forward($controller, array $path = array(), array $query = array())
{
return parent::forward($controller, $path, $query);
}
public function getUser()
{
return parent::getUser();
}
public function isGranted($attributes, $object = null)
{
return parent::isGranted($attributes, $object);
}
public function denyAccessUnlessGranted($attributes, $object = null, $message = 'Access Denied.')
{
parent::denyAccessUnlessGranted($attributes, $object, $message);
}
public function redirectToRoute($route, array $parameters = array(), $status = 302)
{
return parent::redirectToRoute($route, $parameters, $status);
}
public function addFlash($type, $message)
{
parent::addFlash($type, $message);
}
public function isCsrfTokenValid($id, $token)
{
return parent::isCsrfTokenValid($id, $token);
}
public function renderView($view, array $parameters = array())
{
return parent::renderView($view, $parameters);
}
public function render($view, array $parameters = array(), Response $response = null)
{
return parent::render($view, $parameters, $response);
}
public function stream($view, array $parameters = array(), StreamedResponse $response = null)
{
return parent::stream($view, $parameters, $response);
}
public function createNotFoundException($message = 'Not Found', \Exception $previous = null)
{
return parent::createNotFoundException($message, $previous);
}
public function createAccessDeniedException($message = 'Access Denied.', \Exception $previous = null)
{
return parent::createAccessDeniedException($message, $previous);
}
public function createForm($type, $data = null, array $options = array())
{
return parent::createForm($type, $data, $options);
}
public function createFormBuilder($data = null, array $options = array())
{
return parent::createFormBuilder($data, $options);
}
public function getDoctrine()
{
return parent::getDoctrine();
}
}

View File

@@ -0,0 +1,297 @@
<?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\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\ParameterBag;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Exception\HttpException;
use Symfony\Bundle\FrameworkBundle\Controller\RedirectController;
use Symfony\Bundle\FrameworkBundle\Tests\TestCase;
/**
* @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 = array(
'route' => $route,
'permanent' => $permanent,
'_route' => 'current-route',
'_route_params' => array(
'route' => $route,
'permanent' => $permanent,
'additional-parameter' => 'value',
'ignoreAttributes' => $ignoreAttributes,
),
);
$request->attributes = new ParameterBag($attributes);
$router = $this->getMock('Symfony\Component\Routing\RouterInterface');
$router
->expects($this->once())
->method('generate')
->with($this->equalTo($route), $this->equalTo($expectedAttributes))
->will($this->returnValue($url));
$container = $this->getMock('Symfony\Component\DependencyInjection\ContainerInterface');
$container
->expects($this->once())
->method('get')
->with($this->equalTo('router'))
->will($this->returnValue($router));
$controller = new RedirectController();
$controller->setContainer($container);
$returnResponse = $controller->redirectAction($request, $route, $permanent, $ignoreAttributes);
$this->assertRedirectUrl($returnResponse, $url);
$this->assertEquals($expectedCode, $returnResponse->getStatusCode());
}
public function provider()
{
return array(
array(true, false, 301, array('additional-parameter' => 'value')),
array(false, false, 302, array('additional-parameter' => 'value')),
array(false, true, 302, array()),
array(false, array('additional-parameter'), 302, array()),
);
}
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 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->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);
}
public function urlRedirectProvider()
{
return array(
// Standard ports
array('http', null, null, 'http', 80, ''),
array('http', 80, null, 'http', 80, ''),
array('https', null, null, 'http', 80, ''),
array('https', 80, null, 'http', 80, ''),
array('http', null, null, 'https', 443, ''),
array('http', null, 443, 'https', 443, ''),
array('https', null, null, 'https', 443, ''),
array('https', null, 443, 'https', 443, ''),
// Non-standard ports
array('http', null, null, 'http', 8080, ':8080'),
array('http', 4080, null, 'http', 8080, ':4080'),
array('http', 80, null, 'http', 8080, ''),
array('https', null, null, 'http', 8080, ''),
array('https', null, 8443, 'http', 8080, ':8443'),
array('https', null, 443, 'http', 8080, ''),
array('https', null, null, 'https', 8443, ':8443'),
array('https', null, 4443, 'https', 8443, ':4443'),
array('https', null, 443, 'https', 8443, ''),
array('http', null, null, 'https', 8443, ''),
array('http', 8080, 4443, 'https', 8443, ':8080'),
array('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 array(
array('http://www.example.com/base/redirect-path', '/redirect-path', ''),
array('http://www.example.com/base/redirect-path?foo=bar', '/redirect-path?foo=bar', ''),
array('http://www.example.com/base/redirect-path?foo=bar', '/redirect-path', 'foo=bar'),
array('http://www.example.com/base/redirect-path?foo=bar&abc=example', '/redirect-path?foo=bar', 'abc=example'),
array('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->getMock('Symfony\Component\HttpFoundation\Request');
$request
->expects($this->any())
->method('getScheme')
->will($this->returnValue($scheme));
$request
->expects($this->any())
->method('getHost')
->will($this->returnValue($host));
$request
->expects($this->any())
->method('getPort')
->will($this->returnValue($port));
$request
->expects($this->any())
->method('getBaseUrl')
->will($this->returnValue($baseUrl));
$request
->expects($this->any())
->method('getQueryString')
->will($this->returnValue($queryString));
return $request;
}
private function createRedirectController($httpPort = null, $httpsPort = null)
{
$container = $this->getMock('Symfony\Component\DependencyInjection\ContainerInterface');
if (null !== $httpPort) {
$container
->expects($this->once())
->method('hasParameter')
->with($this->equalTo('request_listener.http_port'))
->will($this->returnValue(true));
$container
->expects($this->once())
->method('getParameter')
->with($this->equalTo('request_listener.http_port'))
->will($this->returnValue($httpPort));
}
if (null !== $httpsPort) {
$container
->expects($this->once())
->method('hasParameter')
->with($this->equalTo('request_listener.https_port'))
->will($this->returnValue(true));
$container
->expects($this->once())
->method('getParameter')
->with($this->equalTo('request_listener.https_port'))
->will($this->returnValue($httpsPort));
}
$controller = new RedirectController();
$controller->setContainer($container);
return $controller;
}
public function assertRedirectUrl(Response $returnResponse, $expectedUrl)
{
$this->assertTrue($returnResponse->isRedirect($expectedUrl), "Expected: $expectedUrl\nGot: ".$returnResponse->headers->get('Location'));
}
}

View File

@@ -0,0 +1,99 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Bundle\FrameworkBundle\Tests\DependencyInjection\Compiler;
use Symfony\Component\DependencyInjection\Reference;
use Symfony\Bundle\FrameworkBundle\DependencyInjection\Compiler\AddCacheWarmerPass;
class AddCacheWarmerPassTest extends \PHPUnit_Framework_TestCase
{
public function testThatCacheWarmersAreProcessedInPriorityOrder()
{
$services = array(
'my_cache_warmer_service1' => array(0 => array('priority' => 100)),
'my_cache_warmer_service2' => array(0 => array('priority' => 200)),
'my_cache_warmer_service3' => array(),
);
$definition = $this->getMock('Symfony\Component\DependencyInjection\Definition');
$container = $this->getMock(
'Symfony\Component\DependencyInjection\ContainerBuilder',
array('findTaggedServiceIds', 'getDefinition', 'hasDefinition')
);
$container->expects($this->atLeastOnce())
->method('findTaggedServiceIds')
->will($this->returnValue($services));
$container->expects($this->atLeastOnce())
->method('getDefinition')
->with('cache_warmer')
->will($this->returnValue($definition));
$container->expects($this->atLeastOnce())
->method('hasDefinition')
->with('cache_warmer')
->will($this->returnValue(true));
$definition->expects($this->once())
->method('replaceArgument')
->with(0, array(
new Reference('my_cache_warmer_service2'),
new Reference('my_cache_warmer_service1'),
new Reference('my_cache_warmer_service3'),
));
$addCacheWarmerPass = new AddCacheWarmerPass();
$addCacheWarmerPass->process($container);
}
public function testThatCompilerPassIsIgnoredIfThereIsNoCacheWarmerDefinition()
{
$definition = $this->getMock('Symfony\Component\DependencyInjection\Definition');
$container = $this->getMock(
'Symfony\Component\DependencyInjection\ContainerBuilder',
array('hasDefinition', 'findTaggedServiceIds', 'getDefinition')
);
$container->expects($this->never())->method('findTaggedServiceIds');
$container->expects($this->never())->method('getDefinition');
$container->expects($this->atLeastOnce())
->method('hasDefinition')
->with('cache_warmer')
->will($this->returnValue(false));
$definition->expects($this->never())->method('replaceArgument');
$addCacheWarmerPass = new AddCacheWarmerPass();
$addCacheWarmerPass->process($container);
}
public function testThatCacheWarmersMightBeNotDefined()
{
$definition = $this->getMock('Symfony\Component\DependencyInjection\Definition');
$container = $this->getMock(
'Symfony\Component\DependencyInjection\ContainerBuilder',
array('hasDefinition', 'findTaggedServiceIds', 'getDefinition')
);
$container->expects($this->atLeastOnce())
->method('findTaggedServiceIds')
->will($this->returnValue(array()));
$container->expects($this->never())->method('getDefinition');
$container->expects($this->atLeastOnce())
->method('hasDefinition')
->with('cache_warmer')
->will($this->returnValue(true));
$definition->expects($this->never())->method('replaceArgument');
$addCacheWarmerPass = new AddCacheWarmerPass();
$addCacheWarmerPass->process($container);
}
}

View File

@@ -0,0 +1,119 @@
<?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 Symfony\Bundle\FrameworkBundle\DependencyInjection\Compiler\AddConsoleCommandPass;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Definition;
use Symfony\Component\HttpKernel\Bundle\Bundle;
class AddConsoleCommandPassTest extends \PHPUnit_Framework_TestCase
{
public function testProcess()
{
$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->addTag('console.command');
$container->setDefinition('my-command', $definition);
$container->compile();
$alias = 'console.command.symfony_bundle_frameworkbundle_tests_dependencyinjection_compiler_mycommand';
$this->assertTrue($container->hasAlias($alias));
$this->assertSame('my-command', (string) $container->getAlias($alias));
$this->assertTrue($container->hasParameter('console.command.ids'));
$this->assertSame(array('my-command'), $container->getParameter('console.command.ids'));
}
/**
* @expectedException \InvalidArgumentException
* @expectedExceptionMessage The service "my-command" tagged "console.command" must be public.
*/
public function testProcessThrowAnExceptionIfTheServiceIsNotPublic()
{
$container = new ContainerBuilder();
$container->addCompilerPass(new AddConsoleCommandPass());
$definition = new Definition('Symfony\Bundle\FrameworkBundle\Tests\DependencyInjection\Compiler\MyCommand');
$definition->addTag('console.command');
$definition->setPublic(false);
$container->setDefinition('my-command', $definition);
$container->compile();
}
/**
* @expectedException \InvalidArgumentException
* @expectedExceptionMessage The service "my-command" tagged "console.command" must not be abstract.
*/
public function testProcessThrowAnExceptionIfTheServiceIsAbstract()
{
$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();
}
/**
* @expectedException \InvalidArgumentException
* @expectedExceptionMessage The service "my-command" tagged "console.command" must be a subclass of "Symfony\Component\Console\Command\Command".
*/
public function testProcessThrowAnExceptionIfTheServiceIsNotASubclassOfCommand()
{
$container = new ContainerBuilder();
$container->addCompilerPass(new AddConsoleCommandPass());
$definition = new Definition('SplObjectStorage');
$definition->addTag('console.command');
$container->setDefinition('my-command', $definition);
$container->compile();
}
public function testHttpKernelRegisterCommandsIngoreCommandAsAService()
{
$container = new ContainerBuilder();
$container->addCompilerPass(new AddConsoleCommandPass());
$definition = new Definition('Symfony\Bundle\FrameworkBundle\Tests\DependencyInjection\Compiler\MyCommand');
$definition->addTag('console.command');
$container->setDefinition('my-command', $definition);
$container->compile();
$application = $this->getMock('Symfony\Component\Console\Application');
// Never called, because it's the
// Symfony\Bundle\FrameworkBundle\Console\Application that register
// commands as a service
$application->expects($this->never())->method('add');
$bundle = new ExtensionPresentBundle();
$bundle->setContainer($container);
$bundle->registerCommands($application);
}
}
class MyCommand extends Command
{
}
class ExtensionPresentBundle extends Bundle
{
}

View File

@@ -0,0 +1,87 @@
<?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.
*/
use Symfony\Bundle\FrameworkBundle\DependencyInjection\Compiler\AddConstraintValidatorsPass;
class AddConstraintValidatorsPassTest extends \PHPUnit_Framework_TestCase
{
public function testThatConstraintValidatorServicesAreProcessed()
{
$services = array(
'my_constraint_validator_service1' => array(0 => array('alias' => 'my_constraint_validator_alias1')),
'my_constraint_validator_service2' => array(),
);
$validatorFactoryDefinition = $this->getMock('Symfony\Component\DependencyInjection\Definition');
$container = $this->getMock(
'Symfony\Component\DependencyInjection\ContainerBuilder',
array('findTaggedServiceIds', 'getDefinition', 'hasDefinition')
);
$validatorDefinition1 = $this->getMock('Symfony\Component\DependencyInjection\Definition', array('getClass'));
$validatorDefinition2 = $this->getMock('Symfony\Component\DependencyInjection\Definition', array('getClass'));
$validatorDefinition1->expects($this->atLeastOnce())
->method('getClass')
->willReturn('My\Fully\Qualified\Class\Named\Validator1');
$validatorDefinition2->expects($this->atLeastOnce())
->method('getClass')
->willReturn('My\Fully\Qualified\Class\Named\Validator2');
$container->expects($this->any())
->method('getDefinition')
->with($this->anything())
->will($this->returnValueMap(array(
array('my_constraint_validator_service1', $validatorDefinition1),
array('my_constraint_validator_service2', $validatorDefinition2),
array('validator.validator_factory', $validatorFactoryDefinition),
)));
$container->expects($this->atLeastOnce())
->method('findTaggedServiceIds')
->will($this->returnValue($services));
$container->expects($this->atLeastOnce())
->method('hasDefinition')
->with('validator.validator_factory')
->will($this->returnValue(true));
$validatorFactoryDefinition->expects($this->once())
->method('replaceArgument')
->with(1, array(
'My\Fully\Qualified\Class\Named\Validator1' => 'my_constraint_validator_service1',
'my_constraint_validator_alias1' => 'my_constraint_validator_service1',
'My\Fully\Qualified\Class\Named\Validator2' => 'my_constraint_validator_service2',
));
$addConstraintValidatorsPass = new AddConstraintValidatorsPass();
$addConstraintValidatorsPass->process($container);
}
public function testThatCompilerPassIsIgnoredIfThereIsNoConstraintValidatorFactoryDefinition()
{
$definition = $this->getMock('Symfony\Component\DependencyInjection\Definition');
$container = $this->getMock(
'Symfony\Component\DependencyInjection\ContainerBuilder',
array('hasDefinition', 'findTaggedServiceIds', 'getDefinition')
);
$container->expects($this->never())->method('findTaggedServiceIds');
$container->expects($this->never())->method('getDefinition');
$container->expects($this->atLeastOnce())
->method('hasDefinition')
->with('validator.validator_factory')
->will($this->returnValue(false));
$definition->expects($this->never())->method('replaceArgument');
$addConstraintValidatorsPass = new AddConstraintValidatorsPass();
$addConstraintValidatorsPass->process($container);
}
}

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 Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Definition;
use Symfony\Component\DependencyInjection\Reference;
use Symfony\Bundle\FrameworkBundle\DependencyInjection\Compiler\AddExpressionLanguageProvidersPass;
class AddExpressionLanguageProvidersPassTest extends \PHPUnit_Framework_TestCase
{
public function testProcessForRouter()
{
$container = new ContainerBuilder();
$container->addCompilerPass(new AddExpressionLanguageProvidersPass());
$definition = new Definition('Symfony\Bundle\FrameworkBundle\Tests\DependencyInjection\Compiler\TestProvider');
$definition->addTag('routing.expression_language_provider');
$container->setDefinition('some_routing_provider', $definition);
$container->register('router', '\stdClass');
$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('Symfony\Bundle\FrameworkBundle\Tests\DependencyInjection\Compiler\TestProvider');
$definition->addTag('routing.expression_language_provider');
$container->setDefinition('some_routing_provider', $definition);
$container->register('my_router', '\stdClass');
$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('Symfony\Bundle\FrameworkBundle\Tests\DependencyInjection\Compiler\TestProvider');
$definition->addTag('security.expression_language_provider');
$container->setDefinition('some_security_provider', $definition);
$container->register('security.access.expression_voter', '\stdClass');
$container->compile();
$router = $container->getDefinition('security.access.expression_voter');
$calls = $router->getMethodCalls();
$this->assertCount(1, $calls);
$this->assertEquals('addExpressionLanguageProvider', $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('Symfony\Bundle\FrameworkBundle\Tests\DependencyInjection\Compiler\TestProvider');
$definition->addTag('security.expression_language_provider');
$container->setDefinition('some_security_provider', $definition);
$container->register('my_security.access.expression_voter', '\stdClass');
$container->setAlias('security.access.expression_voter', 'my_security.access.expression_voter');
$container->compile();
$router = $container->getDefinition('my_security.access.expression_voter');
$calls = $router->getMethodCalls();
$this->assertCount(1, $calls);
$this->assertEquals('addExpressionLanguageProvider', $calls[0][0]);
$this->assertEquals(new Reference('some_security_provider'), $calls[0][1][0]);
}
}
class TestProvider
{
}

View File

@@ -0,0 +1,68 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Bundle\FrameworkBundle\Tests\DependencyInjection\Compiler;
use Symfony\Component\DependencyInjection\Reference;
use Symfony\Bundle\FrameworkBundle\DependencyInjection\Compiler\ConfigCachePass;
class ConfigCachePassTest extends \PHPUnit_Framework_TestCase
{
public function testThatCheckersAreProcessedInPriorityOrder()
{
$services = array(
'checker_2' => array(0 => array('priority' => 100)),
'checker_1' => array(0 => array('priority' => 200)),
'checker_3' => array(),
);
$definition = $this->getMock('Symfony\Component\DependencyInjection\Definition');
$container = $this->getMock(
'Symfony\Component\DependencyInjection\ContainerBuilder',
array('findTaggedServiceIds', 'getDefinition', 'hasDefinition')
);
$container->expects($this->atLeastOnce())
->method('findTaggedServiceIds')
->will($this->returnValue($services));
$container->expects($this->atLeastOnce())
->method('getDefinition')
->with('config_cache_factory')
->will($this->returnValue($definition));
$definition->expects($this->once())
->method('replaceArgument')
->with(0, array(
new Reference('checker_1'),
new Reference('checker_2'),
new Reference('checker_3'),
));
$pass = new ConfigCachePass();
$pass->process($container);
}
public function testThatCheckersCanBeMissing()
{
$definition = $this->getMock('Symfony\Component\DependencyInjection\Definition');
$container = $this->getMock(
'Symfony\Component\DependencyInjection\ContainerBuilder',
array('findTaggedServiceIds')
);
$container->expects($this->atLeastOnce())
->method('findTaggedServiceIds')
->will($this->returnValue(array()));
$pass = new ConfigCachePass();
$pass->process($container);
}
}

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\DependencyInjection\Compiler;
use Symfony\Bundle\FrameworkBundle\DependencyInjection\Compiler\FormPass;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Definition;
use Symfony\Component\DependencyInjection\Reference;
use Symfony\Component\Form\AbstractType;
/**
* @author Bernhard Schussek <bschussek@gmail.com>
*/
class FormPassTest extends \PHPUnit_Framework_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->setArguments(array(
new Reference('service_container'),
array(),
array(),
array(),
));
$container->setDefinition('form.extension', $extDefinition);
$container->register('my.type1', __CLASS__.'_Type1')->addTag('form.type');
$container->register('my.type2', __CLASS__.'_Type2')->addTag('form.type');
$container->compile();
$extDefinition = $container->getDefinition('form.extension');
$this->assertEquals(array(
__CLASS__.'_Type1' => 'my.type1',
__CLASS__.'_Type2' => 'my.type2',
), $extDefinition->getArgument(1));
}
public function testAddTaggedTypeExtensions()
{
$container = new ContainerBuilder();
$container->addCompilerPass(new FormPass());
$extDefinition = new Definition('Symfony\Component\Form\Extension\DependencyInjection\DependencyInjectionExtension', array(
new Reference('service_container'),
array(),
array(),
array(),
));
$container->setDefinition('form.extension', $extDefinition);
$container->register('my.type_extension1', 'stdClass')
->addTag('form.type_extension', array('extended_type' => 'type1'));
$container->register('my.type_extension2', 'stdClass')
->addTag('form.type_extension', array('extended_type' => 'type1'));
$container->register('my.type_extension3', 'stdClass')
->addTag('form.type_extension', array('extended_type' => 'type2'));
$container->compile();
$extDefinition = $container->getDefinition('form.extension');
$this->assertSame(array(
'type1' => array(
'my.type_extension1',
'my.type_extension2',
),
'type2' => array(
'my.type_extension3',
),
), $extDefinition->getArgument(2));
}
/**
* @expectedException \InvalidArgumentException
* @expectedExceptionMessage extended-type attribute, none was configured for the "my.type_extension" service
*/
public function testAddTaggedFormTypeExtensionWithoutExtendedTypeAttribute()
{
$container = new ContainerBuilder();
$container->addCompilerPass(new FormPass());
$extDefinition = new Definition('Symfony\Component\Form\Extension\DependencyInjection\DependencyInjectionExtension', array(
new Reference('service_container'),
array(),
array(),
array(),
));
$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->setArguments(array(
new Reference('service_container'),
array(),
array(),
array(),
));
$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(array(
'my.guesser1',
'my.guesser2',
), $extDefinition->getArgument(3));
}
/**
* @dataProvider privateTaggedServicesProvider
*/
public function testPrivateTaggedServices($id, $tagName, $expectedExceptionMessage)
{
$container = new ContainerBuilder();
$container->addCompilerPass(new FormPass());
$extDefinition = new Definition('Symfony\Component\Form\Extension\DependencyInjection\DependencyInjectionExtension');
$extDefinition->setArguments(array(
new Reference('service_container'),
array(),
array(),
array(),
));
$container->setDefinition('form.extension', $extDefinition);
$container->register($id, 'stdClass')->setPublic(false)->addTag($tagName);
$this->setExpectedException('\InvalidArgumentException', $expectedExceptionMessage);
$container->compile();
}
public function privateTaggedServicesProvider()
{
return array(
array('my.type', 'form.type', 'The service "my.type" must be public as form types are lazy-loaded'),
array('my.type_extension', 'form.type_extension', 'The service "my.type_extension" must be public as form type extensions are lazy-loaded'),
array('my.guesser', 'form.type_guesser', 'The service "my.guesser" must be public as form type guessers are lazy-loaded'),
);
}
}
class FormPassTest_Type1 extends AbstractType
{
}
class FormPassTest_Type2 extends AbstractType
{
}

View File

@@ -0,0 +1,86 @@
<?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 Symfony\Bundle\FrameworkBundle\DependencyInjection\Compiler\LoggingTranslatorPass;
class LoggingTranslatorPassTest extends \PHPUnit_Framework_TestCase
{
public function testProcess()
{
$definition = $this->getMock('Symfony\Component\DependencyInjection\Definition');
$container = $this->getMock('Symfony\Component\DependencyInjection\ContainerBuilder');
$parameterBag = $this->getMock('Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface');
$container->expects($this->exactly(2))
->method('hasAlias')
->will($this->returnValue(true));
$container->expects($this->once())
->method('getParameter')
->will($this->returnValue(true));
$container->expects($this->once())
->method('getAlias')
->will($this->returnValue('translation.default'));
$container->expects($this->exactly(3))
->method('getDefinition')
->will($this->returnValue($definition));
$container->expects($this->once())
->method('hasParameter')
->with('translator.logging')
->will($this->returnValue(true));
$definition->expects($this->once())
->method('getClass')
->will($this->returnValue('Symfony\Bundle\FrameworkBundle\Translation\Translator'));
$parameterBag->expects($this->once())
->method('resolveValue')
->will($this->returnValue("Symfony\Bundle\FrameworkBundle\Translation\Translator"));
$container->expects($this->once())
->method('getParameterBag')
->will($this->returnValue($parameterBag));
$pass = new LoggingTranslatorPass();
$pass->process($container);
}
public function testThatCompilerPassIsIgnoredIfThereIsNotLoggerDefinition()
{
$container = $this->getMock('Symfony\Component\DependencyInjection\ContainerBuilder');
$container->expects($this->once())
->method('hasAlias')
->will($this->returnValue(false));
$pass = new LoggingTranslatorPass();
$pass->process($container);
}
public function testThatCompilerPassIsIgnoredIfThereIsNotTranslatorDefinition()
{
$container = $this->getMock('Symfony\Component\DependencyInjection\ContainerBuilder');
$container->expects($this->at(0))
->method('hasAlias')
->will($this->returnValue(true));
$container->expects($this->at(0))
->method('hasAlias')
->will($this->returnValue(false));
$pass = new LoggingTranslatorPass();
$pass->process($container);
}
}

View File

@@ -0,0 +1,95 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Bundle\FrameworkBundle\Tests\DependencyInjection\Compiler;
use Symfony\Component\DependencyInjection\Definition;
use Symfony\Bundle\FrameworkBundle\DependencyInjection\Compiler\ProfilerPass;
class ProfilerPassTest extends \PHPUnit_Framework_TestCase
{
private $profilerDefinition;
protected function setUp()
{
$this->profilerDefinition = new Definition('ProfilerClass');
}
/**
* 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()
{
// one service, with a template key, but no id
$services = array(
'my_collector_service' => array(0 => array('template' => 'foo')),
);
$builder = $this->createContainerMock($services);
$this->setExpectedException('InvalidArgumentException');
$profilerPass = new ProfilerPass();
$profilerPass->process($builder);
}
public function testValidCollector()
{
// one service, with a template key, but no id
$services = array(
'my_collector_service' => array(0 => array('template' => 'foo', 'id' => 'my_collector')),
);
$container = $this->createContainerMock($services);
// fake the getDefinition() to return a Profiler definition
$container->expects($this->atLeastOnce())
->method('getDefinition');
// assert that the data_collector.templates parameter should be set
$container->expects($this->once())
->method('setParameter')
->with('data_collector.templates', array('my_collector_service' => array('my_collector', 'foo')));
$profilerPass = new ProfilerPass();
$profilerPass->process($container);
// grab the method calls off of the "profiler" definition
$methodCalls = $this->profilerDefinition->getMethodCalls();
$this->assertCount(1, $methodCalls);
$this->assertEquals('add', $methodCalls[0][0]); // grab the method part of the first call
}
private function createContainerMock($services)
{
$container = $this->getMock(
'Symfony\Component\DependencyInjection\ContainerBuilder',
array('hasDefinition', 'getDefinition', 'findTaggedServiceIds', 'setParameter')
);
$container->expects($this->any())
->method('hasDefinition')
->with($this->equalTo('profiler'))
->will($this->returnValue(true));
$container->expects($this->any())
->method('getDefinition')
->will($this->returnValue($this->profilerDefinition));
$container->expects($this->atLeastOnce())
->method('findTaggedServiceIds')
->will($this->returnValue($services));
return $container;
}
}

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 Symfony\Bundle\FrameworkBundle\DependencyInjection\Compiler\PropertyInfoPass;
use Symfony\Component\DependencyInjection\Reference;
class PropertyInfoPassTest extends \PHPUnit_Framework_TestCase
{
public function testServicesAreOrderedAccordingToPriority()
{
$services = array(
'n3' => array('tag' => array()),
'n1' => array('tag' => array('priority' => 200)),
'n2' => array('tag' => array('priority' => 100)),
);
$expected = array(
new Reference('n1'),
new Reference('n2'),
new Reference('n3'),
);
$container = $this->getMock('Symfony\Component\DependencyInjection\ContainerBuilder', array('findTaggedServiceIds'));
$container->expects($this->any())
->method('findTaggedServiceIds')
->will($this->returnValue($services));
$propertyInfoPass = new PropertyInfoPass();
$method = new \ReflectionMethod(
'Symfony\Bundle\FrameworkBundle\DependencyInjection\Compiler\PropertyInfoPass',
'findAndSortTaggedServices'
);
$method->setAccessible(true);
$actual = $method->invoke($propertyInfoPass, 'tag', $container);
$this->assertEquals($expected, $actual);
}
public function testReturningEmptyArrayWhenNoService()
{
$container = $this->getMock('Symfony\Component\DependencyInjection\ContainerBuilder', array('findTaggedServiceIds'));
$container->expects($this->any())
->method('findTaggedServiceIds')
->will($this->returnValue(array()));
$propertyInfoPass = new PropertyInfoPass();
$method = new \ReflectionMethod(
'Symfony\Bundle\FrameworkBundle\DependencyInjection\Compiler\PropertyInfoPass',
'findAndSortTaggedServices'
);
$method->setAccessible(true);
$actual = $method->invoke($propertyInfoPass, 'tag', $container);
$this->assertEquals(array(), $actual);
}
}

View File

@@ -0,0 +1,106 @@
<?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 Symfony\Component\DependencyInjection\Reference;
use Symfony\Bundle\FrameworkBundle\DependencyInjection\Compiler\SerializerPass;
/**
* Tests for the SerializerPass class.
*
* @author Javier Lopez <f12loalf@gmail.com>
*/
class SerializerPassTest extends \PHPUnit_Framework_TestCase
{
public function testThrowExceptionWhenNoNormalizers()
{
$container = $this->getMock('Symfony\Component\DependencyInjection\ContainerBuilder', array('hasDefinition', 'findTaggedServiceIds'));
$container->expects($this->once())
->method('hasDefinition')
->with('serializer')
->will($this->returnValue(true));
$container->expects($this->once())
->method('findTaggedServiceIds')
->with('serializer.normalizer')
->will($this->returnValue(array()));
$this->setExpectedException('RuntimeException');
$serializerPass = new SerializerPass();
$serializerPass->process($container);
}
public function testThrowExceptionWhenNoEncoders()
{
$definition = $this->getMock('Symfony\Component\DependencyInjection\Definition');
$container = $this->getMock(
'Symfony\Component\DependencyInjection\ContainerBuilder',
array('hasDefinition', 'findTaggedServiceIds', 'getDefinition')
);
$container->expects($this->once())
->method('hasDefinition')
->with('serializer')
->will($this->returnValue(true));
$container->expects($this->any())
->method('findTaggedServiceIds')
->will($this->onConsecutiveCalls(
array('n' => array('serializer.normalizer')),
array()
));
$container->expects($this->once())
->method('getDefinition')
->will($this->returnValue($definition));
$this->setExpectedException('RuntimeException');
$serializerPass = new SerializerPass();
$serializerPass->process($container);
}
public function testServicesAreOrderedAccordingToPriority()
{
$services = array(
'n3' => array('tag' => array()),
'n1' => array('tag' => array('priority' => 200)),
'n2' => array('tag' => array('priority' => 100)),
);
$expected = array(
new Reference('n1'),
new Reference('n2'),
new Reference('n3'),
);
$container = $this->getMock('Symfony\Component\DependencyInjection\ContainerBuilder', array('findTaggedServiceIds'));
$container->expects($this->any())
->method('findTaggedServiceIds')
->will($this->returnValue($services));
$serializerPass = new SerializerPass();
$method = new \ReflectionMethod(
'Symfony\Bundle\FrameworkBundle\DependencyInjection\Compiler\SerializerPass',
'findAndSortTaggedServices'
);
$method->setAccessible(true);
$actual = $method->invoke($serializerPass, 'tag', $container);
$this->assertEquals($expected, $actual);
}
}

View File

@@ -0,0 +1,48 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Bundle\FrameworkBundle\Tests\DependencyInjection\Compiler;
use Symfony\Component\DependencyInjection\Reference;
use Symfony\Bundle\FrameworkBundle\DependencyInjection\Compiler\TranslatorPass;
class TranslatorPassTest extends \PHPUnit_Framework_TestCase
{
public function testValidCollector()
{
$definition = $this->getMock('Symfony\Component\DependencyInjection\Definition');
$definition->expects($this->at(0))
->method('addMethodCall')
->with('addLoader', array('xliff', new Reference('xliff')));
$definition->expects($this->at(1))
->method('addMethodCall')
->with('addLoader', array('xlf', new Reference('xliff')));
$container = $this->getMock(
'Symfony\Component\DependencyInjection\ContainerBuilder',
array('hasDefinition', 'getDefinition', 'findTaggedServiceIds', 'findDefinition')
);
$container->expects($this->any())
->method('hasDefinition')
->will($this->returnValue(true));
$container->expects($this->once())
->method('getDefinition')
->will($this->returnValue($definition));
$container->expects($this->once())
->method('findTaggedServiceIds')
->will($this->returnValue(array('xliff' => array(array('alias' => 'xliff', 'legacy-alias' => 'xlf')))));
$container->expects($this->once())
->method('findDefinition')
->will($this->returnValue($this->getMock('Symfony\Component\DependencyInjection\Definition')));
$pass = new TranslatorPass();
$pass->process($container);
}
}

View File

@@ -0,0 +1,52 @@
<?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 Symfony\Bundle\FrameworkBundle\DependencyInjection\Compiler\UnusedTagsPass;
class UnusedTagsPassTest extends \PHPUnit_Framework_TestCase
{
public function testProcess()
{
$pass = new UnusedTagsPass();
$formatter = $this->getMock('Symfony\Component\DependencyInjection\Compiler\LoggingFormatter');
$formatter
->expects($this->at(0))
->method('format')
->with($pass, 'Tag "kenrel.event_subscriber" was defined on service(s) "foo", "bar", but was never used. Did you mean "kernel.event_subscriber"?')
;
$compiler = $this->getMock('Symfony\Component\DependencyInjection\Compiler\Compiler');
$compiler->expects($this->once())->method('getLoggingFormatter')->will($this->returnValue($formatter));
$container = $this->getMock('Symfony\Component\DependencyInjection\ContainerBuilder',
array('findTaggedServiceIds', 'getCompiler', 'findUnusedTags', 'findTags')
);
$container->expects($this->once())->method('getCompiler')->will($this->returnValue($compiler));
$container->expects($this->once())
->method('findTags')
->will($this->returnValue(array('kenrel.event_subscriber')));
$container->expects($this->once())
->method('findUnusedTags')
->will($this->returnValue(array('kenrel.event_subscriber', 'form.type')));
$container->expects($this->once())
->method('findTaggedServiceIds')
->with('kenrel.event_subscriber')
->will($this->returnValue(array(
'foo' => array(),
'bar' => array(),
)));
$pass->process($container);
}
}

View File

@@ -0,0 +1,181 @@
<?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 Symfony\Bundle\FrameworkBundle\DependencyInjection\Configuration;
use Symfony\Component\Config\Definition\Processor;
class ConfigurationTest extends \PHPUnit_Framework_TestCase
{
public function testDefaultConfig()
{
$processor = new Processor();
$config = $processor->processConfiguration(new Configuration(true), array(array('secret' => 's3cr3t')));
$this->assertEquals(
array_merge(array('secret' => 's3cr3t', 'trusted_hosts' => array()), self::getBundleDefaultConfig()),
$config
);
}
public function testDoNoDuplicateDefaultFormResources()
{
$input = array('templating' => array(
'form' => array('resources' => array('FrameworkBundle:Form')),
'engines' => array('php'),
));
$processor = new Processor();
$config = $processor->processConfiguration(new Configuration(true), array($input));
$this->assertEquals(array('FrameworkBundle:Form'), $config['templating']['form']['resources']);
}
/**
* @dataProvider getTestValidTrustedProxiesData
*/
public function testValidTrustedProxies($trustedProxies, $processedProxies)
{
$processor = new Processor();
$configuration = new Configuration(true);
$config = $processor->processConfiguration($configuration, array(array(
'secret' => 's3cr3t',
'trusted_proxies' => $trustedProxies,
)));
$this->assertEquals($processedProxies, $config['trusted_proxies']);
}
public function getTestValidTrustedProxiesData()
{
return array(
array(array('127.0.0.1'), array('127.0.0.1')),
array(array('::1'), array('::1')),
array(array('127.0.0.1', '::1'), array('127.0.0.1', '::1')),
array(null, array()),
array(false, array()),
array(array(), array()),
array(array('10.0.0.0/8'), array('10.0.0.0/8')),
array(array('::ffff:0:0/96'), array('::ffff:0:0/96')),
array(array('0.0.0.0/0'), array('0.0.0.0/0')),
);
}
/**
* @expectedException \Symfony\Component\Config\Definition\Exception\InvalidConfigurationException
*/
public function testInvalidTypeTrustedProxies()
{
$processor = new Processor();
$configuration = new Configuration(true);
$processor->processConfiguration($configuration, array(
array(
'secret' => 's3cr3t',
'trusted_proxies' => 'Not an IP address',
),
));
}
/**
* @expectedException \Symfony\Component\Config\Definition\Exception\InvalidConfigurationException
*/
public function testInvalidValueTrustedProxies()
{
$processor = new Processor();
$configuration = new Configuration(true);
$processor->processConfiguration($configuration, array(
array(
'secret' => 's3cr3t',
'trusted_proxies' => array('Not an IP address'),
),
));
}
public function testAssetsCanBeEnabled()
{
$processor = new Processor();
$configuration = new Configuration(true);
$config = $processor->processConfiguration($configuration, array(array('assets' => null)));
$defaultConfig = array(
'version' => null,
'version_format' => '%%s?%%s',
'base_path' => '',
'base_urls' => array(),
'packages' => array(),
);
$this->assertEquals($defaultConfig, $config['assets']);
}
protected static function getBundleDefaultConfig()
{
return array(
'http_method_override' => true,
'trusted_proxies' => array(),
'ide' => null,
'default_locale' => 'en',
'csrf_protection' => array(
'enabled' => false,
),
'form' => array(
'enabled' => false,
'csrf_protection' => array(
'enabled' => null, // defaults to csrf_protection.enabled
'field_name' => '_token',
),
),
'esi' => array('enabled' => false),
'ssi' => array('enabled' => false),
'fragments' => array(
'enabled' => false,
'path' => '/_fragment',
),
'profiler' => array(
'enabled' => false,
'only_exceptions' => false,
'only_master_requests' => false,
'dsn' => 'file:%kernel.cache_dir%/profiler',
'collect' => true,
),
'translator' => array(
'enabled' => false,
'fallbacks' => array('en'),
'logging' => true,
'paths' => array(),
),
'validation' => array(
'enabled' => false,
'enable_annotations' => false,
'static_method' => array('loadValidatorMetadata'),
'translation_domain' => 'validators',
'strict_email' => false,
),
'annotations' => array(
'cache' => 'file',
'file_cache_dir' => '%kernel.cache_dir%/annotations',
'debug' => true,
),
'serializer' => array(
'enabled' => false,
'enable_annotations' => false,
),
'property_access' => array(
'magic_call' => false,
'throw_exception_on_invalid_index' => false,
),
'property_info' => array(
'enabled' => false,
),
);
}
}

View File

@@ -0,0 +1,16 @@
<?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;
class TestBundle extends \Symfony\Component\HttpKernel\Bundle\Bundle
{
}

View File

@@ -0,0 +1,29 @@
<?php
$container->loadFromExtension('framework', array(
'assets' => array(
'version' => 'SomeVersionScheme',
'base_urls' => 'http://cdn.example.com',
'version_format' => '%%s?version=%%s',
'packages' => array(
'images_path' => array(
'base_path' => '/foo',
),
'images' => array(
'version' => '1.0.0',
'base_urls' => array('http://images1.example.com', 'http://images2.example.com'),
),
'foo' => array(
'version' => '1.0.0',
'version_format' => '%%s-%%s',
),
'bar' => array(
'base_urls' => array('https://bar2.example.com'),
),
'bar_null_version' => array(
'version' => null,
'base_urls' => array('https://bar3.example.com'),
),
),
),
));

View File

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

View File

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

View File

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

View File

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

View File

@@ -0,0 +1,82 @@
<?php
$container->loadFromExtension('framework', array(
'secret' => 's3cr3t',
'default_locale' => 'fr',
'csrf_protection' => true,
'form' => array(
'csrf_protection' => array(
'field_name' => '_csrf',
),
),
'http_method_override' => false,
'trusted_proxies' => array('127.0.0.1', '10.0.0.1'),
'esi' => array(
'enabled' => true,
),
'profiler' => array(
'only_exceptions' => true,
'enabled' => false,
),
'router' => array(
'resource' => '%kernel.root_dir%/config/routing.xml',
'type' => 'xml',
),
'session' => array(
'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' => array(
'cache' => '/path/to/cache',
'engines' => array('php', 'twig'),
'loader' => array('loader.foo', 'loader.bar'),
'form' => array(
'resources' => array('theme1', 'theme2'),
),
'hinclude_default_template' => 'global_hinclude_template',
),
'assets' => array(
'version' => 'v1',
),
'translator' => array(
'enabled' => true,
'fallback' => 'fr',
'paths' => array('%kernel.root_dir%/Fixtures/translations'),
),
'validation' => array(
'enabled' => true,
'cache' => 'validator.mapping.cache.doctrine.apc',
),
'annotations' => array(
'cache' => 'file',
'debug' => true,
'file_cache_dir' => '%kernel.cache_dir%/annotations',
),
'serializer' => array(
'enabled' => true,
'enable_annotations' => true,
'cache' => 'serializer.mapping.cache.apc',
'name_converter' => 'serializer.name_converter.camel_case_to_snake_case',
),
'ide' => 'file%%link%%format',
'request' => array(
'formats' => array(
'csv' => array(
'text/csv',
'text/plain',
),
'pdf' => 'application/pdf',
),
),
));

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -0,0 +1,2 @@
custom:
paths: test

View File

@@ -0,0 +1,26 @@
<?xml version="1.0" ?>
<container xmlns="http://symfony.com/schema/dic/services"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:framework="http://symfony.com/schema/dic/symfony"
xsi:schemaLocation="http://symfony.com/schema/dic/services http://symfony.com/schema/dic/services/services-1.0.xsd
http://symfony.com/schema/dic/symfony http://symfony.com/schema/dic/symfony/symfony-1.0.xsd">
<framework:config>
<framework:assets version="SomeVersionScheme" version-format="%%s?version=%%s">
<framework:base-url>http://cdn.example.com</framework:base-url>
<framework:package name="images_path" base-path="/foo" version-format="%%s-%%s" />
<framework:package name="images" version="1.0.0">
<framework:base-url>http://images1.example.com</framework:base-url>
<framework:base-url>http://images2.example.com</framework:base-url>
</framework:package>
<framework:package name="foo" version="1.0.0" version-format="%%s-%%s" />
<framework:package name="bar">
<framework:base-url>https://bar2.example.com</framework:base-url>
</framework:package>
<framework:package name="bar_null_version" version="">
<framework:base-url>https://bar3.example.com</framework:base-url>
</framework:package>
</framework:assets>
</framework:config>
</container>

View File

@@ -0,0 +1,14 @@
<?xml version="1.0" ?>
<container xmlns="http://symfony.com/schema/dic/services"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:framework="http://symfony.com/schema/dic/symfony"
xsi:schemaLocation="http://symfony.com/schema/dic/services http://symfony.com/schema/dic/services/services-1.0.xsd
http://symfony.com/schema/dic/symfony http://symfony.com/schema/dic/symfony/symfony-1.0.xsd">
<framework:config>
<framework:csrf-protection />
<framework:form />
<framework:session />
</framework:config>
</container>

View File

@@ -0,0 +1,12 @@
<?xml version="1.0" ?>
<container xmlns="http://symfony.com/schema/dic/services"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:framework="http://symfony.com/schema/dic/symfony"
xsi:schemaLocation="http://symfony.com/schema/dic/services http://symfony.com/schema/dic/services/services-1.0.xsd
http://symfony.com/schema/dic/symfony http://symfony.com/schema/dic/symfony/symfony-1.0.xsd">
<framework:config>
<framework:csrf-protection enabled="false" />
</framework:config>
</container>

View File

@@ -0,0 +1,12 @@
<?xml version="1.0" ?>
<container xmlns="http://symfony.com/schema/dic/services"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:framework="http://symfony.com/schema/dic/symfony"
xsi:schemaLocation="http://symfony.com/schema/dic/services http://symfony.com/schema/dic/services/services-1.0.xsd
http://symfony.com/schema/dic/symfony http://symfony.com/schema/dic/symfony/symfony-1.0.xsd">
<framework:config>
<framework:csrf-protection />
</framework:config>
</container>

View File

@@ -0,0 +1,9 @@
<?xml version="1.0" encoding="UTF-8" ?>
<container xmlns="http://symfony.com/schema/dic/services"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:framework="http://symfony.com/schema/dic/symfony"
xsi:schemaLocation="http://symfony.com/schema/dic/services http://symfony.com/schema/dic/services/services-1.0.xsd
http://symfony.com/schema/dic/symfony http://symfony.com/schema/dic/symfony/symfony-1.0.xsd">
<framework:config />
</container>

View File

@@ -0,0 +1,14 @@
<?xml version="1.0" ?>
<container xmlns="http://symfony.com/schema/dic/services"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:framework="http://symfony.com/schema/dic/symfony"
xsi:schemaLocation="http://symfony.com/schema/dic/services http://symfony.com/schema/dic/services/services-1.0.xsd
http://symfony.com/schema/dic/symfony http://symfony.com/schema/dic/symfony/symfony-1.0.xsd">
<framework:config>
<framework:csrf-protection field-name="_custom" />
<framework:session />
<framework:form />
</framework:config>
</container>

View File

@@ -0,0 +1,14 @@
<?xml version="1.0" ?>
<container xmlns="http://symfony.com/schema/dic/services"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:framework="http://symfony.com/schema/dic/symfony"
xsi:schemaLocation="http://symfony.com/schema/dic/services http://symfony.com/schema/dic/services/services-1.0.xsd
http://symfony.com/schema/dic/symfony http://symfony.com/schema/dic/symfony/symfony-1.0.xsd">
<framework:config>
<framework:csrf-protection field-name="_custom_form" />
<framework:form />
<framework:session />
</framework:config>
</container>

View File

@@ -0,0 +1,14 @@
<?xml version="1.0" ?>
<container xmlns="http://symfony.com/schema/dic/services"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:framework="http://symfony.com/schema/dic/symfony"
xsi:schemaLocation="http://symfony.com/schema/dic/services http://symfony.com/schema/dic/services/services-1.0.xsd
http://symfony.com/schema/dic/symfony http://symfony.com/schema/dic/symfony/symfony-1.0.xsd">
<framework:config>
<framework:form enabled="true">
<framework:csrf-protection enabled="false" />
</framework:form>
</framework:config>
</container>

View File

@@ -0,0 +1,45 @@
<?xml version="1.0" ?>
<container xmlns="http://symfony.com/schema/dic/services"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:framework="http://symfony.com/schema/dic/symfony"
xsi:schemaLocation="http://symfony.com/schema/dic/services http://symfony.com/schema/dic/services/services-1.0.xsd
http://symfony.com/schema/dic/symfony http://symfony.com/schema/dic/symfony/symfony-1.0.xsd">
<framework:config secret="s3cr3t" ide="file%%link%%format" default-locale="fr" trusted-proxies="127.0.0.1, 10.0.0.1" http-method-override="false">
<framework:csrf-protection />
<framework:form>
<framework:csrf-protection field-name="_csrf"/>
</framework:form>
<framework:esi enabled="true" />
<framework:profiler only-exceptions="true" enabled="false" />
<framework:router resource="%kernel.root_dir%/config/routing.xml" type="xml" />
<framework:session gc-maxlifetime="90000" gc-probability="1" gc-divisor="108" 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" save-path="/path/to/sessions" />
<framework:request>
<framework:format name="csv">
<framework:mime-type>text/csv</framework:mime-type>
<framework:mime-type>text/plain</framework:mime-type>
</framework:format>
<framework:format name="pdf">
<framework:mime-type>application/pdf</framework:mime-type>
</framework:format>
</framework:request>
<framework:templating cache="/path/to/cache" hinclude-default-template="global_hinclude_template">
<framework:loader>loader.foo</framework:loader>
<framework:loader>loader.bar</framework:loader>
<framework:engine>php</framework:engine>
<framework:engine>twig</framework:engine>
<framework:form>
<framework:resource>theme1</framework:resource>
<framework:resource>theme2</framework:resource>
</framework:form>
</framework:templating>
<framework:assets version="v1" />
<framework:translator enabled="true" fallback="fr" logging="true">
<framework:path>%kernel.root_dir%/Fixtures/translations</framework:path>
</framework:translator>
<framework:validation enabled="true" cache="validator.mapping.cache.doctrine.apc" />
<framework:annotations cache="file" debug="true" file-cache-dir="%kernel.cache_dir%/annotations" />
<framework:serializer enabled="true" enable-annotations="true" cache="serializer.mapping.cache.apc" name-converter="serializer.name_converter.camel_case_to_snake_case" />
</framework:config>
</container>

View File

@@ -0,0 +1,12 @@
<?xml version="1.0" ?>
<container xmlns="http://symfony.com/schema/dic/services"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:framework="http://symfony.com/schema/dic/symfony"
xsi:schemaLocation="http://symfony.com/schema/dic/services http://symfony.com/schema/dic/services/services-1.0.xsd
http://symfony.com/schema/dic/symfony http://symfony.com/schema/dic/symfony/symfony-1.0.xsd">
<framework:config>
<framework:profiler enabled="true" />
</framework:config>
</container>

View File

@@ -0,0 +1,12 @@
<?xml version="1.0" ?>
<container xmlns="http://symfony.com/schema/dic/services"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:framework="http://symfony.com/schema/dic/symfony"
xsi:schemaLocation="http://symfony.com/schema/dic/services http://symfony.com/schema/dic/services/services-1.0.xsd
http://symfony.com/schema/dic/symfony http://symfony.com/schema/dic/symfony/symfony-1.0.xsd">
<framework:config>
<framework:property-access magic-call="true" throw-exception-on-invalid-index="true" />
</framework:config>
</container>

View File

@@ -0,0 +1,11 @@
<?xml version="1.0" encoding="utf-8" ?>
<container xmlns="http://symfony.com/schema/dic/services"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:framework="http://symfony.com/schema/dic/symfony"
xsi:schemaLocation="http://symfony.com/schema/dic/services http://symfony.com/schema/dic/services/services-1.0.xsd
http://symfony.com/schema/dic/symfony http://symfony.com/schema/dic/symfony/symfony-1.0.xsd">
<framework:config>
<framework:property-info enabled="true" />
</framework:config>
</container>

View File

@@ -0,0 +1,11 @@
<?xml version="1.0" ?>
<container xmlns="http://symfony.com/schema/dic/services"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:framework="http://symfony.com/schema/dic/symfony"
xsi:schemaLocation="http://symfony.com/schema/dic/services http://symfony.com/schema/dic/services/services-1.0.xsd
http://symfony.com/schema/dic/symfony http://symfony.com/schema/dic/symfony/symfony-1.0.xsd">
<framework:config>
<framework:request />
</framework:config>
</container>

View File

@@ -0,0 +1,11 @@
<?xml version="1.0" encoding="utf-8" ?>
<container xmlns="http://symfony.com/schema/dic/services"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:framework="http://symfony.com/schema/dic/symfony"
xsi:schemaLocation="http://symfony.com/schema/dic/services http://symfony.com/schema/dic/services/services-1.0.xsd
http://symfony.com/schema/dic/symfony http://symfony.com/schema/dic/symfony/symfony-1.0.xsd">
<framework:config>
<framework:serializer enabled="false" />
</framework:config>
</container>

View File

@@ -0,0 +1,11 @@
<?xml version="1.0" encoding="utf-8" ?>
<container xmlns="http://symfony.com/schema/dic/services"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:framework="http://symfony.com/schema/dic/symfony"
xsi:schemaLocation="http://symfony.com/schema/dic/services http://symfony.com/schema/dic/services/services-1.0.xsd
http://symfony.com/schema/dic/symfony http://symfony.com/schema/dic/symfony/symfony-1.0.xsd">
<framework:config>
<framework:serializer enabled="true" />
</framework:config>
</container>

View File

@@ -0,0 +1,12 @@
<?xml version="1.0" ?>
<container xmlns="http://symfony.com/schema/dic/services"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:framework="http://symfony.com/schema/dic/symfony"
xsi:schemaLocation="http://symfony.com/schema/dic/services http://symfony.com/schema/dic/services/services-1.0.xsd
http://symfony.com/schema/dic/symfony http://symfony.com/schema/dic/symfony/symfony-1.0.xsd">
<framework:config>
<framework:session handler-id="null"/>
</framework:config>
</container>

View File

@@ -0,0 +1,14 @@
<?xml version="1.0" ?>
<container xmlns="http://symfony.com/schema/dic/services"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:framework="http://symfony.com/schema/dic/symfony"
xsi:schemaLocation="http://symfony.com/schema/dic/services http://symfony.com/schema/dic/services/services-1.0.xsd
http://symfony.com/schema/dic/symfony http://symfony.com/schema/dic/symfony/symfony-1.0.xsd">
<framework:config>
<framework:templating>
<framework:engine>php</framework:engine>
<framework:engine>twig</framework:engine>
</framework:templating>
</framework:config>
</container>

View File

@@ -0,0 +1,15 @@
<?xml version="1.0" ?>
<container xmlns="http://symfony.com/schema/dic/services"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:framework="http://symfony.com/schema/dic/symfony"
xsi:schemaLocation="http://symfony.com/schema/dic/services http://symfony.com/schema/dic/services/services-1.0.xsd
http://symfony.com/schema/dic/symfony http://symfony.com/schema/dic/symfony/symfony-1.0.xsd">
<framework:config secret="s3cr3t">
<framework:translator enabled="true">
<framework:fallback>en</framework:fallback>
<framework:fallback>fr</framework:fallback>
</framework:translator>
</framework:config>
</container>

View File

@@ -0,0 +1,12 @@
<?xml version="1.0" ?>
<container xmlns="http://symfony.com/schema/dic/services"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:framework="http://symfony.com/schema/dic/symfony"
xsi:schemaLocation="http://symfony.com/schema/dic/services http://symfony.com/schema/dic/services/services-1.0.xsd
http://symfony.com/schema/dic/symfony http://symfony.com/schema/dic/symfony/symfony-1.0.xsd">
<framework:config secret="s3cr3t">
<framework:validation enabled="true" enable-annotations="true" />
</framework:config>
</container>

View File

@@ -0,0 +1,15 @@
<?xml version="1.0" ?>
<container xmlns="http://symfony.com/schema/dic/services"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:framework="http://symfony.com/schema/dic/symfony"
xsi:schemaLocation="http://symfony.com/schema/dic/services http://symfony.com/schema/dic/services/services-1.0.xsd
http://symfony.com/schema/dic/symfony http://symfony.com/schema/dic/symfony/symfony-1.0.xsd">
<framework:config secret="s3cr3t">
<framework:validation enabled="true">
<framework:static-method>loadFoo</framework:static-method>
<framework:static-method>loadBar</framework:static-method>
</framework:validation>
</framework:config>
</container>

View File

@@ -0,0 +1,12 @@
<?xml version="1.0" ?>
<container xmlns="http://symfony.com/schema/dic/services"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:framework="http://symfony.com/schema/dic/symfony"
xsi:schemaLocation="http://symfony.com/schema/dic/services http://symfony.com/schema/dic/services/services-1.0.xsd
http://symfony.com/schema/dic/symfony http://symfony.com/schema/dic/symfony/symfony-1.0.xsd">
<framework:config secret="s3cr3t">
<framework:validation enabled="true" static-method="false" />
</framework:config>
</container>

View File

@@ -0,0 +1,19 @@
framework:
assets:
version: SomeVersionScheme
version_format: '%%s?version=%%s'
base_urls: http://cdn.example.com
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_null_version:
version: null
base_urls: "https://bar3.example.com"

View File

@@ -0,0 +1,5 @@
framework:
secret: s3cr3t
csrf_protection: ~
form: ~
session: ~

View File

@@ -0,0 +1,2 @@
framework:
csrf_protection: ~

View File

@@ -0,0 +1 @@
framework: ~

View File

@@ -0,0 +1,4 @@
framework:
form:
csrf_protection:
enabled: false

View File

@@ -0,0 +1,61 @@
framework:
secret: s3cr3t
default_locale: fr
csrf_protection: true
form:
csrf_protection:
field_name: _csrf
http_method_override: false
trusted_proxies: ['127.0.0.1', '10.0.0.1']
esi:
enabled: true
profiler:
only_exceptions: true
enabled: false
router:
resource: '%kernel.root_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_probability: 1
gc_divisor: 108
gc_maxlifetime: 90000
save_path: /path/to/sessions
templating:
engines: [php, twig]
loader: [loader.foo, loader.bar]
cache: /path/to/cache
form:
resources: [theme1, theme2]
hinclude_default_template: global_hinclude_template
assets:
version: v1
translator:
enabled: true
fallback: fr
paths: ['%kernel.root_dir%/Fixtures/translations']
validation:
enabled: true
cache: validator.mapping.cache.doctrine.apc
annotations:
cache: file
debug: true
file_cache_dir: '%kernel.cache_dir%/annotations'
serializer:
enabled: true
enable_annotations: true
cache: serializer.mapping.cache.apc
name_converter: serializer.name_converter.camel_case_to_snake_case
ide: file%%link%%format
request:
formats:
csv: ['text/csv', 'text/plain']
pdf: 'application/pdf'

View File

@@ -0,0 +1,3 @@
framework:
profiler:
enabled: true

View File

@@ -0,0 +1,4 @@
framework:
property_access:
magic_call: true
throw_exception_on_invalid_index: true

View File

@@ -0,0 +1,3 @@
framework:
property_info:
enabled: true

View File

@@ -0,0 +1,3 @@
framework:
request:
formats: ~

View File

@@ -0,0 +1,3 @@
framework:
serializer:
enabled: false

View File

@@ -0,0 +1,3 @@
framework:
serializer:
enabled: true

View File

@@ -0,0 +1,3 @@
framework:
session:
handler_id: null

View File

@@ -0,0 +1,3 @@
framework:
templating:
engines: [php, twig]

View File

@@ -0,0 +1,4 @@
framework:
assets: false
templating:
engines: [php]

View File

@@ -0,0 +1,3 @@
framework:
translator:
fallbacks: [en, fr]

View File

@@ -0,0 +1,5 @@
framework:
secret: s3cr3t
validation:
enabled: true
enable_annotations: true

View File

@@ -0,0 +1,5 @@
framework:
secret: s3cr3t
validation:
enabled: true
static_method: [loadFoo, loadBar]

View File

@@ -0,0 +1,5 @@
framework:
secret: s3cr3t
validation:
enabled: true
static_method: false

View File

@@ -0,0 +1,566 @@
<?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 Symfony\Bundle\FrameworkBundle\Tests\TestCase;
use Symfony\Bundle\FrameworkBundle\DependencyInjection\FrameworkExtension;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\DefinitionDecorator;
use Symfony\Component\DependencyInjection\Loader\ClosureLoader;
use Symfony\Component\DependencyInjection\ParameterBag\ParameterBag;
use Symfony\Component\DependencyInjection\Reference;
abstract class FrameworkExtensionTest extends TestCase
{
private static $containerCache = array();
abstract protected function loadFromFile(ContainerBuilder $container, $file);
public function testFormCsrfProtection()
{
$container = $this->createContainerFromFile('full');
$def = $container->getDefinition('form.type_extension.csrf');
$this->assertTrue($container->getParameter('form.type_extension.csrf.enabled'));
$this->assertEquals('%form.type_extension.csrf.enabled%', $def->getArgument(1));
$this->assertEquals('_csrf', $container->getParameter('form.type_extension.csrf.field_name'));
$this->assertEquals('%form.type_extension.csrf.field_name%', $def->getArgument(2));
}
public function testPropertyAccessWithDefaultValue()
{
$container = $this->createContainerFromFile('full');
$def = $container->getDefinition('property_accessor');
$this->assertFalse($def->getArgument(0));
$this->assertFalse($def->getArgument(1));
}
public function testPropertyAccessWithOverriddenValues()
{
$container = $this->createContainerFromFile('property_accessor');
$def = $container->getDefinition('property_accessor');
$this->assertTrue($def->getArgument(0));
$this->assertTrue($def->getArgument(1));
}
/**
* @expectedException \LogicException
* @expectedExceptionMessage CSRF protection needs sessions to be enabled.
*/
public function testCsrfProtectionNeedsSessionToBeEnabled()
{
$this->createContainerFromFile('csrf_needs_session');
}
public function testCsrfProtectionForFormsEnablesCsrfProtectionAutomatically()
{
$container = $this->createContainerFromFile('csrf');
$this->assertTrue($container->hasDefinition('security.csrf.token_manager'));
}
public function testProxies()
{
$container = $this->createContainerFromFile('full');
$this->assertEquals(array('127.0.0.1', '10.0.0.1'), $container->getParameter('kernel.trusted_proxies'));
}
public function testHttpMethodOverride()
{
$container = $this->createContainerFromFile('full');
$this->assertFalse($container->getParameter('kernel.http_method_override'));
}
public function testEsi()
{
$container = $this->createContainerFromFile('full');
$this->assertTrue($container->hasDefinition('esi'), '->registerEsiConfiguration() loads esi.xml');
}
public function testEnabledProfiler()
{
$container = $this->createContainerFromFile('profiler');
$this->assertTrue($container->hasDefinition('profiler'), '->registerProfilerConfiguration() loads profiling.xml');
$this->assertTrue($container->hasDefinition('data_collector.config'), '->registerProfilerConfiguration() loads collectors.xml');
}
public function testDisabledProfiler()
{
$container = $this->createContainerFromFile('full');
$this->assertFalse($container->hasDefinition('profiler'), '->registerProfilerConfiguration() does not load profiling.xml');
$this->assertFalse($container->hasDefinition('data_collector.config'), '->registerProfilerConfiguration() does not load collectors.xml');
}
public function testRouter()
{
$container = $this->createContainerFromFile('full');
$this->assertTrue($container->has('router'), '->registerRouterConfiguration() loads routing.xml');
$arguments = $container->findDefinition('router')->getArguments();
$this->assertEquals($container->getParameter('kernel.root_dir').'/config/routing.xml', $container->getParameter('router.resource'), '->registerRouterConfiguration() sets routing resource');
$this->assertEquals('%router.resource%', $arguments[1], '->registerRouterConfiguration() sets routing resource');
$this->assertEquals('xml', $arguments[2]['resource_type'], '->registerRouterConfiguration() sets routing resource type');
}
/**
* @expectedException \Symfony\Component\Config\Definition\Exception\InvalidConfigurationException
*/
public function testRouterRequiresResourceOption()
{
$container = $this->createContainer();
$loader = new FrameworkExtension();
$loader->load(array(array('router' => true)), $container);
}
public function testSession()
{
$container = $this->createContainerFromFile('full');
$this->assertTrue($container->hasDefinition('session'), '->registerSessionConfiguration() loads session.xml');
$this->assertEquals('fr', $container->getParameter('kernel.default_locale'));
$this->assertEquals('session.storage.native', (string) $container->getAlias('session.storage'));
$this->assertEquals('session.handler.native_file', (string) $container->getAlias('session.handler'));
$options = $container->getParameter('session.storage.options');
$this->assertEquals('_SYMFONY', $options['name']);
$this->assertEquals(86400, $options['cookie_lifetime']);
$this->assertEquals('/', $options['cookie_path']);
$this->assertEquals('example.com', $options['cookie_domain']);
$this->assertTrue($options['cookie_secure']);
$this->assertFalse($options['cookie_httponly']);
$this->assertTrue($options['use_cookies']);
$this->assertEquals(108, $options['gc_divisor']);
$this->assertEquals(1, $options['gc_probability']);
$this->assertEquals(90000, $options['gc_maxlifetime']);
$this->assertEquals('/path/to/sessions', $container->getParameter('session.save_path'));
}
public function testNullSessionHandler()
{
$container = $this->createContainerFromFile('session');
$this->assertTrue($container->hasDefinition('session'), '->registerSessionConfiguration() loads session.xml');
$this->assertNull($container->getDefinition('session.storage.native')->getArgument(1));
$this->assertNull($container->getDefinition('session.storage.php_bridge')->getArgument(0));
}
public function testRequest()
{
$container = $this->createContainerFromFile('full');
$this->assertTrue($container->hasDefinition('request.add_request_formats_listener'), '->registerRequestConfiguration() loads request.xml');
$listenerDef = $container->getDefinition('request.add_request_formats_listener');
$this->assertEquals(array('csv' => array('text/csv', 'text/plain'), 'pdf' => array('application/pdf')), $listenerDef->getArgument(0));
}
public function testEmptyRequestFormats()
{
$container = $this->createContainerFromFile('request');
$this->assertFalse($container->hasDefinition('request.add_request_formats_listener'), '->registerRequestConfiguration() does not load request.xml when no request formats are defined');
}
public function testTemplating()
{
$container = $this->createContainerFromFile('full');
$this->assertTrue($container->hasDefinition('templating.name_parser'), '->registerTemplatingConfiguration() loads templating.xml');
$this->assertEquals('templating.engine.delegating', (string) $container->getAlias('templating'), '->registerTemplatingConfiguration() configures delegating loader if multiple engines are provided');
$this->assertEquals($container->getDefinition('templating.loader.chain'), $container->getDefinition('templating.loader.wrapped'), '->registerTemplatingConfiguration() configures loader chain if multiple loaders are provided');
$this->assertEquals($container->getDefinition('templating.loader'), $container->getDefinition('templating.loader.cache'), '->registerTemplatingConfiguration() configures the loader to use cache');
$this->assertEquals('%templating.loader.cache.path%', $container->getDefinition('templating.loader.cache')->getArgument(1));
$this->assertEquals('/path/to/cache', $container->getParameter('templating.loader.cache.path'));
$this->assertEquals(array('php', 'twig'), $container->getParameter('templating.engines'), '->registerTemplatingConfiguration() sets a templating.engines parameter');
$this->assertEquals(array('FrameworkBundle:Form', 'theme1', 'theme2'), $container->getParameter('templating.helper.form.resources'), '->registerTemplatingConfiguration() registers the theme and adds the base theme');
$this->assertEquals('global_hinclude_template', $container->getParameter('fragment.renderer.hinclude.global_template'), '->registerTemplatingConfiguration() registers the global hinclude.js template');
}
public function testAssets()
{
$container = $this->createContainerFromFile('assets');
$packages = $container->getDefinition('assets.packages');
// default package
$defaultPackage = $container->getDefinition($packages->getArgument(0));
$this->assertUrlPackage($container, $defaultPackage, array('http://cdn.example.com'), 'SomeVersionScheme', '%%s?version=%%s');
// packages
$packages = $packages->getArgument(1);
$this->assertCount(5, $packages);
$package = $container->getDefinition($packages['images_path']);
$this->assertPathPackage($container, $package, '/foo', 'SomeVersionScheme', '%%s?version=%%s');
$package = $container->getDefinition($packages['images']);
$this->assertUrlPackage($container, $package, array('http://images1.example.com', 'http://images2.example.com'), '1.0.0', '%%s?version=%%s');
$package = $container->getDefinition($packages['foo']);
$this->assertPathPackage($container, $package, '', '1.0.0', '%%s-%%s');
$package = $container->getDefinition($packages['bar']);
$this->assertUrlPackage($container, $package, array('https://bar2.example.com'), 'SomeVersionScheme', '%%s?version=%%s');
}
public function testTranslator()
{
$container = $this->createContainerFromFile('full');
$this->assertTrue($container->hasDefinition('translator.default'), '->registerTranslatorConfiguration() loads translation.xml');
$this->assertEquals('translator.default', (string) $container->getAlias('translator'), '->registerTranslatorConfiguration() redefines translator service from identity to real translator');
$options = $container->getDefinition('translator.default')->getArgument(3);
$files = array_map(function ($resource) { return realpath($resource); }, $options['resource_files']['en']);
$ref = new \ReflectionClass('Symfony\Component\Validator\Validation');
$this->assertContains(
strtr(dirname($ref->getFileName()).'/Resources/translations/validators.en.xlf', '/', DIRECTORY_SEPARATOR),
$files,
'->registerTranslatorConfiguration() finds Validator translation resources'
);
$ref = new \ReflectionClass('Symfony\Component\Form\Form');
$this->assertContains(
strtr(dirname($ref->getFileName()).'/Resources/translations/validators.en.xlf', '/', DIRECTORY_SEPARATOR),
$files,
'->registerTranslatorConfiguration() finds Form translation resources'
);
$ref = new \ReflectionClass('Symfony\Component\Security\Core\Security');
$this->assertContains(
strtr(dirname($ref->getFileName()).'/Resources/translations/security.en.xlf', '/', DIRECTORY_SEPARATOR),
$files,
'->registerTranslatorConfiguration() finds Security translation resources'
);
$this->assertContains(
strtr(__DIR__.'/Fixtures/translations/test_paths.en.yml', '/', DIRECTORY_SEPARATOR),
$files,
'->registerTranslatorConfiguration() finds translation resources in custom paths'
);
$calls = $container->getDefinition('translator.default')->getMethodCalls();
$this->assertEquals(array('fr'), $calls[1][1][0]);
}
public function testTranslatorMultipleFallbacks()
{
$container = $this->createContainerFromFile('translator_fallbacks');
$calls = $container->getDefinition('translator.default')->getMethodCalls();
$this->assertEquals(array('en', 'fr'), $calls[1][1][0]);
}
/**
* @expectedException \Symfony\Component\Config\Definition\Exception\InvalidConfigurationException
*/
public function testTemplatingRequiresAtLeastOneEngine()
{
$container = $this->createContainer();
$loader = new FrameworkExtension();
$loader->load(array(array('templating' => null)), $container);
}
public function testValidation()
{
$container = $this->createContainerFromFile('full');
$ref = new \ReflectionClass('Symfony\Component\Form\Form');
$xmlMappings = array(dirname($ref->getFileName()).'/Resources/config/validation.xml');
$calls = $container->getDefinition('validator.builder')->getMethodCalls();
$this->assertCount(6, $calls);
$this->assertSame('setConstraintValidatorFactory', $calls[0][0]);
$this->assertEquals(array(new Reference('validator.validator_factory')), $calls[0][1]);
$this->assertSame('setTranslator', $calls[1][0]);
$this->assertEquals(array(new Reference('translator')), $calls[1][1]);
$this->assertSame('setTranslationDomain', $calls[2][0]);
$this->assertSame(array('%validator.translation_domain%'), $calls[2][1]);
$this->assertSame('addXmlMappings', $calls[3][0]);
$this->assertSame(array($xmlMappings), $calls[3][1]);
$this->assertSame('addMethodMapping', $calls[4][0]);
$this->assertSame(array('loadValidatorMetadata'), $calls[4][1]);
$this->assertSame('setMetadataCache', $calls[5][0]);
$this->assertEquals(array(new Reference('validator.mapping.cache.doctrine.apc')), $calls[5][1]);
}
public function testValidationService()
{
$container = $this->createContainerFromFile('validation_annotations');
$this->assertInstanceOf('Symfony\Component\Validator\Validator\ValidatorInterface', $container->get('validator'));
}
public function testAnnotations()
{
$container = $this->createContainerFromFile('full');
$this->assertEquals($container->getParameter('kernel.cache_dir').'/annotations', $container->getDefinition('annotations.filesystem_cache')->getArgument(0));
$this->assertSame('annotations.cached_reader', (string) $container->getAlias('annotation_reader'));
$this->assertSame('annotations.filesystem_cache', (string) $container->getDefinition('annotations.cached_reader')->getArgument(1));
}
public function testFileLinkFormat()
{
$container = $this->createContainerFromFile('full');
$this->assertEquals('file%link%format', $container->getParameter('templating.helper.code.file_link_format'));
}
public function testValidationAnnotations()
{
$container = $this->createContainerFromFile('validation_annotations');
$calls = $container->getDefinition('validator.builder')->getMethodCalls();
$this->assertCount(6, $calls);
$this->assertSame('enableAnnotationMapping', $calls[4][0]);
$this->assertEquals(array(new Reference('annotation_reader')), $calls[4][1]);
$this->assertSame('addMethodMapping', $calls[5][0]);
$this->assertSame(array('loadValidatorMetadata'), $calls[5][1]);
// no cache this time
}
public function testValidationPaths()
{
require_once __DIR__.'/Fixtures/TestBundle/TestBundle.php';
$container = $this->createContainerFromFile('validation_annotations', array(
'kernel.bundles' => array('TestBundle' => 'Symfony\Bundle\FrameworkBundle\Tests\TestBundle'),
));
$calls = $container->getDefinition('validator.builder')->getMethodCalls();
$this->assertCount(7, $calls);
$this->assertSame('addXmlMappings', $calls[3][0]);
$this->assertSame('addYamlMappings', $calls[4][0]);
$this->assertSame('enableAnnotationMapping', $calls[5][0]);
$this->assertSame('addMethodMapping', $calls[6][0]);
$this->assertSame(array('loadValidatorMetadata'), $calls[6][1]);
$xmlMappings = $calls[3][1][0];
$this->assertCount(2, $xmlMappings);
try {
// Testing symfony/symfony
$this->assertStringEndsWith('Component'.DIRECTORY_SEPARATOR.'Form/Resources/config/validation.xml', $xmlMappings[0]);
} catch (\Exception $e) {
// Testing symfony/framework-bundle with deps=high
$this->assertStringEndsWith('symfony'.DIRECTORY_SEPARATOR.'form/Resources/config/validation.xml', $xmlMappings[0]);
}
$this->assertStringEndsWith('TestBundle'.DIRECTORY_SEPARATOR.'Resources'.DIRECTORY_SEPARATOR.'config'.DIRECTORY_SEPARATOR.'validation.xml', $xmlMappings[1]);
$yamlMappings = $calls[4][1][0];
$this->assertCount(1, $yamlMappings);
$this->assertStringEndsWith('TestBundle'.DIRECTORY_SEPARATOR.'Resources'.DIRECTORY_SEPARATOR.'config'.DIRECTORY_SEPARATOR.'validation.yml', $yamlMappings[0]);
}
public function testValidationNoStaticMethod()
{
$container = $this->createContainerFromFile('validation_no_static_method');
$calls = $container->getDefinition('validator.builder')->getMethodCalls();
$this->assertCount(4, $calls);
$this->assertSame('addXmlMappings', $calls[3][0]);
// no cache, no annotations, no static methods
}
public function testFormsCanBeEnabledWithoutCsrfProtection()
{
$container = $this->createContainerFromFile('form_no_csrf');
$this->assertFalse($container->getParameter('form.type_extension.csrf.enabled'));
}
public function testStopwatchEnabledWithDebugModeEnabled()
{
$container = $this->createContainerFromFile('default_config', array(
'kernel.container_class' => 'foo',
'kernel.debug' => true,
));
$this->assertTrue($container->has('debug.stopwatch'));
}
public function testStopwatchEnabledWithDebugModeDisabled()
{
$container = $this->createContainerFromFile('default_config', array(
'kernel.container_class' => 'foo',
));
$this->assertTrue($container->has('debug.stopwatch'));
}
public function testSerializerDisabled()
{
$container = $this->createContainerFromFile('default_config');
$this->assertFalse($container->has('serializer'));
}
public function testSerializerEnabled()
{
$container = $this->createContainerFromFile('full');
$this->assertTrue($container->has('serializer'));
$argument = $container->getDefinition('serializer.mapping.chain_loader')->getArgument(0);
$this->assertCount(1, $argument);
$this->assertEquals('Symfony\Component\Serializer\Mapping\Loader\AnnotationLoader', $argument[0]->getClass());
$this->assertEquals(new Reference('serializer.mapping.cache.apc'), $container->getDefinition('serializer.mapping.class_metadata_factory')->getArgument(1));
$this->assertEquals(new Reference('serializer.name_converter.camel_case_to_snake_case'), $container->getDefinition('serializer.normalizer.object')->getArgument(1));
}
public function testObjectNormalizerRegistered()
{
$container = $this->createContainerFromFile('full');
$definition = $container->getDefinition('serializer.normalizer.object');
$tag = $definition->getTag('serializer.normalizer');
$this->assertEquals('Symfony\Component\Serializer\Normalizer\ObjectNormalizer', $definition->getClass());
$this->assertEquals(-1000, $tag[0]['priority']);
}
public function testAssetHelperWhenAssetsAreEnabled()
{
$container = $this->createContainerFromFile('full');
$packages = $container->getDefinition('templating.helper.assets')->getArgument(0);
$this->assertSame('assets.packages', (string) $packages);
}
public function testAssetHelperWhenTemplatesAreEnabledAndNoAssetsConfiguration()
{
$container = $this->createContainerFromFile('templating_no_assets');
$packages = $container->getDefinition('templating.helper.assets')->getArgument(0);
$this->assertSame('assets.packages', (string) $packages);
}
public function testAssetsHelperIsRemovedWhenPhpTemplatingEngineIsEnabledAndAssetsAreDisabled()
{
$container = $this->createContainerFromFile('templating_php_assets_disabled');
$this->assertTrue(!$container->has('templating.helper.assets'), 'The templating.helper.assets helper service is removed when assets are disabled.');
}
public function testAssetHelperWhenAssetsAndTemplatesAreDisabled()
{
$container = $this->createContainerFromFile('default_config');
$this->assertFalse($container->hasDefinition('templating.helper.assets'));
}
public function testSerializerServiceIsRegisteredWhenEnabled()
{
$container = $this->createContainerFromFile('serializer_enabled');
$this->assertTrue($container->hasDefinition('serializer'));
}
public function testSerializerServiceIsNotRegisteredWhenDisabled()
{
$container = $this->createContainerFromFile('serializer_disabled');
$this->assertFalse($container->hasDefinition('serializer'));
}
public function testPropertyInfoDisabled()
{
$container = $this->createContainerFromFile('default_config');
$this->assertFalse($container->has('property_info'));
}
public function testPropertyInfoEnabled()
{
$container = $this->createContainerFromFile('property_info');
$this->assertTrue($container->has('property_info'));
}
protected function createContainer(array $data = array())
{
return new ContainerBuilder(new ParameterBag(array_merge(array(
'kernel.bundles' => array('FrameworkBundle' => 'Symfony\\Bundle\\FrameworkBundle\\FrameworkBundle'),
'kernel.cache_dir' => __DIR__,
'kernel.debug' => false,
'kernel.environment' => 'test',
'kernel.name' => 'kernel',
'kernel.root_dir' => __DIR__,
), $data)));
}
protected function createContainerFromFile($file, $data = array())
{
$cacheKey = md5(get_class($this).$file.serialize($data));
if (isset(self::$containerCache[$cacheKey])) {
return self::$containerCache[$cacheKey];
}
$container = $this->createContainer($data);
$container->registerExtension(new FrameworkExtension());
$this->loadFromFile($container, $file);
$container->getCompilerPassConfig()->setOptimizationPasses(array());
$container->getCompilerPassConfig()->setRemovingPasses(array());
$container->compile();
return self::$containerCache[$cacheKey] = $container;
}
protected function createContainerFromClosure($closure, $data = array())
{
$container = $this->createContainer($data);
$container->registerExtension(new FrameworkExtension());
$loader = new ClosureLoader($container);
$loader->load($closure);
$container->getCompilerPassConfig()->setOptimizationPasses(array());
$container->getCompilerPassConfig()->setRemovingPasses(array());
$container->compile();
return $container;
}
private function assertPathPackage(ContainerBuilder $container, DefinitionDecorator $package, $basePath, $version, $format)
{
$this->assertEquals('assets.path_package', $package->getParent());
$this->assertEquals($basePath, $package->getArgument(0));
$this->assertVersionStrategy($container, $package->getArgument(1), $version, $format);
}
private function assertUrlPackage(ContainerBuilder $container, DefinitionDecorator $package, $baseUrls, $version, $format)
{
$this->assertEquals('assets.url_package', $package->getParent());
$this->assertEquals($baseUrls, $package->getArgument(0));
$this->assertVersionStrategy($container, $package->getArgument(1), $version, $format);
}
private function assertVersionStrategy(ContainerBuilder $container, Reference $reference, $version, $format)
{
$versionStrategy = $container->getDefinition($reference);
if (null === $version) {
$this->assertEquals('assets.empty_version_strategy', (string) $reference);
} else {
$this->assertEquals('assets.static_version_strategy', $versionStrategy->getParent());
$this->assertEquals($version, $versionStrategy->getArgument(0));
$this->assertEquals($format, $versionStrategy->getArgument(1));
}
}
}

View File

@@ -0,0 +1,59 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Bundle\FrameworkBundle\Tests\DependencyInjection;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Loader\PhpFileLoader;
use Symfony\Component\Config\FileLocator;
class PhpFrameworkExtensionTest extends FrameworkExtensionTest
{
protected function loadFromFile(ContainerBuilder $container, $file)
{
$loader = new PhpFileLoader($container, new FileLocator(__DIR__.'/Fixtures/php'));
$loader->load($file.'.php');
}
/**
* @expectedException \LogicException
*/
public function testAssetsCannotHavePathAndUrl()
{
$this->createContainerFromClosure(function ($container) {
$container->loadFromExtension('framework', array(
'assets' => array(
'base_urls' => 'http://cdn.example.com',
'base_path' => '/foo',
),
));
});
}
/**
* @expectedException \LogicException
*/
public function testAssetPackageCannotHavePathAndUrl()
{
$this->createContainerFromClosure(function ($container) {
$container->loadFromExtension('framework', array(
'assets' => array(
'packages' => array(
'impossible' => array(
'base_urls' => 'http://cdn.example.com',
'base_path' => '/foo',
),
),
),
));
});
}
}

View File

@@ -0,0 +1,30 @@
<?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 Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Loader\XmlFileLoader;
use Symfony\Component\Config\FileLocator;
class XmlFrameworkExtensionTest extends FrameworkExtensionTest
{
protected function loadFromFile(ContainerBuilder $container, $file)
{
$loader = new XmlFileLoader($container, new FileLocator(__DIR__.'/Fixtures/xml'));
$loader->load($file.'.xml');
}
public function testAssetsHelperIsRemovedWhenPhpTemplatingEngineIsEnabledAndAssetsAreDisabled()
{
$this->markTestSkipped('The assets key cannot be set to false using the XML configuration format.');
}
}

View File

@@ -0,0 +1,25 @@
<?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 Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Loader\YamlFileLoader;
use Symfony\Component\Config\FileLocator;
class YamlFrameworkExtensionTest extends FrameworkExtensionTest
{
protected function loadFromFile(ContainerBuilder $container, $file)
{
$loader = new YamlFileLoader($container, new FileLocator(__DIR__.'/Fixtures/yml'));
$loader->load($file.'.yml');
}
}

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