Merge branch '2.7'

* 2.7:
  [2.7] Added deprecated in debug command
  [FrameworkBundle] remove usage of deprecated Definition::setFactoryClass(), Definition::setFactoryService() and Definition::setFactoryMethod() methods.
  fixed some deprecated notices
  [Validator] fixed some legacy tests
  [Validator] fixed remaining notice
  [DX] Attempt to improve logging messages with  parameters
This commit is contained in:
Fabien Potencier 2015-01-16 23:00:38 +01:00
commit 56ad3e6668
77 changed files with 648 additions and 206 deletions

View File

@ -57,6 +57,10 @@ EOF
*/
protected function execute(InputInterface $input, OutputInterface $output)
{
if (false !== strpos($input->getFirstArgument(), ':d')) {
$output->writeln('<comment>The use of "config:debug" command is deprecated since version 2.7 and will be removed in 3.0. Use the "debug:config" instead.</comment>');
}
$name = $input->getArgument('name');
if (empty($name)) {

View File

@ -94,6 +94,10 @@ EOF
*/
protected function execute(InputInterface $input, OutputInterface $output)
{
if (false !== strpos($input->getFirstArgument(), ':d')) {
$output->writeln('<comment>The use of "container:debug" command is deprecated since version 2.7 and will be removed in 3.0. Use the "debug:container" instead.</comment>');
}
$this->validateInput($input);
if ($input->getOption('parameters')) {

View File

@ -64,7 +64,7 @@ class RouterDebugCommand extends ContainerAwareCommand
The <info>%command.name%</info> displays the configured routes:
<info>php %command.full_name%</info>
EOF
)
;
@ -77,6 +77,10 @@ EOF
*/
protected function execute(InputInterface $input, OutputInterface $output)
{
if (false !== strpos($input->getFirstArgument(), ':d')) {
$output->writeln('<comment>The use of "router:debug" command is deprecated since version 2.7 and will be removed in 3.0. Use the "debug:router" instead.</comment>');
}
$name = $input->getArgument('name');
$helper = new DescriptorHelper();

View File

@ -81,6 +81,10 @@ EOF
*/
protected function execute(InputInterface $input, OutputInterface $output)
{
if (false !== strpos($input->getFirstArgument(), ':d')) {
$output->writeln('<comment>The use of "translation:debug" command is deprecated since version 2.7 and will be removed in 3.0. Use the "debug:translation" instead.</comment>');
}
$locale = $input->getArgument('locale');
$domain = $input->getOption('domain');
$bundle = $this->getContainer()->get('kernel')->getBundle($input->getArgument('bundle'));

View File

@ -212,23 +212,24 @@ class JsonDescriptor extends Descriptor
'synthetic' => $definition->isSynthetic(),
'lazy' => $definition->isLazy(),
);
if (method_exists($definition, 'isSynchronized')) {
$data['synchronized'] = $definition->isSynchronized();
$data['synchronized'] = $definition->isSynchronized(false);
}
$data['abstract'] = $definition->isAbstract();
$data['file'] = $definition->getFile();
if ($definition->getFactoryClass()) {
$data['factory_class'] = $definition->getFactoryClass();
if ($definition->getFactoryClass(false)) {
$data['factory_class'] = $definition->getFactoryClass(false);
}
if ($definition->getFactoryService()) {
$data['factory_service'] = $definition->getFactoryService();
if ($definition->getFactoryService(false)) {
$data['factory_service'] = $definition->getFactoryService(false);
}
if ($definition->getFactoryMethod()) {
$data['factory_method'] = $definition->getFactoryMethod();
if ($definition->getFactoryMethod(false)) {
$data['factory_method'] = $definition->getFactoryMethod(false);
}
if ($factory = $definition->getFactory()) {

View File

@ -186,7 +186,7 @@ class MarkdownDescriptor extends Descriptor
;
if (method_exists($definition, 'isSynchronized')) {
$output .= "\n".'- Synchronized: '.($definition->isSynchronized() ? 'yes' : 'no');
$output .= "\n".'- Synchronized: '.($definition->isSynchronized(false) ? 'yes' : 'no');
}
$output .= "\n".'- Abstract: '.($definition->isAbstract() ? 'yes' : 'no');
@ -195,16 +195,16 @@ class MarkdownDescriptor extends Descriptor
$output .= "\n".'- File: `'.$definition->getFile().'`';
}
if ($definition->getFactoryClass()) {
$output .= "\n".'- Factory Class: `'.$definition->getFactoryClass().'`';
if ($definition->getFactoryClass(false)) {
$output .= "\n".'- Factory Class: `'.$definition->getFactoryClass(false).'`';
}
if ($definition->getFactoryService()) {
$output .= "\n".'- Factory Service: `'.$definition->getFactoryService().'`';
if ($definition->getFactoryService(false)) {
$output .= "\n".'- Factory Service: `'.$definition->getFactoryService(false).'`';
}
if ($definition->getFactoryMethod()) {
$output .= "\n".'- Factory Method: `'.$definition->getFactoryMethod().'`';
if ($definition->getFactoryMethod(false)) {
$output .= "\n".'- Factory Method: `'.$definition->getFactoryMethod(false).'`';
}
if ($factory = $definition->getFactory()) {

View File

@ -264,7 +264,7 @@ class TextDescriptor extends Descriptor
$description[] = sprintf('<comment>Synthetic</comment> %s', $definition->isSynthetic() ? 'yes' : 'no');
$description[] = sprintf('<comment>Lazy</comment> %s', $definition->isLazy() ? 'yes' : 'no');
if (method_exists($definition, 'isSynchronized')) {
$description[] = sprintf('<comment>Synchronized</comment> %s', $definition->isSynchronized() ? 'yes' : 'no');
$description[] = sprintf('<comment>Synchronized</comment> %s', $definition->isSynchronized(false) ? 'yes' : 'no');
}
$description[] = sprintf('<comment>Abstract</comment> %s', $definition->isAbstract() ? 'yes' : 'no');
@ -272,16 +272,16 @@ class TextDescriptor extends Descriptor
$description[] = sprintf('<comment>Required File</comment> %s', $definition->getFile() ? $definition->getFile() : '-');
}
if ($definition->getFactoryClass()) {
$description[] = sprintf('<comment>Factory Class</comment> %s', $definition->getFactoryClass());
if ($definition->getFactoryClass(false)) {
$description[] = sprintf('<comment>Factory Class</comment> %s', $definition->getFactoryClass(false));
}
if ($definition->getFactoryService()) {
$description[] = sprintf('<comment>Factory Service</comment> %s', $definition->getFactoryService());
if ($definition->getFactoryService(false)) {
$description[] = sprintf('<comment>Factory Service</comment> %s', $definition->getFactoryService(false));
}
if ($definition->getFactoryMethod()) {
$description[] = sprintf('<comment>Factory Method</comment> %s', $definition->getFactoryMethod());
if ($definition->getFactoryMethod(false)) {
$description[] = sprintf('<comment>Factory Method</comment> %s', $definition->getFactoryMethod(false));
}
if ($factory = $definition->getFactory()) {

View File

@ -66,6 +66,21 @@ abstract class AbstractDescriptorTest extends \PHPUnit_Framework_TestCase
return $this->getContainerBuilderDescriptionTestData(ObjectsProvider::getContainerBuilders());
}
/** @dataProvider provideLegacySynchronizedServiceDefinitionTestData */
public function testLegacyDescribeSynchronizedServiceDefinition(Definition $definition, $expectedDescription)
{
$this->iniSet('error_reporting', -1 & ~E_USER_DEPRECATED);
$this->assertDescription($expectedDescription, $definition);
}
public function provideLegacySynchronizedServiceDefinitionTestData()
{
$this->iniSet('error_reporting', -1 & ~E_USER_DEPRECATED);
return $this->getDescriptionTestData(ObjectsProvider::getLegacyContainerDefinitions());
}
/** @dataProvider getDescribeContainerDefinitionTestData */
public function testDescribeContainerDefinition(Definition $definition, $expectedDescription)
{

View File

@ -97,10 +97,40 @@ class ObjectsProvider
->setPublic(true)
->setSynthetic(false)
->setLazy(true)
->setSynchronized(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')),
);
}
/**
* @deprecated since version 2.7, to be removed in 3.0
* @internal
*/
public static function getLegacyContainerDefinitions()
{
$definition1 = new Definition('Full\\Qualified\\Class1');
$definition2 = new Definition('Full\\Qualified\\Class2');
return array(
'legacy_synchronized_service_definition_1' => $definition1
->setPublic(true)
->setSynthetic(false)
->setLazy(true)
->setSynchronized(true)
->setAbstract(true)
->setFactoryClass('Full\\Qualified\\FactoryClass', 'get')
->setFactoryMethod('get'),
'legacy_synchronized_service_definition_2' => $definition2
->setPublic(false)
->setSynthetic(true)
->setFile('/path/to/file')
@ -110,7 +140,8 @@ class ObjectsProvider
->addTag('tag1', array('attr1' => 'val1', 'attr2' => 'val2'))
->addTag('tag1', array('attr3' => 'val3'))
->addTag('tag2')
->setFactory(array(new Reference('factory.service'), 'get')),
->setFactoryService('factory.service')
->setFactoryMethod('get'),
);
}

View File

@ -6,7 +6,7 @@
"public": true,
"synthetic": false,
"lazy": true,
"synchronized": true,
"synchronized": false,
"abstract": true,
"file": null,
"factory_class": "Full\\Qualified\\FactoryClass",

View File

@ -12,7 +12,7 @@ definition_1
- Public: yes
- Synthetic: no
- Lazy: yes
- Synchronized: yes
- Synchronized: no
- Abstract: yes
- Factory Class: `Full\Qualified\FactoryClass`
- Factory Method: `get`
@ -37,4 +37,4 @@ alias_2
Services
--------
- `service_container`: `Symfony\Component\DependencyInjection\ContainerBuilder`
- `service_container`: `Symfony\Component\DependencyInjection\ContainerBuilder`

View File

@ -2,7 +2,7 @@
<container>
<alias id="alias_1" service="service_1" public="true"/>
<alias id="alias_2" service="service_2" public="false"/>
<definition id="definition_1" class="Full\Qualified\Class1" scope="container" public="true" synthetic="false" lazy="true" synchronized="true" abstract="true" file="">
<definition id="definition_1" class="Full\Qualified\Class1" scope="container" public="true" synthetic="false" lazy="true" synchronized="false" abstract="true" file="">
<factory class="Full\Qualified\FactoryClass" method="get"/>
</definition>
<service id="service_container" class="Symfony\Component\DependencyInjection\ContainerBuilder"/>

View File

@ -6,7 +6,7 @@
"public": true,
"synthetic": false,
"lazy": true,
"synchronized": true,
"synchronized": false,
"abstract": true,
"file": null,
"factory_class": "Full\\Qualified\\FactoryClass",

View File

@ -12,7 +12,7 @@ definition_1
- Public: yes
- Synthetic: no
- Lazy: yes
- Synchronized: yes
- Synchronized: no
- Abstract: yes
- Factory Class: `Full\Qualified\FactoryClass`
- Factory Method: `get`
@ -57,4 +57,4 @@ alias_2
Services
--------
- `service_container`: `Symfony\Component\DependencyInjection\ContainerBuilder`
- `service_container`: `Symfony\Component\DependencyInjection\ContainerBuilder`

View File

@ -2,7 +2,7 @@
<container>
<alias id="alias_1" service="service_1" public="true"/>
<alias id="alias_2" service="service_2" public="false"/>
<definition id="definition_1" class="Full\Qualified\Class1" scope="container" public="true" synthetic="false" lazy="true" synchronized="true" abstract="true" file="">
<definition id="definition_1" class="Full\Qualified\Class1" scope="container" public="true" synthetic="false" lazy="true" synchronized="false" abstract="true" file="">
<factory class="Full\Qualified\FactoryClass" method="get"/>
</definition>
<definition id="definition_2" class="Full\Qualified\Class2" scope="container" public="false" synthetic="true" lazy="false" synchronized="false" abstract="false" file="/path/to/file">

View File

@ -4,7 +4,7 @@
"public": true,
"synthetic": false,
"lazy": true,
"synchronized": true,
"synchronized": false,
"abstract": true,
"file": null,
"factory_class": "Full\\Qualified\\FactoryClass",

View File

@ -3,7 +3,7 @@
- Public: yes
- Synthetic: no
- Lazy: yes
- Synchronized: yes
- Synchronized: no
- Abstract: yes
- Factory Class: `Full\Qualified\FactoryClass`
- Factory Method: `get`
- Factory Method: `get`

View File

@ -5,7 +5,7 @@
<comment>Public</comment> yes
<comment>Synthetic</comment> no
<comment>Lazy</comment> yes
<comment>Synchronized</comment> yes
<comment>Synchronized</comment> no
<comment>Abstract</comment> yes
<comment>Factory Class</comment> Full\Qualified\FactoryClass
<comment>Factory Method</comment> get

View File

@ -1,4 +1,4 @@
<?xml version="1.0" encoding="UTF-8"?>
<definition class="Full\Qualified\Class1" scope="container" public="true" synthetic="false" lazy="true" synchronized="true" abstract="true" file="">
<definition class="Full\Qualified\Class1" scope="container" public="true" synthetic="false" lazy="true" synchronized="false" abstract="true" file="">
<factory class="Full\Qualified\FactoryClass" method="get"/>
</definition>

View File

@ -0,0 +1,15 @@
{
"class": "Full\\Qualified\\Class1",
"scope": "container",
"public": true,
"synthetic": false,
"lazy": true,
"synchronized": true,
"abstract": true,
"file": null,
"factory_class": "Full\\Qualified\\FactoryClass",
"factory_method": "get",
"tags": [
]
}

View File

@ -0,0 +1,9 @@
- Class: `Full\Qualified\Class1`
- Scope: `container`
- Public: yes
- Synthetic: no
- Lazy: yes
- Synchronized: yes
- Abstract: yes
- Factory Class: `Full\Qualified\FactoryClass`
- Factory Method: `get`

View File

@ -0,0 +1,11 @@
<comment>Service Id</comment> -
<comment>Class</comment> Full\Qualified\Class1
<comment>Tags</comment> -
<comment>Scope</comment> container
<comment>Public</comment> yes
<comment>Synthetic</comment> no
<comment>Lazy</comment> yes
<comment>Synchronized</comment> yes
<comment>Abstract</comment> yes
<comment>Factory Class</comment> Full\Qualified\FactoryClass
<comment>Factory Method</comment> get

View File

@ -0,0 +1,2 @@
<?xml version="1.0" encoding="UTF-8"?>
<definition class="Full\Qualified\Class1" factory-class="Full\Qualified\FactoryClass" factory-method="get" scope="container" public="true" synthetic="false" lazy="true" synchronized="true" abstract="true" file=""/>

View File

@ -0,0 +1,33 @@
{
"class": "Full\\Qualified\\Class2",
"scope": "container",
"public": false,
"synthetic": true,
"lazy": false,
"synchronized": false,
"abstract": false,
"file": "\/path\/to\/file",
"factory_service": "factory.service",
"factory_method": "get",
"tags": [
{
"name": "tag1",
"parameters": {
"attr1": "val1",
"attr2": "val2"
}
},
{
"name": "tag1",
"parameters": {
"attr3": "val3"
}
},
{
"name": "tag2",
"parameters": [
]
}
]
}

View File

@ -0,0 +1,16 @@
- Class: `Full\Qualified\Class2`
- Scope: `container`
- Public: no
- Synthetic: yes
- Lazy: no
- Synchronized: no
- Abstract: no
- File: `/path/to/file`
- Factory Service: `factory.service`
- Factory Method: `get`
- Tag: `tag1`
- Attr1: val1
- Attr2: val2
- Tag: `tag1`
- Attr3: val3
- Tag: `tag2`

View File

@ -0,0 +1,15 @@
<comment>Service Id</comment> -
<comment>Class</comment> Full\Qualified\Class2
<comment>Tags</comment>
- tag1 (<info>attr1</info>: val1, <info>attr2</info>: val2)
- tag1 (<info>attr3</info>: val3)
- tag2 ()
<comment>Scope</comment> container
<comment>Public</comment> no
<comment>Synthetic</comment> yes
<comment>Lazy</comment> no
<comment>Synchronized</comment> no
<comment>Abstract</comment> no
<comment>Required File</comment> /path/to/file
<comment>Factory Service</comment> factory.service
<comment>Factory Method</comment> get

View File

@ -0,0 +1,13 @@
<?xml version="1.0" encoding="UTF-8"?>
<definition class="Full\Qualified\Class2" factory-service="factory.service" factory-method="get" scope="container" public="false" synthetic="true" lazy="false" synchronized="false" abstract="false" file="/path/to/file">
<tags>
<tag name="tag1">
<parameter name="attr1">val1</parameter>
<parameter name="attr2">val2</parameter>
</tag>
<tag name="tag1">
<parameter name="attr3">val3</parameter>
</tag>
<tag name="tag2"/>
</tags>
</definition>

View File

@ -12,6 +12,8 @@
namespace Symfony\Bundle\TwigBundle\Command;
use Symfony\Bridge\Twig\Command\DebugCommand as BaseDebugCommand;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\DependencyInjection\ContainerAwareInterface;
@ -52,4 +54,13 @@ class DebugCommand extends BaseDebugCommand implements ContainerAwareInterface
$this->setAliases(array('twig:debug'));
}
protected function execute(InputInterface $input, OutputInterface $output)
{
if (false !== strpos($input->getFirstArgument(), ':d')) {
$output->writeln('<comment>The use of "twig:debug" command is deprecated since version 2.7 and will be removed in 3.0. Use the "debug:twig" instead.</comment>');
}
parent::execute($input, $output);
}
}

View File

@ -13,6 +13,7 @@ namespace Symfony\Bundle\TwigBundle\DependencyInjection\Compiler;
use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\DependencyInjection\Reference;
/**
@ -59,6 +60,10 @@ class ExtensionPass implements CompilerPassInterface
$container->getDefinition('twig.extension.code')->replaceArgument(0, $container->getParameter('templating.helper.code.file_link_format'));
}
if (!$container->has('security.token_storage')) {
$container->getDefinition('twig.app_variable')->addMethodCall('setSecurity', array(new Reference('security.context', ContainerInterface::IGNORE_ON_INVALID_REFERENCE)));
}
if ($container->has('templating')) {
$container->getDefinition('twig.cache_warmer')->addTag('kernel.cache_warmer');

View File

@ -98,7 +98,7 @@ class Definition
*/
public function setFactoryClass($factoryClass)
{
trigger_error('The '.__METHOD__.' is deprecated since version 2.6 and will be removed in 3.0. Use Definition::setFactory() instead.', E_USER_DEPRECATED);
trigger_error('The '.__METHOD__.' method is deprecated since version 2.6 and will be removed in 3.0. Use Definition::setFactory() instead.', E_USER_DEPRECATED);
$this->factoryClass = $factoryClass;
@ -116,7 +116,7 @@ class Definition
public function getFactoryClass($triggerDeprecationError = true)
{
if ($triggerDeprecationError) {
trigger_error('The '.__METHOD__.' is deprecated since version 2.6 and will be removed in 3.0.', E_USER_DEPRECATED);
trigger_error('The '.__METHOD__.' method is deprecated since version 2.6 and will be removed in 3.0.', E_USER_DEPRECATED);
}
return $this->factoryClass;
@ -134,7 +134,7 @@ class Definition
*/
public function setFactoryMethod($factoryMethod)
{
trigger_error('The '.__METHOD__.' is deprecated since version 2.6 and will be removed in 3.0. Use Definition::setFactory() instead.', E_USER_DEPRECATED);
trigger_error('The '.__METHOD__.' method is deprecated since version 2.6 and will be removed in 3.0. Use Definition::setFactory() instead.', E_USER_DEPRECATED);
$this->factoryMethod = $factoryMethod;
@ -187,7 +187,7 @@ class Definition
public function getFactoryMethod($triggerDeprecationError = true)
{
if ($triggerDeprecationError) {
trigger_error('The '.__METHOD__.' is deprecated since version 2.6 and will be removed in 3.0.', E_USER_DEPRECATED);
trigger_error('The '.__METHOD__.' method is deprecated since version 2.6 and will be removed in 3.0.', E_USER_DEPRECATED);
}
return $this->factoryMethod;
@ -205,7 +205,7 @@ class Definition
*/
public function setFactoryService($factoryService)
{
trigger_error('The '.__METHOD__.' is deprecated since version 2.6 and will be removed in 3.0. Use Definition::setFactory() instead.', E_USER_DEPRECATED);
trigger_error('The '.__METHOD__.' method is deprecated since version 2.6 and will be removed in 3.0. Use Definition::setFactory() instead.', E_USER_DEPRECATED);
$this->factoryService = $factoryService;
@ -223,7 +223,7 @@ class Definition
public function getFactoryService($triggerDeprecationError = true)
{
if ($triggerDeprecationError) {
trigger_error('The '.__METHOD__.' is deprecated since version 2.6 and will be removed in 3.0.', E_USER_DEPRECATED);
trigger_error('The '.__METHOD__.' method is deprecated since version 2.6 and will be removed in 3.0.', E_USER_DEPRECATED);
}
return $this->factoryService;
@ -667,7 +667,7 @@ class Definition
public function setSynchronized($boolean, $triggerDeprecationError = true)
{
if ($triggerDeprecationError) {
trigger_error('The '.__METHOD__.' method is deprecated in version 2.7 and will be removed in version 3.0.', E_USER_DEPRECATED);
trigger_error('The '.__METHOD__.' method is deprecated since version 2.7 and will be removed in 3.0.', E_USER_DEPRECATED);
}
$this->synchronized = (bool) $boolean;
@ -687,7 +687,7 @@ class Definition
public function isSynchronized($triggerDeprecationError = true)
{
if ($triggerDeprecationError) {
trigger_error('The '.__METHOD__.' method is deprecated in version 2.7 and will be removed in version 3.0.', E_USER_DEPRECATED);
trigger_error('The '.__METHOD__.' method is deprecated since version 2.7 and will be removed in 3.0.', E_USER_DEPRECATED);
}
return $this->synchronized;

View File

@ -53,8 +53,10 @@ class CheckDefinitionValidityPassTest extends \PHPUnit_Framework_TestCase
/**
* @expectedException \Symfony\Component\DependencyInjection\Exception\RuntimeException
*/
public function testProcessDetectsBothFactorySyntaxesUsed()
public function testLegacyProcessDetectsBothFactorySyntaxesUsed()
{
$this->iniSet('error_reporting', -1 & ~E_USER_DEPRECATED);
$container = new ContainerBuilder();
$container->register('a')->setFactory(array('a', 'b'))->setFactoryClass('a');

View File

@ -44,11 +44,35 @@ class DefinitionDecoratorTest extends \PHPUnit_Framework_TestCase
return array(
array('class', 'class'),
array('factory', 'factory'),
array('configurator', 'configurator'),
array('file', 'file'),
);
}
/**
* @dataProvider provideLegacyPropertyTests
*/
public function testLegacySetProperty($property, $changeKey)
{
$this->iniSet('error_reporting', -1 & ~E_USER_DEPRECATED);
$def = new DefinitionDecorator('foo');
$getter = 'get'.ucfirst($property);
$setter = 'set'.ucfirst($property);
$this->assertNull($def->$getter());
$this->assertSame($def, $def->$setter('foo'));
$this->assertEquals('foo', $def->$getter());
$this->assertEquals(array($changeKey => true), $def->getChanges());
}
public function provideLegacyPropertyTests()
{
return array(
array('factoryClass', 'factory_class'),
array('factoryMethod', 'factory_method'),
array('factoryService', 'factory_service'),
array('configurator', 'configurator'),
array('file', 'file'),
);
}

View File

@ -23,6 +23,13 @@ class GraphvizDumperTest extends \PHPUnit_Framework_TestCase
self::$fixturesPath = __DIR__.'/../Fixtures/';
}
public function testLegacyDump()
{
$container = include self::$fixturesPath.'/containers/legacy-container9.php';
$dumper = new GraphvizDumper($container);
$this->assertEquals(str_replace('%path%', __DIR__, file_get_contents(self::$fixturesPath.'/graphviz/legacy-services9.dot')), $dumper->dump(), '->dump() dumps services');
}
public function testDump()
{
$dumper = new GraphvizDumper($container = new ContainerBuilder());

View File

@ -47,10 +47,31 @@ class XmlDumperTest extends \PHPUnit_Framework_TestCase
$this->assertXmlStringEqualsXmlFile(self::$fixturesPath.'/xml/services8.xml', $dumper->dump(), '->dump() dumps parameters');
}
public function testLegacyAddService()
{
$this->iniSet('error_reporting', -1 & ~E_USER_DEPRECATED);
$container = include self::$fixturesPath.'/containers/legacy-container9.php';
$dumper = new XmlDumper($container);
$this->assertEquals(str_replace('%path%', self::$fixturesPath.DIRECTORY_SEPARATOR.'includes'.DIRECTORY_SEPARATOR, file_get_contents(self::$fixturesPath.'/xml/legacy-services9.xml')), $dumper->dump(), '->dump() dumps services');
$dumper = new XmlDumper($container = new ContainerBuilder());
$container->register('foo', 'FooClass')->addArgument(new \stdClass());
try {
$dumper->dump();
$this->fail('->dump() throws a RuntimeException if the container to be dumped has reference to objects or resources');
} catch (\Exception $e) {
$this->assertInstanceOf('\RuntimeException', $e, '->dump() throws a RuntimeException if the container to be dumped has reference to objects or resources');
$this->assertEquals('Unable to dump a service container if a parameter is an object or a resource.', $e->getMessage(), '->dump() throws a RuntimeException if the container to be dumped has reference to objects or resources');
}
}
public function testAddService()
{
$container = include self::$fixturesPath.'/containers/container9.php';
$dumper = new XmlDumper($container);
$this->assertEquals(str_replace('%path%', self::$fixturesPath.DIRECTORY_SEPARATOR.'includes'.DIRECTORY_SEPARATOR, file_get_contents(self::$fixturesPath.'/xml/services9.xml')), $dumper->dump(), '->dump() dumps services');
$dumper = new XmlDumper($container = new ContainerBuilder());

View File

@ -40,6 +40,26 @@ class YamlDumperTest extends \PHPUnit_Framework_TestCase
$this->assertStringEqualsFile(self::$fixturesPath.'/yaml/services8.yml', $dumper->dump(), '->dump() dumps parameters');
}
public function testLegacyAddService()
{
$this->iniSet('error_reporting', -1 & ~E_USER_DEPRECATED);
$container = include self::$fixturesPath.'/containers/legacy-container9.php';
$dumper = new YamlDumper($container);
$this->assertEquals(str_replace('%path%', self::$fixturesPath.DIRECTORY_SEPARATOR.'includes'.DIRECTORY_SEPARATOR, file_get_contents(self::$fixturesPath.'/yaml/legacy-services9.yml')), $dumper->dump(), '->dump() dumps services');
$dumper = new YamlDumper($container = new ContainerBuilder());
$container->register('foo', 'FooClass')->addArgument(new \stdClass());
try {
$dumper->dump();
$this->fail('->dump() throws a RuntimeException if the container to be dumped has reference to objects or resources');
} catch (\Exception $e) {
$this->assertInstanceOf('\RuntimeException', $e, '->dump() throws a RuntimeException if the container to be dumped has reference to objects or resources');
$this->assertEquals('Unable to dump a service container if a parameter is an object or a resource.', $e->getMessage(), '->dump() throws a RuntimeException if the container to be dumped has reference to objects or resources');
}
}
public function testAddService()
{
$container = include self::$fixturesPath.'/containers/container9.php';

View File

@ -9,33 +9,31 @@ use Symfony\Component\DependencyInjection\Parameter;
use Symfony\Component\ExpressionLanguage\Expression;
$container = new ContainerBuilder();
$container->
register('foo', 'Bar\FooClass')->
addTag('foo', array('foo' => 'foo'))->
addTag('foo', array('bar' => 'bar', 'baz' => 'baz'))->
setFactoryClass('Bar\\FooClass')->
setFactoryMethod('getInstance')->
setArguments(array('foo', new Reference('foo.baz'), array('%foo%' => 'foo is %foo%', 'foobar' => '%foo%'), true, new Reference('service_container')))->
setProperties(array('foo' => 'bar', 'moo' => new Reference('foo.baz'), 'qux' => array('%foo%' => 'foo is %foo%', 'foobar' => '%foo%')))->
addMethodCall('setBar', array(new Reference('bar')))->
addMethodCall('initialize')->
setConfigurator('sc_configure')
$container
->register('foo', 'Bar\FooClass')
->addTag('foo', array('foo' => 'foo'))
->addTag('foo', array('bar' => 'bar', 'baz' => 'baz'))
->setFactory(array('Bar\\FooClass', 'getInstance'))
->setArguments(array('foo', new Reference('foo.baz'), array('%foo%' => 'foo is %foo%', 'foobar' => '%foo%'), true, new Reference('service_container')))
->setProperties(array('foo' => 'bar', 'moo' => new Reference('foo.baz'), 'qux' => array('%foo%' => 'foo is %foo%', 'foobar' => '%foo%')))
->addMethodCall('setBar', array(new Reference('bar')))
->addMethodCall('initialize')
->setConfigurator('sc_configure')
;
$container->
register('bar', 'Bar\FooClass')->
setArguments(array('foo', new Reference('foo.baz'), new Parameter('foo_bar')))->
setScope('container')->
setConfigurator(array(new Reference('foo.baz'), 'configure'))
$container
->register('foo.baz', '%baz_class%')
->setFactory(array('%baz_class%', 'getInstance'))
->setConfigurator(array('%baz_class%', 'configureStatic1'))
;
$container->
register('foo.baz', '%baz_class%')->
setFactoryClass('%baz_class%')->
setFactoryMethod('getInstance')->
setConfigurator(array('%baz_class%', 'configureStatic1'))
$container
->register('bar', 'Bar\FooClass')
->setArguments(array('foo', new Reference('foo.baz'), new Parameter('foo_bar')))
->setScope('container')
->setConfigurator(array(new Reference('foo.baz'), 'configure'))
;
$container->
register('foo_bar', '%foo_class%')->
setScope('prototype')
$container
->register('foo_bar', '%foo_class%')
->setScope('prototype')
;
$container->getParameterBag()->clear();
$container->getParameterBag()->add(array(
@ -45,21 +43,15 @@ $container->getParameterBag()->add(array(
));
$container->setAlias('alias_for_foo', 'foo');
$container->setAlias('alias_for_alias', 'alias_for_foo');
$container->
register('method_call1', 'Bar\FooClass')->
setFile(realpath(__DIR__.'/../includes/foo.php'))->
addMethodCall('setBar', array(new Reference('foo')))->
addMethodCall('setBar', array(new Reference('foo2', ContainerInterface::NULL_ON_INVALID_REFERENCE)))->
addMethodCall('setBar', array(new Reference('foo3', ContainerInterface::IGNORE_ON_INVALID_REFERENCE)))->
addMethodCall('setBar', array(new Reference('foobaz', ContainerInterface::IGNORE_ON_INVALID_REFERENCE)))->
addMethodCall('setBar', array(new Expression('service("foo").foo() ~ (container.hasparameter("foo") ? parameter("foo") : "default")')))
$container
->register('method_call1', 'Bar\FooClass')
->setFile(realpath(__DIR__.'/../includes/foo.php'))
->addMethodCall('setBar', array(new Reference('foo')))
->addMethodCall('setBar', array(new Reference('foo2', ContainerInterface::NULL_ON_INVALID_REFERENCE)))
->addMethodCall('setBar', array(new Reference('foo3', ContainerInterface::IGNORE_ON_INVALID_REFERENCE)))
->addMethodCall('setBar', array(new Reference('foobaz', ContainerInterface::IGNORE_ON_INVALID_REFERENCE)))
->addMethodCall('setBar', array(new Expression('service("foo").foo() ~ (container.hasparameter("foo") ? parameter("foo") : "default")')))
;
$container->
register('factory_service', 'Bar')->
setFactoryService('foo.baz')->
setFactoryMethod('getInstance')
;
$container
->register('foo_with_inline', 'Foo')
->addMethodCall('setBar', array(new Reference('inlined')))
@ -104,6 +96,10 @@ $container
->setScope('container')
->setPublic(false)
;
$container
->register('factory_service', 'Bar')
->setFactory(array(new Reference('foo.baz'), 'getInstance'))
;
$container
->register('new_factory_service', 'FooBarBaz')
->setProperty('foo', 'bar')

View File

@ -0,0 +1,39 @@
<?php
require_once __DIR__.'/../includes/classes.php';
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Reference;
use Symfony\Component\ExpressionLanguage\Expression;
$container = new ContainerBuilder();
$container->
register('foo', 'Bar\FooClass')->
addTag('foo', array('foo' => 'foo'))->
addTag('foo', array('bar' => 'bar'))->
setFactoryClass('Bar\\FooClass')->
setFactoryMethod('getInstance')->
setArguments(array('foo', new Reference('foo.baz'), array('%foo%' => 'foo is %foo%', 'foobar' => '%foo%'), true, new Reference('service_container')))->
setProperties(array('foo' => 'bar', 'moo' => new Reference('foo.baz'), 'qux' => array('%foo%' => 'foo is %foo%', 'foobar' => '%foo%')))->
addMethodCall('setBar', array(new Reference('bar')))->
addMethodCall('initialize')->
setConfigurator('sc_configure')
;
$container->
register('foo.baz', '%baz_class%')->
setFactoryClass('%baz_class%')->
setFactoryMethod('getInstance')->
setConfigurator(array('%baz_class%', 'configureStatic1'))
;
$container->
register('factory_service', 'Bar')->
setFactoryService('foo.baz')->
setFactoryMethod('getInstance')
;
$container->getParameterBag()->clear();
$container->getParameterBag()->add(array(
'baz_class' => 'BazClass',
'foo' => 'bar',
));
return $container;

View File

@ -0,0 +1,15 @@
digraph sc {
ratio="compress"
node [fontsize="11" fontname="Arial" shape="record"];
edge [fontsize="9" fontname="Arial" color="grey" arrowhead="open" arrowsize="0.5"];
node_foo [label="foo\nBar\\FooClass\n", shape=record, fillcolor="#eeeeee", style="filled"];
node_foo_baz [label="foo.baz\nBazClass\n", shape=record, fillcolor="#eeeeee", style="filled"];
node_factory_service [label="factory_service\nBar\n", shape=record, fillcolor="#eeeeee", style="filled"];
node_service_container [label="service_container\nSymfony\\Component\\DependencyInjection\\ContainerBuilder\n", shape=record, fillcolor="#9999ff", style="filled"];
node_bar [label="bar\n\n", shape=record, fillcolor="#ff9999", style="filled"];
node_foo -> node_foo_baz [label="" style="filled"];
node_foo -> node_service_container [label="" style="filled"];
node_foo -> node_foo_baz [label="" style="dashed"];
node_foo -> node_bar [label="setBar()" style="dashed"];
}

View File

@ -4,11 +4,10 @@ digraph sc {
edge [fontsize="9" fontname="Arial" color="grey" arrowhead="open" arrowsize="0.5"];
node_foo [label="foo (alias_for_foo)\nBar\\FooClass\n", shape=record, fillcolor="#eeeeee", style="filled"];
node_bar [label="bar\nBar\\FooClass\n", shape=record, fillcolor="#eeeeee", style="filled"];
node_foo_baz [label="foo.baz\nBazClass\n", shape=record, fillcolor="#eeeeee", style="filled"];
node_bar [label="bar\nBar\\FooClass\n", shape=record, fillcolor="#eeeeee", style="filled"];
node_foo_bar [label="foo_bar\nBar\\FooClass\n", shape=record, fillcolor="#eeeeee", style="dotted"];
node_method_call1 [label="method_call1\nBar\\FooClass\n", shape=record, fillcolor="#eeeeee", style="filled"];
node_factory_service [label="factory_service\nBar\n", shape=record, fillcolor="#eeeeee", style="filled"];
node_foo_with_inline [label="foo_with_inline\nFoo\n", shape=record, fillcolor="#eeeeee", style="filled"];
node_inlined [label="inlined\nBar\n", shape=record, fillcolor="#eeeeee", style="filled"];
node_baz [label="baz\nBaz\n", shape=record, fillcolor="#eeeeee", style="filled"];
@ -19,6 +18,7 @@ digraph sc {
node_decorator_service [label="decorator_service\nstdClass\n", shape=record, fillcolor="#eeeeee", style="filled"];
node_decorator_service_with_name [label="decorator_service_with_name\nstdClass\n", shape=record, fillcolor="#eeeeee", style="filled"];
node_new_factory [label="new_factory\nFactoryClass\n", shape=record, fillcolor="#eeeeee", style="filled"];
node_factory_service [label="factory_service\nBar\n", shape=record, fillcolor="#eeeeee", style="filled"];
node_new_factory_service [label="new_factory_service\nFooBarBaz\n", shape=record, fillcolor="#eeeeee", style="filled"];
node_service_from_static_method [label="service_from_static_method\nBar\\FooClass\n", shape=record, fillcolor="#eeeeee", style="filled"];
node_service_container [label="service_container\nSymfony\\Component\\DependencyInjection\\ContainerBuilder\n", shape=record, fillcolor="#9999ff", style="filled"];

View File

@ -0,0 +1,10 @@
<?xml version="1.0" ?>
<container xmlns="http://symfony.com/schema/dic/services"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://symfony.com/schema/dic/services http://symfony.com/schema/dic/services/services-1.0.xsd">
<services>
<service id="constructor" class="FooClass" factory-method="getInstance" />
<service id="factory_service" factory-method="getInstance" factory-service="baz_factory" />
</services>
</container>

View File

@ -0,0 +1,36 @@
<?xml version="1.0" encoding="utf-8"?>
<container xmlns="http://symfony.com/schema/dic/services" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://symfony.com/schema/dic/services http://symfony.com/schema/dic/services/services-1.0.xsd">
<parameters>
<parameter key="baz_class">BazClass</parameter>
<parameter key="foo">bar</parameter>
</parameters>
<services>
<service id="foo" class="Bar\FooClass" factory-method="getInstance" factory-class="Bar\FooClass">
<tag name="foo" foo="foo"/>
<tag name="foo" bar="bar"/>
<argument>foo</argument>
<argument type="service" id="foo.baz"/>
<argument type="collection">
<argument key="%foo%">foo is %foo%</argument>
<argument key="foobar">%foo%</argument>
</argument>
<argument>true</argument>
<argument type="service" id="service_container"/>
<property name="foo">bar</property>
<property name="moo" type="service" id="foo.baz"/>
<property name="qux" type="collection">
<property key="%foo%">foo is %foo%</property>
<property key="foobar">%foo%</property>
</property>
<call method="setBar">
<argument type="service" id="bar"/>
</call>
<call method="initialize"/>
<configurator function="sc_configure"/>
</service>
<service id="foo.baz" class="%baz_class%" factory-method="getInstance" factory-class="%baz_class%">
<configurator class="%baz_class%" method="configureStatic1"/>
</service>
<service id="factory_service" class="Bar" factory-method="getInstance" factory-service="foo.baz"/>
</services>
</container>

View File

@ -9,7 +9,6 @@
<service id="scope.container" class="FooClass" scope="container" />
<service id="scope.custom" class="FooClass" scope="custom" />
<service id="scope.prototype" class="FooClass" scope="prototype" />
<service id="constructor" class="FooClass" factory-method="getInstance" />
<service id="file" class="FooClass">
<file>%path%/foo.php</file>
</service>
@ -48,7 +47,6 @@
</service>
<service id="alias_for_foo" alias="foo" />
<service id="another_alias_for_foo" alias="foo" public="false" />
<service id="factory_service" factory-method="getInstance" factory-service="baz_factory" />
<service id="request" class="Request" synthetic="true" synchronized="true" lazy="true"/>
<service id="decorator_service" decorates="decorated" />
<service id="decorator_service_with_name" decorates="decorated" decoration-inner-name="decorated.pif-pouf"/>

View File

@ -6,7 +6,7 @@
<parameter key="foo">bar</parameter>
</parameters>
<services>
<service id="foo" class="Bar\FooClass" factory-method="getInstance" factory-class="Bar\FooClass">
<service id="foo" class="Bar\FooClass">
<tag name="foo" foo="foo"/>
<tag name="foo" bar="bar" baz="baz"/>
<argument>foo</argument>
@ -27,17 +27,19 @@
<argument type="service" id="bar"/>
</call>
<call method="initialize"/>
<factory class="Bar\FooClass" method="getInstance"/>
<configurator function="sc_configure"/>
</service>
<service id="foo.baz" class="%baz_class%">
<factory class="%baz_class%" method="getInstance"/>
<configurator class="%baz_class%" method="configureStatic1"/>
</service>
<service id="bar" class="Bar\FooClass">
<argument>foo</argument>
<argument type="service" id="foo.baz"/>
<argument>%foo_bar%</argument>
<configurator service="foo.baz" method="configure"/>
</service>
<service id="foo.baz" class="%baz_class%" factory-method="getInstance" factory-class="%baz_class%">
<configurator class="%baz_class%" method="configureStatic1"/>
</service>
<service id="foo_bar" class="%foo_class%" scope="prototype"/>
<service id="method_call1" class="Bar\FooClass">
<file>%path%foo.php</file>
@ -57,7 +59,6 @@
<argument type="expression">service("foo").foo() ~ (container.hasparameter("foo") ? parameter("foo") : "default")</argument>
</call>
</service>
<service id="factory_service" class="Bar" factory-method="getInstance" factory-service="foo.baz"/>
<service id="foo_with_inline" class="Foo">
<call method="setBar">
<argument type="service" id="inlined"/>
@ -89,6 +90,9 @@
<service id="new_factory" class="FactoryClass" public="false">
<property name="foo">bar</property>
</service>
<service id="factory_service" class="Bar">
<factory service="foo.baz" method="getInstance"/>
</service>
<service id="new_factory_service" class="FooBarBaz">
<property name="foo">bar</property>
<factory service="new_factory" method="getInstance"/>

View File

@ -0,0 +1,3 @@
services:
constructor: { class: FooClass, factory_method: getInstance }
factory_service: { class: BazClass, factory_method: getInstance, factory_service: baz_factory }

View File

@ -0,0 +1,28 @@
parameters:
baz_class: BazClass
foo: bar
services:
foo:
class: Bar\FooClass
tags:
- { name: foo, foo: foo }
- { name: foo, bar: bar }
factory_class: Bar\FooClass
factory_method: getInstance
arguments: [foo, '@foo.baz', { '%foo%': 'foo is %foo%', foobar: '%foo%' }, true, '@service_container']
properties: { foo: bar, moo: '@foo.baz', qux: { '%foo%': 'foo is %foo%', foobar: '%foo%' } }
calls:
- [setBar, ['@bar']]
- [initialize, { }]
configurator: sc_configure
foo.baz:
class: %baz_class%
factory_class: %baz_class%
factory_method: getInstance
configurator: ['%baz_class%', configureStatic1]
factory_service:
class: Bar
factory_method: getInstance
factory_service: foo.baz

View File

@ -4,7 +4,6 @@ services:
scope.container: { class: FooClass, scope: container }
scope.custom: { class: FooClass, scope: custom }
scope.prototype: { class: FooClass, scope: prototype }
constructor: { class: FooClass, factory_method: getInstance }
file: { class: FooClass, file: %path%/foo.php }
arguments: { class: FooClass, arguments: [foo, @foo, [true, false]] }
configurator1: { class: FooClass, configurator: sc_configure }
@ -24,7 +23,6 @@ services:
another_alias_for_foo:
alias: foo
public: false
factory_service: { class: BazClass, factory_method: getInstance, factory_service: baz_factory }
request:
class: Request
synthetic: true

View File

@ -9,24 +9,22 @@ services:
tags:
- { name: foo, foo: foo }
- { name: foo, bar: bar, baz: baz }
factory_class: Bar\FooClass
factory_method: getInstance
arguments: [foo, '@foo.baz', { '%foo%': 'foo is %foo%', foobar: '%foo%' }, true, '@service_container']
properties: { foo: bar, moo: '@foo.baz', qux: { '%foo%': 'foo is %foo%', foobar: '%foo%' } }
calls:
- [setBar, ['@bar']]
- [initialize, { }]
factory: [Bar\FooClass, getInstance]
configurator: sc_configure
foo.baz:
class: %baz_class%
factory: ['%baz_class%', getInstance]
configurator: ['%baz_class%', configureStatic1]
bar:
class: Bar\FooClass
arguments: [foo, '@foo.baz', '%foo_bar%']
configurator: ['@foo.baz', configure]
foo.baz:
class: %baz_class%
factory_class: %baz_class%
factory_method: getInstance
configurator: ['%baz_class%', configureStatic1]
foo_bar:
class: %foo_class%
scope: prototype
@ -40,10 +38,6 @@ services:
- [setBar, ['@?foobaz']]
- [setBar, ['@=service("foo").foo() ~ (container.hasparameter("foo") ? parameter("foo") : "default")']]
factory_service:
class: Bar
factory_method: getInstance
factory_service: foo.baz
foo_with_inline:
class: Foo
calls:
@ -86,6 +80,9 @@ services:
class: FactoryClass
public: false
properties: { foo: bar }
factory_service:
class: Bar
factory: ['@foo.baz', getInstance]
new_factory_service:
class: FooBarBaz
properties: { foo: bar }

View File

@ -191,6 +191,21 @@ class XmlFileLoaderTest extends \PHPUnit_Framework_TestCase
$this->assertEquals('BazClass', $inner->getClass(), '->load() uses the same configuration as for the anonymous ones');
}
public function testLegacyLoadServices()
{
$this->iniSet('error_reporting', -1 & ~E_USER_DEPRECATED);
$container = new ContainerBuilder();
$loader = new XmlFileLoader($container, new FileLocator(self::$fixturesPath.'/xml'));
$loader->load('legacy-services6.xml');
$services = $container->getDefinitions();
$this->assertEquals('FooClass', $services['constructor']->getClass());
$this->assertEquals('getInstance', $services['constructor']->getFactoryMethod());
$this->assertNull($services['factory_service']->getClass());
$this->assertEquals('baz_factory', $services['factory_service']->getFactoryService());
$this->assertEquals('getInstance', $services['factory_service']->getFactoryMethod());
}
public function testLoadServices()
{
$container = new ContainerBuilder();
@ -203,7 +218,6 @@ class XmlFileLoaderTest extends \PHPUnit_Framework_TestCase
$this->assertEquals('container', $services['scope.container']->getScope());
$this->assertEquals('custom', $services['scope.custom']->getScope());
$this->assertEquals('prototype', $services['scope.prototype']->getScope());
$this->assertEquals('getInstance', $services['constructor']->getFactoryMethod(), '->load() parses the factory-method attribute');
$this->assertEquals('%path%/foo.php', $services['file']->getFile(), '->load() parses the file tag');
$this->assertEquals(array('foo', new Reference('foo'), array(true, false)), $services['arguments']->getArguments(), '->load() parses the argument tags');
$this->assertEquals('sc_configure', $services['configurator1']->getConfigurator(), '->load() parses the configurator tag');
@ -211,9 +225,6 @@ class XmlFileLoaderTest extends \PHPUnit_Framework_TestCase
$this->assertEquals(array('BazClass', 'configureStatic'), $services['configurator3']->getConfigurator(), '->load() parses the configurator tag');
$this->assertEquals(array(array('setBar', array()), array('setBar', array(new Expression('service("foo").foo() ~ (container.hasparameter("foo") ? parameter("foo") : "default")')))), $services['method_call1']->getMethodCalls(), '->load() parses the method_call tag');
$this->assertEquals(array(array('setBar', array('foo', new Reference('foo'), array(true, false)))), $services['method_call2']->getMethodCalls(), '->load() parses the method_call tag');
$this->assertNull($services['factory_service']->getClass());
$this->assertEquals('getInstance', $services['factory_service']->getFactoryMethod());
$this->assertEquals('baz_factory', $services['factory_service']->getFactoryService());
$this->assertEquals('factory', $services['new_factory1']->getFactory(), '->load() parses the factory tag');
$this->assertEquals(array(new Reference('baz', ContainerInterface::EXCEPTION_ON_INVALID_REFERENCE, false), 'getClass'), $services['new_factory2']->getFactory(), '->load() parses the factory tag');
$this->assertEquals(array('BazClass', 'getInstance'), $services['new_factory3']->getFactory(), '->load() parses the factory tag');

View File

@ -120,6 +120,19 @@ class YamlFileLoaderTest extends \PHPUnit_Framework_TestCase
$loader->load('services4_bad_import.yml');
}
public function testLegacyLoadServices()
{
$container = new ContainerBuilder();
$loader = new YamlFileLoader($container, new FileLocator(self::$fixturesPath.'/yaml'));
$loader->load('legacy-services6.yml');
$services = $container->getDefinitions();
$this->assertEquals('FooClass', $services['constructor']->getClass());
$this->assertEquals('getInstance', $services['constructor']->getFactoryMethod());
$this->assertEquals('BazClass', $services['factory_service']->getClass());
$this->assertEquals('baz_factory', $services['factory_service']->getFactoryService());
$this->assertEquals('getInstance', $services['factory_service']->getFactoryMethod());
}
public function testLoadServices()
{
$container = new ContainerBuilder();
@ -132,7 +145,6 @@ class YamlFileLoaderTest extends \PHPUnit_Framework_TestCase
$this->assertEquals('container', $services['scope.container']->getScope());
$this->assertEquals('custom', $services['scope.custom']->getScope());
$this->assertEquals('prototype', $services['scope.prototype']->getScope());
$this->assertEquals('getInstance', $services['constructor']->getFactoryMethod(), '->load() parses the factory_method attribute');
$this->assertEquals('%path%/foo.php', $services['file']->getFile(), '->load() parses the file tag');
$this->assertEquals(array('foo', new Reference('foo'), array(true, false)), $services['arguments']->getArguments(), '->load() parses the argument tags');
$this->assertEquals('sc_configure', $services['configurator1']->getConfigurator(), '->load() parses the configurator tag');
@ -140,7 +152,6 @@ class YamlFileLoaderTest extends \PHPUnit_Framework_TestCase
$this->assertEquals(array('BazClass', 'configureStatic'), $services['configurator3']->getConfigurator(), '->load() parses the configurator tag');
$this->assertEquals(array(array('setBar', array()), array('setBar', array()), array('setBar', array(new Expression('service("foo").foo() ~ (container.hasparameter("foo") ? parameter("foo") : "default")')))), $services['method_call1']->getMethodCalls(), '->load() parses the method_call tag');
$this->assertEquals(array(array('setBar', array('foo', new Reference('foo'), array(true, false)))), $services['method_call2']->getMethodCalls(), '->load() parses the method_call tag');
$this->assertEquals('baz_factory', $services['factory_service']->getFactoryService());
$this->assertEquals('factory', $services['new_factory1']->getFactory(), '->load() parses the factory tag');
$this->assertEquals(array(new Reference('baz'), 'getClass'), $services['new_factory2']->getFactory(), '->load() parses the factory tag');
$this->assertEquals(array('BazClass', 'getInstance'), $services['new_factory3']->getFactory(), '->load() parses the factory tag');

View File

@ -146,7 +146,7 @@ class TraceableEventDispatcher implements TraceableEventDispatcherInterface
$allListeners = $this->getListeners();
} catch (\Exception $e) {
if (null !== $this->logger) {
$this->logger->info(sprintf('An exception was thrown while getting the uncalled listeners (%s)', $e->getMessage()), array('exception' => $e));
$this->logger->info('An exception was thrown while getting the uncalled listeners.', array('exception' => $e));
}
// unable to retrieve the uncalled listeners

View File

@ -51,7 +51,7 @@ class ControllerResolver implements ControllerResolverInterface
{
if (!$controller = $request->attributes->get('_controller')) {
if (null !== $this->logger) {
$this->logger->warning('Unable to look for the controller as the "_controller" parameter is missing');
$this->logger->warning('Unable to look for the controller as the "_controller" parameter is missing.');
}
return false;

View File

@ -140,7 +140,7 @@ class RouterListener implements EventSubscriberInterface
}
if (null !== $this->logger) {
$this->logger->info(sprintf('Matched route "%s"', $parameters['_route']), array(
$this->logger->info(sprintf('Matched route "%s".', $parameters['_route']), array(
'route_parameters' => $parameters,
'request_uri' => $request->getUri(),
));

View File

@ -117,7 +117,7 @@ class Profiler
}
if (!($ret = $this->storage->write($profile)) && null !== $this->logger) {
$this->logger->warning('Unable to store the profiler information.');
$this->logger->warning('Unable to store the profiler information.', array('configured_storage' => get_class($this->storage)));
}
return $ret;

View File

@ -20,7 +20,7 @@ class ControllerResolverTest extends \PHPUnit_Framework_TestCase
public function testGetControllerWithoutControllerParameter()
{
$logger = $this->getMock('Psr\Log\LoggerInterface');
$logger->expects($this->once())->method('warning')->with('Unable to look for the controller as the "_controller" parameter is missing');
$logger->expects($this->once())->method('warning')->with('Unable to look for the controller as the "_controller" parameter is missing.');
$resolver = $this->createControllerResolver($logger);
$request = Request::create('/');

View File

@ -64,7 +64,7 @@ class AclVoter implements VoterInterface
if (null === $object) {
if (null !== $this->logger) {
$this->logger->debug(sprintf('Object identity unavailable. Voting to %s', $this->allowIfObjectIdentityUnavailable ? 'grant access' : 'abstain'));
$this->logger->debug(sprintf('Object identity unavailable. Voting to %s.', $this->allowIfObjectIdentityUnavailable ? 'grant access' : 'abstain'));
}
return $this->allowIfObjectIdentityUnavailable ? self::ACCESS_GRANTED : self::ACCESS_ABSTAIN;
@ -79,7 +79,7 @@ class AclVoter implements VoterInterface
$oid = $object;
} elseif (null === $oid = $this->objectIdentityRetrievalStrategy->getObjectIdentity($object)) {
if (null !== $this->logger) {
$this->logger->debug(sprintf('Object identity unavailable. Voting to %s', $this->allowIfObjectIdentityUnavailable ? 'grant access' : 'abstain'));
$this->logger->debug(sprintf('Object identity unavailable. Voting to %s.', $this->allowIfObjectIdentityUnavailable ? 'grant access' : 'abstain'));
}
return $this->allowIfObjectIdentityUnavailable ? self::ACCESS_GRANTED : self::ACCESS_ABSTAIN;
@ -96,13 +96,13 @@ class AclVoter implements VoterInterface
if (null === $field && $acl->isGranted($masks, $sids, false)) {
if (null !== $this->logger) {
$this->logger->debug('ACL found, permission granted. Voting to grant access');
$this->logger->debug('ACL found, permission granted. Voting to grant access.');
}
return self::ACCESS_GRANTED;
} elseif (null !== $field && $acl->isFieldGranted($field, $masks, $sids, false)) {
if (null !== $this->logger) {
$this->logger->debug('ACL found, permission granted. Voting to grant access');
$this->logger->debug('ACL found, permission granted. Voting to grant access.');
}
return self::ACCESS_GRANTED;

View File

@ -92,7 +92,7 @@ class DefaultAuthenticationFailureHandler implements AuthenticationFailureHandle
if ($this->options['failure_forward']) {
if (null !== $this->logger) {
$this->logger->debug(sprintf('Forwarding to %s', $this->options['failure_path']));
$this->logger->debug('Authentication failure, forward triggered.', array('failure_path' => $this->options['failure_path']));
}
$subRequest = $this->httpUtils->createRequest($request, $this->options['failure_path']);
@ -102,7 +102,7 @@ class DefaultAuthenticationFailureHandler implements AuthenticationFailureHandle
}
if (null !== $this->logger) {
$this->logger->debug(sprintf('Redirecting to %s', $this->options['failure_path']));
$this->logger->debug('Authentication failure, redirect triggered.', array('failure_path' => $this->options['failure_path']));
}
$request->getSession()->set(Security::AUTHENTICATION_ERROR, $exception);

View File

@ -57,7 +57,7 @@ class SimpleAuthenticationHandler implements AuthenticationFailureHandlerInterfa
{
if ($this->simpleAuthenticator instanceof AuthenticationSuccessHandlerInterface) {
if ($this->logger) {
$this->logger->debug(sprintf('Using the %s object as authentication success handler', get_class($this->simpleAuthenticator)));
$this->logger->debug('Selected an authentication success handler.', array('handler' => get_class($this->simpleAuthenticator)));
}
$response = $this->simpleAuthenticator->onAuthenticationSuccess($request, $token);
@ -71,7 +71,7 @@ class SimpleAuthenticationHandler implements AuthenticationFailureHandlerInterfa
}
if ($this->logger) {
$this->logger->debug('Fallback to the default authentication success handler');
$this->logger->debug('Fallback to the default authentication success handler.');
}
return $this->successHandler->onAuthenticationSuccess($request, $token);
@ -84,7 +84,7 @@ class SimpleAuthenticationHandler implements AuthenticationFailureHandlerInterfa
{
if ($this->simpleAuthenticator instanceof AuthenticationFailureHandlerInterface) {
if ($this->logger) {
$this->logger->debug(sprintf('Using the %s object as authentication failure handler', get_class($this->simpleAuthenticator)));
$this->logger->debug('Selected an authentication failure handler.', array('handler' => get_class($this->simpleAuthenticator)));
}
$response = $this->simpleAuthenticator->onAuthenticationFailure($request, $exception);
@ -98,7 +98,7 @@ class SimpleAuthenticationHandler implements AuthenticationFailureHandlerInterfa
}
if ($this->logger) {
$this->logger->debug('Fallback to the default authentication failure handler');
$this->logger->debug('Fallback to the default authentication failure handler.');
}
return $this->failureHandler->onAuthenticationFailure($request, $exception);

View File

@ -54,7 +54,7 @@ class DigestAuthenticationEntryPoint implements AuthenticationEntryPointInterfac
}
if (null !== $this->logger) {
$this->logger->debug(sprintf('WWW-Authenticate header sent to user agent: "%s"', $authenticateHeader));
$this->logger->debug('WWW-Authenticate header sent.', array('header' => $authenticateHeader));
}
$response = new Response();

View File

@ -193,7 +193,7 @@ abstract class AbstractAuthenticationListener implements ListenerInterface
private function onFailure(Request $request, AuthenticationException $failed)
{
if (null !== $this->logger) {
$this->logger->info(sprintf('Authentication request failed: %s', $failed->getMessage()));
$this->logger->info('Authentication request failed.', array('exception' => $failed));
}
$token = $this->tokenStorage->getToken();
@ -213,7 +213,7 @@ abstract class AbstractAuthenticationListener implements ListenerInterface
private function onSuccess(Request $request, TokenInterface $token)
{
if (null !== $this->logger) {
$this->logger->info(sprintf('User "%s" has been authenticated successfully', $token->getUsername()));
$this->logger->info('User has been authenticated successfully.', array('username' => $token->getUsername()));
}
$this->tokenStorage->setToken($token);

View File

@ -56,10 +56,6 @@ abstract class AbstractPreAuthenticatedListener implements ListenerInterface
{
$request = $event->getRequest();
if (null !== $this->logger) {
$this->logger->debug(sprintf('Checking secure context token: %s', $this->tokenStorage->getToken()));
}
try {
list($user, $credentials) = $this->getPreAuthenticatedData($request);
} catch (BadCredentialsException $exception) {
@ -68,6 +64,10 @@ abstract class AbstractPreAuthenticatedListener implements ListenerInterface
return;
}
if (null !== $this->logger) {
$this->logger->debug('Checking current security token.', array('token' => (string) $this->tokenStorage->getToken()));
}
if (null !== $token = $this->tokenStorage->getToken()) {
if ($token instanceof PreAuthenticatedToken && $this->providerKey == $token->getProviderKey() && $token->isAuthenticated() && $token->getUsername() === $user) {
return;
@ -75,14 +75,14 @@ abstract class AbstractPreAuthenticatedListener implements ListenerInterface
}
if (null !== $this->logger) {
$this->logger->debug(sprintf('Trying to pre-authenticate user "%s"', $user));
$this->logger->debug('Trying to pre-authenticate user.', array('username' => (string) $user));
}
try {
$token = $this->authenticationManager->authenticate(new PreAuthenticatedToken($user, $credentials, $this->providerKey));
if (null !== $this->logger) {
$this->logger->info(sprintf('Authentication success: %s', $token));
$this->logger->info('Pre-authentication successful.', array('token' => (string) $token));
}
$this->tokenStorage->setToken($token);
@ -107,7 +107,7 @@ abstract class AbstractPreAuthenticatedListener implements ListenerInterface
$this->tokenStorage->setToken(null);
if (null !== $this->logger) {
$this->logger->info(sprintf("Cleared security context due to exception: %s", $exception->getMessage()));
$this->logger->info('Cleared security token due to an exception.', array('exception' => $exception));
}
}
}

View File

@ -59,11 +59,11 @@ class AnonymousAuthenticationListener implements ListenerInterface
$this->tokenStorage->setToken($token);
if (null !== $this->logger) {
$this->logger->info('Populated TokenStorage with an anonymous Token');
$this->logger->info('Populated the TokenStorage with an anonymous Token.');
}
} catch (AuthenticationException $failed) {
if (null !== $this->logger) {
$this->logger->info(sprintf('Anonymous authentication failed: %s', $failed->getMessage()));
$this->logger->info('Anonymous authentication failed.', array('exception' => $failed));
}
}
}

View File

@ -67,7 +67,7 @@ class BasicAuthenticationListener implements ListenerInterface
}
if (null !== $this->logger) {
$this->logger->info(sprintf('Basic Authentication Authorization header found for user "%s"', $username));
$this->logger->info('Basic authentication Authorization header found for user.', array('username' => $username));
}
try {
@ -80,7 +80,7 @@ class BasicAuthenticationListener implements ListenerInterface
}
if (null !== $this->logger) {
$this->logger->info(sprintf('Authentication request failed for user "%s": %s', $username, $failed->getMessage()));
$this->logger->info('Basic authentication failed for user.', array('username' => $username, 'exception' => $failed));
}
if ($this->ignoreFailure) {

View File

@ -44,11 +44,11 @@ class ChannelListener implements ListenerInterface
{
$request = $event->getRequest();
list($attributes, $channel) = $this->map->getPatterns($request);
list(, $channel) = $this->map->getPatterns($request);
if ('https' === $channel && !$request->isSecure()) {
if (null !== $this->logger) {
$this->logger->info('Redirecting to HTTPS');
$this->logger->info('Redirecting to HTTPS.');
}
$response = $this->authenticationEntryPoint->start($request);
@ -60,7 +60,7 @@ class ChannelListener implements ListenerInterface
if ('http' === $channel && $request->isSecure()) {
if (null !== $this->logger) {
$this->logger->info('Redirecting to HTTP');
$this->logger->info('Redirecting to HTTP.');
}
$response = $this->authenticationEntryPoint->start($request);

View File

@ -34,6 +34,7 @@ class ContextListener implements ListenerInterface
{
private $tokenStorage;
private $contextKey;
private $sessionKey;
private $logger;
private $userProviders;
private $dispatcher;
@ -54,12 +55,13 @@ class ContextListener implements ListenerInterface
$this->tokenStorage = $tokenStorage;
$this->userProviders = $userProviders;
$this->contextKey = $contextKey;
$this->sessionKey = '_security_'.$contextKey;
$this->logger = $logger;
$this->dispatcher = $dispatcher;
}
/**
* Reads the SecurityContext from the session.
* Reads the Security Token from the session.
*
* @param GetResponseEvent $event A GetResponseEvent instance
*/
@ -73,7 +75,7 @@ class ContextListener implements ListenerInterface
$request = $event->getRequest();
$session = $request->hasPreviousSession() ? $request->getSession() : null;
if (null === $session || null === $token = $session->get('_security_'.$this->contextKey)) {
if (null === $session || null === $token = $session->get($this->sessionKey)) {
$this->tokenStorage->setToken(null);
return;
@ -82,14 +84,14 @@ class ContextListener implements ListenerInterface
$token = unserialize($token);
if (null !== $this->logger) {
$this->logger->debug('Read SecurityContext from the session');
$this->logger->debug('Read existing security token from the session.', array('key' => $this->sessionKey));
}
if ($token instanceof TokenInterface) {
$token = $this->refreshUser($token);
} elseif (null !== $token) {
if (null !== $this->logger) {
$this->logger->warning(sprintf('Session includes a "%s" where a security token is expected', is_object($token) ? get_class($token) : gettype($token)));
$this->logger->warning('Expected a security token from the session, got something else.', array('key' => $this->sessionKey, 'received' => $token));
}
$token = null;
@ -113,10 +115,6 @@ class ContextListener implements ListenerInterface
return;
}
if (null !== $this->logger) {
$this->logger->debug('Write SecurityContext in the session');
}
$request = $event->getRequest();
$session = $request->getSession();
@ -126,10 +124,14 @@ class ContextListener implements ListenerInterface
if ((null === $token = $this->tokenStorage->getToken()) || ($token instanceof AnonymousToken)) {
if ($request->hasPreviousSession()) {
$session->remove('_security_'.$this->contextKey);
$session->remove($this->sessionKey);
}
} else {
$session->set('_security_'.$this->contextKey, serialize($token));
$session->set($this->sessionKey, serialize($token));
if (null !== $this->logger) {
$this->logger->debug('Stored the security token in the session.', array('key' => $this->sessionKey));
}
}
}
@ -149,17 +151,13 @@ class ContextListener implements ListenerInterface
return $token;
}
if (null !== $this->logger) {
$this->logger->debug(sprintf('Reloading user from user provider.'));
}
foreach ($this->userProviders as $provider) {
try {
$refreshedUser = $provider->refreshUser($user);
$token->setUser($refreshedUser);
if (null !== $this->logger) {
$this->logger->debug(sprintf('Username "%s" was reloaded from user provider.', $refreshedUser->getUsername()));
$this->logger->debug('User was reloaded from a user provider.', array('username' => $refreshedUser->getUsername(), 'provider' => get_class($provider)));
}
return $token;
@ -167,7 +165,7 @@ class ContextListener implements ListenerInterface
// let's try the next user provider
} catch (UsernameNotFoundException $notFound) {
if (null !== $this->logger) {
$this->logger->warning(sprintf('Username "%s" could not be found.', $notFound->getUsername()));
$this->logger->warning('Username could not be found in the selected user provider.', array('username' => $notFound->getUsername(), 'provider' => get_class($provider)));
}
return;

View File

@ -74,7 +74,7 @@ class DigestAuthenticationListener implements ListenerInterface
}
if (null !== $this->logger) {
$this->logger->debug(sprintf('Digest Authorization header received from user agent: %s', $header));
$this->logger->debug('Digest Authorization header received from user agent.', array('header' => $header));
}
try {
@ -89,7 +89,7 @@ class DigestAuthenticationListener implements ListenerInterface
$user = $this->provider->loadUserByUsername($digestAuth->getUsername());
if (null === $user) {
throw new AuthenticationServiceException('AuthenticationDao returned null, which is an interface contract violation');
throw new AuthenticationServiceException('Digest User provider returned null, which is an interface contract violation');
}
$serverDigestMd5 = $digestAuth->calculateServerDigest($user->getPassword(), $request->getMethod());
@ -101,7 +101,7 @@ class DigestAuthenticationListener implements ListenerInterface
if ($serverDigestMd5 !== $digestAuth->getResponse()) {
if (null !== $this->logger) {
$this->logger->debug(sprintf("Expected response: '%s' but received: '%s'; is AuthenticationDao returning clear text passwords?", $serverDigestMd5, $digestAuth->getResponse()));
$this->logger->debug("Unexpected response from the DigestAuth received; is the header returning a clear text passwords?", array('expected' => $serverDigestMd5, 'received' => $digestAuth->getResponse()));
}
$this->fail($event, $request, new BadCredentialsException('Incorrect response'));
@ -116,7 +116,7 @@ class DigestAuthenticationListener implements ListenerInterface
}
if (null !== $this->logger) {
$this->logger->info(sprintf('Authentication success for user "%s" with response "%s"', $digestAuth->getUsername(), $digestAuth->getResponse()));
$this->logger->info('Digest authentication successful.', array('username' => $digestAuth->getUsername(), 'received' => $digestAuth->getResponse()));
}
$this->tokenStorage->setToken(new UsernamePasswordToken($user, $user->getPassword(), $this->providerKey));
@ -130,7 +130,7 @@ class DigestAuthenticationListener implements ListenerInterface
}
if (null !== $this->logger) {
$this->logger->info($authException);
$this->logger->info('Digest authentication failed.', array('exception' => $authException));
}
$event->setResponse($this->authenticationEntryPoint->start($request, $authException));

View File

@ -102,7 +102,7 @@ class ExceptionListener
private function handleAuthenticationException(GetResponseForExceptionEvent $event, AuthenticationException $exception)
{
if (null !== $this->logger) {
$this->logger->info(sprintf('Authentication exception occurred; redirecting to authentication entry point (%s)', $exception->getMessage()));
$this->logger->info('An AuthenticationException was thrown; redirecting to authentication entry point.', array('exception' => $exception));
}
try {
@ -119,7 +119,7 @@ class ExceptionListener
$token = $this->tokenStorage->getToken();
if (!$this->authenticationTrustResolver->isFullFledged($token)) {
if (null !== $this->logger) {
$this->logger->debug(sprintf('Access is denied (user is not fully authenticated) by "%s" at line %s; redirecting to authentication entry point', $exception->getFile(), $exception->getLine()));
$this->logger->debug('Access denied, the user is not fully authenticated; redirecting to authentication entry point.', array('exception' => $exception));
}
try {
@ -135,7 +135,7 @@ class ExceptionListener
}
if (null !== $this->logger) {
$this->logger->debug(sprintf('Access is denied (and user is neither anonymous, nor remember-me) by "%s" at line %s', $exception->getFile(), $exception->getLine()));
$this->logger->debug('Access denied, the user is neither anonymous, nor remember-me.', array('exception' => $exception));
}
try {
@ -153,7 +153,7 @@ class ExceptionListener
}
} catch (\Exception $e) {
if (null !== $this->logger) {
$this->logger->error(sprintf('Exception thrown when handling an exception (%s: %s)', get_class($e), $e->getMessage()));
$this->logger->error('An exception was thrown when handling an AccessDeniedException.', array('exception' => $e));
}
$event->setException(new \RuntimeException('Exception thrown when handling an exception.', 0, $e));
@ -163,7 +163,7 @@ class ExceptionListener
private function handleLogoutException(GetResponseForExceptionEvent $event, LogoutException $exception)
{
if (null !== $this->logger) {
$this->logger->info(sprintf('Logout exception occurred; wrapping with AccessDeniedHttpException (%s)', $exception->getMessage()));
$this->logger->info('A LogoutException was thrown.', array('exception' => $exception));
}
}
@ -182,7 +182,7 @@ class ExceptionListener
}
if (null !== $this->logger) {
$this->logger->debug('Calling Authentication entry point');
$this->logger->debug('Calling Authentication entry point.');
}
$this->setTargetPath($request);
@ -190,6 +190,10 @@ class ExceptionListener
if ($authException instanceof AccountStatusException) {
// remove the security token to prevent infinite redirect loops
$this->tokenStorage->setToken(null);
if (null !== $this->logger) {
$this->logger->info('The security token was removed due to an AccountStatusException.', array('exception' => $authException));
}
}
return $this->authenticationEntryPoint->start($request, $authException);

View File

@ -81,14 +81,14 @@ class RememberMeListener implements ListenerInterface
}
if (null !== $this->logger) {
$this->logger->debug('Token storage populated with remember-me token.');
$this->logger->debug('Populated the token storage with a remember-me token.');
}
} catch (AuthenticationException $failed) {
if (null !== $this->logger) {
$this->logger->warning(
'Token storage not populated with remember-me token as the'
'The token storage was not populated with remember-me token as the'
.' AuthenticationManager rejected the AuthenticationToken returned'
.' by the RememberMeServices: '.$failed->getMessage()
.' by the RememberMeServices.', array('exception' => $failed)
);
}

View File

@ -73,7 +73,7 @@ class SimplePreAuthenticationListener implements ListenerInterface
$request = $event->getRequest();
if (null !== $this->logger) {
$this->logger->info(sprintf('Attempting simple pre-authorization %s', $this->providerKey));
$this->logger->info('Attempting SimplePreAuthentication.', array('key' => $this->providerKey, 'authenticator' => get_class($this->simpleAuthenticator)));
}
if (null !== $this->tokenStorage->getToken() && !$this->tokenStorage->getToken() instanceof AnonymousToken) {
@ -99,7 +99,7 @@ class SimplePreAuthenticationListener implements ListenerInterface
$this->tokenStorage->setToken(null);
if (null !== $this->logger) {
$this->logger->info(sprintf('Authentication request failed: %s', $e->getMessage()));
$this->logger->info('SimplePreAuthentication request failed.', array('exception' => $e, 'authenticator' => get_class($this->simpleAuthenticator)));
}
if ($this->simpleAuthenticator instanceof AuthenticationFailureHandlerInterface) {

View File

@ -127,7 +127,7 @@ class SwitchUserListener implements ListenerInterface
$username = $request->get($this->usernameParameter);
if (null !== $this->logger) {
$this->logger->info(sprintf('Attempt to switch to user "%s"', $username));
$this->logger->info('Attempting to switch to user.', array('username' => $username));
}
$user = $this->provider->loadUserByUsername($username);

View File

@ -137,7 +137,7 @@ abstract class AbstractRememberMeServices implements RememberMeServicesInterface
}
} catch (AuthenticationException $invalid) {
if (null !== $this->logger) {
$this->logger->debug('Remember-Me authentication failed: '.$invalid->getMessage());
$this->logger->debug('Remember-Me authentication failed.', array('exception' => $invalid));
}
}
@ -282,7 +282,7 @@ abstract class AbstractRememberMeServices implements RememberMeServicesInterface
protected function cancelCookie(Request $request)
{
if (null !== $this->logger) {
$this->logger->debug(sprintf('Clearing remember-me cookie "%s"', $this->options['name']));
$this->logger->debug('Clearing remember-me cookie.', array('name' => $this->options['name']));
}
$request->attributes->set(self::COOKIE_ATTR_NAME, new Cookie($this->options['name'], null, 1, $this->options['path'], $this->options['domain']));
@ -304,7 +304,7 @@ abstract class AbstractRememberMeServices implements RememberMeServicesInterface
$parameter = $request->get($this->options['remember_me_parameter'], null, true);
if (null === $parameter && null !== $this->logger) {
$this->logger->debug(sprintf('Did not send remember-me cookie (remember-me parameter "%s" was not sent).', $this->options['remember_me_parameter']));
$this->logger->debug('Did not send remember-me cookie.', array('parameter' => $this->options['remember_me_parameter']));
}
return $parameter === 'true' || $parameter === 'on' || $parameter === '1' || $parameter === 'yes';

View File

@ -105,7 +105,10 @@ class DefaultAuthenticationFailureHandlerTest extends \PHPUnit_Framework_TestCas
public function testRedirectIsLogged()
{
$this->logger->expects($this->once())->method('debug')->with('Redirecting to /login');
$this->logger
->expects($this->once())
->method('debug')
->with('Authentication failure, redirect triggered.', array('failure_path' => '/login'));
$handler = new DefaultAuthenticationFailureHandler($this->httpKernel, $this->httpUtils, array(), $this->logger);
$handler->onAuthenticationFailure($this->request, $this->exception);
@ -119,7 +122,10 @@ class DefaultAuthenticationFailureHandlerTest extends \PHPUnit_Framework_TestCas
->method('createRequest')->with($this->request, '/login')
->will($this->returnValue($this->getRequest()));
$this->logger->expects($this->once())->method('debug')->with('Forwarding to /login');
$this->logger
->expects($this->once())
->method('debug')
->with('Authentication failure, forward triggered.', array('failure_path' => '/login'));
$handler = new DefaultAuthenticationFailureHandler($this->httpKernel, $this->httpUtils, $options, $this->logger);
$handler->onAuthenticationFailure($this->request, $this->exception);

View File

@ -77,7 +77,7 @@ class AnonymousAuthenticationListenerTest extends \PHPUnit_Framework_TestCase
$logger = $this->getMock('Psr\Log\LoggerInterface');
$logger->expects($this->once())
->method('info')
->with('Populated TokenStorage with an anonymous Token')
->with('Populated the TokenStorage with an anonymous Token.')
;
$authenticationManager = $this->getMock('Symfony\Component\Security\Core\Authentication\AuthenticationManagerInterface');

View File

@ -57,10 +57,10 @@ class CacheLoader extends Loader
if (is_file($path)) {
if (null !== $this->logger) {
$this->logger->debug(sprintf('Fetching template "%s" from cache', $template->get('name')));
$this->logger->debug('Fetching template from cache.', array('name' => $template->get('name')));
} elseif (null !== $this->debugger) {
// just for BC, to be removed in 3.0
$this->debugger->log(sprintf('Fetching template "%s" from cache', $template->get('name')));
$this->debugger->log(sprintf('Fetching template "%s" from cache.', $template->get('name')));
}
return new FileStorage($path);
@ -79,10 +79,10 @@ class CacheLoader extends Loader
file_put_contents($path, $content);
if (null !== $this->logger) {
$this->logger->debug(sprintf('Storing template "%s" in cache', $template->get('name')));
$this->logger->debug('Storing template in cache.', array('name' => $template->get('name')));
} elseif (null !== $this->debugger) {
// just for BC, to be removed in 3.0
$this->debugger->log(sprintf('Storing template "%s" in cache', $template->get('name')));
$this->debugger->log(sprintf('Storing template "%s" in cache.', $template->get('name')));
}
return new FileStorage($path);

View File

@ -60,29 +60,31 @@ class FilesystemLoader extends Loader
$replacements['%'.$key.'%'] = $value;
}
$logs = array();
$fileFailures = array();
foreach ($this->templatePathPatterns as $templatePathPattern) {
if (is_file($file = strtr($templatePathPattern, $replacements)) && is_readable($file)) {
if (null !== $this->logger) {
$this->logger->debug(sprintf('Loaded template file "%s"', $file));
$this->logger->debug('Loaded template file.', array('file' => $file));
} elseif (null !== $this->debugger) {
// just for BC, to be removed in 3.0
$this->debugger->log(sprintf('Loaded template file "%s"', $file));
$this->debugger->log(sprintf('Loaded template file "%s".', $file));
}
return new FileStorage($file);
}
if (null !== $this->logger || null !== $this->debugger) {
$logs[] = sprintf('Failed loading template file "%s"', $file);
$fileFailures[] = $file;
}
}
foreach ($logs as $log) {
// only log failures if no template could be loaded at all
foreach ($fileFailures as $file) {
if (null !== $this->logger) {
$this->logger->debug($log);
$this->logger->debug('Failed loading template file.', array('file' => $file));
} elseif (null !== $this->debugger) {
$this->debugger->log($log);
// just for BC, to be removed in 3.0
$this->debugger->log(sprintf('Failed loading template file "%s".', $file));
}
}

View File

@ -35,12 +35,18 @@ class CacheLoaderTest extends \PHPUnit_Framework_TestCase
$this->assertFalse($loader->load(new TemplateReference('foo', 'php')), '->load() returns false if the embed loader is not able to load the template');
$logger = $this->getMock('Psr\Log\LoggerInterface');
$logger->expects($this->once())->method('debug')->with('Storing template "index" in cache');
$logger
->expects($this->once())
->method('debug')
->with('Storing template in cache.', array('name' => 'index'));
$loader->setLogger($logger);
$loader->load(new TemplateReference('index'));
$logger = $this->getMock('Psr\Log\LoggerInterface');
$logger->expects($this->once())->method('debug')->with('Fetching template "index" from cache');
$logger
->expects($this->once())
->method('debug')
->with('Fetching template from cache.', array('name' => 'index'));
$loader->setLogger($logger);
$loader->load(new TemplateReference('index'));
}

View File

@ -90,12 +90,21 @@ class CollectionValidator extends ConstraintValidator
if (!$constraint->allowExtraFields) {
foreach ($value as $field => $fieldValue) {
if (!isset($constraint->fields[$field])) {
$this->buildViolationInContext($context, $constraint->extraFieldsMessage)
->atPath('['.$field.']')
->setParameter('{{ field }}', $this->formatValue($field))
->setInvalidValue($fieldValue)
->setCode(Collection::NO_SUCH_FIELD_ERROR)
->addViolation();
if ($context instanceof ExecutionContextInterface) {
$context->buildViolation($constraint->extraFieldsMessage)
->atPath('['.$field.']')
->setParameter('{{ field }}', $this->formatValue($field))
->setInvalidValue($fieldValue)
->setCode(Collection::NO_SUCH_FIELD_ERROR)
->addViolation();
} else {
$this->buildViolationInContext($context, $constraint->extraFieldsMessage)
->atPath('['.$field.']')
->setParameter('{{ field }}', $this->formatValue($field))
->setInvalidValue($fieldValue)
->setCode(Collection::NO_SUCH_FIELD_ERROR)
->addViolation();
}
}
}
}

View File

@ -35,8 +35,10 @@ class MemberMetadataTest extends \PHPUnit_Framework_TestCase
$this->metadata = null;
}
public function testAddValidSetsMemberToCascaded()
public function testLegacyAddValidSetsMemberToCascaded()
{
$this->iniSet('error_reporting', -1 & ~E_USER_DEPRECATED);
$result = $this->metadata->addConstraint(new Valid());
$this->assertEquals(array(), $this->metadata->getConstraints());
@ -44,8 +46,10 @@ class MemberMetadataTest extends \PHPUnit_Framework_TestCase
$this->assertTrue($this->metadata->isCascaded());
}
public function testAddOtherConstraintDoesNotSetMemberToCascaded()
public function testLegacyAddOtherConstraintDoesNotSetMemberToCascaded()
{
$this->iniSet('error_reporting', -1 & ~E_USER_DEPRECATED);
$result = $this->metadata->addConstraint($constraint = new ConstraintA());
$this->assertEquals(array($constraint), $this->metadata->getConstraints());