From 2397bcbe948b92cdbd0217254493842a38085a07 Mon Sep 17 00:00:00 2001 From: Johannes Schmitt Date: Wed, 13 Apr 2011 00:51:22 +0200 Subject: [PATCH 01/91] [DependencyInjection] better logging --- .../Compiler/CompilerDebugDumpPass.php | 24 ++++++++++++++++ .../FrameworkBundle/FrameworkBundle.php | 3 ++ .../DependencyInjection/Compiler/Compiler.php | 16 +++++++++-- .../Compiler/InlineServiceDefinitionsPass.php | 13 +++++++-- .../Compiler/LoggingFormatter.php | 28 +++++++++++++++++++ .../RemoveAbstractDefinitionsPass.php | 6 +++- .../Compiler/RemovePrivateAliasesPass.php | 6 +++- .../Compiler/RemoveUnusedDefinitionsPass.php | 8 ++++-- 8 files changed, 96 insertions(+), 8 deletions(-) create mode 100644 src/Symfony/Bundle/FrameworkBundle/DependencyInjection/Compiler/CompilerDebugDumpPass.php create mode 100644 src/Symfony/Component/DependencyInjection/Compiler/LoggingFormatter.php diff --git a/src/Symfony/Bundle/FrameworkBundle/DependencyInjection/Compiler/CompilerDebugDumpPass.php b/src/Symfony/Bundle/FrameworkBundle/DependencyInjection/Compiler/CompilerDebugDumpPass.php new file mode 100644 index 0000000000..bb28a56795 --- /dev/null +++ b/src/Symfony/Bundle/FrameworkBundle/DependencyInjection/Compiler/CompilerDebugDumpPass.php @@ -0,0 +1,24 @@ +getCompilerLogFilename($container), false); + $cache->write(serialize($container->getCompiler()->getLog())); + } + + public static function getCompilerLogFilename(ContainerInterface $container) + { + $class = $container->getParameter('kernel.container_class'); + + return $container->getParameter('kernel.cache_dir').'/'.$class.'Compiler.log'; + } +} \ No newline at end of file diff --git a/src/Symfony/Bundle/FrameworkBundle/FrameworkBundle.php b/src/Symfony/Bundle/FrameworkBundle/FrameworkBundle.php index 9dae9332ec..8d84720806 100644 --- a/src/Symfony/Bundle/FrameworkBundle/FrameworkBundle.php +++ b/src/Symfony/Bundle/FrameworkBundle/FrameworkBundle.php @@ -11,6 +11,8 @@ namespace Symfony\Bundle\FrameworkBundle; +use Symfony\Bundle\FrameworkBundle\DependencyInjection\Compiler\CompilerDebugDumpPass; + use Symfony\Bundle\FrameworkBundle\DependencyInjection\Compiler\AddConstraintValidatorsPass; use Symfony\Bundle\FrameworkBundle\DependencyInjection\Compiler\AddFieldFactoryGuessersPass; use Symfony\Bundle\FrameworkBundle\DependencyInjection\Compiler\TemplatingPass; @@ -82,5 +84,6 @@ class FrameworkBundle extends Bundle $container->addCompilerPass(new TranslatorPass()); $container->addCompilerPass(new AddCacheWarmerPass()); $container->addCompilerPass(new ContainerBuilderDebugDumpPass(), PassConfig::TYPE_BEFORE_REMOVING); + $container->addCompilerPass(new CompilerDebugDumpPass(), PassConfig::TYPE_AFTER_REMOVING); } } diff --git a/src/Symfony/Component/DependencyInjection/Compiler/Compiler.php b/src/Symfony/Component/DependencyInjection/Compiler/Compiler.php index bf41c8470d..e7a72d17bf 100644 --- a/src/Symfony/Component/DependencyInjection/Compiler/Compiler.php +++ b/src/Symfony/Component/DependencyInjection/Compiler/Compiler.php @@ -25,6 +25,7 @@ class Compiler private $currentPass; private $currentStartTime; private $log; + private $loggingFormatter; private $serviceReferenceGraph; /** @@ -34,6 +35,7 @@ class Compiler { $this->passConfig = new PassConfig(); $this->serviceReferenceGraph = new ServiceReferenceGraph(); + $this->loggingFormatter = new LoggingFormatter(); $this->log = array(); } @@ -57,6 +59,16 @@ class Compiler return $this->serviceReferenceGraph; } + /** + * Returns the logging formatter which can be used by compilation passes. + * + * @return LoggingFormatter + */ + public function getLoggingFormatter() + { + return $this->loggingFormatter; + } + /** * Adds a pass to the PassConfig. * @@ -71,7 +83,7 @@ class Compiler /** * Adds a log message. * - * @param string $string The log message + * @param string $string The log message */ public function addLogMessage($string) { @@ -91,7 +103,7 @@ class Compiler /** * Run the Compiler and process all Passes. * - * @param ContainerBuilder $container + * @param ContainerBuilder $container */ public function compile(ContainerBuilder $container) { diff --git a/src/Symfony/Component/DependencyInjection/Compiler/InlineServiceDefinitionsPass.php b/src/Symfony/Component/DependencyInjection/Compiler/InlineServiceDefinitionsPass.php index 842a5b3f65..7d891b546a 100644 --- a/src/Symfony/Component/DependencyInjection/Compiler/InlineServiceDefinitionsPass.php +++ b/src/Symfony/Component/DependencyInjection/Compiler/InlineServiceDefinitionsPass.php @@ -25,6 +25,9 @@ class InlineServiceDefinitionsPass implements RepeatablePassInterface { private $repeatedPass; private $graph; + private $compiler; + private $formatter; + private $currentId; /** * {@inheritDoc} @@ -41,9 +44,13 @@ class InlineServiceDefinitionsPass implements RepeatablePassInterface */ public function process(ContainerBuilder $container) { - $this->graph = $container->getCompiler()->getServiceReferenceGraph(); + $this->compiler = $container->getCompiler(); + $this->formatter = $this->compiler->getLoggingFormatter(); + $this->graph = $this->compiler->getServiceReferenceGraph(); + + foreach ($container->getDefinitions() as $id => $definition) { + $this->currentId = $id; - foreach ($container->getDefinitions() as $definition) { $definition->setArguments( $this->inlineArguments($container, $definition->getArguments()) ); @@ -75,6 +82,8 @@ class InlineServiceDefinitionsPass implements RepeatablePassInterface } if ($this->isInlinableDefinition($container, $id, $definition = $container->getDefinition($id))) { + $this->compiler->addLogMessage($this->formatter->formatInlineDefinition($this, $id, $this->currentId)); + if (ContainerInterface::SCOPE_PROTOTYPE !== $definition->getScope()) { $arguments[$k] = $definition; } else { diff --git a/src/Symfony/Component/DependencyInjection/Compiler/LoggingFormatter.php b/src/Symfony/Component/DependencyInjection/Compiler/LoggingFormatter.php new file mode 100644 index 0000000000..06e8466d1f --- /dev/null +++ b/src/Symfony/Component/DependencyInjection/Compiler/LoggingFormatter.php @@ -0,0 +1,28 @@ + + */ +class LoggingFormatter +{ + public function formatRemoveDefinition(CompilerPassInterface $pass, $id, $reason) + { + return $this->format($pass, sprintf('Removed definition "%s"; reason: %s', $id, $reason)); + } + + public function formatInlineDefinition(CompilerPassInterface $pass, $id, $target) + { + return $this->format($pass, sprintf('Inlined definition "%s" to "%s".', $id, $target)); + } + + public function format(CompilerPassInterface $pass, $message) + { + return sprintf('%s: %s', get_class($pass), $message); + } +} \ No newline at end of file diff --git a/src/Symfony/Component/DependencyInjection/Compiler/RemoveAbstractDefinitionsPass.php b/src/Symfony/Component/DependencyInjection/Compiler/RemoveAbstractDefinitionsPass.php index 91882ac942..f3b51f9038 100644 --- a/src/Symfony/Component/DependencyInjection/Compiler/RemoveAbstractDefinitionsPass.php +++ b/src/Symfony/Component/DependencyInjection/Compiler/RemoveAbstractDefinitionsPass.php @@ -13,13 +13,17 @@ class RemoveAbstractDefinitionsPass implements CompilerPassInterface /** * Removes abstract definitions from the ContainerBuilder * - * @param ContainerBuilder $container + * @param ContainerBuilder $container */ public function process(ContainerBuilder $container) { + $compiler = $container->getCompiler(); + $formatter = $compiler->getLoggingFormatter(); + foreach ($container->getDefinitions() as $id => $definition) { if ($definition->isAbstract()) { $container->remove($id); + $compiler->addLogMessage($formatter->formatRemoveDefinition($this, $id, 'abstract')); } } } diff --git a/src/Symfony/Component/DependencyInjection/Compiler/RemovePrivateAliasesPass.php b/src/Symfony/Component/DependencyInjection/Compiler/RemovePrivateAliasesPass.php index 03fb92afa0..72674072cb 100644 --- a/src/Symfony/Component/DependencyInjection/Compiler/RemovePrivateAliasesPass.php +++ b/src/Symfony/Component/DependencyInjection/Compiler/RemovePrivateAliasesPass.php @@ -25,16 +25,20 @@ class RemovePrivateAliasesPass implements CompilerPassInterface /** * Removes private aliases from the ContainerBuilder * - * @param ContainerBuilder $container + * @param ContainerBuilder $container */ public function process(ContainerBuilder $container) { + $compiler = $container->getCompiler(); + $formatter = $compiler->getLoggingFormatter(); + foreach ($container->getAliases() as $id => $alias) { if ($alias->isPublic()) { continue; } $container->removeAlias($id); + $compiler->addLogMessage($formatter->formatRemoveDefinition($this, $id, 'private alias')); } } } \ No newline at end of file diff --git a/src/Symfony/Component/DependencyInjection/Compiler/RemoveUnusedDefinitionsPass.php b/src/Symfony/Component/DependencyInjection/Compiler/RemoveUnusedDefinitionsPass.php index c87e790b72..9b91f6ad8c 100644 --- a/src/Symfony/Component/DependencyInjection/Compiler/RemoveUnusedDefinitionsPass.php +++ b/src/Symfony/Component/DependencyInjection/Compiler/RemoveUnusedDefinitionsPass.php @@ -36,12 +36,14 @@ class RemoveUnusedDefinitionsPass implements RepeatablePassInterface /** * Processes the ContainerBuilder to remove unused definitions. * - * @param ContainerBuilder $container + * @param ContainerBuilder $container * @return void */ public function process(ContainerBuilder $container) { - $graph = $container->getCompiler()->getServiceReferenceGraph(); + $compiler = $container->getCompiler(); + $formatter = $compiler->getLoggingFormatter(); + $graph = $compiler->getServiceReferenceGraph(); $hasChanged = false; foreach ($container->getDefinitions() as $id => $definition) { @@ -71,8 +73,10 @@ class RemoveUnusedDefinitionsPass implements RepeatablePassInterface $container->setDefinition((string) reset($referencingAliases), $definition); $definition->setPublic(true); $container->remove($id); + $compiler->addLogMessage($formatter->formatRemovedDefinition($this, $id, 'replaces alias '.reset($referencingAliases))); } else if (0 === count($referencingAliases) && false === $isReferenced) { $container->remove($id); + $compiler->addLogMessage($formatter->formatRemoveDefinition($this, $id, 'unused')); $hasChanged = true; } } From 672291087c67c8cf0cd173c3ea82266a606a76d9 Mon Sep 17 00:00:00 2001 From: Kris Wallsmith Date: Wed, 13 Apr 2011 05:45:41 -0700 Subject: [PATCH 02/91] removed a lot of special normalization logic in the configuration by using xml values instead of attributes --- .../DependencyInjection/Configuration.php | 35 +++---------------- .../Resources/config/schema/doctrine-1.0.xsd | 14 +++++--- .../Fixtures/config/xml/dbal_types.xml | 2 +- .../Fixtures/config/xml/orm_functions.xml | 6 ++-- .../config/xml/orm_hydration_mode.xml | 2 +- .../DependencyInjection/Configuration.php | 32 +++-------------- .../Resources/config/schema/symfony-1.0.xsd | 13 ++++--- .../DependencyInjection/Fixtures/xml/full.xml | 4 +-- .../Fixtures/xml/validation_annotations.xml | 2 +- .../DependencyInjection/Configuration.php | 7 +--- .../Resources/config/schema/monolog-1.0.xsd | 8 ++--- .../DependencyInjection/Configuration.php | 7 +--- .../Resources/config/schema/twig-1.0.xsd | 6 +--- .../DependencyInjection/Fixtures/xml/full.xml | 4 +-- .../Config/Definition/PrototypedArrayNode.php | 5 +++ 15 files changed, 46 insertions(+), 101 deletions(-) diff --git a/src/Symfony/Bundle/DoctrineBundle/DependencyInjection/Configuration.php b/src/Symfony/Bundle/DoctrineBundle/DependencyInjection/Configuration.php index 10a0324349..86b006d638 100644 --- a/src/Symfony/Bundle/DoctrineBundle/DependencyInjection/Configuration.php +++ b/src/Symfony/Bundle/DoctrineBundle/DependencyInjection/Configuration.php @@ -70,12 +70,7 @@ class Configuration implements ConfigurationInterface ->children() ->arrayNode('types') ->useAttributeAsKey('name') - ->prototype('scalar') - ->beforeNormalization() - ->ifTrue(function($v) { return is_array($v) && isset($v['class']); }) - ->then(function($v) { return $v['class']; }) - ->end() - ->end() + ->prototype('scalar')->end() ->end() ->end() ->fixXmlConfig('connection') @@ -167,12 +162,7 @@ class Configuration implements ConfigurationInterface ->children() ->arrayNode('hydrators') ->useAttributeAsKey('name') - ->prototype('scalar') - ->beforeNormalization() - ->ifTrue(function($v) { return is_array($v) && isset($v['class']); }) - ->then(function($v) { return $v['class']; }) - ->end() - ->end() + ->prototype('scalar')->end() ->end() ->end() ->fixXmlConfig('mapping') @@ -204,30 +194,15 @@ class Configuration implements ConfigurationInterface ->children() ->arrayNode('string_functions') ->useAttributeAsKey('name') - ->prototype('scalar') - ->beforeNormalization() - ->ifTrue(function($v) { return is_array($v) && isset($v['class']); }) - ->then(function($v) { return $v['class']; }) - ->end() - ->end() + ->prototype('scalar')->end() ->end() ->arrayNode('numeric_functions') ->useAttributeAsKey('name') - ->prototype('scalar') - ->beforeNormalization() - ->ifTrue(function($v) { return is_array($v) && isset($v['class']); }) - ->then(function($v) { return $v['class']; }) - ->end() - ->end() + ->prototype('scalar')->end() ->end() ->arrayNode('datetime_functions') ->useAttributeAsKey('name') - ->prototype('scalar') - ->beforeNormalization() - ->ifTrue(function($v) { return is_array($v) && isset($v['class']); }) - ->then(function($v) { return $v['class']; }) - ->end() - ->end() + ->prototype('scalar')->end() ->end() ->end() ->end() diff --git a/src/Symfony/Bundle/DoctrineBundle/Resources/config/schema/doctrine-1.0.xsd b/src/Symfony/Bundle/DoctrineBundle/Resources/config/schema/doctrine-1.0.xsd index e28636b6eb..99021559ee 100644 --- a/src/Symfony/Bundle/DoctrineBundle/Resources/config/schema/doctrine-1.0.xsd +++ b/src/Symfony/Bundle/DoctrineBundle/Resources/config/schema/doctrine-1.0.xsd @@ -43,8 +43,11 @@ - - + + + + + @@ -112,7 +115,10 @@ - - + + + + + diff --git a/src/Symfony/Bundle/DoctrineBundle/Tests/DependencyInjection/Fixtures/config/xml/dbal_types.xml b/src/Symfony/Bundle/DoctrineBundle/Tests/DependencyInjection/Fixtures/config/xml/dbal_types.xml index 7bbad12c7f..368cc890e1 100644 --- a/src/Symfony/Bundle/DoctrineBundle/Tests/DependencyInjection/Fixtures/config/xml/dbal_types.xml +++ b/src/Symfony/Bundle/DoctrineBundle/Tests/DependencyInjection/Fixtures/config/xml/dbal_types.xml @@ -8,7 +8,7 @@ - + Symfony\Bundle\DoctrineBundle\Tests\DependencyInjection\TestType diff --git a/src/Symfony/Bundle/DoctrineBundle/Tests/DependencyInjection/Fixtures/config/xml/orm_functions.xml b/src/Symfony/Bundle/DoctrineBundle/Tests/DependencyInjection/Fixtures/config/xml/orm_functions.xml index b1fd7bd935..07814ab913 100644 --- a/src/Symfony/Bundle/DoctrineBundle/Tests/DependencyInjection/Fixtures/config/xml/orm_functions.xml +++ b/src/Symfony/Bundle/DoctrineBundle/Tests/DependencyInjection/Fixtures/config/xml/orm_functions.xml @@ -12,9 +12,9 @@ - - - + Symfony\Bundle\DoctrineBundle\Tests\DependencyInjection\TestStringFunction + Symfony\Bundle\DoctrineBundle\Tests\DependencyInjection\TestNumericFunction + Symfony\Bundle\DoctrineBundle\Tests\DependencyInjection\TestDatetimeFunction diff --git a/src/Symfony/Bundle/DoctrineBundle/Tests/DependencyInjection/Fixtures/config/xml/orm_hydration_mode.xml b/src/Symfony/Bundle/DoctrineBundle/Tests/DependencyInjection/Fixtures/config/xml/orm_hydration_mode.xml index fc5f393c58..03e8a766de 100644 --- a/src/Symfony/Bundle/DoctrineBundle/Tests/DependencyInjection/Fixtures/config/xml/orm_hydration_mode.xml +++ b/src/Symfony/Bundle/DoctrineBundle/Tests/DependencyInjection/Fixtures/config/xml/orm_hydration_mode.xml @@ -10,7 +10,7 @@ - + Symfony\Bundle\DoctrineBundle\Tests\DependencyInjection\TestHydrator diff --git a/src/Symfony/Bundle/FrameworkBundle/DependencyInjection/Configuration.php b/src/Symfony/Bundle/FrameworkBundle/DependencyInjection/Configuration.php index b6addf9a05..dce083d225 100644 --- a/src/Symfony/Bundle/FrameworkBundle/DependencyInjection/Configuration.php +++ b/src/Symfony/Bundle/FrameworkBundle/DependencyInjection/Configuration.php @@ -195,12 +195,7 @@ class Configuration implements ConfigurationInterface ->ifTrue(function($v){ return !is_array($v); }) ->then(function($v){ return array($v); }) ->end() - ->prototype('scalar') - ->beforeNormalization() - ->ifTrue(function($v) { return is_array($v) && isset($v['value']); }) - ->then(function($v){ return $v['value']; }) - ->end() - ->end() + ->prototype('scalar')->end() ->end() ->scalarNode('cache')->end() ->scalarNode('cache_warmer')->defaultFalse()->end() @@ -213,13 +208,8 @@ class Configuration implements ConfigurationInterface ->beforeNormalization() ->ifTrue(function($v){ return !is_array($v); }) ->then(function($v){ return array($v); }) - ->end() - ->prototype('scalar') - ->beforeNormalization() - ->ifTrue(function($v) { return is_array($v) && isset($v['id']); }) - ->then(function($v){ return $v['id']; }) - ->end() ->end() + ->prototype('scalar')->end() ->end() ->end() ->fixXmlConfig('loader') @@ -237,18 +227,11 @@ class Configuration implements ConfigurationInterface ->arrayNode('packages') ->useAttributeAsKey('name') ->prototype('array') - ->children() - ->scalarNode('version')->defaultNull()->end() - ->end() ->fixXmlConfig('base_url') ->children() + ->scalarNode('version')->defaultNull()->end() ->arrayNode('base_urls') - ->prototype('scalar') - ->beforeNormalization() - ->ifTrue(function($v) { return is_array($v) && isset($v['value']); }) - ->then(function($v){ return $v['value']; }) - ->end() - ->end() + ->prototype('scalar')->end() ->end() ->end() ->end() @@ -300,12 +283,7 @@ class Configuration implements ConfigurationInterface ->children() ->arrayNode('namespaces') ->useAttributeAsKey('prefix') - ->prototype('scalar') - ->beforeNormalization() - ->ifTrue(function($v) { return is_array($v) && isset($v['namespace']); }) - ->then(function($v){ return $v['namespace']; }) - ->end() - ->end() + ->prototype('scalar')->end() ->end() ->end() ->end() diff --git a/src/Symfony/Bundle/FrameworkBundle/Resources/config/schema/symfony-1.0.xsd b/src/Symfony/Bundle/FrameworkBundle/Resources/config/schema/symfony-1.0.xsd index f146f0abb2..326a4f4a87 100644 --- a/src/Symfony/Bundle/FrameworkBundle/Resources/config/schema/symfony-1.0.xsd +++ b/src/Symfony/Bundle/FrameworkBundle/Resources/config/schema/symfony-1.0.xsd @@ -94,7 +94,7 @@ - + @@ -104,10 +104,6 @@ - - - - @@ -133,7 +129,10 @@ - - + + + + + diff --git a/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/Fixtures/xml/full.xml b/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/Fixtures/xml/full.xml index 6bb8b66835..0c4511af8a 100644 --- a/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/Fixtures/xml/full.xml +++ b/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/Fixtures/xml/full.xml @@ -15,8 +15,8 @@ loader.foo loader.bar - - + php + twig http://cdn.example.com http://images1.example.com diff --git a/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/Fixtures/xml/validation_annotations.xml b/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/Fixtures/xml/validation_annotations.xml index 18e058aed6..aef3e01f09 100644 --- a/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/Fixtures/xml/validation_annotations.xml +++ b/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/Fixtures/xml/validation_annotations.xml @@ -8,7 +8,7 @@ - + Application\Validator\Constraints\ diff --git a/src/Symfony/Bundle/MonologBundle/DependencyInjection/Configuration.php b/src/Symfony/Bundle/MonologBundle/DependencyInjection/Configuration.php index 22269be9b1..a6c76a77a2 100644 --- a/src/Symfony/Bundle/MonologBundle/DependencyInjection/Configuration.php +++ b/src/Symfony/Bundle/MonologBundle/DependencyInjection/Configuration.php @@ -96,12 +96,7 @@ class Configuration implements ConfigurationInterface $node ->canBeUnset() ->performNoDeepMerging() - ->prototype('scalar') - ->beforeNormalization() - ->ifTrue(function($v) { return is_array($v) && isset($v['callback']); }) - ->then(function($v){ return $v['callback']; }) - ->end() - ->end() + ->prototype('scalar')->end() ; return $node; diff --git a/src/Symfony/Bundle/MonologBundle/Resources/config/schema/monolog-1.0.xsd b/src/Symfony/Bundle/MonologBundle/Resources/config/schema/monolog-1.0.xsd index ee58895137..8f61e3d39c 100644 --- a/src/Symfony/Bundle/MonologBundle/Resources/config/schema/monolog-1.0.xsd +++ b/src/Symfony/Bundle/MonologBundle/Resources/config/schema/monolog-1.0.xsd @@ -10,13 +10,13 @@ - + - + @@ -34,10 +34,6 @@ - - - - diff --git a/src/Symfony/Bundle/TwigBundle/DependencyInjection/Configuration.php b/src/Symfony/Bundle/TwigBundle/DependencyInjection/Configuration.php index 9e3e5450a6..d22d365f36 100644 --- a/src/Symfony/Bundle/TwigBundle/DependencyInjection/Configuration.php +++ b/src/Symfony/Bundle/TwigBundle/DependencyInjection/Configuration.php @@ -43,12 +43,7 @@ class Configuration implements ConfigurationInterface ->fixXmlConfig('extension') ->children() ->arrayNode('extensions') - ->prototype('scalar') - ->beforeNormalization() - ->ifTrue(function($v) { return is_array($v) && isset($v['id']); }) - ->then(function($v){ return $v['id']; }) - ->end() - ->end() + ->prototype('scalar')->end() ->end() ->end() ; diff --git a/src/Symfony/Bundle/TwigBundle/Resources/config/schema/twig-1.0.xsd b/src/Symfony/Bundle/TwigBundle/Resources/config/schema/twig-1.0.xsd index d972068c7d..f6163abd33 100644 --- a/src/Symfony/Bundle/TwigBundle/Resources/config/schema/twig-1.0.xsd +++ b/src/Symfony/Bundle/TwigBundle/Resources/config/schema/twig-1.0.xsd @@ -11,7 +11,7 @@ - + @@ -36,10 +36,6 @@ - - - - diff --git a/src/Symfony/Bundle/TwigBundle/Tests/DependencyInjection/Fixtures/xml/full.xml b/src/Symfony/Bundle/TwigBundle/Tests/DependencyInjection/Fixtures/xml/full.xml index bd5d8bf8b3..f0355e9bb2 100644 --- a/src/Symfony/Bundle/TwigBundle/Tests/DependencyInjection/Fixtures/xml/full.xml +++ b/src/Symfony/Bundle/TwigBundle/Tests/DependencyInjection/Fixtures/xml/full.xml @@ -12,7 +12,7 @@ 3.14 - - + twig.extension.debug + twig.extension.text diff --git a/src/Symfony/Component/Config/Definition/PrototypedArrayNode.php b/src/Symfony/Component/Config/Definition/PrototypedArrayNode.php index 14d4ed9fce..64048c22ad 100644 --- a/src/Symfony/Component/Config/Definition/PrototypedArrayNode.php +++ b/src/Symfony/Component/Config/Definition/PrototypedArrayNode.php @@ -194,6 +194,11 @@ class PrototypedArrayNode extends ArrayNode if ($this->removeKeyAttribute) { unset($v[$this->keyAttribute]); } + + // if only "value" is left + if (1 == count($v) && isset($v['value'])) { + $v = $v['value']; + } } if (array_key_exists($k, $normalized)) { From db90e0ab8d4f148236598f751c6b43f0d1d9c795 Mon Sep 17 00:00:00 2001 From: Samuel Laulhau Date: Thu, 14 Apr 2011 13:11:03 +0200 Subject: [PATCH 03/91] fix Undefined property: Symfony\Bundle\FrameworkBundle\Command\CacheClearCommand:: --- .../Bundle/FrameworkBundle/Command/CacheClearCommand.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Symfony/Bundle/FrameworkBundle/Command/CacheClearCommand.php b/src/Symfony/Bundle/FrameworkBundle/Command/CacheClearCommand.php index bf1f323685..14ef5f12ca 100644 --- a/src/Symfony/Bundle/FrameworkBundle/Command/CacheClearCommand.php +++ b/src/Symfony/Bundle/FrameworkBundle/Command/CacheClearCommand.php @@ -57,7 +57,7 @@ EOF $oldCacheDir = $realCacheDir.'_old'; if (!is_writable($realCacheDir)) { - throw new \RuntimeException(sprintf('Unable to write in the "%s" directory', $this->realCacheDir)); + throw new \RuntimeException(sprintf('Unable to write in the "%s" directory', $realCacheDir)); } if ($input->getOption('no-warmup')) { From ee05534815220825899fa9a7287af1aa9c79b9a3 Mon Sep 17 00:00:00 2001 From: "Johannes M. Schmitt" Date: Thu, 14 Apr 2011 20:42:19 +0200 Subject: [PATCH 04/91] [DependencyInjection] dump a readable format --- .../DependencyInjection/Compiler/CompilerDebugDumpPass.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Symfony/Bundle/FrameworkBundle/DependencyInjection/Compiler/CompilerDebugDumpPass.php b/src/Symfony/Bundle/FrameworkBundle/DependencyInjection/Compiler/CompilerDebugDumpPass.php index bb28a56795..9d5507082b 100644 --- a/src/Symfony/Bundle/FrameworkBundle/DependencyInjection/Compiler/CompilerDebugDumpPass.php +++ b/src/Symfony/Bundle/FrameworkBundle/DependencyInjection/Compiler/CompilerDebugDumpPass.php @@ -12,7 +12,7 @@ class CompilerDebugDumpPass implements CompilerPassInterface public function process(ContainerBuilder $container) { $cache = new ConfigCache($this->getCompilerLogFilename($container), false); - $cache->write(serialize($container->getCompiler()->getLog())); + $cache->write(implode("\n", $container->getCompiler()->getLog())); } public static function getCompilerLogFilename(ContainerInterface $container) From 6ea9fb16c7128b10977f5f8f13d7a8ddc81e2a25 Mon Sep 17 00:00:00 2001 From: "Johannes M. Schmitt" Date: Thu, 14 Apr 2011 21:01:37 +0200 Subject: [PATCH 05/91] [DependencyInjection] refactored code a bit, added some more logging messages --- .../DependencyInjection/Compiler/Compiler.php | 5 ++++- .../Compiler/InlineServiceDefinitionsPass.php | 2 +- .../Compiler/LoggingFormatter.php | 18 ++++++++++++++---- .../Compiler/RemoveAbstractDefinitionsPass.php | 2 +- .../Compiler/RemovePrivateAliasesPass.php | 2 +- .../Compiler/RemoveUnusedDefinitionsPass.php | 2 +- .../ResolveDefinitionTemplatesPass.php | 6 ++++++ 7 files changed, 28 insertions(+), 9 deletions(-) diff --git a/src/Symfony/Component/DependencyInjection/Compiler/Compiler.php b/src/Symfony/Component/DependencyInjection/Compiler/Compiler.php index e7a72d17bf..87cbf966c9 100644 --- a/src/Symfony/Component/DependencyInjection/Compiler/Compiler.php +++ b/src/Symfony/Component/DependencyInjection/Compiler/Compiler.php @@ -107,11 +107,14 @@ class Compiler */ public function compile(ContainerBuilder $container) { + $start = microtime(true); foreach ($this->passConfig->getPasses() as $pass) { $this->startPass($pass); $pass->process($container); $this->endPass($pass); } + + $this->addLogMessage(sprintf('Compilation finished in %.3fs.', microtime(true) - $start)); } /** @@ -133,6 +136,6 @@ class Compiler private function endPass(CompilerPassInterface $pass) { $this->currentPass = null; - $this->addLogMessage(sprintf('%s finished in %.3fs', get_class($pass), microtime(true) - $this->currentStartTime)); + $this->addLogMessage($this->loggingFormatter->formatPassTime($pass, microtime(true) - $this->currentStartTime)); } } \ No newline at end of file diff --git a/src/Symfony/Component/DependencyInjection/Compiler/InlineServiceDefinitionsPass.php b/src/Symfony/Component/DependencyInjection/Compiler/InlineServiceDefinitionsPass.php index 7d891b546a..1341745119 100644 --- a/src/Symfony/Component/DependencyInjection/Compiler/InlineServiceDefinitionsPass.php +++ b/src/Symfony/Component/DependencyInjection/Compiler/InlineServiceDefinitionsPass.php @@ -82,7 +82,7 @@ class InlineServiceDefinitionsPass implements RepeatablePassInterface } if ($this->isInlinableDefinition($container, $id, $definition = $container->getDefinition($id))) { - $this->compiler->addLogMessage($this->formatter->formatInlineDefinition($this, $id, $this->currentId)); + $this->compiler->addLogMessage($this->formatter->formatInlineService($this, $id, $this->currentId)); if (ContainerInterface::SCOPE_PROTOTYPE !== $definition->getScope()) { $arguments[$k] = $definition; diff --git a/src/Symfony/Component/DependencyInjection/Compiler/LoggingFormatter.php b/src/Symfony/Component/DependencyInjection/Compiler/LoggingFormatter.php index 06e8466d1f..63171acf86 100644 --- a/src/Symfony/Component/DependencyInjection/Compiler/LoggingFormatter.php +++ b/src/Symfony/Component/DependencyInjection/Compiler/LoggingFormatter.php @@ -11,14 +11,24 @@ use Symfony\Component\DependencyInjection\Definition; */ class LoggingFormatter { - public function formatRemoveDefinition(CompilerPassInterface $pass, $id, $reason) + public function formatRemoveService(CompilerPassInterface $pass, $id, $reason) { - return $this->format($pass, sprintf('Removed definition "%s"; reason: %s', $id, $reason)); + return $this->format($pass, sprintf('Removed service "%s"; reason: %s', $id, $reason)); } - public function formatInlineDefinition(CompilerPassInterface $pass, $id, $target) + public function formatInlineService(CompilerPassInterface $pass, $id, $target) { - return $this->format($pass, sprintf('Inlined definition "%s" to "%s".', $id, $target)); + return $this->format($pass, sprintf('Inlined service "%s" to "%s".', $id, $target)); + } + + public function formatResolveInheritance(CompilerPassInterface $pass, $childId, $parentId) + { + return $this->format($pass, sprintf('Resolving inheritance for "%s" (parent: %s).', $childId, $parentId)); + } + + public function formatPassTime(CompilerPassInterface $pass, $time) + { + return $this->format($pass, sprintf('finished in %.3fs.', $time)); } public function format(CompilerPassInterface $pass, $message) diff --git a/src/Symfony/Component/DependencyInjection/Compiler/RemoveAbstractDefinitionsPass.php b/src/Symfony/Component/DependencyInjection/Compiler/RemoveAbstractDefinitionsPass.php index f3b51f9038..c0657b3789 100644 --- a/src/Symfony/Component/DependencyInjection/Compiler/RemoveAbstractDefinitionsPass.php +++ b/src/Symfony/Component/DependencyInjection/Compiler/RemoveAbstractDefinitionsPass.php @@ -23,7 +23,7 @@ class RemoveAbstractDefinitionsPass implements CompilerPassInterface foreach ($container->getDefinitions() as $id => $definition) { if ($definition->isAbstract()) { $container->remove($id); - $compiler->addLogMessage($formatter->formatRemoveDefinition($this, $id, 'abstract')); + $compiler->addLogMessage($formatter->formatRemoveService($this, $id, 'abstract')); } } } diff --git a/src/Symfony/Component/DependencyInjection/Compiler/RemovePrivateAliasesPass.php b/src/Symfony/Component/DependencyInjection/Compiler/RemovePrivateAliasesPass.php index 72674072cb..5b7d36289f 100644 --- a/src/Symfony/Component/DependencyInjection/Compiler/RemovePrivateAliasesPass.php +++ b/src/Symfony/Component/DependencyInjection/Compiler/RemovePrivateAliasesPass.php @@ -38,7 +38,7 @@ class RemovePrivateAliasesPass implements CompilerPassInterface } $container->removeAlias($id); - $compiler->addLogMessage($formatter->formatRemoveDefinition($this, $id, 'private alias')); + $compiler->addLogMessage($formatter->formatRemoveService($this, $id, 'private alias')); } } } \ No newline at end of file diff --git a/src/Symfony/Component/DependencyInjection/Compiler/RemoveUnusedDefinitionsPass.php b/src/Symfony/Component/DependencyInjection/Compiler/RemoveUnusedDefinitionsPass.php index 9b91f6ad8c..f3a3556015 100644 --- a/src/Symfony/Component/DependencyInjection/Compiler/RemoveUnusedDefinitionsPass.php +++ b/src/Symfony/Component/DependencyInjection/Compiler/RemoveUnusedDefinitionsPass.php @@ -76,7 +76,7 @@ class RemoveUnusedDefinitionsPass implements RepeatablePassInterface $compiler->addLogMessage($formatter->formatRemovedDefinition($this, $id, 'replaces alias '.reset($referencingAliases))); } else if (0 === count($referencingAliases) && false === $isReferenced) { $container->remove($id); - $compiler->addLogMessage($formatter->formatRemoveDefinition($this, $id, 'unused')); + $compiler->addLogMessage($formatter->formatRemoveService($this, $id, 'unused')); $hasChanged = true; } } diff --git a/src/Symfony/Component/DependencyInjection/Compiler/ResolveDefinitionTemplatesPass.php b/src/Symfony/Component/DependencyInjection/Compiler/ResolveDefinitionTemplatesPass.php index a19370e1ec..f253a8f94e 100644 --- a/src/Symfony/Component/DependencyInjection/Compiler/ResolveDefinitionTemplatesPass.php +++ b/src/Symfony/Component/DependencyInjection/Compiler/ResolveDefinitionTemplatesPass.php @@ -15,6 +15,8 @@ use Symfony\Component\DependencyInjection\ContainerBuilder; class ResolveDefinitionTemplatesPass implements CompilerPassInterface { private $container; + private $compiler; + private $formatter; /** * Process the ContainerBuilder to replace DefinitionDecorator instances with their real Definition instances. @@ -24,6 +26,9 @@ class ResolveDefinitionTemplatesPass implements CompilerPassInterface public function process(ContainerBuilder $container) { $this->container = $container; + $this->compiler = $container->getCompiler(); + $this->formatter = $this->compiler->getLoggingFormatter(); + foreach (array_keys($container->getDefinitions()) as $id) { // yes, we are specifically fetching the definition from the // container to ensure we are not operating on stale data @@ -54,6 +59,7 @@ class ResolveDefinitionTemplatesPass implements CompilerPassInterface $parentDef = $this->resolveDefinition($parent, $parentDef); } + $this->compiler->addLogMessage($this->formatter->formatResolveInheritance($this, $id, $parent)); $def = new Definition(); // merge in parent definition From e5b6ce1d084ddd59be27646a0128247caeba30c2 Mon Sep 17 00:00:00 2001 From: "Johannes M. Schmitt" Date: Thu, 14 Apr 2011 21:04:45 +0200 Subject: [PATCH 06/91] [FrameworkBundle] whitespace fix --- src/Symfony/Bundle/FrameworkBundle/FrameworkBundle.php | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/src/Symfony/Bundle/FrameworkBundle/FrameworkBundle.php b/src/Symfony/Bundle/FrameworkBundle/FrameworkBundle.php index 8d84720806..1688fa0832 100644 --- a/src/Symfony/Bundle/FrameworkBundle/FrameworkBundle.php +++ b/src/Symfony/Bundle/FrameworkBundle/FrameworkBundle.php @@ -11,8 +11,6 @@ namespace Symfony\Bundle\FrameworkBundle; -use Symfony\Bundle\FrameworkBundle\DependencyInjection\Compiler\CompilerDebugDumpPass; - use Symfony\Bundle\FrameworkBundle\DependencyInjection\Compiler\AddConstraintValidatorsPass; use Symfony\Bundle\FrameworkBundle\DependencyInjection\Compiler\AddFieldFactoryGuessersPass; use Symfony\Bundle\FrameworkBundle\DependencyInjection\Compiler\TemplatingPass; @@ -24,6 +22,7 @@ use Symfony\Bundle\FrameworkBundle\DependencyInjection\Compiler\AddClassesToAuto use Symfony\Bundle\FrameworkBundle\DependencyInjection\Compiler\TranslatorPass; use Symfony\Bundle\FrameworkBundle\DependencyInjection\Compiler\AddCacheWarmerPass; use Symfony\Bundle\FrameworkBundle\DependencyInjection\Compiler\ContainerBuilderDebugDumpPass; +use Symfony\Bundle\FrameworkBundle\DependencyInjection\Compiler\CompilerDebugDumpPass; use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\DependencyInjection\Compiler\PassConfig; use Symfony\Component\DependencyInjection\Scope; From 75ac0f5dc3438649fdda5d58d17d73ded53c9224 Mon Sep 17 00:00:00 2001 From: "Johannes M. Schmitt" Date: Thu, 14 Apr 2011 21:07:16 +0200 Subject: [PATCH 07/91] [DependencyInjection] fixed method name --- .../Compiler/RemoveUnusedDefinitionsPass.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Symfony/Component/DependencyInjection/Compiler/RemoveUnusedDefinitionsPass.php b/src/Symfony/Component/DependencyInjection/Compiler/RemoveUnusedDefinitionsPass.php index f3a3556015..1ad361d612 100644 --- a/src/Symfony/Component/DependencyInjection/Compiler/RemoveUnusedDefinitionsPass.php +++ b/src/Symfony/Component/DependencyInjection/Compiler/RemoveUnusedDefinitionsPass.php @@ -73,7 +73,7 @@ class RemoveUnusedDefinitionsPass implements RepeatablePassInterface $container->setDefinition((string) reset($referencingAliases), $definition); $definition->setPublic(true); $container->remove($id); - $compiler->addLogMessage($formatter->formatRemovedDefinition($this, $id, 'replaces alias '.reset($referencingAliases))); + $compiler->addLogMessage($formatter->formatRemoveService($this, $id, 'replaces alias '.reset($referencingAliases))); } else if (0 === count($referencingAliases) && false === $isReferenced) { $container->remove($id); $compiler->addLogMessage($formatter->formatRemoveService($this, $id, 'unused')); From 1992c3b96dabfcff0f809137e2e08c3dbac484bc Mon Sep 17 00:00:00 2001 From: "Johannes M. Schmitt" Date: Thu, 14 Apr 2011 21:29:46 +0200 Subject: [PATCH 08/91] [DependencyInjection] fixes a bug which might have occurred when using property injection under certain circumstances --- .../Compiler/LoggingFormatter.php | 5 +++++ .../ReplaceAliasByActualDefinitionPass.php | 18 ++++++++++++++++-- 2 files changed, 21 insertions(+), 2 deletions(-) diff --git a/src/Symfony/Component/DependencyInjection/Compiler/LoggingFormatter.php b/src/Symfony/Component/DependencyInjection/Compiler/LoggingFormatter.php index 63171acf86..57a1af54d6 100644 --- a/src/Symfony/Component/DependencyInjection/Compiler/LoggingFormatter.php +++ b/src/Symfony/Component/DependencyInjection/Compiler/LoggingFormatter.php @@ -21,6 +21,11 @@ class LoggingFormatter return $this->format($pass, sprintf('Inlined service "%s" to "%s".', $id, $target)); } + public function formatUpdateReference(CompilerPassInterface $pass, $serviceId, $oldDestId, $newDestId) + { + return $this->format($pass, sprintf('Changed reference of service "%s" previously pointing to "%s" to "%s".', $serviceId, $oldDestId, $newDestId)); + } + public function formatResolveInheritance(CompilerPassInterface $pass, $childId, $parentId) { return $this->format($pass, sprintf('Resolving inheritance for "%s" (parent: %s).', $childId, $parentId)); diff --git a/src/Symfony/Component/DependencyInjection/Compiler/ReplaceAliasByActualDefinitionPass.php b/src/Symfony/Component/DependencyInjection/Compiler/ReplaceAliasByActualDefinitionPass.php index 509e9746db..61c4a1f2db 100644 --- a/src/Symfony/Component/DependencyInjection/Compiler/ReplaceAliasByActualDefinitionPass.php +++ b/src/Symfony/Component/DependencyInjection/Compiler/ReplaceAliasByActualDefinitionPass.php @@ -22,13 +22,20 @@ use Symfony\Component\DependencyInjection\Reference; */ class ReplaceAliasByActualDefinitionPass implements CompilerPassInterface { + private $compiler; + private $formatter; + private $sourceId; + /** * Process the Container to replace aliases with service definitions. * - * @param ContainerBuilder $container + * @param ContainerBuilder $container */ public function process(ContainerBuilder $container) { + $this->compiler = $container->getCompiler(); + $this->formatter = $this->compiler->getLoggingFormatter(); + foreach ($container->getAliases() as $id => $alias) { $aliasId = (string) $alias; @@ -67,7 +74,9 @@ class ReplaceAliasByActualDefinitionPass implements CompilerPassInterface } } - foreach ($container->getDefinitions() as $definition) { + foreach ($container->getDefinitions() as $id => $definition) { + $this->sourceId = $id; + $definition->setArguments( $this->updateArgumentReferences($definition->getArguments(), $currentId, $newId) ); @@ -75,6 +84,10 @@ class ReplaceAliasByActualDefinitionPass implements CompilerPassInterface $definition->setMethodCalls( $this->updateArgumentReferences($definition->getMethodCalls(), $currentId, $newId) ); + + $definition->setProperties( + $this->updateArgumentReferences($definition->getProperties(), $currentId, $newId) + ); } } @@ -93,6 +106,7 @@ class ReplaceAliasByActualDefinitionPass implements CompilerPassInterface } else if ($argument instanceof Reference) { if ($currentId === (string) $argument) { $arguments[$k] = new Reference($newId, $argument->getInvalidBehavior()); + $this->compiler->addLogMessage($this->formatter->formatUpdateReference($this, $this->sourceId, $currentId, $newId)); } } } From 6d7a9d752dafefe64d9b31bfca3ace77e96af380 Mon Sep 17 00:00:00 2001 From: Johannes Schmitt Date: Fri, 15 Apr 2011 00:11:50 +0200 Subject: [PATCH 09/91] [DependencyInjection] adds emulation of "exception-on-invalid-reference" behavior This pass requires that all of references are valid at the end of the compilation process. --- UPDATE.md | 5 ++ .../Debug/TraceableEventDispatcher.php | 4 +- ...xceptionOnInvalidReferenceBehaviorPass.php | 46 +++++++++++++++++++ .../Compiler/PassConfig.php | 1 + .../DependencyInjection/Container.php | 3 +- .../Exception/NonExistentServiceException.php | 38 +++++++++++++++ ...tionOnInvalidReferenceBehaviorPassTest.php | 42 +++++++++++++++++ .../DependencyInjection/ContainerTest.php | 3 +- 8 files changed, 137 insertions(+), 5 deletions(-) create mode 100644 src/Symfony/Component/DependencyInjection/Compiler/CheckExceptionOnInvalidReferenceBehaviorPass.php create mode 100644 src/Symfony/Component/DependencyInjection/Exception/NonExistentServiceException.php create mode 100644 tests/Symfony/Tests/Component/DependencyInjection/Compiler/CheckExceptionOnInvalidReferenceBehaviorPassTest.php diff --git a/UPDATE.md b/UPDATE.md index a4c65143aa..38664a4f34 100644 --- a/UPDATE.md +++ b/UPDATE.md @@ -20,6 +20,11 @@ PR11 to PR12 MyBundle +* The Dependency Injection Container now strongly validates the references of + all your services at the end of its compilation process. If you have invalid + references this will result in a compile-time exception instead of a run-time + exception (the previous behavior). + PR10 to PR11 ------------ diff --git a/src/Symfony/Bundle/FrameworkBundle/Debug/TraceableEventDispatcher.php b/src/Symfony/Bundle/FrameworkBundle/Debug/TraceableEventDispatcher.php index fc94368cd9..bdea0f0456 100644 --- a/src/Symfony/Bundle/FrameworkBundle/Debug/TraceableEventDispatcher.php +++ b/src/Symfony/Bundle/FrameworkBundle/Debug/TraceableEventDispatcher.php @@ -123,10 +123,10 @@ class TraceableEventDispatcher extends ContainerAwareEventDispatcher implements /** * Returns information about the listener - * + * * @param object $listener The listener * @param string $eventName The event name - * + * * @return array Informations about the listener */ private function getListenerInfo($listener, $eventName) diff --git a/src/Symfony/Component/DependencyInjection/Compiler/CheckExceptionOnInvalidReferenceBehaviorPass.php b/src/Symfony/Component/DependencyInjection/Compiler/CheckExceptionOnInvalidReferenceBehaviorPass.php new file mode 100644 index 0000000000..39894dbc8b --- /dev/null +++ b/src/Symfony/Component/DependencyInjection/Compiler/CheckExceptionOnInvalidReferenceBehaviorPass.php @@ -0,0 +1,46 @@ + + */ +class CheckExceptionOnInvalidReferenceBehaviorPass implements CompilerPassInterface +{ + private $container; + private $sourceId; + + public function process(ContainerBuilder $container) + { + $this->container = $container; + + foreach ($container->getDefinitions() as $id => $definition) { + $this->sourceId = $id; + $this->processReferences($definition->getArguments()); + $this->processReferences($definition->getMethodCalls()); + $this->processReferences($definition->getProperties()); + } + } + + private function processReferences(array $arguments) + { + foreach ($arguments as $argument) { + if (is_array($argument)) { + $this->processReferences($argument); + } else if ($argument instanceof Reference && ContainerInterface::EXCEPTION_ON_INVALID_REFERENCE === $argument->getInvalidBehavior()) { + $destId = (string) $argument; + + if (!$this->container->has($destId)) { + throw new NonExistentServiceException($destId, $this->sourceId); + } + } + } + } +} \ No newline at end of file diff --git a/src/Symfony/Component/DependencyInjection/Compiler/PassConfig.php b/src/Symfony/Component/DependencyInjection/Compiler/PassConfig.php index b340c38616..fc48e0b25f 100644 --- a/src/Symfony/Component/DependencyInjection/Compiler/PassConfig.php +++ b/src/Symfony/Component/DependencyInjection/Compiler/PassConfig.php @@ -66,6 +66,7 @@ class PassConfig new AnalyzeServiceReferencesPass(), new RemoveUnusedDefinitionsPass(), )), + new CheckExceptionOnInvalidReferenceBehaviorPass(), ); } diff --git a/src/Symfony/Component/DependencyInjection/Container.php b/src/Symfony/Component/DependencyInjection/Container.php index 1cd5733aaa..06f05cbbd5 100644 --- a/src/Symfony/Component/DependencyInjection/Container.php +++ b/src/Symfony/Component/DependencyInjection/Container.php @@ -11,6 +11,7 @@ namespace Symfony\Component\DependencyInjection; +use Symfony\Component\DependencyInjection\Exception\NonExistentServiceException; use Symfony\Component\DependencyInjection\Exception\CircularReferenceException; use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface; use Symfony\Component\DependencyInjection\ParameterBag\ParameterBag; @@ -237,7 +238,7 @@ class Container implements ContainerInterface } if (self::EXCEPTION_ON_INVALID_REFERENCE === $invalidBehavior) { - throw new \InvalidArgumentException(sprintf('The service "%s" does not exist.', $id)); + throw new NonExistentServiceException($id); } } diff --git a/src/Symfony/Component/DependencyInjection/Exception/NonExistentServiceException.php b/src/Symfony/Component/DependencyInjection/Exception/NonExistentServiceException.php new file mode 100644 index 0000000000..ee42ea9972 --- /dev/null +++ b/src/Symfony/Component/DependencyInjection/Exception/NonExistentServiceException.php @@ -0,0 +1,38 @@ + + */ +class NonExistentServiceException extends InvalidArgumentException +{ + private $id; + private $sourceId; + + public function __construct($id, $sourceId = null) + { + if (null === $sourceId) { + $msg = sprintf('You have requested a non-existent service "%s".', $id); + } else { + $msg = sprintf('The service "%s" has a dependency on a non-existent service "%s".', $sourceId, $id); + } + + parent::__construct($msg); + + $this->id = $id; + $this->sourceId = $sourceId; + } + + public function getId() + { + return $this->id; + } + + public function getSourceId() + { + return $this->sourceId; + } +} \ No newline at end of file diff --git a/tests/Symfony/Tests/Component/DependencyInjection/Compiler/CheckExceptionOnInvalidReferenceBehaviorPassTest.php b/tests/Symfony/Tests/Component/DependencyInjection/Compiler/CheckExceptionOnInvalidReferenceBehaviorPassTest.php new file mode 100644 index 0000000000..9a5f8cae3c --- /dev/null +++ b/tests/Symfony/Tests/Component/DependencyInjection/Compiler/CheckExceptionOnInvalidReferenceBehaviorPassTest.php @@ -0,0 +1,42 @@ +register('a', '\stdClass') + ->addArgument(new Reference('b')) + ; + $container->register('b', '\stdClass'); + } + + /** + * @expectedException Symfony\Component\DependencyInjection\Exception\NonExistentServiceException + */ + public function testProcessThrowsExceptionOnInvalidReference() + { + $container = new ContainerBuilder(); + + $container + ->register('a', '\stdClass') + ->addArgument(new Reference('b')) + ; + + $this->process($container); + } + + private function process(ContainerBuilder $container) + { + $pass = new CheckExceptionOnInvalidReferenceBehaviorPass(); + $pass->process($container); + } +} \ No newline at end of file diff --git a/tests/Symfony/Tests/Component/DependencyInjection/ContainerTest.php b/tests/Symfony/Tests/Component/DependencyInjection/ContainerTest.php index 5dc890b433..fc307babbb 100644 --- a/tests/Symfony/Tests/Component/DependencyInjection/ContainerTest.php +++ b/tests/Symfony/Tests/Component/DependencyInjection/ContainerTest.php @@ -161,8 +161,7 @@ class ContainerTest extends \PHPUnit_Framework_TestCase $sc->get(''); $this->fail('->get() throws a \InvalidArgumentException exception if the service is empty'); } catch (\Exception $e) { - $this->assertInstanceOf('\InvalidArgumentException', $e, '->get() throws a \InvalidArgumentException exception if the service is empty'); - $this->assertEquals('The service "" does not exist.', $e->getMessage(), '->get() throws a \InvalidArgumentException exception if the service is empty'); + $this->assertInstanceOf('Symfony\Component\DependencyInjection\Exception\NonExistentServiceException', $e, '->get() throws a NonExistentServiceException exception if the service is empty'); } $this->assertNull($sc->get('', ContainerInterface::NULL_ON_INVALID_REFERENCE)); } From ff41541d456906234756867838384f7caf771098 Mon Sep 17 00:00:00 2001 From: Johannes Schmitt Date: Fri, 15 Apr 2011 08:19:28 +0200 Subject: [PATCH 10/91] [DependencyInjection] removed pass time --- .../DependencyInjection/Compiler/Compiler.php | 26 ------------------- .../Compiler/LoggingFormatter.php | 5 ---- 2 files changed, 31 deletions(-) diff --git a/src/Symfony/Component/DependencyInjection/Compiler/Compiler.php b/src/Symfony/Component/DependencyInjection/Compiler/Compiler.php index 87cbf966c9..9c0adf6c50 100644 --- a/src/Symfony/Component/DependencyInjection/Compiler/Compiler.php +++ b/src/Symfony/Component/DependencyInjection/Compiler/Compiler.php @@ -22,8 +22,6 @@ use Symfony\Component\DependencyInjection\Compiler\PassConfig; class Compiler { private $passConfig; - private $currentPass; - private $currentStartTime; private $log; private $loggingFormatter; private $serviceReferenceGraph; @@ -109,33 +107,9 @@ class Compiler { $start = microtime(true); foreach ($this->passConfig->getPasses() as $pass) { - $this->startPass($pass); $pass->process($container); - $this->endPass($pass); } $this->addLogMessage(sprintf('Compilation finished in %.3fs.', microtime(true) - $start)); } - - /** - * Starts an individual pass. - * - * @param CompilerPassInterface $pass The pass to start - */ - private function startPass(CompilerPassInterface $pass) - { - $this->currentPass = $pass; - $this->currentStartTime = microtime(true); - } - - /** - * Ends an individual pass. - * - * @param CompilerPassInterface $pass The compiler pass - */ - private function endPass(CompilerPassInterface $pass) - { - $this->currentPass = null; - $this->addLogMessage($this->loggingFormatter->formatPassTime($pass, microtime(true) - $this->currentStartTime)); - } } \ No newline at end of file diff --git a/src/Symfony/Component/DependencyInjection/Compiler/LoggingFormatter.php b/src/Symfony/Component/DependencyInjection/Compiler/LoggingFormatter.php index 57a1af54d6..af359e5d2c 100644 --- a/src/Symfony/Component/DependencyInjection/Compiler/LoggingFormatter.php +++ b/src/Symfony/Component/DependencyInjection/Compiler/LoggingFormatter.php @@ -31,11 +31,6 @@ class LoggingFormatter return $this->format($pass, sprintf('Resolving inheritance for "%s" (parent: %s).', $childId, $parentId)); } - public function formatPassTime(CompilerPassInterface $pass, $time) - { - return $this->format($pass, sprintf('finished in %.3fs.', $time)); - } - public function format(CompilerPassInterface $pass, $message) { return sprintf('%s: %s', get_class($pass), $message); From fd5caa9546eda2ba1c12ae8fb533f921f4611f8e Mon Sep 17 00:00:00 2001 From: Johannes Schmitt Date: Fri, 15 Apr 2011 08:47:28 +0200 Subject: [PATCH 11/91] [DependencyInjection] also check references of inlined services --- ...xceptionOnInvalidReferenceBehaviorPass.php | 15 +++++++++++--- ...tionOnInvalidReferenceBehaviorPassTest.php | 20 +++++++++++++++++++ 2 files changed, 32 insertions(+), 3 deletions(-) diff --git a/src/Symfony/Component/DependencyInjection/Compiler/CheckExceptionOnInvalidReferenceBehaviorPass.php b/src/Symfony/Component/DependencyInjection/Compiler/CheckExceptionOnInvalidReferenceBehaviorPass.php index 39894dbc8b..55bef03c10 100644 --- a/src/Symfony/Component/DependencyInjection/Compiler/CheckExceptionOnInvalidReferenceBehaviorPass.php +++ b/src/Symfony/Component/DependencyInjection/Compiler/CheckExceptionOnInvalidReferenceBehaviorPass.php @@ -2,6 +2,8 @@ namespace Symfony\Component\DependencyInjection\Compiler; +use Symfony\Component\DependencyInjection\Definition; + use Symfony\Component\DependencyInjection\Exception\NonExistentServiceException; use Symfony\Component\DependencyInjection\ContainerInterface; use Symfony\Component\DependencyInjection\Reference; @@ -23,17 +25,24 @@ class CheckExceptionOnInvalidReferenceBehaviorPass implements CompilerPassInterf foreach ($container->getDefinitions() as $id => $definition) { $this->sourceId = $id; - $this->processReferences($definition->getArguments()); - $this->processReferences($definition->getMethodCalls()); - $this->processReferences($definition->getProperties()); + $this->processDefinition($definition); } } + private function processDefinition(Definition $definition) + { + $this->processReferences($definition->getArguments()); + $this->processReferences($definition->getMethodCalls()); + $this->processReferences($definition->getProperties()); + } + private function processReferences(array $arguments) { foreach ($arguments as $argument) { if (is_array($argument)) { $this->processReferences($argument); + } else if ($argument instanceof Definition) { + $this->processDefinition($argument); } else if ($argument instanceof Reference && ContainerInterface::EXCEPTION_ON_INVALID_REFERENCE === $argument->getInvalidBehavior()) { $destId = (string) $argument; diff --git a/tests/Symfony/Tests/Component/DependencyInjection/Compiler/CheckExceptionOnInvalidReferenceBehaviorPassTest.php b/tests/Symfony/Tests/Component/DependencyInjection/Compiler/CheckExceptionOnInvalidReferenceBehaviorPassTest.php index 9a5f8cae3c..4db6b8a990 100644 --- a/tests/Symfony/Tests/Component/DependencyInjection/Compiler/CheckExceptionOnInvalidReferenceBehaviorPassTest.php +++ b/tests/Symfony/Tests/Component/DependencyInjection/Compiler/CheckExceptionOnInvalidReferenceBehaviorPassTest.php @@ -2,6 +2,8 @@ namespace Symfony\Tests\Component\DependencyInjection\Compiler; +use Symfony\Component\DependencyInjection\Definition; + use Symfony\Component\DependencyInjection\Compiler\CheckExceptionOnInvalidReferenceBehaviorPass; use Symfony\Component\DependencyInjection\Reference; use Symfony\Component\DependencyInjection\ContainerBuilder; @@ -34,6 +36,24 @@ class CheckExceptionOnInvalidReferenceBehaviorPassTest extends \PHPUnit_Framewor $this->process($container); } + /** + * @expectedException Symfony\Component\DependencyInjection\Exception\NonExistentServiceException + */ + public function testProcessThrowsExceptionOnInvalidReferenceFromInlinedDefinition() + { + $container = new ContainerBuilder(); + + $def = new Definition(); + $def->addArgument(new Reference('b')); + + $container + ->register('a', '\stdClass') + ->addArgument($def) + ; + + $this->process($container); + } + private function process(ContainerBuilder $container) { $pass = new CheckExceptionOnInvalidReferenceBehaviorPass(); From 49ecb90221637e437213dbb16eb634d205dc9e8b Mon Sep 17 00:00:00 2001 From: "Johannes M. Schmitt" Date: Fri, 15 Apr 2011 10:14:13 +0200 Subject: [PATCH 12/91] [DependencyInjection] enable debug related passes only in debug environment --- src/Symfony/Bundle/FrameworkBundle/FrameworkBundle.php | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/src/Symfony/Bundle/FrameworkBundle/FrameworkBundle.php b/src/Symfony/Bundle/FrameworkBundle/FrameworkBundle.php index 1688fa0832..dedd53aed9 100644 --- a/src/Symfony/Bundle/FrameworkBundle/FrameworkBundle.php +++ b/src/Symfony/Bundle/FrameworkBundle/FrameworkBundle.php @@ -82,7 +82,10 @@ class FrameworkBundle extends Bundle $container->addCompilerPass(new AddClassesToAutoloadMapPass()); $container->addCompilerPass(new TranslatorPass()); $container->addCompilerPass(new AddCacheWarmerPass()); - $container->addCompilerPass(new ContainerBuilderDebugDumpPass(), PassConfig::TYPE_BEFORE_REMOVING); - $container->addCompilerPass(new CompilerDebugDumpPass(), PassConfig::TYPE_AFTER_REMOVING); + + if ($container->getParameter('kernel.debug')) { + $container->addCompilerPass(new ContainerBuilderDebugDumpPass(), PassConfig::TYPE_BEFORE_REMOVING); + $container->addCompilerPass(new CompilerDebugDumpPass(), PassConfig::TYPE_AFTER_REMOVING); + } } } From de390fd89329a50a5b094f779a868980374e2149 Mon Sep 17 00:00:00 2001 From: Fabien Potencier Date: Fri, 15 Apr 2011 10:42:56 +0200 Subject: [PATCH 13/91] [DependencyInjection] removed timing info as it is useless --- .../Component/DependencyInjection/Compiler/Compiler.php | 2 -- .../Component/DependencyInjection/Compiler/RepeatedPass.php | 3 --- 2 files changed, 5 deletions(-) diff --git a/src/Symfony/Component/DependencyInjection/Compiler/Compiler.php b/src/Symfony/Component/DependencyInjection/Compiler/Compiler.php index 9c0adf6c50..9158d41f68 100644 --- a/src/Symfony/Component/DependencyInjection/Compiler/Compiler.php +++ b/src/Symfony/Component/DependencyInjection/Compiler/Compiler.php @@ -109,7 +109,5 @@ class Compiler foreach ($this->passConfig->getPasses() as $pass) { $pass->process($container); } - - $this->addLogMessage(sprintf('Compilation finished in %.3fs.', microtime(true) - $start)); } } \ No newline at end of file diff --git a/src/Symfony/Component/DependencyInjection/Compiler/RepeatedPass.php b/src/Symfony/Component/DependencyInjection/Compiler/RepeatedPass.php index 4b14337ed6..f0f3fbddc7 100644 --- a/src/Symfony/Component/DependencyInjection/Compiler/RepeatedPass.php +++ b/src/Symfony/Component/DependencyInjection/Compiler/RepeatedPass.php @@ -53,9 +53,6 @@ class RepeatedPass implements CompilerPassInterface foreach ($this->passes as $pass) { $time = microtime(true); $pass->process($container); - $compiler->addLogMessage(sprintf( - '%s finished in %.3fs', get_class($pass), microtime(true) - $time - )); } if ($this->repeat) { From 855206fcb51a43698d37b87aad0085938d3c36b4 Mon Sep 17 00:00:00 2001 From: Fabien Potencier Date: Fri, 15 Apr 2011 10:47:21 +0200 Subject: [PATCH 14/91] updated UPDATE file --- UPDATE.md | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/UPDATE.md b/UPDATE.md index a4c65143aa..243c7fef87 100644 --- a/UPDATE.md +++ b/UPDATE.md @@ -9,16 +9,20 @@ timeline closely anyway. PR11 to PR12 ------------ -* AsseticBundle's XML `bundle` node has been normalized to match other similar - nodes +* XML configurations have been normalized. All tags with only one attribute + have been converted to tag content: Before: + + After: MyBundle + twig + twig.extension.debug PR10 to PR11 ------------ From ad112da5bce28955298d55d3d0e0bf8b24984881 Mon Sep 17 00:00:00 2001 From: Fabien Potencier Date: Fri, 15 Apr 2011 11:31:08 +0200 Subject: [PATCH 15/91] added the request content to the request data collector --- .../Resources/views/Collector/request.html.twig | 10 ++++++++++ .../HttpKernel/DataCollector/RequestDataCollector.php | 6 ++++++ 2 files changed, 16 insertions(+) diff --git a/src/Symfony/Bundle/WebProfilerBundle/Resources/views/Collector/request.html.twig b/src/Symfony/Bundle/WebProfilerBundle/Resources/views/Collector/request.html.twig index 0df1a08c04..d2f7b00db6 100644 --- a/src/Symfony/Bundle/WebProfilerBundle/Resources/views/Collector/request.html.twig +++ b/src/Symfony/Bundle/WebProfilerBundle/Resources/views/Collector/request.html.twig @@ -75,6 +75,16 @@ {% include 'WebProfilerBundle:Profiler:bag.html.twig' with { 'bag': collector.requestheaders } only %} +

Request Content

+ +

+ {% if collector.content %} +

{{ collector.content }}
+ {% else %} + No content + {% endif %} +

+

Request Server Parameters

{% include 'WebProfilerBundle:Profiler:bag.html.twig' with { 'bag': collector.requestserver } only %} diff --git a/src/Symfony/Component/HttpKernel/DataCollector/RequestDataCollector.php b/src/Symfony/Component/HttpKernel/DataCollector/RequestDataCollector.php index 12d7fbc59d..bf8164bdb8 100644 --- a/src/Symfony/Component/HttpKernel/DataCollector/RequestDataCollector.php +++ b/src/Symfony/Component/HttpKernel/DataCollector/RequestDataCollector.php @@ -46,6 +46,7 @@ class RequestDataCollector extends DataCollector $this->data = array( 'format' => $request->getRequestFormat(), + 'content' => $request->getContent(), 'content_type' => $response->headers->get('Content-Type') ? $response->headers->get('Content-Type') : 'text/html', 'status_code' => $response->getStatusCode(), 'request_query' => $request->query->all(), @@ -99,6 +100,11 @@ class RequestDataCollector extends DataCollector return $this->data['session_attributes']; } + public function getContent() + { + return $this->data['content']; + } + public function getContentType() { return $this->data['content_type']; From 1e78ec395c0776e2793260d8ddd6178abe4b5f98 Mon Sep 17 00:00:00 2001 From: hidenorigoto Date: Fri, 15 Apr 2011 19:02:37 +0900 Subject: [PATCH 16/91] [HttpFoundation] fixed wrong method name --- src/Symfony/Component/HttpFoundation/Request.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Symfony/Component/HttpFoundation/Request.php b/src/Symfony/Component/HttpFoundation/Request.php index c390c4b6d6..05af73444a 100644 --- a/src/Symfony/Component/HttpFoundation/Request.php +++ b/src/Symfony/Component/HttpFoundation/Request.php @@ -126,7 +126,7 @@ class Request * * @return Request A new request */ - static public function createfromGlobals() + static public function createFromGlobals() { return new static($_GET, $_POST, array(), $_COOKIE, $_FILES, $_SERVER); } From 7e58c3f9768a94ab5b4989b743e5e59a2d76f75d Mon Sep 17 00:00:00 2001 From: Fabien Potencier Date: Fri, 15 Apr 2011 12:04:48 +0200 Subject: [PATCH 17/91] [Routing] allowed default route variables to be null --- src/Symfony/Component/Routing/Route.php | 12 ++++++++++++ src/Symfony/Component/Routing/RouteCompiler.php | 2 +- 2 files changed, 13 insertions(+), 1 deletion(-) diff --git a/src/Symfony/Component/Routing/Route.php b/src/Symfony/Component/Routing/Route.php index fb2e90507d..bcd54e506e 100644 --- a/src/Symfony/Component/Routing/Route.php +++ b/src/Symfony/Component/Routing/Route.php @@ -159,6 +159,18 @@ class Route return isset($this->defaults[$name]) ? $this->defaults[$name] : null; } + /** + * Checks if a default value is set for the given variable. + * + * @param string $name A variable name + * + * @return Boolean true if the default value is set, false otherwise + */ + public function hasDefault($name) + { + return array_key_exists($name, $this->defaults); + } + /** * Sets a default value. * diff --git a/src/Symfony/Component/Routing/RouteCompiler.php b/src/Symfony/Component/Routing/RouteCompiler.php index 0bff64903e..7c1bd5da5e 100644 --- a/src/Symfony/Component/Routing/RouteCompiler.php +++ b/src/Symfony/Component/Routing/RouteCompiler.php @@ -212,7 +212,7 @@ class RouteCompiler implements RouteCompilerInterface $this->segments[] = preg_quote($separator, '#').'(?P<'.$variable.'>'.$requirement.')'; $this->variables[$variable] = $name; - if (null === $this->route->getDefault($variable)) { + if (!$this->route->hasDefault($variable)) { $this->firstOptional = count($this->segments); } } From e898445b941ad93aeb3f62f98764a0077ea4d35a Mon Sep 17 00:00:00 2001 From: Brikou CARRE Date: Fri, 15 Apr 2011 21:12:02 +0200 Subject: [PATCH 18/91] removed empty lines/trailing spaces --- .../Twig/TokenParser/TransTokenParser.php | 2 +- .../Command/CreateDatabaseDoctrineCommand.php | 2 +- .../Command/DoctrineCommand.php | 2 +- .../Command/DropDatabaseDoctrineCommand.php | 2 +- .../GenerateRepositoriesDoctrineCommand.php | 2 +- .../Command/ImportMappingDoctrineCommand.php | 2 +- .../Command/InfoDoctrineCommand.php | 2 +- .../DependencyInjection/Configuration.php | 4 +- ...GenerateRepositoriesDoctrineODMCommand.php | 2 +- .../DoctrineMongoDBDataCollector.php | 2 +- .../CacheWarmer/TemplatePathsCacheWarmer.php | 4 +- .../Bundle/FrameworkBundle/Console/Shell.php | 12 ++--- .../Debug/TraceableEventDispatcher.php | 4 +- .../Loader/CachedTemplateLocator.php | 4 +- .../Templating/TemplateNameParser.php | 2 +- .../Fixtures/TestBundle/TestBundle.php | 2 +- .../FrameworkExtensionTest.php | 2 +- .../Tests/Templating/TemplateTest.php | 2 +- .../DependencyInjection/MainConfiguration.php | 2 +- .../Security/Factory/RememberMeFactory.php | 2 +- .../DataCollector/MessageDataCollector.php | 4 +- .../DependencyInjection/Configuration.php | 2 +- .../Logger/MessageLogger.php | 2 +- .../Bundle/TwigBundle/Node/FormThemeNode.php | 2 +- .../Bundle/TwigBundle/Node/HelperNode.php | 2 +- .../TokenParser/FormThemeTokenParser.php | 2 +- .../TokenParser/IncludeTokenParser.php | 2 +- .../Component/Config/Definition/BaseNode.php | 20 ++++---- .../Builder/ArrayNodeDefinition.php | 4 +- .../Config/Definition/Builder/NodeBuilder.php | 6 +-- .../Builder/NodeParentInterface.php | 1 - .../Builder/ParentNodeDefinitionInterface.php | 1 - .../Config/Definition/Builder/TreeBuilder.php | 6 +-- .../Builder/VariableNodeDefinition.php | 4 +- .../Config/Definition/NodeInterface.php | 16 +++---- .../Component/Config/Definition/Processor.php | 2 +- .../Component/Config/Loader/Loader.php | 4 +- src/Symfony/Component/Console/Application.php | 2 +- .../Component/CssSelector/Node/ClassNode.php | 2 +- .../CssSelector/Node/ElementNode.php | 2 +- .../CssSelector/Node/FunctionNode.php | 32 ++++++------- .../Component/CssSelector/Node/HashNode.php | 2 +- .../Component/CssSelector/Node/PseudoNode.php | 2 +- .../Component/DependencyInjection/Alias.php | 2 +- .../Compiler/CheckDefinitionValidityPass.php | 2 +- .../Compiler/RepeatablePassInterface.php | 2 +- .../Compiler/RepeatedPass.php | 2 +- .../Compiler/ServiceReferenceGraph.php | 16 +++---- .../Compiler/ServiceReferenceGraphEdge.php | 6 +-- .../Compiler/ServiceReferenceGraphNode.php | 4 +- .../DefinitionDecorator.php | 14 +++--- .../ParameterBag/FrozenParameterBag.php | 2 +- .../ParameterBag/ParameterBag.php | 4 +- .../DependencyInjection/Variable.php | 2 +- src/Symfony/Component/Form/MoneyField.php | 2 +- .../File/Exception/AccessDeniedException.php | 2 +- .../File/Exception/FileException.php | 2 +- .../File/Exception/FileNotFoundException.php | 2 +- .../MimeType/ContentTypeMimeTypeGuesser.php | 2 +- .../MimeType/FileBinaryMimeTypeGuesser.php | 4 +- .../File/MimeType/FileinfoMimeTypeGuesser.php | 2 +- .../File/MimeType/MimeTypeGuesser.php | 2 +- .../MimeType/MimeTypeGuesserInterface.php | 2 +- .../Routing/Loader/AnnotationFileLoader.php | 2 +- .../RememberMe/PersistentTokenInterface.php | 8 ++-- .../Core/Exception/CookieTheftException.php | 2 +- .../Core/Exception/TokenNotFoundException.php | 2 +- .../Serializer/Encoder/XmlEncoder.php | 2 +- .../Component/Templating/EngineInterface.php | 2 +- .../Templating/Loader/FilesystemLoader.php | 6 +-- .../Component/Translation/Interval.php | 2 +- .../Translation/Loader/CsvFileLoader.php | 4 +- src/Symfony/Component/Yaml/Escaper.php | 2 +- .../Component/BrowserKit/ResponseTest.php | 6 +-- .../ClassLoader/ClassCollectionLoaderTest.php | 2 +- .../Definition/Builder/NodeBuilderTest.php | 4 +- .../Definition/PrototypedArrayNodeTest.php | 2 +- .../Config/Fixtures/Builder/NodeBuilder.php | 2 +- .../Dumper/YamlDumperTest.php | 2 +- .../Component/HttpFoundation/CookieTest.php | 4 +- .../Component/HttpFoundation/RequestTest.php | 4 +- .../HttpKernel/Bundle/BundleTest.php | 8 ++-- .../ExceptionDataCollectorTest.php | 8 ++-- .../DataCollector/LoggerDataCollectorTest.php | 10 ++-- .../DataCollector/MemoryDataCollectorTest.php | 6 +-- .../RequestDataCollectorTest.php | 14 +++--- .../HttpKernel/Debug/ErrorHandlerTest.php | 18 +++---- .../Exception/FlattenExceptionTest.php | 16 +++---- .../Command/FooCommand.php | 2 +- .../Tests/Component/HttpKernel/KernelTest.php | 2 +- .../Dumper/PhpGeneratorDumperTest.php | 20 ++++---- .../Routing/Generator/UrlGeneratorTest.php | 18 +++---- .../Security/Acl/Domain/AuditLoggerTest.php | 14 +++--- .../Security/Acl/Domain/EntryTest.php | 48 +++++++++---------- .../Security/Acl/Domain/FieldEntryTest.php | 32 ++++++------- .../Acl/Permission/MaskBuilderTest.php | 32 ++++++------- .../Security/Acl/Voter/AclVoterTest.php | 6 +-- .../Serializer/Encoder/XmlEncoderTest.php | 18 +++---- 98 files changed, 292 insertions(+), 294 deletions(-) diff --git a/src/Symfony/Bridge/Twig/TokenParser/TransTokenParser.php b/src/Symfony/Bridge/Twig/TokenParser/TransTokenParser.php index 85a74845bc..0814fc1d01 100644 --- a/src/Symfony/Bridge/Twig/TokenParser/TransTokenParser.php +++ b/src/Symfony/Bridge/Twig/TokenParser/TransTokenParser.php @@ -14,7 +14,7 @@ namespace Symfony\Bridge\Twig\TokenParser; use Symfony\Bridge\Twig\Node\TransNode; /** - * + * * * @author Fabien Potencier */ diff --git a/src/Symfony/Bundle/DoctrineBundle/Command/CreateDatabaseDoctrineCommand.php b/src/Symfony/Bundle/DoctrineBundle/Command/CreateDatabaseDoctrineCommand.php index 7a67cdcd35..2be80fb775 100644 --- a/src/Symfony/Bundle/DoctrineBundle/Command/CreateDatabaseDoctrineCommand.php +++ b/src/Symfony/Bundle/DoctrineBundle/Command/CreateDatabaseDoctrineCommand.php @@ -48,7 +48,7 @@ EOT protected function execute(InputInterface $input, OutputInterface $output) { $connection = $this->getDoctrineConnection($input->getOption('connection')); - + $params = $connection->getParams(); $name = isset($params['path']) ? $params['path']:$params['dbname']; diff --git a/src/Symfony/Bundle/DoctrineBundle/Command/DoctrineCommand.php b/src/Symfony/Bundle/DoctrineBundle/Command/DoctrineCommand.php index f7b390cc60..c64e418228 100644 --- a/src/Symfony/Bundle/DoctrineBundle/Command/DoctrineCommand.php +++ b/src/Symfony/Bundle/DoctrineBundle/Command/DoctrineCommand.php @@ -39,7 +39,7 @@ abstract class DoctrineCommand extends Command { /** * Convenience method to push the helper sets of a given entity manager into the application. - * + * * @param Application $application * @param string $emName */ diff --git a/src/Symfony/Bundle/DoctrineBundle/Command/DropDatabaseDoctrineCommand.php b/src/Symfony/Bundle/DoctrineBundle/Command/DropDatabaseDoctrineCommand.php index 572c1e829c..2f7579d2b5 100644 --- a/src/Symfony/Bundle/DoctrineBundle/Command/DropDatabaseDoctrineCommand.php +++ b/src/Symfony/Bundle/DoctrineBundle/Command/DropDatabaseDoctrineCommand.php @@ -53,7 +53,7 @@ EOT protected function execute(InputInterface $input, OutputInterface $output) { $connection = $this->getDoctrineConnection($input->getOption('connection')); - + $params = $connection->getParams(); $name = isset($params['path'])?$params['path']:(isset($params['dbname'])?$params['dbname']:false); diff --git a/src/Symfony/Bundle/DoctrineBundle/Command/GenerateRepositoriesDoctrineCommand.php b/src/Symfony/Bundle/DoctrineBundle/Command/GenerateRepositoriesDoctrineCommand.php index 72d3ba2897..6c9e46930a 100644 --- a/src/Symfony/Bundle/DoctrineBundle/Command/GenerateRepositoriesDoctrineCommand.php +++ b/src/Symfony/Bundle/DoctrineBundle/Command/GenerateRepositoriesDoctrineCommand.php @@ -51,7 +51,7 @@ EOT if ($metadatas = $this->getBundleMetadatas($foundBundle)) { $output->writeln(sprintf('Generating entity repositories for "%s"', $foundBundle->getName())); $generator = new EntityRepositoryGenerator(); - + foreach ($metadatas as $metadata) { if ($filterEntity && $filterEntity !== $metadata->reflClass->getShortname()) { continue; diff --git a/src/Symfony/Bundle/DoctrineBundle/Command/ImportMappingDoctrineCommand.php b/src/Symfony/Bundle/DoctrineBundle/Command/ImportMappingDoctrineCommand.php index 7e889bcb36..5a34a963d9 100644 --- a/src/Symfony/Bundle/DoctrineBundle/Command/ImportMappingDoctrineCommand.php +++ b/src/Symfony/Bundle/DoctrineBundle/Command/ImportMappingDoctrineCommand.php @@ -77,7 +77,7 @@ EOT $em = $this->getEntityManager($this->container, $input->getOption('em')); $databaseDriver = new DatabaseDriver($em->getConnection()->getSchemaManager()); $em->getConfiguration()->setMetadataDriverImpl($databaseDriver); - + $emName = $input->getOption('em'); $emName = $emName ? $emName : 'default'; diff --git a/src/Symfony/Bundle/DoctrineBundle/Command/InfoDoctrineCommand.php b/src/Symfony/Bundle/DoctrineBundle/Command/InfoDoctrineCommand.php index 7399ac344e..fa357ad84a 100644 --- a/src/Symfony/Bundle/DoctrineBundle/Command/InfoDoctrineCommand.php +++ b/src/Symfony/Bundle/DoctrineBundle/Command/InfoDoctrineCommand.php @@ -69,7 +69,7 @@ EOT $output->write(sprintf("Found %d entities mapped in entity manager %s:\n", count($entityClassNames), $entityManagerName), true); - + foreach ($entityClassNames as $entityClassName) { try { $cm = $entityManager->getClassMetadata($entityClassName); diff --git a/src/Symfony/Bundle/DoctrineBundle/DependencyInjection/Configuration.php b/src/Symfony/Bundle/DoctrineBundle/DependencyInjection/Configuration.php index 86b006d638..9ecd176db3 100644 --- a/src/Symfony/Bundle/DoctrineBundle/DependencyInjection/Configuration.php +++ b/src/Symfony/Bundle/DoctrineBundle/DependencyInjection/Configuration.php @@ -36,7 +36,7 @@ class Configuration implements ConfigurationInterface { $this->debug = (Boolean) $debug; } - + /** * Generates the configuration tree builder. * @@ -127,7 +127,7 @@ class Configuration implements ConfigurationInterface { $node ->children() - ->arrayNode('orm') + ->arrayNode('orm') ->children() ->scalarNode('default_entity_manager')->end() ->booleanNode('auto_generate_proxy_classes')->defaultFalse()->end() diff --git a/src/Symfony/Bundle/DoctrineMongoDBBundle/Command/GenerateRepositoriesDoctrineODMCommand.php b/src/Symfony/Bundle/DoctrineMongoDBBundle/Command/GenerateRepositoriesDoctrineODMCommand.php index 3233cbab82..c20774315c 100644 --- a/src/Symfony/Bundle/DoctrineMongoDBBundle/Command/GenerateRepositoriesDoctrineODMCommand.php +++ b/src/Symfony/Bundle/DoctrineMongoDBBundle/Command/GenerateRepositoriesDoctrineODMCommand.php @@ -51,7 +51,7 @@ EOT if ($metadatas = $this->getBundleMetadatas($foundBundle)) { $output->writeln(sprintf('Generating document repositories for "%s"', $foundBundle->getName())); $generator = new DocumentRepositoryGenerator(); - + foreach ($metadatas as $metadata) { if ($filterDocument && $filterDocument !== $metadata->reflClass->getShortname()) { continue; diff --git a/src/Symfony/Bundle/DoctrineMongoDBBundle/DataCollector/DoctrineMongoDBDataCollector.php b/src/Symfony/Bundle/DoctrineMongoDBBundle/DataCollector/DoctrineMongoDBDataCollector.php index e6c14eca15..dc2e675726 100644 --- a/src/Symfony/Bundle/DoctrineMongoDBBundle/DataCollector/DoctrineMongoDBDataCollector.php +++ b/src/Symfony/Bundle/DoctrineMongoDBBundle/DataCollector/DoctrineMongoDBDataCollector.php @@ -18,7 +18,7 @@ use Symfony\Component\HttpFoundation\Response; /** * Data collector for the Doctrine MongoDB ODM. - * + * * @author Kris Wallsmith */ class DoctrineMongoDBDataCollector extends DataCollector diff --git a/src/Symfony/Bundle/FrameworkBundle/CacheWarmer/TemplatePathsCacheWarmer.php b/src/Symfony/Bundle/FrameworkBundle/CacheWarmer/TemplatePathsCacheWarmer.php index 22263594b4..b8a142f03c 100644 --- a/src/Symfony/Bundle/FrameworkBundle/CacheWarmer/TemplatePathsCacheWarmer.php +++ b/src/Symfony/Bundle/FrameworkBundle/CacheWarmer/TemplatePathsCacheWarmer.php @@ -91,8 +91,8 @@ class TemplatePathsCacheWarmer extends CacheWarmer $template = $this->parser->parseFromFilename($file->getRelativePathname()); if (false !== $template) { if (null !== $bundle) { - $template->set('bundle', $bundle); - } + $template->set('bundle', $bundle); + } $templates[$template->getSignature()] = $this->locator->locate($template); } } diff --git a/src/Symfony/Bundle/FrameworkBundle/Console/Shell.php b/src/Symfony/Bundle/FrameworkBundle/Console/Shell.php index f0628684a1..33100bdaca 100644 --- a/src/Symfony/Bundle/FrameworkBundle/Console/Shell.php +++ b/src/Symfony/Bundle/FrameworkBundle/Console/Shell.php @@ -29,14 +29,14 @@ class Shell extends BaseShell { return << - _____ __ ___ - / ____| / _| |__ \ + _____ __ ___ + / ____| / _| |__ \ | (___ _ _ _ __ ___ | |_ ___ _ __ _ _ ) | - \___ \| | | | '_ ` _ \| _/ _ \| '_ \| | | | / / - ____) | |_| | | | | | | || (_) | | | | |_| |/ /_ + \___ \| | | | '_ ` _ \| _/ _ \| '_ \| | | | / / + ____) | |_| | | | | | | || (_) | | | | |_| |/ /_ |_____/ \__, |_| |_| |_|_| \___/|_| |_|\__, |____| - __/ | __/ | - |___/ |___/ + __/ | __/ | + |___/ |___/ EOF diff --git a/src/Symfony/Bundle/FrameworkBundle/Debug/TraceableEventDispatcher.php b/src/Symfony/Bundle/FrameworkBundle/Debug/TraceableEventDispatcher.php index fc94368cd9..bdea0f0456 100644 --- a/src/Symfony/Bundle/FrameworkBundle/Debug/TraceableEventDispatcher.php +++ b/src/Symfony/Bundle/FrameworkBundle/Debug/TraceableEventDispatcher.php @@ -123,10 +123,10 @@ class TraceableEventDispatcher extends ContainerAwareEventDispatcher implements /** * Returns information about the listener - * + * * @param object $listener The listener * @param string $eventName The event name - * + * * @return array Informations about the listener */ private function getListenerInfo($listener, $eventName) diff --git a/src/Symfony/Bundle/FrameworkBundle/Templating/Loader/CachedTemplateLocator.php b/src/Symfony/Bundle/FrameworkBundle/Templating/Loader/CachedTemplateLocator.php index 4e32326379..49d8f6f51b 100644 --- a/src/Symfony/Bundle/FrameworkBundle/Templating/Loader/CachedTemplateLocator.php +++ b/src/Symfony/Bundle/FrameworkBundle/Templating/Loader/CachedTemplateLocator.php @@ -66,9 +66,9 @@ class CachedTemplateLocator extends TemplateLocator /** * Returns the template path from the cache - * + * * @param TemplateReferenceInterface $template The template - * + * * @return string|null The path when it is present in the cache, false otherwise */ protected function getCachedTemplatePath(TemplateReferenceInterface $template) diff --git a/src/Symfony/Bundle/FrameworkBundle/Templating/TemplateNameParser.php b/src/Symfony/Bundle/FrameworkBundle/Templating/TemplateNameParser.php index f7a6466b3c..9c6f48db24 100644 --- a/src/Symfony/Bundle/FrameworkBundle/Templating/TemplateNameParser.php +++ b/src/Symfony/Bundle/FrameworkBundle/Templating/TemplateNameParser.php @@ -83,7 +83,7 @@ class TemplateNameParser extends BaseTemplateNameParser * Convert a filename to a template. * * @param string $file The filename - * + * * @return TemplateReferenceInterface A template */ public function parseFromFilename($file) diff --git a/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/Fixtures/TestBundle/TestBundle.php b/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/Fixtures/TestBundle/TestBundle.php index e79da04999..ab6b62a8c1 100644 --- a/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/Fixtures/TestBundle/TestBundle.php +++ b/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/Fixtures/TestBundle/TestBundle.php @@ -4,5 +4,5 @@ namespace Symfony\Bundle\FrameworkBundle\Tests; class TestBundle extends \Symfony\Component\HttpKernel\Bundle\Bundle { - + } \ No newline at end of file diff --git a/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/FrameworkExtensionTest.php b/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/FrameworkExtensionTest.php index 167fdf2f99..3bd27dfbec 100644 --- a/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/FrameworkExtensionTest.php +++ b/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/FrameworkExtensionTest.php @@ -182,7 +182,7 @@ abstract class FrameworkExtensionTest extends TestCase 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'), )); diff --git a/src/Symfony/Bundle/FrameworkBundle/Tests/Templating/TemplateTest.php b/src/Symfony/Bundle/FrameworkBundle/Tests/Templating/TemplateTest.php index 32053262b2..df38b286da 100644 --- a/src/Symfony/Bundle/FrameworkBundle/Tests/Templating/TemplateTest.php +++ b/src/Symfony/Bundle/FrameworkBundle/Tests/Templating/TemplateTest.php @@ -34,7 +34,7 @@ class TemplateTest extends TestCase { if (!$template->get('bundle')) { $this->assertEquals($template->getPath(), $path); - } + } } public function getTemplateToPathProvider() diff --git a/src/Symfony/Bundle/SecurityBundle/DependencyInjection/MainConfiguration.php b/src/Symfony/Bundle/SecurityBundle/DependencyInjection/MainConfiguration.php index 4cc90a3665..6884cfafff 100644 --- a/src/Symfony/Bundle/SecurityBundle/DependencyInjection/MainConfiguration.php +++ b/src/Symfony/Bundle/SecurityBundle/DependencyInjection/MainConfiguration.php @@ -24,7 +24,7 @@ class MainConfiguration implements ConfigurationInterface /** * Constructor. * - * @param array $factories + * @param array $factories */ public function __construct(array $factories) { diff --git a/src/Symfony/Bundle/SecurityBundle/DependencyInjection/Security/Factory/RememberMeFactory.php b/src/Symfony/Bundle/SecurityBundle/DependencyInjection/Security/Factory/RememberMeFactory.php index 68c7c5227e..c9cfb6a788 100644 --- a/src/Symfony/Bundle/SecurityBundle/DependencyInjection/Security/Factory/RememberMeFactory.php +++ b/src/Symfony/Bundle/SecurityBundle/DependencyInjection/Security/Factory/RememberMeFactory.php @@ -111,7 +111,7 @@ class RememberMeFactory implements SecurityFactoryInterface public function addConfiguration(NodeDefinition $node) { $builder = $node->children(); - + $builder ->scalarNode('key')->isRequired()->cannotBeEmpty()->end() ->scalarNode('token_provider')->end() diff --git a/src/Symfony/Bundle/SwiftmailerBundle/DataCollector/MessageDataCollector.php b/src/Symfony/Bundle/SwiftmailerBundle/DataCollector/MessageDataCollector.php index d038159e47..8f78d2498d 100644 --- a/src/Symfony/Bundle/SwiftmailerBundle/DataCollector/MessageDataCollector.php +++ b/src/Symfony/Bundle/SwiftmailerBundle/DataCollector/MessageDataCollector.php @@ -25,7 +25,7 @@ class MessageDataCollector extends DataCollector { protected $logger; protected $mailer; - + public function __construct(\Swift_Events_SendListener $logger, \Swift_Mailer $mailer) { $this->logger = $logger; @@ -51,7 +51,7 @@ class MessageDataCollector extends DataCollector { return $this->data['messages']; } - + public function isSpool() { return $this->data['isSpool']; diff --git a/src/Symfony/Bundle/SwiftmailerBundle/DependencyInjection/Configuration.php b/src/Symfony/Bundle/SwiftmailerBundle/DependencyInjection/Configuration.php index 8200c40897..ac2423ecb0 100644 --- a/src/Symfony/Bundle/SwiftmailerBundle/DependencyInjection/Configuration.php +++ b/src/Symfony/Bundle/SwiftmailerBundle/DependencyInjection/Configuration.php @@ -36,7 +36,7 @@ class Configuration implements ConfigurationInterface { $this->debug = (Boolean) $debug; } - + /** * Generates the configuration tree builder. * diff --git a/src/Symfony/Bundle/SwiftmailerBundle/Logger/MessageLogger.php b/src/Symfony/Bundle/SwiftmailerBundle/Logger/MessageLogger.php index e5534dea31..62d72b862a 100644 --- a/src/Symfony/Bundle/SwiftmailerBundle/Logger/MessageLogger.php +++ b/src/Symfony/Bundle/SwiftmailerBundle/Logger/MessageLogger.php @@ -53,7 +53,7 @@ class MessageLogger implements \Swift_Events_SendListener /** * Empty the message list - * + * */ public function clear() { diff --git a/src/Symfony/Bundle/TwigBundle/Node/FormThemeNode.php b/src/Symfony/Bundle/TwigBundle/Node/FormThemeNode.php index 1a0b7edafd..418d1af1c1 100644 --- a/src/Symfony/Bundle/TwigBundle/Node/FormThemeNode.php +++ b/src/Symfony/Bundle/TwigBundle/Node/FormThemeNode.php @@ -12,7 +12,7 @@ namespace Symfony\Bundle\TwigBundle\Node; /** - * + * * * @author Fabien Potencier */ diff --git a/src/Symfony/Bundle/TwigBundle/Node/HelperNode.php b/src/Symfony/Bundle/TwigBundle/Node/HelperNode.php index 9a9709b6da..9df2baa668 100644 --- a/src/Symfony/Bundle/TwigBundle/Node/HelperNode.php +++ b/src/Symfony/Bundle/TwigBundle/Node/HelperNode.php @@ -12,7 +12,7 @@ namespace Symfony\Bundle\TwigBundle\Node; /** - * + * * * @author Fabien Potencier */ diff --git a/src/Symfony/Bundle/TwigBundle/TokenParser/FormThemeTokenParser.php b/src/Symfony/Bundle/TwigBundle/TokenParser/FormThemeTokenParser.php index d30bb7a285..f2b80f064b 100644 --- a/src/Symfony/Bundle/TwigBundle/TokenParser/FormThemeTokenParser.php +++ b/src/Symfony/Bundle/TwigBundle/TokenParser/FormThemeTokenParser.php @@ -14,7 +14,7 @@ namespace Symfony\Bundle\TwigBundle\TokenParser; use Symfony\Bundle\TwigBundle\Node\FormThemeNode; /** - * + * * * @author Fabien Potencier */ diff --git a/src/Symfony/Bundle/TwigBundle/TokenParser/IncludeTokenParser.php b/src/Symfony/Bundle/TwigBundle/TokenParser/IncludeTokenParser.php index 42e1f81061..cb7db4fd52 100644 --- a/src/Symfony/Bundle/TwigBundle/TokenParser/IncludeTokenParser.php +++ b/src/Symfony/Bundle/TwigBundle/TokenParser/IncludeTokenParser.php @@ -14,7 +14,7 @@ namespace Symfony\Bundle\TwigBundle\TokenParser; use Symfony\Bundle\TwigBundle\Node\IncludeNode; /** - * + * * * @author Fabien Potencier */ diff --git a/src/Symfony/Component/Config/Definition/BaseNode.php b/src/Symfony/Component/Config/Definition/BaseNode.php index d8c51ac66c..4ba29a6aa3 100644 --- a/src/Symfony/Component/Config/Definition/BaseNode.php +++ b/src/Symfony/Component/Config/Definition/BaseNode.php @@ -56,8 +56,8 @@ abstract class BaseNode implements NodeInterface /** * Adds an equivalent value. * - * @param mixed $originalValue - * @param mixed $equivalentValue + * @param mixed $originalValue + * @param mixed $equivalentValue */ public function addEquivalentValue($originalValue, $equivalentValue) { @@ -143,8 +143,8 @@ abstract class BaseNode implements NodeInterface /** * Merges two values together. * - * @param mixed $leftSide - * @param mixed $rightSide + * @param mixed $leftSide + * @param mixed $rightSide * @return mixed The merged value * @throws ForbiddenOverwriteException */ @@ -196,7 +196,7 @@ abstract class BaseNode implements NodeInterface /** * Finalizes a value, applying all finalization closures. * - * @param mixed $value The value to finalize + * @param mixed $value The value to finalize * @return mixed The finalized value */ public final function finalize($value) @@ -231,7 +231,7 @@ abstract class BaseNode implements NodeInterface * @throws InvalidTypeException when the value is invalid */ abstract protected function validateType($value); - + /** * Normalizes the value. * @@ -239,16 +239,16 @@ abstract class BaseNode implements NodeInterface * @return mixed The normalized value */ abstract protected function normalizeValue($value); - + /** * Merges two values together * - * @param mixed $leftSide - * @param mixed $rightSide + * @param mixed $leftSide + * @param mixed $rightSide * @return mixed The merged value */ abstract protected function mergeValues($leftSide, $rightSide); - + /** * Finalizes a value * diff --git a/src/Symfony/Component/Config/Definition/Builder/ArrayNodeDefinition.php b/src/Symfony/Component/Config/Definition/Builder/ArrayNodeDefinition.php index ca1712f853..bede6e991b 100644 --- a/src/Symfony/Component/Config/Definition/Builder/ArrayNodeDefinition.php +++ b/src/Symfony/Component/Config/Definition/Builder/ArrayNodeDefinition.php @@ -97,7 +97,7 @@ class ArrayNodeDefinition extends NodeDefinition implements ParentNodeDefinition return $this; } - + /** * Requires the node to have at least one element. * @@ -238,7 +238,7 @@ class ArrayNodeDefinition extends NodeDefinition implements ParentNodeDefinition /** * Returns a node builder to be used to add children and protoype - * + * * @return NodeBuilder The node builder */ protected function getNodeBuilder() diff --git a/src/Symfony/Component/Config/Definition/Builder/NodeBuilder.php b/src/Symfony/Component/Config/Definition/Builder/NodeBuilder.php index c6eb376224..ca8d222ef2 100644 --- a/src/Symfony/Component/Config/Definition/Builder/NodeBuilder.php +++ b/src/Symfony/Component/Config/Definition/Builder/NodeBuilder.php @@ -96,7 +96,7 @@ class NodeBuilder implements NodeParentInterface { return $this->node($name, 'variable'); } - + /** * Returns the parent node. * @@ -154,9 +154,9 @@ class NodeBuilder implements NodeParentInterface /** * Returns the class name of the node definition - * + * * @param string $type The node type - * + * * @return string The node definition class name * * @throws \RuntimeException When the node type is not registered diff --git a/src/Symfony/Component/Config/Definition/Builder/NodeParentInterface.php b/src/Symfony/Component/Config/Definition/Builder/NodeParentInterface.php index ca2f5a8148..24f397193e 100644 --- a/src/Symfony/Component/Config/Definition/Builder/NodeParentInterface.php +++ b/src/Symfony/Component/Config/Definition/Builder/NodeParentInterface.php @@ -19,4 +19,3 @@ namespace Symfony\Component\Config\Definition\Builder; interface NodeParentInterface { } - \ No newline at end of file diff --git a/src/Symfony/Component/Config/Definition/Builder/ParentNodeDefinitionInterface.php b/src/Symfony/Component/Config/Definition/Builder/ParentNodeDefinitionInterface.php index a67ed52701..2d95954239 100644 --- a/src/Symfony/Component/Config/Definition/Builder/ParentNodeDefinitionInterface.php +++ b/src/Symfony/Component/Config/Definition/Builder/ParentNodeDefinitionInterface.php @@ -24,4 +24,3 @@ interface ParentNodeDefinitionInterface function setBuilder(NodeBuilder $builder); } - \ No newline at end of file diff --git a/src/Symfony/Component/Config/Definition/Builder/TreeBuilder.php b/src/Symfony/Component/Config/Definition/Builder/TreeBuilder.php index 047235081c..3c1362a8d1 100644 --- a/src/Symfony/Component/Config/Definition/Builder/TreeBuilder.php +++ b/src/Symfony/Component/Config/Definition/Builder/TreeBuilder.php @@ -24,7 +24,7 @@ class TreeBuilder implements NodeParentInterface /** * Creates the root node. - * + * * @param string $name The name of the root node * @param string $type The type of the root node * @param NodeBuilder $builder A custom node builder instance @@ -36,7 +36,7 @@ class TreeBuilder implements NodeParentInterface public function root($name, $type = 'array', NodeBuilder $builder = null) { $builder = null === $builder ? new NodeBuilder() : $builder; - + $this->root = $builder->node($name, $type); $this->root->setParent($this); @@ -56,7 +56,7 @@ class TreeBuilder implements NodeParentInterface if (null !== $this->tree) { return $this->tree; } - + return $this->tree = $this->root->getNode(true); } } \ No newline at end of file diff --git a/src/Symfony/Component/Config/Definition/Builder/VariableNodeDefinition.php b/src/Symfony/Component/Config/Definition/Builder/VariableNodeDefinition.php index f9439fbdb2..f7da120661 100644 --- a/src/Symfony/Component/Config/Definition/Builder/VariableNodeDefinition.php +++ b/src/Symfony/Component/Config/Definition/Builder/VariableNodeDefinition.php @@ -37,7 +37,7 @@ class VariableNodeDefinition extends NodeDefinition protected function createNode() { $node = $this->instantiateNode(); - + if (null !== $this->normalization) { $node->setNormalizationClosures($this->normalization->before); } @@ -65,5 +65,5 @@ class VariableNodeDefinition extends NodeDefinition return $node; } - + } \ No newline at end of file diff --git a/src/Symfony/Component/Config/Definition/NodeInterface.php b/src/Symfony/Component/Config/Definition/NodeInterface.php index 33d53feb99..74f50aed58 100644 --- a/src/Symfony/Component/Config/Definition/NodeInterface.php +++ b/src/Symfony/Component/Config/Definition/NodeInterface.php @@ -34,21 +34,21 @@ interface NodeInterface * @return string The node path */ function getPath(); - + /** * Returns true when the node is required. * * @return Boolean If the node is required */ function isRequired(); - + /** * Returns true when the node has a default value. * * @return Boolean If the node has a default value */ function hasDefaultValue(); - + /** * Returns the default value of the node. * @@ -56,7 +56,7 @@ interface NodeInterface * @throws \RuntimeException if the node has no default value */ function getDefaultValue(); - + /** * Normalizes the supplied value. * @@ -64,16 +64,16 @@ interface NodeInterface * @return mixed The normalized value */ function normalize($value); - + /** * Merges two values together. * - * @param mixed $leftSide - * @param mixed $rightSide + * @param mixed $leftSide + * @param mixed $rightSide * @return mixed The merged values */ function merge($leftSide, $rightSide); - + /** * Finalizes a value. * diff --git a/src/Symfony/Component/Config/Definition/Processor.php b/src/Symfony/Component/Config/Definition/Processor.php index 3f7a7f1a43..42a184e61c 100644 --- a/src/Symfony/Component/Config/Definition/Processor.php +++ b/src/Symfony/Component/Config/Definition/Processor.php @@ -23,7 +23,7 @@ class Processor * * @param NodeInterface $configTree The node tree describing the configuration * @param array $configs An array of configuration items to process - * + * * @return array The processed configuration */ public function process(NodeInterface $configTree, array $configs) diff --git a/src/Symfony/Component/Config/Loader/Loader.php b/src/Symfony/Component/Config/Loader/Loader.php index 584b7b3734..f02110c28e 100644 --- a/src/Symfony/Component/Config/Loader/Loader.php +++ b/src/Symfony/Component/Config/Loader/Loader.php @@ -63,7 +63,7 @@ abstract class Loader implements LoaderInterface */ public function resolve($resource, $type = null) { - + if ($this->supports($resource, $type)) { return $this; } @@ -76,5 +76,5 @@ abstract class Loader implements LoaderInterface return $loader; } - + } diff --git a/src/Symfony/Component/Console/Application.php b/src/Symfony/Component/Console/Application.php index 9e88575a54..1ad936321a 100644 --- a/src/Symfony/Component/Console/Application.php +++ b/src/Symfony/Component/Console/Application.php @@ -759,7 +759,7 @@ class Application * Gets the name of the command based on input. * * @param InputInterface $input The input interface - * + * * @return string The command name */ protected function getCommandName(InputInterface $input) diff --git a/src/Symfony/Component/CssSelector/Node/ClassNode.php b/src/Symfony/Component/CssSelector/Node/ClassNode.php index 10950f90b7..b54d2f1539 100644 --- a/src/Symfony/Component/CssSelector/Node/ClassNode.php +++ b/src/Symfony/Component/CssSelector/Node/ClassNode.php @@ -39,7 +39,7 @@ class ClassNode implements NodeInterface } /** - * {@inheritDoc} + * {@inheritDoc} */ public function __toString() { diff --git a/src/Symfony/Component/CssSelector/Node/ElementNode.php b/src/Symfony/Component/CssSelector/Node/ElementNode.php index 97c96f7a9d..37e8ce0f61 100644 --- a/src/Symfony/Component/CssSelector/Node/ElementNode.php +++ b/src/Symfony/Component/CssSelector/Node/ElementNode.php @@ -31,7 +31,7 @@ class ElementNode implements NodeInterface * * @param string $namespace Namespace * @param string $element Element - */ + */ public function __construct($namespace, $element) { $this->namespace = $namespace; diff --git a/src/Symfony/Component/CssSelector/Node/FunctionNode.php b/src/Symfony/Component/CssSelector/Node/FunctionNode.php index 6a1bdbcbc4..c8b0b76a59 100644 --- a/src/Symfony/Component/CssSelector/Node/FunctionNode.php +++ b/src/Symfony/Component/CssSelector/Node/FunctionNode.php @@ -37,7 +37,7 @@ class FunctionNode implements NodeInterface * @param NodeInterface $selector The XPath expression * @param string $type * @param string $name - * @param XPathExpr $expr + * @param XPathExpr $expr */ public function __construct($selector, $type, $name, $expr) { @@ -76,10 +76,10 @@ class FunctionNode implements NodeInterface /** * undocumented function * - * @param XPathExpr $xpath - * @param mixed $expr - * @param string $last - * @param string $addNameTest + * @param XPathExpr $xpath + * @param mixed $expr + * @param string $last + * @param string $addNameTest * @return XPathExpr */ protected function _xpath_nth_child($xpath, $expr, $last = false, $addNameTest = true) @@ -148,8 +148,8 @@ class FunctionNode implements NodeInterface /** * undocumented function * - * @param XPathExpr $xpath - * @param XPathExpr $expr + * @param XPathExpr $xpath + * @param XPathExpr $expr * @return XPathExpr */ protected function _xpath_nth_last_child($xpath, $expr) @@ -160,8 +160,8 @@ class FunctionNode implements NodeInterface /** * undocumented function * - * @param XPathExpr $xpath - * @param XPathExpr $expr + * @param XPathExpr $xpath + * @param XPathExpr $expr * @return XPathExpr */ protected function _xpath_nth_of_type($xpath, $expr) @@ -176,8 +176,8 @@ class FunctionNode implements NodeInterface /** * undocumented function * - * @param XPathExpr $xpath - * @param XPathExpr $expr + * @param XPathExpr $xpath + * @param XPathExpr $expr * @return XPathExpr */ protected function _xpath_nth_last_of_type($xpath, $expr) @@ -188,8 +188,8 @@ class FunctionNode implements NodeInterface /** * undocumented function * - * @param XPathExpr $xpath - * @param XPathExpr $expr + * @param XPathExpr $xpath + * @param XPathExpr $expr * @return XPathExpr */ protected function _xpath_contains($xpath, $expr) @@ -211,8 +211,8 @@ class FunctionNode implements NodeInterface /** * undocumented function * - * @param XPathExpr $xpath - * @param XPathExpr $expr + * @param XPathExpr $xpath + * @param XPathExpr $expr * @return XPathExpr */ protected function _xpath_not($xpath, $expr) @@ -229,7 +229,7 @@ class FunctionNode implements NodeInterface /** * Parses things like '1n+2', or 'an+b' generally, returning (a, b) * - * @param mixed $s + * @param mixed $s * @return array */ protected function parseSeries($s) diff --git a/src/Symfony/Component/CssSelector/Node/HashNode.php b/src/Symfony/Component/CssSelector/Node/HashNode.php index 9507277c8c..54d51ee045 100644 --- a/src/Symfony/Component/CssSelector/Node/HashNode.php +++ b/src/Symfony/Component/CssSelector/Node/HashNode.php @@ -38,7 +38,7 @@ class HashNode implements NodeInterface $this->id = $id; } - /** + /** * {@inheritDoc} */ public function __toString() diff --git a/src/Symfony/Component/CssSelector/Node/PseudoNode.php b/src/Symfony/Component/CssSelector/Node/PseudoNode.php index f1988c7092..d15f0e5289 100644 --- a/src/Symfony/Component/CssSelector/Node/PseudoNode.php +++ b/src/Symfony/Component/CssSelector/Node/PseudoNode.php @@ -119,7 +119,7 @@ class PseudoNode implements NodeInterface return $xpath; } - /** + /** * Sets the XPath to be the last child. * * @param XPathExpr $xpath The XPath expression diff --git a/src/Symfony/Component/DependencyInjection/Alias.php b/src/Symfony/Component/DependencyInjection/Alias.php index 76e7624a91..c6aa80c069 100644 --- a/src/Symfony/Component/DependencyInjection/Alias.php +++ b/src/Symfony/Component/DependencyInjection/Alias.php @@ -31,7 +31,7 @@ class Alias /** * Checks if this DI Alias should be public or not. * - * @return boolean + * @return boolean */ public function isPublic() { diff --git a/src/Symfony/Component/DependencyInjection/Compiler/CheckDefinitionValidityPass.php b/src/Symfony/Component/DependencyInjection/Compiler/CheckDefinitionValidityPass.php index 928ef081d5..547e11c3ee 100644 --- a/src/Symfony/Component/DependencyInjection/Compiler/CheckDefinitionValidityPass.php +++ b/src/Symfony/Component/DependencyInjection/Compiler/CheckDefinitionValidityPass.php @@ -23,7 +23,7 @@ class CheckDefinitionValidityPass implements CompilerPassInterface /** * Processes the ContainerBuilder to validate the Definition. * - * @param ContainerBuilder $container + * @param ContainerBuilder $container * @throws \RuntimeException When the Definition is invalid */ public function process(ContainerBuilder $container) diff --git a/src/Symfony/Component/DependencyInjection/Compiler/RepeatablePassInterface.php b/src/Symfony/Component/DependencyInjection/Compiler/RepeatablePassInterface.php index 43bbdf1ca5..a737052072 100644 --- a/src/Symfony/Component/DependencyInjection/Compiler/RepeatablePassInterface.php +++ b/src/Symfony/Component/DependencyInjection/Compiler/RepeatablePassInterface.php @@ -22,7 +22,7 @@ interface RepeatablePassInterface extends CompilerPassInterface /** * Sets the RepeatedPass interface. * - * @param RepeatedPass $repeatedPass + * @param RepeatedPass $repeatedPass */ function setRepeatedPass(RepeatedPass $repeatedPass); } \ No newline at end of file diff --git a/src/Symfony/Component/DependencyInjection/Compiler/RepeatedPass.php b/src/Symfony/Component/DependencyInjection/Compiler/RepeatedPass.php index f0f3fbddc7..7ed16bc7ca 100644 --- a/src/Symfony/Component/DependencyInjection/Compiler/RepeatedPass.php +++ b/src/Symfony/Component/DependencyInjection/Compiler/RepeatedPass.php @@ -44,7 +44,7 @@ class RepeatedPass implements CompilerPassInterface /** * Process the repeatable passes that run more than once. * - * @param ContainerBuilder $container + * @param ContainerBuilder $container */ public function process(ContainerBuilder $container) { diff --git a/src/Symfony/Component/DependencyInjection/Compiler/ServiceReferenceGraph.php b/src/Symfony/Component/DependencyInjection/Compiler/ServiceReferenceGraph.php index ce512e7d64..8eb76ddb6a 100644 --- a/src/Symfony/Component/DependencyInjection/Compiler/ServiceReferenceGraph.php +++ b/src/Symfony/Component/DependencyInjection/Compiler/ServiceReferenceGraph.php @@ -46,7 +46,7 @@ class ServiceReferenceGraph * * @param string $id The id to retrieve * @return ServiceReferenceGraphNode The node matching the supplied identifier - * @throws \InvalidArgumentException + * @throws \InvalidArgumentException */ public function getNode($id) { @@ -78,11 +78,11 @@ class ServiceReferenceGraph /** * Connects 2 nodes together in the Graph. * - * @param string $sourceId - * @param string $sourceValue - * @param string $destId - * @param string $destValue - * @param string $reference + * @param string $sourceId + * @param string $sourceValue + * @param string $destId + * @param string $destValue + * @param string $reference */ public function connect($sourceId, $sourceValue, $destId, $destValue = null, $reference = null) { @@ -97,8 +97,8 @@ class ServiceReferenceGraph /** * Creates a graph node. * - * @param string $id - * @param string $value + * @param string $id + * @param string $value * @return ServiceReferenceGraphNode */ private function createNode($id, $value) diff --git a/src/Symfony/Component/DependencyInjection/Compiler/ServiceReferenceGraphEdge.php b/src/Symfony/Component/DependencyInjection/Compiler/ServiceReferenceGraphEdge.php index b768b59bf3..6331edc22c 100644 --- a/src/Symfony/Component/DependencyInjection/Compiler/ServiceReferenceGraphEdge.php +++ b/src/Symfony/Component/DependencyInjection/Compiler/ServiceReferenceGraphEdge.php @@ -27,9 +27,9 @@ class ServiceReferenceGraphEdge /** * Constructor. * - * @param ServiceReferenceGraphNode $sourceNode - * @param ServiceReferenceGraphNode $destNode - * @param string $value + * @param ServiceReferenceGraphNode $sourceNode + * @param ServiceReferenceGraphNode $destNode + * @param string $value */ public function __construct(ServiceReferenceGraphNode $sourceNode, ServiceReferenceGraphNode $destNode, $value = null) { diff --git a/src/Symfony/Component/DependencyInjection/Compiler/ServiceReferenceGraphNode.php b/src/Symfony/Component/DependencyInjection/Compiler/ServiceReferenceGraphNode.php index 0070781ca9..6c71683d5f 100644 --- a/src/Symfony/Component/DependencyInjection/Compiler/ServiceReferenceGraphNode.php +++ b/src/Symfony/Component/DependencyInjection/Compiler/ServiceReferenceGraphNode.php @@ -45,7 +45,7 @@ class ServiceReferenceGraphNode /** * Adds an in edge to this node. * - * @param ServiceReferenceGraphEdge $edge + * @param ServiceReferenceGraphEdge $edge */ public function addInEdge(ServiceReferenceGraphEdge $edge) { @@ -55,7 +55,7 @@ class ServiceReferenceGraphNode /** * Adds an out edge to this node. * - * @param ServiceReferenceGraphEdge $edge + * @param ServiceReferenceGraphEdge $edge */ public function addOutEdge(ServiceReferenceGraphEdge $edge) { diff --git a/src/Symfony/Component/DependencyInjection/DefinitionDecorator.php b/src/Symfony/Component/DependencyInjection/DefinitionDecorator.php index 0b68b7c215..50395cc5e0 100644 --- a/src/Symfony/Component/DependencyInjection/DefinitionDecorator.php +++ b/src/Symfony/Component/DependencyInjection/DefinitionDecorator.php @@ -44,7 +44,7 @@ class DefinitionDecorator extends Definition { return $this->changes; } - + /** * {@inheritDoc} */ @@ -54,7 +54,7 @@ class DefinitionDecorator extends Definition return parent::setClass($class); } - + /** * {@inheritDoc} */ @@ -64,7 +64,7 @@ class DefinitionDecorator extends Definition return parent::setFactoryClass($class); } - + /** * {@inheritDoc} */ @@ -74,7 +74,7 @@ class DefinitionDecorator extends Definition return parent::setFactoryMethod($method); } - + /** * {@inheritDoc} */ @@ -84,7 +84,7 @@ class DefinitionDecorator extends Definition return parent::setFactoryService($service); } - + /** * {@inheritDoc} */ @@ -94,7 +94,7 @@ class DefinitionDecorator extends Definition return parent::setConfigurator($callable); } - + /** * {@inheritDoc} */ @@ -104,7 +104,7 @@ class DefinitionDecorator extends Definition return parent::setFile($file); } - + /** * {@inheritDoc} */ diff --git a/src/Symfony/Component/DependencyInjection/ParameterBag/FrozenParameterBag.php b/src/Symfony/Component/DependencyInjection/ParameterBag/FrozenParameterBag.php index 75cc168b4d..e9590933cd 100644 --- a/src/Symfony/Component/DependencyInjection/ParameterBag/FrozenParameterBag.php +++ b/src/Symfony/Component/DependencyInjection/ParameterBag/FrozenParameterBag.php @@ -12,7 +12,7 @@ namespace Symfony\Component\DependencyInjection\ParameterBag; /** - * + * * @author Fabien Potencier */ class FrozenParameterBag extends ParameterBag diff --git a/src/Symfony/Component/DependencyInjection/ParameterBag/ParameterBag.php b/src/Symfony/Component/DependencyInjection/ParameterBag/ParameterBag.php index cb3de82639..75d862d5b4 100644 --- a/src/Symfony/Component/DependencyInjection/ParameterBag/ParameterBag.php +++ b/src/Symfony/Component/DependencyInjection/ParameterBag/ParameterBag.php @@ -12,7 +12,7 @@ namespace Symfony\Component\DependencyInjection\ParameterBag; /** - * + * * @author Fabien Potencier */ class ParameterBag implements ParameterBagInterface @@ -149,7 +149,7 @@ class ParameterBag implements ParameterBagInterface * * @see resolveValue * - * @param array $match + * @param array $match * @return string */ private function resolveValueCallback($match) diff --git a/src/Symfony/Component/DependencyInjection/Variable.php b/src/Symfony/Component/DependencyInjection/Variable.php index 894107b4a4..11f255649f 100644 --- a/src/Symfony/Component/DependencyInjection/Variable.php +++ b/src/Symfony/Component/DependencyInjection/Variable.php @@ -31,7 +31,7 @@ class Variable /** * Constructor * - * @param string $name + * @param string $name */ public function __construct($name) { diff --git a/src/Symfony/Component/Form/MoneyField.php b/src/Symfony/Component/Form/MoneyField.php index ac8e4cf256..7bd1fb8d1e 100644 --- a/src/Symfony/Component/Form/MoneyField.php +++ b/src/Symfony/Component/Form/MoneyField.php @@ -24,7 +24,7 @@ use Symfony\Component\Form\ValueTransformer\MoneyToLocalizedStringTransformer; * * currency: The currency to display the money with. This is the 3-letter * ISO 4217 currency code. * * divisor: A number to divide the money by before displaying. Default 1. - * + * * @see Symfony\Component\Form\NumberField * @author Bernhard Schussek */ diff --git a/src/Symfony/Component/HttpFoundation/File/Exception/AccessDeniedException.php b/src/Symfony/Component/HttpFoundation/File/Exception/AccessDeniedException.php index aa1a1ad01a..fc6ea5e807 100644 --- a/src/Symfony/Component/HttpFoundation/File/Exception/AccessDeniedException.php +++ b/src/Symfony/Component/HttpFoundation/File/Exception/AccessDeniedException.php @@ -2,7 +2,7 @@ /* * This file is part of the Symfony package. - * + * * (c) Fabien Potencier * * For the full copyright and license information, please view the LICENSE diff --git a/src/Symfony/Component/HttpFoundation/File/Exception/FileException.php b/src/Symfony/Component/HttpFoundation/File/Exception/FileException.php index ff1c2dbb81..7d8310909f 100644 --- a/src/Symfony/Component/HttpFoundation/File/Exception/FileException.php +++ b/src/Symfony/Component/HttpFoundation/File/Exception/FileException.php @@ -2,7 +2,7 @@ /* * This file is part of the Symfony package. - * + * * (c) Fabien Potencier * * For the full copyright and license information, please view the LICENSE diff --git a/src/Symfony/Component/HttpFoundation/File/Exception/FileNotFoundException.php b/src/Symfony/Component/HttpFoundation/File/Exception/FileNotFoundException.php index 07d368b611..60ba964745 100644 --- a/src/Symfony/Component/HttpFoundation/File/Exception/FileNotFoundException.php +++ b/src/Symfony/Component/HttpFoundation/File/Exception/FileNotFoundException.php @@ -2,7 +2,7 @@ /* * This file is part of the Symfony package. - * + * * (c) Fabien Potencier * * For the full copyright and license information, please view the LICENSE diff --git a/src/Symfony/Component/HttpFoundation/File/MimeType/ContentTypeMimeTypeGuesser.php b/src/Symfony/Component/HttpFoundation/File/MimeType/ContentTypeMimeTypeGuesser.php index f0a1fdecad..fb900b2bc2 100644 --- a/src/Symfony/Component/HttpFoundation/File/MimeType/ContentTypeMimeTypeGuesser.php +++ b/src/Symfony/Component/HttpFoundation/File/MimeType/ContentTypeMimeTypeGuesser.php @@ -2,7 +2,7 @@ /* * This file is part of the Symfony package. - * + * * (c) Fabien Potencier * * For the full copyright and license information, please view the LICENSE diff --git a/src/Symfony/Component/HttpFoundation/File/MimeType/FileBinaryMimeTypeGuesser.php b/src/Symfony/Component/HttpFoundation/File/MimeType/FileBinaryMimeTypeGuesser.php index e9a352f0ec..84862b0124 100644 --- a/src/Symfony/Component/HttpFoundation/File/MimeType/FileBinaryMimeTypeGuesser.php +++ b/src/Symfony/Component/HttpFoundation/File/MimeType/FileBinaryMimeTypeGuesser.php @@ -2,7 +2,7 @@ /* * This file is part of the Symfony package. - * + * * (c) Fabien Potencier * * For the full copyright and license information, please view the LICENSE @@ -48,7 +48,7 @@ class FileBinaryMimeTypeGuesser implements MimeTypeGuesserInterface if (!self::isSupported()) { return null; } - + ob_start(); // need to use --mime instead of -i. see #6641 diff --git a/src/Symfony/Component/HttpFoundation/File/MimeType/FileinfoMimeTypeGuesser.php b/src/Symfony/Component/HttpFoundation/File/MimeType/FileinfoMimeTypeGuesser.php index e55e7d54cb..f3b39a3eb0 100644 --- a/src/Symfony/Component/HttpFoundation/File/MimeType/FileinfoMimeTypeGuesser.php +++ b/src/Symfony/Component/HttpFoundation/File/MimeType/FileinfoMimeTypeGuesser.php @@ -2,7 +2,7 @@ /* * This file is part of the Symfony package. - * + * * (c) Fabien Potencier * * For the full copyright and license information, please view the LICENSE diff --git a/src/Symfony/Component/HttpFoundation/File/MimeType/MimeTypeGuesser.php b/src/Symfony/Component/HttpFoundation/File/MimeType/MimeTypeGuesser.php index 2cecb141b7..cfb0cb8fcd 100644 --- a/src/Symfony/Component/HttpFoundation/File/MimeType/MimeTypeGuesser.php +++ b/src/Symfony/Component/HttpFoundation/File/MimeType/MimeTypeGuesser.php @@ -2,7 +2,7 @@ /* * This file is part of the Symfony package. - * + * * (c) Fabien Potencier * * For the full copyright and license information, please view the LICENSE diff --git a/src/Symfony/Component/HttpFoundation/File/MimeType/MimeTypeGuesserInterface.php b/src/Symfony/Component/HttpFoundation/File/MimeType/MimeTypeGuesserInterface.php index adf29479d5..0665970c79 100644 --- a/src/Symfony/Component/HttpFoundation/File/MimeType/MimeTypeGuesserInterface.php +++ b/src/Symfony/Component/HttpFoundation/File/MimeType/MimeTypeGuesserInterface.php @@ -2,7 +2,7 @@ /* * This file is part of the Symfony package. - * + * * (c) Fabien Potencier * * For the full copyright and license information, please view the LICENSE diff --git a/src/Symfony/Component/Routing/Loader/AnnotationFileLoader.php b/src/Symfony/Component/Routing/Loader/AnnotationFileLoader.php index 032d6883c9..3d7dbac5c6 100644 --- a/src/Symfony/Component/Routing/Loader/AnnotationFileLoader.php +++ b/src/Symfony/Component/Routing/Loader/AnnotationFileLoader.php @@ -84,7 +84,7 @@ class AnnotationFileLoader extends FileLoader * * @param string $file A PHP file path * - * @return string|false Full class name if found, false otherwise + * @return string|false Full class name if found, false otherwise */ protected function findClass($file) { diff --git a/src/Symfony/Component/Security/Core/Authentication/RememberMe/PersistentTokenInterface.php b/src/Symfony/Component/Security/Core/Authentication/RememberMe/PersistentTokenInterface.php index bfd077e151..fe1db512d6 100644 --- a/src/Symfony/Component/Security/Core/Authentication/RememberMe/PersistentTokenInterface.php +++ b/src/Symfony/Component/Security/Core/Authentication/RememberMe/PersistentTokenInterface.php @@ -14,7 +14,7 @@ namespace Symfony\Component\Security\Core\Authentication\RememberMe; /** * Interface to be implemented by persistent token classes (such as * Doctrine entities representing a remember-me token) - * + * * @author Johannes M. Schmitt */ interface PersistentTokenInterface @@ -24,19 +24,19 @@ interface PersistentTokenInterface * @return string */ function getUsername(); - + /** * Returns the series * @return string */ function getSeries(); - + /** * Returns the token value * @return string */ function getTokenValue(); - + /** * Returns the last time the cookie was used * @return \DateTime diff --git a/src/Symfony/Component/Security/Core/Exception/CookieTheftException.php b/src/Symfony/Component/Security/Core/Exception/CookieTheftException.php index 6dbead5462..83e61d737f 100644 --- a/src/Symfony/Component/Security/Core/Exception/CookieTheftException.php +++ b/src/Symfony/Component/Security/Core/Exception/CookieTheftException.php @@ -14,7 +14,7 @@ namespace Symfony\Component\Security\Core\Exception; /** * This exception is thrown when the RememberMeServices implementation * detects that a presented cookie has already been used by someone else. - * + * * @author Johannes M. Schmitt */ class CookieTheftException extends AuthenticationException diff --git a/src/Symfony/Component/Security/Core/Exception/TokenNotFoundException.php b/src/Symfony/Component/Security/Core/Exception/TokenNotFoundException.php index f25905d3f7..593f3ad269 100644 --- a/src/Symfony/Component/Security/Core/Exception/TokenNotFoundException.php +++ b/src/Symfony/Component/Security/Core/Exception/TokenNotFoundException.php @@ -1,4 +1,4 @@ - 3 && ctype_alpha($file[0]) - && $file[1] == ':' + if ($file[0] == '/' || $file[0] == '\\' + || (strlen($file) > 3 && ctype_alpha($file[0]) + && $file[1] == ':' && ($file[2] == '\\' || $file[2] == '/') ) ) { diff --git a/src/Symfony/Component/Translation/Interval.php b/src/Symfony/Component/Translation/Interval.php index 63c89c5605..8e0d22f788 100644 --- a/src/Symfony/Component/Translation/Interval.php +++ b/src/Symfony/Component/Translation/Interval.php @@ -57,7 +57,7 @@ class Interval $leftNumber = self::convertNumber($matches['left']); $rightNumber = self::convertNumber($matches['right']); - return + return ('[' === $matches['left_delimiter'] ? $number >= $leftNumber : $number > $leftNumber) && (']' === $matches['right_delimiter'] ? $number <= $rightNumber : $number < $rightNumber) ; diff --git a/src/Symfony/Component/Translation/Loader/CsvFileLoader.php b/src/Symfony/Component/Translation/Loader/CsvFileLoader.php index daf95189c1..95ac3823c1 100644 --- a/src/Symfony/Component/Translation/Loader/CsvFileLoader.php +++ b/src/Symfony/Component/Translation/Loader/CsvFileLoader.php @@ -30,13 +30,13 @@ class CsvFileLoader extends ArrayLoader implements LoaderInterface public function load($resource, $locale, $domain = 'messages') { $messages = array(); - + try { $file = new \SplFileObject($resource, 'rb'); } catch(\RuntimeException $e) { throw new \InvalidArgumentException(sprintf('Error opening file "%s".', $resource)); } - + $file->setFlags(\SplFileObject::READ_CSV | \SplFileObject::SKIP_EMPTY); $file->setCsvControl(';'); diff --git a/src/Symfony/Component/Yaml/Escaper.php b/src/Symfony/Component/Yaml/Escaper.php index 9ff9272ff8..81a7d5fe1b 100644 --- a/src/Symfony/Component/Yaml/Escaper.php +++ b/src/Symfony/Component/Yaml/Escaper.php @@ -49,7 +49,7 @@ class Escaper { return preg_match('/'.self::REGEX_CHARACTER_TO_ESCAPE.'/u', $value); } - + /** * Escapes and surrounds a PHP value with double quotes. * diff --git a/tests/Symfony/Tests/Component/BrowserKit/ResponseTest.php b/tests/Symfony/Tests/Component/BrowserKit/ResponseTest.php index 347a8fe21f..6e0f52b909 100644 --- a/tests/Symfony/Tests/Component/BrowserKit/ResponseTest.php +++ b/tests/Symfony/Tests/Component/BrowserKit/ResponseTest.php @@ -61,14 +61,14 @@ class ResponseTest extends \PHPUnit_Framework_TestCase { $headers = array( 'content-type' => 'text/html; charset=utf-8', - 'set-cookie' => array('foo=bar', 'bar=foo') + 'set-cookie' => array('foo=bar', 'bar=foo') ); - + $expected = 'content-type: text/html; charset=utf-8'."\n"; $expected.= 'set-cookie: foo=bar'."\n"; $expected.= 'set-cookie: bar=foo'."\n\n"; $expected.= 'foo'; - + $response = new Response('foo', 304, $headers); $this->assertEquals($expected, $response->__toString(), '->__toString() returns the headers and the content as a string'); diff --git a/tests/Symfony/Tests/Component/ClassLoader/ClassCollectionLoaderTest.php b/tests/Symfony/Tests/Component/ClassLoader/ClassCollectionLoaderTest.php index 3fee2ed324..9b69b4014c 100644 --- a/tests/Symfony/Tests/Component/ClassLoader/ClassCollectionLoaderTest.php +++ b/tests/Symfony/Tests/Component/ClassLoader/ClassCollectionLoaderTest.php @@ -43,7 +43,7 @@ namespace Foo { class Foo {} } -namespace Bar +namespace Bar { class Foo {} } diff --git a/tests/Symfony/Tests/Component/Config/Definition/Builder/NodeBuilderTest.php b/tests/Symfony/Tests/Component/Config/Definition/Builder/NodeBuilderTest.php index 8fc6bc248b..34ddb51f9a 100644 --- a/tests/Symfony/Tests/Component/Config/Definition/Builder/NodeBuilderTest.php +++ b/tests/Symfony/Tests/Component/Config/Definition/Builder/NodeBuilderTest.php @@ -30,7 +30,7 @@ class NodeBuilderTest extends \PHPUnit_Framework_TestCase public function testAddingANewNodeType() { $class = __NAMESPACE__.'\\SomeNodeDefinition'; - + $builder = new BaseNodeBuilder(); $node = $builder ->setNodeClass('newtype', $class) @@ -66,7 +66,7 @@ class NodeBuilderTest extends \PHPUnit_Framework_TestCase $node2 = $builder->node('', 'custom'); $this->assertEquals(get_class($node1), get_class($node2)); - } + } } class SomeNodeDefinition extends BaseVariableNodeDefinition diff --git a/tests/Symfony/Tests/Component/Config/Definition/PrototypedArrayNodeTest.php b/tests/Symfony/Tests/Component/Config/Definition/PrototypedArrayNodeTest.php index 3ce18790c1..697969f257 100644 --- a/tests/Symfony/Tests/Component/Config/Definition/PrototypedArrayNodeTest.php +++ b/tests/Symfony/Tests/Component/Config/Definition/PrototypedArrayNodeTest.php @@ -8,7 +8,7 @@ use Symfony\Component\Config\Definition\ScalarNode; class PrototypedArrayNodeTest extends \PHPUnit_Framework_TestCase { - + public function testGetDefaultValueReturnsAnEmptyArrayForPrototypes() { $node = new PrototypedArrayNode('root'); diff --git a/tests/Symfony/Tests/Component/Config/Fixtures/Builder/NodeBuilder.php b/tests/Symfony/Tests/Component/Config/Fixtures/Builder/NodeBuilder.php index a3ae249d4f..fb582d6c46 100644 --- a/tests/Symfony/Tests/Component/Config/Fixtures/Builder/NodeBuilder.php +++ b/tests/Symfony/Tests/Component/Config/Fixtures/Builder/NodeBuilder.php @@ -20,6 +20,6 @@ class NodeBuilder extends BaseNodeBuilder return __NAMESPACE__.'\\'.ucfirst($type).'NodeDefinition'; default: return parent::getNodeClass($type); - } + } } } \ No newline at end of file diff --git a/tests/Symfony/Tests/Component/DependencyInjection/Dumper/YamlDumperTest.php b/tests/Symfony/Tests/Component/DependencyInjection/Dumper/YamlDumperTest.php index 77528fee3f..f3a357bce9 100644 --- a/tests/Symfony/Tests/Component/DependencyInjection/Dumper/YamlDumperTest.php +++ b/tests/Symfony/Tests/Component/DependencyInjection/Dumper/YamlDumperTest.php @@ -79,7 +79,7 @@ interfaces: FooClass: calls: - [setBar, [someValue]] - + services: foo: diff --git a/tests/Symfony/Tests/Component/HttpFoundation/CookieTest.php b/tests/Symfony/Tests/Component/HttpFoundation/CookieTest.php index aa65b26db4..b2e869c589 100644 --- a/tests/Symfony/Tests/Component/HttpFoundation/CookieTest.php +++ b/tests/Symfony/Tests/Component/HttpFoundation/CookieTest.php @@ -69,13 +69,13 @@ class CookieTest extends \PHPUnit_Framework_TestCase { new Cookie('MyCookie', $value); } - + /** * @expectedException InvalidArgumentException */ public function testInvalidExpiration() { - $cookie = new Cookie('MyCookie', 'foo','bar'); + $cookie = new Cookie('MyCookie', 'foo','bar'); } /** diff --git a/tests/Symfony/Tests/Component/HttpFoundation/RequestTest.php b/tests/Symfony/Tests/Component/HttpFoundation/RequestTest.php index d93359a7db..019fa215f0 100644 --- a/tests/Symfony/Tests/Component/HttpFoundation/RequestTest.php +++ b/tests/Symfony/Tests/Component/HttpFoundation/RequestTest.php @@ -116,7 +116,7 @@ class RequestTest extends \PHPUnit_Framework_TestCase public function testGetFormatFromMimeType($format, $mimeTypes) { $request = new Request(); - foreach ($mimeTypes as $mime) { + foreach ($mimeTypes as $mime) { $this->assertEquals($format, $request->getFormat($mime)); } $request->setFormat($format, $mimeTypes); @@ -634,7 +634,7 @@ class RequestTest extends \PHPUnit_Framework_TestCase $request = new Request(); $request->headers->set('Accept-Charset', 'ISO-8859-1, US-ASCII, UTF-8; q=0.8, ISO-10646-UCS-2; q=0.6'); $this->assertEquals(array('ISO-8859-1', 'US-ASCII', 'UTF-8', 'ISO-10646-UCS-2'), $request->getCharsets()); - + $request = new Request(); $request->headers->set('Accept-Charset', 'ISO-8859-1,utf-8;q=0.7,*;q=0.7'); $this->assertEquals(array('ISO-8859-1', '*', 'utf-8'), $request->getCharsets()); diff --git a/tests/Symfony/Tests/Component/HttpKernel/Bundle/BundleTest.php b/tests/Symfony/Tests/Component/HttpKernel/Bundle/BundleTest.php index eb50422611..8028edc7ab 100644 --- a/tests/Symfony/Tests/Component/HttpKernel/Bundle/BundleTest.php +++ b/tests/Symfony/Tests/Component/HttpKernel/Bundle/BundleTest.php @@ -24,13 +24,13 @@ class BundleTest extends \PHPUnit_Framework_TestCase $cmd = new FooCommand(); $app = $this->getMock('Symfony\Component\Console\Application'); $app->expects($this->once())->method('add')->with($this->equalTo($cmd)); - + $bundle = new ExtensionPresentBundle(); $bundle->registerCommands($app); - + $bundle2 = new ExtensionAbsentBundle(); - + $this->assertNull($bundle2->registerCommands($app)); - + } } \ No newline at end of file diff --git a/tests/Symfony/Tests/Component/HttpKernel/DataCollector/ExceptionDataCollectorTest.php b/tests/Symfony/Tests/Component/HttpKernel/DataCollector/ExceptionDataCollectorTest.php index 4e105d6694..88360c6f0f 100644 --- a/tests/Symfony/Tests/Component/HttpKernel/DataCollector/ExceptionDataCollectorTest.php +++ b/tests/Symfony/Tests/Component/HttpKernel/DataCollector/ExceptionDataCollectorTest.php @@ -24,11 +24,11 @@ class ExceptionDataCollectorTest extends \PHPUnit_Framework_TestCase $c = new ExceptionDataCollector(); $flattened = FlattenException::create($e); $trace = $flattened->getTrace(); - + $this->assertFalse($c->hasException()); - + $c->collect(new Request(), new Response(),$e); - + $this->assertTrue($c->hasException()); $this->assertEquals($flattened,$c->getException()); $this->assertSame('foo',$c->getMessage()); @@ -36,5 +36,5 @@ class ExceptionDataCollectorTest extends \PHPUnit_Framework_TestCase $this->assertSame('exception',$c->getName()); $this->assertSame($trace,$c->getTrace()); } - + } diff --git a/tests/Symfony/Tests/Component/HttpKernel/DataCollector/LoggerDataCollectorTest.php b/tests/Symfony/Tests/Component/HttpKernel/DataCollector/LoggerDataCollectorTest.php index 84033306e7..529211e89f 100644 --- a/tests/Symfony/Tests/Component/HttpKernel/DataCollector/LoggerDataCollectorTest.php +++ b/tests/Symfony/Tests/Component/HttpKernel/DataCollector/LoggerDataCollectorTest.php @@ -22,14 +22,14 @@ class LoggerDataCollectorTest extends \PHPUnit_Framework_TestCase public function testCollect() { $c = new LoggerDataCollector(new TestLogger()); - + $c->collect(new Request(), new Response()); - + $this->assertSame('logger',$c->getName()); $this->assertSame(1337,$c->countErrors()); $this->assertSame(array('foo'),$c->getLogs()); } - + } class TestLogger extends Logger implements DebugLoggerInterface @@ -38,12 +38,12 @@ class TestLogger extends Logger implements DebugLoggerInterface { return 1337; } - + public function getDebugLogger() { return new static(); } - + public function getLogs($priority = false) { return array('foo'); diff --git a/tests/Symfony/Tests/Component/HttpKernel/DataCollector/MemoryDataCollectorTest.php b/tests/Symfony/Tests/Component/HttpKernel/DataCollector/MemoryDataCollectorTest.php index 2d0c4ff503..d52f5a9b2b 100644 --- a/tests/Symfony/Tests/Component/HttpKernel/DataCollector/MemoryDataCollectorTest.php +++ b/tests/Symfony/Tests/Component/HttpKernel/DataCollector/MemoryDataCollectorTest.php @@ -20,11 +20,11 @@ class MemoryDataCollectorTest extends \PHPUnit_Framework_TestCase public function testCollect() { $c = new MemoryDataCollector(); - + $c->collect(new Request(), new Response()); - + $this->assertInternalType('integer',$c->getMemory()); $this->assertSame('memory',$c->getName()); } - + } diff --git a/tests/Symfony/Tests/Component/HttpKernel/DataCollector/RequestDataCollectorTest.php b/tests/Symfony/Tests/Component/HttpKernel/DataCollector/RequestDataCollectorTest.php index 09736efbb1..e8e4ce4d60 100644 --- a/tests/Symfony/Tests/Component/HttpKernel/DataCollector/RequestDataCollectorTest.php +++ b/tests/Symfony/Tests/Component/HttpKernel/DataCollector/RequestDataCollectorTest.php @@ -24,9 +24,9 @@ class RequestDataCollectorTest extends \PHPUnit_Framework_TestCase public function testCollect(Request $request, Response $response) { $c = new RequestDataCollector(); - + $c->collect($request, $response); - + $this->assertSame('request',$c->getName()); $this->assertInstanceOf('Symfony\Component\HttpFoundation\HeaderBag',$c->getRequestHeaders()); $this->assertInstanceOf('Symfony\Component\HttpFoundation\ParameterBag',$c->getRequestServer()); @@ -36,27 +36,27 @@ class RequestDataCollectorTest extends \PHPUnit_Framework_TestCase $this->assertInstanceOf('Symfony\Component\HttpFoundation\ParameterBag',$c->getRequestQuery()); $this->assertEquals('html',$c->getFormat()); $this->assertEquals(array(),$c->getSessionAttributes()); - + $this->assertInstanceOf('Symfony\Component\HttpFoundation\HeaderBag',$c->getResponseHeaders()); $this->assertEquals(200,$c->getStatusCode()); $this->assertEquals('application/json',$c->getContentType()); } - + public function provider() { $request = Request::create('http://test.com/foo?bar=baz'); $request->attributes->set('foo', 'bar'); - + $response = new Response(); $response->setStatusCode(200); $response->headers->set('Content-Type', 'application/json'); $response->headers->setCookie(new Cookie('foo','bar',1,'/foo','localhost',true,true)); $response->headers->setCookie(new Cookie('bar','foo',new \DateTime('@946684800'))); $response->headers->setCookie(new Cookie('bazz','foo','2000-12-12')); - + return array( array($request,$response) ); } - + } diff --git a/tests/Symfony/Tests/Component/HttpKernel/Debug/ErrorHandlerTest.php b/tests/Symfony/Tests/Component/HttpKernel/Debug/ErrorHandlerTest.php index 6e7607e1db..6c96cf3c9e 100644 --- a/tests/Symfony/Tests/Component/HttpKernel/Debug/ErrorHandlerTest.php +++ b/tests/Symfony/Tests/Component/HttpKernel/Debug/ErrorHandlerTest.php @@ -21,27 +21,27 @@ use Symfony\Component\HttpKernel\Debug\ErrorException; */ class ErrorHandlerTest extends \PHPUnit_Framework_TestCase { - + public function testConstruct() { $e = new ErrorHandler(3); - + $this->assertInstanceOf('Symfony\Component\HttpKernel\Debug\ErrorHandler',$e); - + $level = new \ReflectionProperty(get_class($e),'level'); $level->setAccessible(true); - + $this->assertEquals(3,$level->getValue($e)); } - + public function testRegister() { $e = new ErrorHandler(3); $e = $this->getMock(get_class($e), array('handle')); $e->expects($this->once())->method('handle'); - + $e->register(); - + try{ trigger_error('foo'); }catch(\Exception $e){ @@ -52,10 +52,10 @@ class ErrorHandlerTest extends \PHPUnit_Framework_TestCase { $e = new ErrorHandler(0); $this->assertFalse($e->handle(0,'foo','foo.php',12,'foo')); - + $e = new ErrorHandler(3); $this->assertFalse($e->handle(4,'foo','foo.php',12,'foo')); - + $e = new ErrorHandler(3); try{ $e->handle(1, 'foo', 'foo.php', 12,'foo'); diff --git a/tests/Symfony/Tests/Component/HttpKernel/Exception/FlattenExceptionTest.php b/tests/Symfony/Tests/Component/HttpKernel/Exception/FlattenExceptionTest.php index 3a4f577be3..48dcd77886 100644 --- a/tests/Symfony/Tests/Component/HttpKernel/Exception/FlattenExceptionTest.php +++ b/tests/Symfony/Tests/Component/HttpKernel/Exception/FlattenExceptionTest.php @@ -21,7 +21,7 @@ class FlattenExceptionTest extends \PHPUnit_Framework_TestCase { $flattened = FlattenException::create($exception); $flattened2 = FlattenException::create($exception); - + $flattened->setPrevious($flattened2); $this->assertEquals($exception->getMessage(), $flattened->getMessage(), 'The message is copied from the original exception.'); @@ -29,7 +29,7 @@ class FlattenExceptionTest extends \PHPUnit_Framework_TestCase $this->assertEquals(get_class($exception), $flattened->getClass(), 'The class is set to the class of the original exception'); } - + /** * @dataProvider flattenDataProvider */ @@ -37,14 +37,14 @@ class FlattenExceptionTest extends \PHPUnit_Framework_TestCase { $flattened = FlattenException::create($exception); $flattened2 = FlattenException::create($exception); - + $flattened->setPrevious($flattened2); - + $this->assertSame($flattened2,$flattened->getPrevious()); - + $this->assertSame(array($flattened2),$flattened->getPreviouses()); } - + /** * @dataProvider flattenDataProvider */ @@ -52,7 +52,7 @@ class FlattenExceptionTest extends \PHPUnit_Framework_TestCase { $flattened = FlattenException::create($exception); $flattened->setTrace(array(),'foo.php',123); - + $this->assertEquals(array( array( 'message'=> 'test', @@ -64,7 +64,7 @@ class FlattenExceptionTest extends \PHPUnit_Framework_TestCase ) ),$flattened->toArray()); } - + public function flattenDataProvider() { return array( diff --git a/tests/Symfony/Tests/Component/HttpKernel/Fixtures/ExtensionPresentBundle/Command/FooCommand.php b/tests/Symfony/Tests/Component/HttpKernel/Fixtures/ExtensionPresentBundle/Command/FooCommand.php index 1914ad70a0..398cb817fc 100644 --- a/tests/Symfony/Tests/Component/HttpKernel/Fixtures/ExtensionPresentBundle/Command/FooCommand.php +++ b/tests/Symfony/Tests/Component/HttpKernel/Fixtures/ExtensionPresentBundle/Command/FooCommand.php @@ -19,5 +19,5 @@ class FooCommand extends Command { $this->setName('foo'); } - + } diff --git a/tests/Symfony/Tests/Component/HttpKernel/KernelTest.php b/tests/Symfony/Tests/Component/HttpKernel/KernelTest.php index 9bce11e431..aa5c1aba60 100644 --- a/tests/Symfony/Tests/Component/HttpKernel/KernelTest.php +++ b/tests/Symfony/Tests/Component/HttpKernel/KernelTest.php @@ -341,7 +341,7 @@ EOF; $kernel->locateResource('@Bundle1Bundle/config/routing.xml'); } - + public function testLocateResourceReturnsTheFirstThatMatches() { $kernel = $this->getKernel(); diff --git a/tests/Symfony/Tests/Component/Routing/Generator/Dumper/PhpGeneratorDumperTest.php b/tests/Symfony/Tests/Component/Routing/Generator/Dumper/PhpGeneratorDumperTest.php index 1374024521..ca43691ba5 100644 --- a/tests/Symfony/Tests/Component/Routing/Generator/Dumper/PhpGeneratorDumperTest.php +++ b/tests/Symfony/Tests/Component/Routing/Generator/Dumper/PhpGeneratorDumperTest.php @@ -21,12 +21,12 @@ class PhpGeneratorDumperTest extends \PHPUnit_Framework_TestCase * @var RouteCollection */ private $routeCollection; - + /** * @var PhpGeneratorDumper */ private $generatorDumper; - + /** * @var string */ @@ -45,7 +45,7 @@ class PhpGeneratorDumperTest extends \PHPUnit_Framework_TestCase protected function tearDown() { parent::tearDown(); - + @unlink($this->testTmpFilepath); } @@ -53,7 +53,7 @@ class PhpGeneratorDumperTest extends \PHPUnit_Framework_TestCase { $this->routeCollection->add('Test', new Route('/testing/{foo}')); $this->routeCollection->add('Test2', new Route('/testing2')); - + file_put_contents($this->testTmpFilepath, $this->generatorDumper->dump()); include ($this->testTmpFilepath); @@ -64,7 +64,7 @@ class PhpGeneratorDumperTest extends \PHPUnit_Framework_TestCase 'port' => 80, 'is_secure' => false )); - + $absoluteUrlWithParameter = $projectUrlGenerator->generate('Test', array('foo' => 'bar'), true); $absoluteUrlWithoutParameter = $projectUrlGenerator->generate('Test2', array(), true); $relativeUrlWithParameter = $projectUrlGenerator->generate('Test', array('foo' => 'bar'), false); @@ -75,7 +75,7 @@ class PhpGeneratorDumperTest extends \PHPUnit_Framework_TestCase $this->assertEquals($relativeUrlWithParameter, '/app.php/testing/bar'); $this->assertEquals($relativeUrlWithoutParameter, '/app.php/testing2'); } - + /** * @expectedException \InvalidArgumentException */ @@ -91,17 +91,17 @@ class PhpGeneratorDumperTest extends \PHPUnit_Framework_TestCase 'port' => 80, 'is_secure' => false )); - + $projectUrlGenerator->generate('Test', array()); } - + public function testDumpForRouteWithDefaults() { $this->routeCollection->add('Test', new Route('/testing/{foo}', array('foo' => 'bar'))); - + file_put_contents($this->testTmpFilepath, $this->generatorDumper->dump(array('class' => 'DefaultRoutesUrlGenerator'))); include ($this->testTmpFilepath); - + $projectUrlGenerator = new \DefaultRoutesUrlGenerator(array()); $url = $projectUrlGenerator->generate('Test', array()); diff --git a/tests/Symfony/Tests/Component/Routing/Generator/UrlGeneratorTest.php b/tests/Symfony/Tests/Component/Routing/Generator/UrlGeneratorTest.php index 5cdf04393a..381193e433 100644 --- a/tests/Symfony/Tests/Component/Routing/Generator/UrlGeneratorTest.php +++ b/tests/Symfony/Tests/Component/Routing/Generator/UrlGeneratorTest.php @@ -104,7 +104,7 @@ class UrlGeneratorTest extends \PHPUnit_Framework_TestCase $this->assertEquals('/app.php/testing', $url); } - + public function testRelativeUrlWithParameter() { $this->routeCollection->add('test', new Route('/testing/{foo}')); @@ -119,7 +119,7 @@ class UrlGeneratorTest extends \PHPUnit_Framework_TestCase $this->assertEquals('/app.php/testing/bar', $url); } - + public function testRelativeUrlWithExtraParameters() { $this->routeCollection->add('test', new Route('/testing')); @@ -134,7 +134,7 @@ class UrlGeneratorTest extends \PHPUnit_Framework_TestCase $this->assertEquals('/app.php/testing?foo=bar', $url); } - + public function testAbsoluteUrlWithExtraParameters() { $this->routeCollection->add('test', new Route('/testing')); @@ -149,15 +149,15 @@ class UrlGeneratorTest extends \PHPUnit_Framework_TestCase $this->assertEquals('http://localhost/app.php/testing?foo=bar', $url); } - + /** * @expectedException \InvalidArgumentException */ public function testGenerateWithoutRoutes() - { + { $this->generator->generate('test', array(), true); } - + /** * @expectedException \InvalidArgumentException */ @@ -166,7 +166,7 @@ class UrlGeneratorTest extends \PHPUnit_Framework_TestCase $this->routeCollection->add('test', new Route('/testing/{foo}')); $this->generator->generate('test', array(), true); } - + /** * @expectedException \InvalidArgumentException */ @@ -176,7 +176,7 @@ class UrlGeneratorTest extends \PHPUnit_Framework_TestCase $this->routeCollection->add('test', $route); $this->generator->generate('test', array('foo' => 'bar'), true); } - + /** * @expectedException \InvalidArgumentException */ @@ -185,5 +185,5 @@ class UrlGeneratorTest extends \PHPUnit_Framework_TestCase $route = new Route('/testing/{foo}', array(), array('foo' => 'd+')); $this->routeCollection->add('test', $route); $this->generator->generate('test', array('foo' => 'bar'), true); - } + } } diff --git a/tests/Symfony/Tests/Component/Security/Acl/Domain/AuditLoggerTest.php b/tests/Symfony/Tests/Component/Security/Acl/Domain/AuditLoggerTest.php index 4974559986..0061c5993f 100644 --- a/tests/Symfony/Tests/Component/Security/Acl/Domain/AuditLoggerTest.php +++ b/tests/Symfony/Tests/Component/Security/Acl/Domain/AuditLoggerTest.php @@ -20,14 +20,14 @@ class AuditLoggerTest extends \PHPUnit_Framework_TestCase { $logger = $this->getLogger(); $ace = $this->getEntry(); - + if (true === $granting) { $ace ->expects($this->once()) ->method('isAuditSuccess') ->will($this->returnValue($audit)) ; - + $ace ->expects($this->never()) ->method('isAuditFailure') @@ -37,7 +37,7 @@ class AuditLoggerTest extends \PHPUnit_Framework_TestCase ->expects($this->never()) ->method('isAuditSuccess') ; - + $ace ->expects($this->once()) ->method('isAuditFailure') @@ -57,10 +57,10 @@ class AuditLoggerTest extends \PHPUnit_Framework_TestCase ->method('doLog') ; } - + $logger->logIfNeeded($granting, $ace); } - + public function getTestLogData() { return array( @@ -70,12 +70,12 @@ class AuditLoggerTest extends \PHPUnit_Framework_TestCase array(false, true), ); } - + protected function getEntry() { return $this->getMock('Symfony\Component\Security\Acl\Model\AuditableEntryInterface'); } - + protected function getLogger() { return $this->getMockForAbstractClass('Symfony\Component\Security\Acl\Domain\AuditLogger'); diff --git a/tests/Symfony/Tests/Component/Security/Acl/Domain/EntryTest.php b/tests/Symfony/Tests/Component/Security/Acl/Domain/EntryTest.php index a484694915..0916462296 100644 --- a/tests/Symfony/Tests/Component/Security/Acl/Domain/EntryTest.php +++ b/tests/Symfony/Tests/Component/Security/Acl/Domain/EntryTest.php @@ -18,7 +18,7 @@ class EntryTest extends \PHPUnit_Framework_TestCase public function testConstructor() { $ace = $this->getAce($acl = $this->getAcl(), $sid = $this->getSid()); - + $this->assertEquals(123, $ace->getId()); $this->assertSame($acl, $ace->getAcl()); $this->assertSame($sid, $ace->getSecurityIdentity()); @@ -28,54 +28,54 @@ class EntryTest extends \PHPUnit_Framework_TestCase $this->assertTrue($ace->isAuditSuccess()); $this->assertFalse($ace->isAuditFailure()); } - + public function testSetAuditSuccess() { $ace = $this->getAce(); - + $this->assertTrue($ace->isAuditSuccess()); $ace->setAuditSuccess(false); $this->assertFalse($ace->isAuditSuccess()); $ace->setAuditsuccess(true); $this->assertTrue($ace->isAuditSuccess()); } - + public function testSetAuditFailure() { $ace = $this->getAce(); - + $this->assertFalse($ace->isAuditFailure()); $ace->setAuditFailure(true); $this->assertTrue($ace->isAuditFailure()); $ace->setAuditFailure(false); $this->assertFalse($ace->isAuditFailure()); } - + public function testSetMask() { $ace = $this->getAce(); - + $this->assertEquals(123456, $ace->getMask()); $ace->setMask(4321); $this->assertEquals(4321, $ace->getMask()); } - + public function testSetStrategy() { $ace = $this->getAce(); - + $this->assertEquals('foostrat', $ace->getStrategy()); $ace->setStrategy('foo'); $this->assertEquals('foo', $ace->getStrategy()); } - + public function testSerializeUnserialize() { $ace = $this->getAce(); - + $serialized = serialize($ace); $uAce = unserialize($serialized); - + $this->assertNull($uAce->getAcl()); $this->assertInstanceOf('Symfony\Component\Security\Acl\Model\SecurityIdentityInterface', $uAce->getSecurityIdentity()); $this->assertEquals($ace->getId(), $uAce->getId()); @@ -85,7 +85,7 @@ class EntryTest extends \PHPUnit_Framework_TestCase $this->assertEquals($ace->isAuditSuccess(), $uAce->isAuditSuccess()); $this->assertEquals($ace->isAuditFailure(), $uAce->isAuditFailure()); } - + protected function getAce($acl = null, $sid = null) { if (null === $acl) { @@ -94,24 +94,24 @@ class EntryTest extends \PHPUnit_Framework_TestCase if (null === $sid) { $sid = $this->getSid(); } - + return new Entry( - 123, - $acl, - $sid, - 'foostrat', - 123456, - true, - false, + 123, + $acl, + $sid, + 'foostrat', + 123456, + true, + false, true - ); + ); } - + protected function getAcl() { return $this->getMock('Symfony\Component\Security\Acl\Model\AclInterface'); } - + protected function getSid() { return $this->getMock('Symfony\Component\Security\Acl\Model\SecurityIdentityInterface'); diff --git a/tests/Symfony/Tests/Component/Security/Acl/Domain/FieldEntryTest.php b/tests/Symfony/Tests/Component/Security/Acl/Domain/FieldEntryTest.php index 4b2e31ab2c..c8dc733826 100644 --- a/tests/Symfony/Tests/Component/Security/Acl/Domain/FieldEntryTest.php +++ b/tests/Symfony/Tests/Component/Security/Acl/Domain/FieldEntryTest.php @@ -18,17 +18,17 @@ class FieldEntryTest extends \PHPUnit_Framework_TestCase public function testConstructor() { $ace = $this->getAce(); - + $this->assertEquals('foo', $ace->getField()); } - + public function testSerializeUnserialize() { $ace = $this->getAce(); - + $serialized = serialize($ace); $uAce = unserialize($serialized); - + $this->assertNull($uAce->getAcl()); $this->assertInstanceOf('Symfony\Component\Security\Acl\Model\SecurityIdentityInterface', $uAce->getSecurityIdentity()); $this->assertEquals($ace->getId(), $uAce->getId()); @@ -39,7 +39,7 @@ class FieldEntryTest extends \PHPUnit_Framework_TestCase $this->assertEquals($ace->isAuditSuccess(), $uAce->isAuditSuccess()); $this->assertEquals($ace->isAuditFailure(), $uAce->isAuditFailure()); } - + protected function getAce($acl = null, $sid = null) { if (null === $acl) { @@ -48,25 +48,25 @@ class FieldEntryTest extends \PHPUnit_Framework_TestCase if (null === $sid) { $sid = $this->getSid(); } - + return new FieldEntry( - 123, - $acl, + 123, + $acl, 'foo', - $sid, - 'foostrat', - 123456, - true, - false, + $sid, + 'foostrat', + 123456, + true, + false, true - ); + ); } - + protected function getAcl() { return $this->getMock('Symfony\Component\Security\Acl\Model\AclInterface'); } - + protected function getSid() { return $this->getMock('Symfony\Component\Security\Acl\Model\SecurityIdentityInterface'); diff --git a/tests/Symfony/Tests/Component/Security/Acl/Permission/MaskBuilderTest.php b/tests/Symfony/Tests/Component/Security/Acl/Permission/MaskBuilderTest.php index 3ab64b41cc..2a5b5ed92d 100644 --- a/tests/Symfony/Tests/Component/Security/Acl/Permission/MaskBuilderTest.php +++ b/tests/Symfony/Tests/Component/Security/Acl/Permission/MaskBuilderTest.php @@ -23,7 +23,7 @@ class MaskBuilderTest extends \PHPUnit_Framework_TestCase { new MaskBuilder($invalidMask); } - + public function getInvalidConstructorData() { return array( @@ -33,32 +33,32 @@ class MaskBuilderTest extends \PHPUnit_Framework_TestCase array(new \stdClass()), ); } - + public function testConstructorWithoutArguments() { $builder = new MaskBuilder(); - + $this->assertEquals(0, $builder->get()); } - + public function testConstructor() { $builder = new MaskBuilder(123456); - + $this->assertEquals(123456, $builder->get()); } - + public function testAddAndRemove() { $builder = new MaskBuilder(); - + $builder ->add('view') ->add('eDiT') ->add('ownEr') ; $mask = $builder->get(); - + $this->assertEquals(MaskBuilder::MASK_VIEW, $mask & MaskBuilder::MASK_VIEW); $this->assertEquals(MaskBuilder::MASK_EDIT, $mask & MaskBuilder::MASK_EDIT); $this->assertEquals(MaskBuilder::MASK_OWNER, $mask & MaskBuilder::MASK_OWNER); @@ -66,37 +66,37 @@ class MaskBuilderTest extends \PHPUnit_Framework_TestCase $this->assertEquals(0, $mask & MaskBuilder::MASK_CREATE); $this->assertEquals(0, $mask & MaskBuilder::MASK_DELETE); $this->assertEquals(0, $mask & MaskBuilder::MASK_UNDELETE); - + $builder->remove('edit')->remove('OWner'); $mask = $builder->get(); $this->assertEquals(0, $mask & MaskBuilder::MASK_EDIT); $this->assertEquals(0, $mask & MaskBuilder::MASK_OWNER); $this->assertEquals(MaskBuilder::MASK_VIEW, $mask & MaskBuilder::MASK_VIEW); } - + public function testGetPattern() { $builder = new MaskBuilder; $this->assertEquals(MaskBuilder::ALL_OFF, $builder->getPattern()); - + $builder->add('view'); $this->assertEquals(str_repeat('.', 31).'V', $builder->getPattern()); - + $builder->add('owner'); $this->assertEquals(str_repeat('.', 24).'N......V', $builder->getPattern()); - + $builder->add(1 << 10); $this->assertEquals(str_repeat('.', 21).MaskBuilder::ON.'..N......V', $builder->getPattern()); } - + public function testReset() { $builder = new MaskBuilder(); $this->assertEquals(0, $builder->get()); - + $builder->add('view'); $this->assertTrue($builder->get() > 0); - + $builder->reset(); $this->assertEquals(0, $builder->get()); } diff --git a/tests/Symfony/Tests/Component/Security/Acl/Voter/AclVoterTest.php b/tests/Symfony/Tests/Component/Security/Acl/Voter/AclVoterTest.php index 94f35545e5..885304fb35 100644 --- a/tests/Symfony/Tests/Component/Security/Acl/Voter/AclVoterTest.php +++ b/tests/Symfony/Tests/Component/Security/Acl/Voter/AclVoterTest.php @@ -360,13 +360,13 @@ class AclVoterTest extends \PHPUnit_Framework_TestCase $this->assertSame(VoterInterface::ACCESS_DENIED, $voter->vote($this->getToken(), new FieldVote(new \stdClass(), 'foo'), array('VIEW'))); } - + public function testWhenReceivingAnObjectIdentityInterfaceWeDontRetrieveANewObjectIdentity() { list($voter, $provider, $permissionMap, $oidStrategy, $sidStrategy) = $this->getVoter(); - + $oid = new ObjectIdentity('someID','someType'); - + $permissionMap ->expects($this->once()) ->method('contains') diff --git a/tests/Symfony/Tests/Component/Serializer/Encoder/XmlEncoderTest.php b/tests/Symfony/Tests/Component/Serializer/Encoder/XmlEncoderTest.php index 737d41b350..80df994b61 100644 --- a/tests/Symfony/Tests/Component/Serializer/Encoder/XmlEncoderTest.php +++ b/tests/Symfony/Tests/Component/Serializer/Encoder/XmlEncoderTest.php @@ -111,16 +111,16 @@ class XmlEncoderTest extends \PHPUnit_Framework_TestCase $this->assertEquals($expected, $this->encoder->encode($array, 'xml')); } - + public function testEncodeScalarWithAttribute() { $array = array( 'person' => array('@gender' => 'M', '#' => 'Peter'), ); - + $expected = ''."\n". ''."\n"; - + $this->assertEquals($expected, $this->encoder->encode($array, 'xml')); } @@ -147,19 +147,19 @@ class XmlEncoderTest extends \PHPUnit_Framework_TestCase $this->assertEquals(get_object_vars($obj), $this->encoder->decode($source, 'xml')); } - + public function testDecodeScalarWithAttribute() { $source = ''."\n". 'Peter'."\n"; - + $expected = array( 'person' => array('@gender' => 'M', '#' => 'Peter'), ); - + $this->assertEquals($expected, $this->encoder->decode($source, 'xml')); } - + public function testDecodeArray() { $source = ''."\n". @@ -169,14 +169,14 @@ class XmlEncoderTest extends \PHPUnit_Framework_TestCase 'DamienClay'. ''. ''."\n"; - + $expected = array( 'people' => array('person' => array( array('firstname' => 'Benjamin', 'lastname' => 'Alexandre'), array('firstname' => 'Damien', 'lastname' => 'Clay') )) ); - + $this->assertEquals($expected, $this->encoder->decode($source, 'xml')); } From ad86f9ff0d7d6361dae191c792a827c97b4d1525 Mon Sep 17 00:00:00 2001 From: Tim Nagel Date: Sat, 16 Apr 2011 16:21:04 +1000 Subject: [PATCH 19/91] [Security] Added missing phpdoc --- .../Acl/Model/FieldAwareEntryInterface.php | 5 +++++ .../Security/Core/SecurityContext.php | 8 ++++++++ .../Core/SecurityContextInterface.php | 20 +++++++++++++++++++ 3 files changed, 33 insertions(+) diff --git a/src/Symfony/Component/Security/Acl/Model/FieldAwareEntryInterface.php b/src/Symfony/Component/Security/Acl/Model/FieldAwareEntryInterface.php index 032d6e34a1..bcf292cdaf 100644 --- a/src/Symfony/Component/Security/Acl/Model/FieldAwareEntryInterface.php +++ b/src/Symfony/Component/Security/Acl/Model/FieldAwareEntryInterface.php @@ -18,5 +18,10 @@ namespace Symfony\Component\Security\Acl\Model; */ interface FieldAwareEntryInterface { + /** + * Returns the field used for this entry. + * + * @return string + */ function getField(); } \ No newline at end of file diff --git a/src/Symfony/Component/Security/Core/SecurityContext.php b/src/Symfony/Component/Security/Core/SecurityContext.php index 76ec4c1092..2910e3b44c 100644 --- a/src/Symfony/Component/Security/Core/SecurityContext.php +++ b/src/Symfony/Component/Security/Core/SecurityContext.php @@ -45,6 +45,14 @@ class SecurityContext implements SecurityContextInterface $this->alwaysAuthenticate = $alwaysAuthenticate; } + /** + * Checks if the attributes are granted against the current token. + * + * @throws AuthenticationCredentialsNotFoundException when the security context has no authentication token. + * @param mixed $attributes + * @param mixed|null $object + * @return boolean + */ public final function isGranted($attributes, $object = null) { if (null === $this->token) { diff --git a/src/Symfony/Component/Security/Core/SecurityContextInterface.php b/src/Symfony/Component/Security/Core/SecurityContextInterface.php index a811557727..a47c89dbcb 100644 --- a/src/Symfony/Component/Security/Core/SecurityContextInterface.php +++ b/src/Symfony/Component/Security/Core/SecurityContextInterface.php @@ -15,7 +15,27 @@ interface SecurityContextInterface const AUTHENTICATION_ERROR = '_security.last_error'; const LAST_USERNAME = '_security.last_username'; + /** + * Returns the current security token. + * + * @return TokenInterface|null A TokenInterface instance or null if no authentication information is available + */ function getToken(); + + /** + * Sets the authentication token. + * + * @param TokenInterface $token + * @return void + */ function setToken(TokenInterface $token); + + /** + * Checks if the attributes are granted against the current authentication token and optionally supplied object. + * + * @param array $attributes + * @param mixed $object + * @return boolean + */ function isGranted($attributes, $object = null); } \ No newline at end of file From c6818d8bf75a840acce5bdf9a0968f1a4bccb6ff Mon Sep 17 00:00:00 2001 From: Fabien Potencier Date: Sat, 16 Apr 2011 16:26:13 +0200 Subject: [PATCH 20/91] [HttpKernel] added support for controllers as arrays and object with an __invoke method Controllers can now be any valid PHP callable --- .../Controller/ControllerResolver.php | 10 ++- .../Controller/ControllerResolverTest.php | 28 ++++++++ .../Component/HttpKernel/HttpKernelTest.php | 64 +++++++++++++++++++ 3 files changed, 100 insertions(+), 2 deletions(-) diff --git a/src/Symfony/Component/HttpKernel/Controller/ControllerResolver.php b/src/Symfony/Component/HttpKernel/Controller/ControllerResolver.php index c4ddddbdcf..ce95590f97 100644 --- a/src/Symfony/Component/HttpKernel/Controller/ControllerResolver.php +++ b/src/Symfony/Component/HttpKernel/Controller/ControllerResolver.php @@ -60,7 +60,7 @@ class ControllerResolver implements ControllerResolverInterface return false; } - if ($controller instanceof \Closure) { + if (is_array($controller) || method_exists($controller, '__invoke')) { return $controller; } @@ -92,15 +92,21 @@ class ControllerResolver implements ControllerResolverInterface if (is_array($controller)) { $r = new \ReflectionMethod($controller[0], $controller[1]); $repr = sprintf('%s::%s()', get_class($controller[0]), $controller[1]); + } elseif (is_object($controller)) { + $r = new \ReflectionObject($controller); + $r = $r->getMethod('__invoke'); + $repr = get_class($controller); } else { $r = new \ReflectionFunction($controller); - $repr = 'Closure'; + $repr = $controller; } $arguments = array(); foreach ($r->getParameters() as $param) { if (array_key_exists($param->getName(), $attributes)) { $arguments[] = $attributes[$param->getName()]; + } elseif ($param->getClass() && $param->getClass()->isInstance($request)) { + $arguments[] = $request; } elseif ($param->isDefaultValueAvailable()) { $arguments[] = $param->getDefaultValue(); } else { diff --git a/tests/Symfony/Tests/Component/HttpKernel/Controller/ControllerResolverTest.php b/tests/Symfony/Tests/Component/HttpKernel/Controller/ControllerResolverTest.php index d2e4940702..334fcb2af9 100644 --- a/tests/Symfony/Tests/Component/HttpKernel/Controller/ControllerResolverTest.php +++ b/tests/Symfony/Tests/Component/HttpKernel/Controller/ControllerResolverTest.php @@ -36,6 +36,18 @@ class ControllerResolverTest extends \PHPUnit_Framework_TestCase $controller = $resolver->getController($request); $this->assertSame($lambda, $controller); + $request->attributes->set('_controller', $this); + $controller = $resolver->getController($request); + $this->assertSame($this, $controller); + + $request->attributes->set('_controller', array($this, 'controllerMethod1')); + $controller = $resolver->getController($request); + $this->assertSame(array($this, 'controllerMethod1'), $controller); + + $request->attributes->set('_controller', array('Symfony\Tests\Component\HttpKernel\ControllerResolverTest', 'controllerMethod4')); + $controller = $resolver->getController($request); + $this->assertSame(array('Symfony\Tests\Component\HttpKernel\ControllerResolverTest', 'controllerMethod4'), $controller); + $request->attributes->set('_controller', 'foo'); try { $resolver->getController($request); @@ -98,6 +110,14 @@ class ControllerResolverTest extends \PHPUnit_Framework_TestCase } catch (\Exception $e) { $this->assertInstanceOf('\RuntimeException', $e, '->getArguments() throws a \RuntimeException exception if it cannot determine the argument value'); } + + $request = Request::create('/'); + $controller = array(new self(), 'controllerMethod5'); + $this->assertEquals(array($request), $resolver->getArguments($request, $controller), '->getArguments() injects the request'); + } + + public function __invoke() + { } protected function controllerMethod1($foo) @@ -111,4 +131,12 @@ class ControllerResolverTest extends \PHPUnit_Framework_TestCase protected function controllerMethod3($foo, $bar = null, $foobar) { } + + static protected function controllerMethod4() + { + } + + protected function controllerMethod5(Request $request) + { + } } diff --git a/tests/Symfony/Tests/Component/HttpKernel/HttpKernelTest.php b/tests/Symfony/Tests/Component/HttpKernel/HttpKernelTest.php index 2e86b88b83..852c9f2bcd 100644 --- a/tests/Symfony/Tests/Component/HttpKernel/HttpKernelTest.php +++ b/tests/Symfony/Tests/Component/HttpKernel/HttpKernelTest.php @@ -88,6 +88,47 @@ class HttpKernelTest extends \PHPUnit_Framework_TestCase $kernel->handle(new Request()); } + public function testHandleWhenNoControllerIsAClosure() + { + $response = new Response('foo'); + $dispatcher = new EventDispatcher(); + $kernel = new HttpKernel($dispatcher, $this->getResolver(function () use ($response) { return $response; })); + + $this->assertSame($response, $kernel->handle(new Request())); + } + + public function testHandleWhenNoControllerIsAnObjectWithInvoke() + { + $dispatcher = new EventDispatcher(); + $kernel = new HttpKernel($dispatcher, $this->getResolver(new Controller())); + + $this->assertEquals(new Response('foo'), $kernel->handle(new Request())); + } + + public function testHandleWhenNoControllerIsAFunction() + { + $dispatcher = new EventDispatcher(); + $kernel = new HttpKernel($dispatcher, $this->getResolver('Symfony\Tests\Component\HttpKernel\controller_func')); + + $this->assertEquals(new Response('foo'), $kernel->handle(new Request())); + } + + public function testHandleWhenNoControllerIsAnArray() + { + $dispatcher = new EventDispatcher(); + $kernel = new HttpKernel($dispatcher, $this->getResolver(array(new Controller(), 'controller'))); + + $this->assertEquals(new Response('foo'), $kernel->handle(new Request())); + } + + public function testHandleWhenNoControllerIsAStaticArray() + { + $dispatcher = new EventDispatcher(); + $kernel = new HttpKernel($dispatcher, $this->getResolver(array('Symfony\Tests\Component\HttpKernel\Controller', 'staticcontroller'))); + + $this->assertEquals(new Response('foo'), $kernel->handle(new Request())); + } + /** * @expectedException LogicException */ @@ -140,3 +181,26 @@ class HttpKernelTest extends \PHPUnit_Framework_TestCase return $resolver; } } + +class Controller +{ + public function __invoke() + { + return new Response('foo'); + } + + public function controller() + { + return new Response('foo'); + } + + static public function staticController() + { + return new Response('foo'); + } +} + +function controller_func() +{ + return new Response('foo'); +} From 54c3d236c2a28c02e8a11c533932dd3ea390933a Mon Sep 17 00:00:00 2001 From: hidenorigoto Date: Sun, 17 Apr 2011 10:45:32 +0900 Subject: [PATCH 21/91] [BrowserKit] added the method to Client which enables to set single server parameter --- src/Symfony/Component/BrowserKit/Client.php | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/src/Symfony/Component/BrowserKit/Client.php b/src/Symfony/Component/BrowserKit/Client.php index 07b8f93690..e647da6142 100644 --- a/src/Symfony/Component/BrowserKit/Client.php +++ b/src/Symfony/Component/BrowserKit/Client.php @@ -108,6 +108,17 @@ abstract class Client ), $server); } + /** + * Sets single server parameter. + * + * @param string $key A key of the parameter + * @param string $value A value of the parameter + */ + public function setServerParameter($key, $value) + { + $this->server[$key] = $value; + } + /** * Returns the History instance. * From 1d85a3dcb176189125dab3a00130d5f90e751337 Mon Sep 17 00:00:00 2001 From: hidenorigoto Date: Sun, 17 Apr 2011 11:22:59 +0900 Subject: [PATCH 22/91] [BrowserKit] added getServerParameter method which makes setServerParameters/setServerParameter methods testable --- src/Symfony/Component/BrowserKit/Client.php | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/src/Symfony/Component/BrowserKit/Client.php b/src/Symfony/Component/BrowserKit/Client.php index e647da6142..bf8a14efd6 100644 --- a/src/Symfony/Component/BrowserKit/Client.php +++ b/src/Symfony/Component/BrowserKit/Client.php @@ -119,6 +119,18 @@ abstract class Client $this->server[$key] = $value; } + /** + * Gets single server parameter for specified key. + * + * @param string $key A key of the parameter to get + * @param string $default A default value when key is undefined + * @return string A value of the parameter + */ + public function getServerParameter($key, $default = '') + { + return (isset($this->server[$key])) ? $this->server[$key] : $default; + } + /** * Returns the History instance. * From 43952b31759824084acb4aae79152050ef54942f Mon Sep 17 00:00:00 2001 From: hidenorigoto Date: Sun, 17 Apr 2011 11:24:55 +0900 Subject: [PATCH 23/91] [BrowserKit] added tests for setServerParameter/getServerParameter methods --- .../Tests/Component/BrowserKit/ClientTest.php | 23 +++++++++++++++++++ 1 file changed, 23 insertions(+) diff --git a/tests/Symfony/Tests/Component/BrowserKit/ClientTest.php b/tests/Symfony/Tests/Component/BrowserKit/ClientTest.php index f64c9ff94e..7a9de55dd2 100644 --- a/tests/Symfony/Tests/Component/BrowserKit/ClientTest.php +++ b/tests/Symfony/Tests/Component/BrowserKit/ClientTest.php @@ -308,4 +308,27 @@ class ClientTest extends \PHPUnit_Framework_TestCase $this->assertInstanceof('RuntimeException', $e, '->request() throws a \RuntimeException if the script has an error'); } } + + public function testGetServerParameter() + { + $client = new TestClient(); + $this->assertEquals('localhost', $client->getServerParameter('HTTP_HOST')); + $this->assertEquals('Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.6; en-US; rv:1.9.2.3) Gecko/20100401 Firefox/3.6.3', $client->getServerParameter('HTTP_USER_AGENT')); + + $this->assertEquals('testvalue', $client->getServerParameter('testkey', 'testvalue')); + } + + public function testSetServerParameter() + { + $client = new TestClient(); + + $this->assertEquals('localhost', $client->getServerParameter('HTTP_HOST')); + $this->assertEquals('Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.6; en-US; rv:1.9.2.3) Gecko/20100401 Firefox/3.6.3', $client->getServerParameter('HTTP_USER_AGENT')); + + $client->setServerParameter('HTTP_HOST', 'testhost'); + $this->assertEquals('testhost', $client->getServerParameter('HTTP_HOST')); + + $client->setServerParameter('HTTP_USER_AGENT', 'testua'); + $this->assertEquals('testua', $client->getServerParameter('HTTP_USER_AGENT')); + } } From 30bac46e1bcda1ecd4f77354b9b88832113b785a Mon Sep 17 00:00:00 2001 From: "Johannes M. Schmitt" Date: Sun, 17 Apr 2011 12:29:05 +0200 Subject: [PATCH 24/91] [DependencyInjection] make base class of generated container configurable --- src/Symfony/Component/HttpKernel/Kernel.php | 19 ++++++++++++++++--- 1 file changed, 16 insertions(+), 3 deletions(-) diff --git a/src/Symfony/Component/HttpKernel/Kernel.php b/src/Symfony/Component/HttpKernel/Kernel.php index a758242faf..8a2da2f19f 100644 --- a/src/Symfony/Component/HttpKernel/Kernel.php +++ b/src/Symfony/Component/HttpKernel/Kernel.php @@ -435,6 +435,18 @@ abstract class Kernel implements KernelInterface return $this->name.ucfirst($this->environment).($this->debug ? 'Debug' : '').'ProjectContainer'; } + /** + * Gets the container's base class. + * + * All names except Container must be fully qualified. + * + * @return string + */ + protected function getContainerBaseClass() + { + return 'Container'; + } + /** * Initializes the service container. * @@ -448,7 +460,7 @@ abstract class Kernel implements KernelInterface $fresh = true; if (!$cache->isFresh()) { $container = $this->buildContainer(); - $this->dumpContainer($cache, $container, $class); + $this->dumpContainer($cache, $container, $class, $this->getContainerBaseClass()); $fresh = false; } @@ -556,12 +568,13 @@ abstract class Kernel implements KernelInterface * @param ConfigCache $cache The config cache * @param ContainerBuilder $container The service container * @param string $class The name of the class to generate + * @param string $baseClass The name of the container's base class */ - protected function dumpContainer(ConfigCache $cache, ContainerBuilder $container, $class) + protected function dumpContainer(ConfigCache $cache, ContainerBuilder $container, $class, $baseClass) { // cache the container $dumper = new PhpDumper($container); - $content = $dumper->dump(array('class' => $class)); + $content = $dumper->dump(array('class' => $class, 'base_class' => $baseClass)); if (!$this->debug) { $content = self::stripComments($content); } From 45a551e9d5e7efcb0cabe12d5e19fd85301992c9 Mon Sep 17 00:00:00 2001 From: Fabien Potencier Date: Sun, 17 Apr 2011 14:10:13 +0200 Subject: [PATCH 25/91] [DoctrineBundle] removed unused file --- .../DependencyInjection/TestHydrator.php | 20 ------------------- 1 file changed, 20 deletions(-) delete mode 100644 src/Symfony/Bundle/DoctrineBundle/Tests/DependencyInjection/TestHydrator.php diff --git a/src/Symfony/Bundle/DoctrineBundle/Tests/DependencyInjection/TestHydrator.php b/src/Symfony/Bundle/DoctrineBundle/Tests/DependencyInjection/TestHydrator.php deleted file mode 100644 index 8867c30a71..0000000000 --- a/src/Symfony/Bundle/DoctrineBundle/Tests/DependencyInjection/TestHydrator.php +++ /dev/null @@ -1,20 +0,0 @@ - - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -namespace Symfony\Bundle\DoctrineBundle\Tests\DependencyInjection; - -class TestHydrator extends \Doctrine\ORM\Internal\Hydration\AbstractHydrator -{ - protected function _hydrateAll(); - { - return array(); - } -} From 874c4b6e07f31b6cb0af92e1ed748d485bfc52af Mon Sep 17 00:00:00 2001 From: Lukas Kahwe Smith Date: Sun, 17 Apr 2011 17:00:42 +0200 Subject: [PATCH 26/91] added a DecodeInterface (and SerializerAwareInterface) to make it easier to identify if an Encoder also supports decoding --- .../Serializer/Encoder/AbstractEncoder.php | 5 ++- .../Serializer/Encoder/DecoderInterface.php | 32 ++++++++++++++++ .../Serializer/Encoder/EncoderInterface.php | 26 ------------- .../Serializer/Encoder/JsonEncoder.php | 2 +- .../Serializer/Encoder/XmlEncoder.php | 2 +- .../Serializer/SerializerAwareInterface.php | 38 +++++++++++++++++++ 6 files changed, 75 insertions(+), 30 deletions(-) create mode 100644 src/Symfony/Component/Serializer/Encoder/DecoderInterface.php create mode 100644 src/Symfony/Component/Serializer/SerializerAwareInterface.php diff --git a/src/Symfony/Component/Serializer/Encoder/AbstractEncoder.php b/src/Symfony/Component/Serializer/Encoder/AbstractEncoder.php index eb7245d6f7..a2e9035696 100644 --- a/src/Symfony/Component/Serializer/Encoder/AbstractEncoder.php +++ b/src/Symfony/Component/Serializer/Encoder/AbstractEncoder.php @@ -3,6 +3,7 @@ namespace Symfony\Component\Serializer\Encoder; use Symfony\Component\Serializer\SerializerInterface; +use Symfony\Component\Serializer\SerializerAwareInterface; /* * This file is part of the Symfony framework. @@ -18,7 +19,7 @@ use Symfony\Component\Serializer\SerializerInterface; * * @author Jordi Boggiano */ -abstract class AbstractEncoder implements EncoderInterface +abstract class AbstractEncoder implements SerializerAwareInterface, EncoderInterface { protected $serializer; @@ -37,4 +38,4 @@ abstract class AbstractEncoder implements EncoderInterface { return $this->serializer; } -} \ No newline at end of file +} diff --git a/src/Symfony/Component/Serializer/Encoder/DecoderInterface.php b/src/Symfony/Component/Serializer/Encoder/DecoderInterface.php new file mode 100644 index 0000000000..ab49c69fab --- /dev/null +++ b/src/Symfony/Component/Serializer/Encoder/DecoderInterface.php @@ -0,0 +1,32 @@ + + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +/** + * Defines the interface of encoders + * + * @author Jordi Boggiano + */ +interface DecoderInterface +{ + /** + * Decodes a string into PHP data + * + * @param string $data data to decode + * @param string $format format to decode from + * @return mixed + * @api + */ + function decode($data, $format); +} diff --git a/src/Symfony/Component/Serializer/Encoder/EncoderInterface.php b/src/Symfony/Component/Serializer/Encoder/EncoderInterface.php index b7401e0451..e2044404ea 100644 --- a/src/Symfony/Component/Serializer/Encoder/EncoderInterface.php +++ b/src/Symfony/Component/Serializer/Encoder/EncoderInterface.php @@ -29,30 +29,4 @@ interface EncoderInterface * @api */ function encode($data, $format); - - /** - * Decodes a string into PHP data - * - * @param string $data data to decode - * @param string $format format to decode from - * @return mixed - * @api - */ - function decode($data, $format); - - /** - * Sets the owning Serializer object - * - * @param SerializerInterface $serializer - * @api - */ - function setSerializer(SerializerInterface $serializer); - - /** - * Gets the owning Serializer object - * - * @return SerializerInterface - * @api - */ - function getSerializer(); } diff --git a/src/Symfony/Component/Serializer/Encoder/JsonEncoder.php b/src/Symfony/Component/Serializer/Encoder/JsonEncoder.php index 31e4b001c0..5ab6876430 100644 --- a/src/Symfony/Component/Serializer/Encoder/JsonEncoder.php +++ b/src/Symfony/Component/Serializer/Encoder/JsonEncoder.php @@ -18,7 +18,7 @@ use Symfony\Component\Serializer\SerializerInterface; * * @author Jordi Boggiano */ -class JsonEncoder extends AbstractEncoder +class JsonEncoder extends AbstractEncoder implements DecoderInterface { /** * {@inheritdoc} diff --git a/src/Symfony/Component/Serializer/Encoder/XmlEncoder.php b/src/Symfony/Component/Serializer/Encoder/XmlEncoder.php index 2e0c0af51e..c465f1b8f7 100644 --- a/src/Symfony/Component/Serializer/Encoder/XmlEncoder.php +++ b/src/Symfony/Component/Serializer/Encoder/XmlEncoder.php @@ -20,7 +20,7 @@ use Symfony\Component\Serializer\SerializerInterface; * @author John Wards * @author Fabian Vogler */ -class XmlEncoder extends AbstractEncoder +class XmlEncoder extends AbstractEncoder implements DecoderInterface { private $dom; private $format; diff --git a/src/Symfony/Component/Serializer/SerializerAwareInterface.php b/src/Symfony/Component/Serializer/SerializerAwareInterface.php new file mode 100644 index 0000000000..625601e701 --- /dev/null +++ b/src/Symfony/Component/Serializer/SerializerAwareInterface.php @@ -0,0 +1,38 @@ + + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +/** + * Defines the interface of encoders + * + * @author Jordi Boggiano + */ +interface SerializerAwareInterface +{ + /** + * Sets the owning Serializer object + * + * @param SerializerInterface $serializer + * @api + */ + function setSerializer(SerializerInterface $serializer); + + /** + * Gets the owning Serializer object + * + * @return SerializerInterface + * @api + */ + function getSerializer(); +} From cc0832992ca1e0114e2ca808a5bd9440a6e93b49 Mon Sep 17 00:00:00 2001 From: Ivan Rey Date: Sun, 17 Apr 2011 21:29:35 -0500 Subject: [PATCH 27/91] BugFix: In windows environments it is necessary to replace backslash with forward slash in search string as well --- src/Symfony/Bundle/DoctrineBundle/Command/DoctrineCommand.php | 3 ++- .../DoctrineMongoDBBundle/Command/DoctrineODMCommand.php | 3 ++- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/src/Symfony/Bundle/DoctrineBundle/Command/DoctrineCommand.php b/src/Symfony/Bundle/DoctrineBundle/Command/DoctrineCommand.php index f7b390cc60..d88a58deb7 100644 --- a/src/Symfony/Bundle/DoctrineBundle/Command/DoctrineCommand.php +++ b/src/Symfony/Bundle/DoctrineBundle/Command/DoctrineCommand.php @@ -165,7 +165,8 @@ abstract class DoctrineCommand extends Command protected function findBasePathForBundle($bundle) { $path = str_replace('\\', '/', $bundle->getNamespace()); - $destination = str_replace('/'.$path, "", $bundle->getPath(), $c); + $search = str_replace('\\','/',$bundle->getPath()); + $destination = str_replace('/'.$path, "", $search, $c); if ($c != 1) { throw new \RuntimeException("Something went terribly wrong."); diff --git a/src/Symfony/Bundle/DoctrineMongoDBBundle/Command/DoctrineODMCommand.php b/src/Symfony/Bundle/DoctrineMongoDBBundle/Command/DoctrineODMCommand.php index 61f1c1f221..2e70c2a08a 100644 --- a/src/Symfony/Bundle/DoctrineMongoDBBundle/Command/DoctrineODMCommand.php +++ b/src/Symfony/Bundle/DoctrineMongoDBBundle/Command/DoctrineODMCommand.php @@ -109,7 +109,8 @@ abstract class DoctrineODMCommand extends Command protected function findBasePathForBundle($bundle) { $path = str_replace('\\', '/', $bundle->getNamespace()); - $destination = str_replace('/'.$path, "", $bundle->getPath(), $c); + $search = str_replace('\\','/',$bundle->getPath()); + $destination = str_replace('/'.$path, "", $search, $c); if ($c != 1) { throw new \RuntimeException("Something went terribly wrong."); From ef810026346e1af5c90f86ae6fc19e823e4c24e5 Mon Sep 17 00:00:00 2001 From: Ivan Rey Date: Sun, 17 Apr 2011 21:30:23 -0500 Subject: [PATCH 28/91] Better Exception Message --- src/Symfony/Bundle/DoctrineBundle/Command/DoctrineCommand.php | 2 +- .../Bundle/DoctrineMongoDBBundle/Command/DoctrineODMCommand.php | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/Symfony/Bundle/DoctrineBundle/Command/DoctrineCommand.php b/src/Symfony/Bundle/DoctrineBundle/Command/DoctrineCommand.php index d88a58deb7..272bfbe1dd 100644 --- a/src/Symfony/Bundle/DoctrineBundle/Command/DoctrineCommand.php +++ b/src/Symfony/Bundle/DoctrineBundle/Command/DoctrineCommand.php @@ -169,7 +169,7 @@ abstract class DoctrineCommand extends Command $destination = str_replace('/'.$path, "", $search, $c); if ($c != 1) { - throw new \RuntimeException("Something went terribly wrong."); + throw new \RuntimeException("Can't find base path for bundle. Path: $path , Destination: $destination"); } return $destination; diff --git a/src/Symfony/Bundle/DoctrineMongoDBBundle/Command/DoctrineODMCommand.php b/src/Symfony/Bundle/DoctrineMongoDBBundle/Command/DoctrineODMCommand.php index 2e70c2a08a..5705f0f1c1 100644 --- a/src/Symfony/Bundle/DoctrineMongoDBBundle/Command/DoctrineODMCommand.php +++ b/src/Symfony/Bundle/DoctrineMongoDBBundle/Command/DoctrineODMCommand.php @@ -113,7 +113,7 @@ abstract class DoctrineODMCommand extends Command $destination = str_replace('/'.$path, "", $search, $c); if ($c != 1) { - throw new \RuntimeException("Something went terribly wrong."); + throw new \RuntimeException("Can't find base path for bundle. Path: $path , Destination: $destination"); } return $destination; From fa2e4c5dd11072aee0e91b22131b6a34370a6d36 Mon Sep 17 00:00:00 2001 From: Ivan Rey Date: Sun, 17 Apr 2011 21:35:37 -0500 Subject: [PATCH 29/91] BugFix reflClass is not always initialized getReflClass should be used instead since it initializes the variable if it's not set --- .../DoctrineBundle/Command/GenerateEntitiesDoctrineCommand.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Symfony/Bundle/DoctrineBundle/Command/GenerateEntitiesDoctrineCommand.php b/src/Symfony/Bundle/DoctrineBundle/Command/GenerateEntitiesDoctrineCommand.php index 365f87ccd4..d2e4025cc1 100644 --- a/src/Symfony/Bundle/DoctrineBundle/Command/GenerateEntitiesDoctrineCommand.php +++ b/src/Symfony/Bundle/DoctrineBundle/Command/GenerateEntitiesDoctrineCommand.php @@ -60,7 +60,7 @@ EOT $entityGenerator = $this->getEntityGenerator(); foreach ($metadatas as $metadata) { - if ($filterEntity && $metadata->reflClass->getShortName() !== $filterEntity) { + if ($filterEntity && $metadata->getReflClass()->getShortName() !== $filterEntity) { continue; } From 4cdd482762bf5f282b132ee18666822e9539ffaa Mon Sep 17 00:00:00 2001 From: Jordi Boggiano Date: Mon, 18 Apr 2011 09:27:58 +0200 Subject: [PATCH 30/91] [MonologBundle] Add logger alias to monolog.logger --- .../DependencyInjection/Compiler/LoggerChannelPass.php | 4 ++-- src/Symfony/Bundle/MonologBundle/Resources/config/monolog.xml | 1 + 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/src/Symfony/Bundle/MonologBundle/DependencyInjection/Compiler/LoggerChannelPass.php b/src/Symfony/Bundle/MonologBundle/DependencyInjection/Compiler/LoggerChannelPass.php index 7df19c1b21..dd1a17f462 100644 --- a/src/Symfony/Bundle/MonologBundle/DependencyInjection/Compiler/LoggerChannelPass.php +++ b/src/Symfony/Bundle/MonologBundle/DependencyInjection/Compiler/LoggerChannelPass.php @@ -27,13 +27,13 @@ class LoggerChannelPass implements CompilerPassInterface public function process(ContainerBuilder $container) { - if (false === $container->hasDefinition('monolog.logger')) { + if (!$container->hasDefinition('monolog.logger')) { return; } foreach ($container->findTaggedServiceIds('monolog.logger') as $id => $tags) { foreach ($tags as $tag) { - if (!empty ($tag['channel']) && 'app' !== $tag['channel']) { + if (!empty($tag['channel']) && 'app' !== $tag['channel']) { $definition = $container->getDefinition($id); $loggerId = sprintf('monolog.logger.%s', $tag['channel']); $this->createLogger($tag['channel'], $loggerId, $container); diff --git a/src/Symfony/Bundle/MonologBundle/Resources/config/monolog.xml b/src/Symfony/Bundle/MonologBundle/Resources/config/monolog.xml index 0fb3396887..1530c34b1c 100644 --- a/src/Symfony/Bundle/MonologBundle/Resources/config/monolog.xml +++ b/src/Symfony/Bundle/MonologBundle/Resources/config/monolog.xml @@ -20,6 +20,7 @@ app + From 5e998146c2f0c16edba63b1f1eaa1eeeb646c09b Mon Sep 17 00:00:00 2001 From: Jordi Boggiano Date: Mon, 18 Apr 2011 10:04:25 +0200 Subject: [PATCH 31/91] [MonologBundle] Make monolog.logger private --- src/Symfony/Bundle/MonologBundle/Resources/config/monolog.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Symfony/Bundle/MonologBundle/Resources/config/monolog.xml b/src/Symfony/Bundle/MonologBundle/Resources/config/monolog.xml index 1530c34b1c..f9d84105a8 100644 --- a/src/Symfony/Bundle/MonologBundle/Resources/config/monolog.xml +++ b/src/Symfony/Bundle/MonologBundle/Resources/config/monolog.xml @@ -17,7 +17,7 @@ - + app From 1ecaade68d04655268e44484cea74c50aa7e5ba2 Mon Sep 17 00:00:00 2001 From: Lukas Kahwe Smith Date: Mon, 18 Apr 2011 15:35:05 +0200 Subject: [PATCH 32/91] added support for parameters with default null --- .../Routing/Generator/UrlGenerator.php | 7 +++++-- .../Routing/Generator/UrlGeneratorTest.php | 17 ++++++++++++++++- 2 files changed, 21 insertions(+), 3 deletions(-) diff --git a/src/Symfony/Component/Routing/Generator/UrlGenerator.php b/src/Symfony/Component/Routing/Generator/UrlGenerator.php index e83d40d612..79fea790fb 100644 --- a/src/Symfony/Component/Routing/Generator/UrlGenerator.php +++ b/src/Symfony/Component/Routing/Generator/UrlGenerator.php @@ -99,8 +99,11 @@ class UrlGenerator implements UrlGeneratorInterface throw new \InvalidArgumentException(sprintf('Parameter "%s" for route "%s" must match "%s" ("%s" given).', $token[3], $name, $requirements[$token[3]], $tparams[$token[3]])); } - // %2F is not valid in a URL, so we don't encode it (which is fine as the requirements explicitely allowed it) - $url = $token[1].str_replace('%2F', '/', urlencode($tparams[$token[3]])).$url; + if (isset($tparams[$token[3]])) { + // %2F is not valid in a URL, so we don't encode it (which is fine as the requirements explicitly allowed it) + $url = $token[1].str_replace('%2F', '/', urlencode($tparams[$token[3]])).$url; + } + $optional = false; } } elseif ('text' === $token[0]) { diff --git a/tests/Symfony/Tests/Component/Routing/Generator/UrlGeneratorTest.php b/tests/Symfony/Tests/Component/Routing/Generator/UrlGeneratorTest.php index 5cdf04393a..3e0bd24332 100644 --- a/tests/Symfony/Tests/Component/Routing/Generator/UrlGeneratorTest.php +++ b/tests/Symfony/Tests/Component/Routing/Generator/UrlGeneratorTest.php @@ -119,7 +119,22 @@ class UrlGeneratorTest extends \PHPUnit_Framework_TestCase $this->assertEquals('/app.php/testing/bar', $url); } - + + public function testRelativeUrlWithNullParameter() + { + $this->routeCollection->add('test', new Route('/testing.{format}', array('format' => null))); + $this->generator->setContext(array( + 'base_url'=>'/app.php', + 'method'=>'GET', + 'host'=>'localhost', + 'port'=>80, + 'is_secure'=>false)); + + $url = $this->generator->generate('test', array(), false); + + $this->assertEquals('/app.php/testing', $url); + } + public function testRelativeUrlWithExtraParameters() { $this->routeCollection->add('test', new Route('/testing')); From 5ff67a8d540fb8e7e1c2671c773fa77d9f05e42d Mon Sep 17 00:00:00 2001 From: Fabien Potencier Date: Tue, 19 Apr 2011 14:02:32 +0200 Subject: [PATCH 33/91] made request data collector more robust when the user got the request content as a resource --- .../Resources/views/Collector/request.html.twig | 4 +++- .../HttpKernel/DataCollector/RequestDataCollector.php | 10 +++++++++- 2 files changed, 12 insertions(+), 2 deletions(-) diff --git a/src/Symfony/Bundle/WebProfilerBundle/Resources/views/Collector/request.html.twig b/src/Symfony/Bundle/WebProfilerBundle/Resources/views/Collector/request.html.twig index d2f7b00db6..d37ac01ab9 100644 --- a/src/Symfony/Bundle/WebProfilerBundle/Resources/views/Collector/request.html.twig +++ b/src/Symfony/Bundle/WebProfilerBundle/Resources/views/Collector/request.html.twig @@ -78,7 +78,9 @@

Request Content

- {% if collector.content %} + {% if collector.content is false %} + Request content not available (it was retrieved as a resource). + {% elseif collector.content %}

{{ collector.content }}
{% else %} No content diff --git a/src/Symfony/Component/HttpKernel/DataCollector/RequestDataCollector.php b/src/Symfony/Component/HttpKernel/DataCollector/RequestDataCollector.php index bf8164bdb8..69c38f59ab 100644 --- a/src/Symfony/Component/HttpKernel/DataCollector/RequestDataCollector.php +++ b/src/Symfony/Component/HttpKernel/DataCollector/RequestDataCollector.php @@ -44,9 +44,17 @@ class RequestDataCollector extends DataCollector $attributes[$key] = is_object($value) ? sprintf('Object(%s)', get_class($value)) : $value; } + $content = null; + try { + $content = $request->getContent(); + } catch (\LogicException $e) { + // the user already got the request content as a resource + $content = false; + } + $this->data = array( 'format' => $request->getRequestFormat(), - 'content' => $request->getContent(), + 'content' => $content, 'content_type' => $response->headers->get('Content-Type') ? $response->headers->get('Content-Type') : 'text/html', 'status_code' => $response->getStatusCode(), 'request_query' => $request->query->all(), From 4d60d3d9850d21c961813a11cb7a49dfda776aee Mon Sep 17 00:00:00 2001 From: Fabien Potencier Date: Tue, 19 Apr 2011 14:05:08 +0200 Subject: [PATCH 34/91] updated UPDATE file --- UPDATE.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/UPDATE.md b/UPDATE.md index 243c7fef87..469931e4fa 100644 --- a/UPDATE.md +++ b/UPDATE.md @@ -9,6 +9,8 @@ timeline closely anyway. PR11 to PR12 ------------ +* HttpFoundation\Cookie::getExpire() was renamed to getExpiresTime() + * XML configurations have been normalized. All tags with only one attribute have been converted to tag content: From 95d4bcc5dbfb4b81f03cfb867af18ae37e591745 Mon Sep 17 00:00:00 2001 From: Fabien Potencier Date: Tue, 19 Apr 2011 14:09:00 +0200 Subject: [PATCH 35/91] fixed unit tests (broken by previous commit) --- src/Symfony/Bundle/FrameworkBundle/Console/Shell.php | 12 ++++++------ .../ClassLoader/ClassCollectionLoaderTest.php | 2 +- .../DependencyInjection/Dumper/YamlDumperTest.php | 2 +- 3 files changed, 8 insertions(+), 8 deletions(-) diff --git a/src/Symfony/Bundle/FrameworkBundle/Console/Shell.php b/src/Symfony/Bundle/FrameworkBundle/Console/Shell.php index 33100bdaca..f0628684a1 100644 --- a/src/Symfony/Bundle/FrameworkBundle/Console/Shell.php +++ b/src/Symfony/Bundle/FrameworkBundle/Console/Shell.php @@ -29,14 +29,14 @@ class Shell extends BaseShell { return << - _____ __ ___ - / ____| / _| |__ \ + _____ __ ___ + / ____| / _| |__ \ | (___ _ _ _ __ ___ | |_ ___ _ __ _ _ ) | - \___ \| | | | '_ ` _ \| _/ _ \| '_ \| | | | / / - ____) | |_| | | | | | | || (_) | | | | |_| |/ /_ + \___ \| | | | '_ ` _ \| _/ _ \| '_ \| | | | / / + ____) | |_| | | | | | | || (_) | | | | |_| |/ /_ |_____/ \__, |_| |_| |_|_| \___/|_| |_|\__, |____| - __/ | __/ | - |___/ |___/ + __/ | __/ | + |___/ |___/ EOF diff --git a/tests/Symfony/Tests/Component/ClassLoader/ClassCollectionLoaderTest.php b/tests/Symfony/Tests/Component/ClassLoader/ClassCollectionLoaderTest.php index 9b69b4014c..3fee2ed324 100644 --- a/tests/Symfony/Tests/Component/ClassLoader/ClassCollectionLoaderTest.php +++ b/tests/Symfony/Tests/Component/ClassLoader/ClassCollectionLoaderTest.php @@ -43,7 +43,7 @@ namespace Foo { class Foo {} } -namespace Bar +namespace Bar { class Foo {} } diff --git a/tests/Symfony/Tests/Component/DependencyInjection/Dumper/YamlDumperTest.php b/tests/Symfony/Tests/Component/DependencyInjection/Dumper/YamlDumperTest.php index f3a357bce9..77528fee3f 100644 --- a/tests/Symfony/Tests/Component/DependencyInjection/Dumper/YamlDumperTest.php +++ b/tests/Symfony/Tests/Component/DependencyInjection/Dumper/YamlDumperTest.php @@ -79,7 +79,7 @@ interfaces: FooClass: calls: - [setBar, [someValue]] - + services: foo: From dd7b4a13b6ea019c615251e7ae4ebaccaf3ba6fd Mon Sep 17 00:00:00 2001 From: Fabien Potencier Date: Tue, 19 Apr 2011 14:15:50 +0200 Subject: [PATCH 36/91] fixed CS --- .../Bundle/DoctrineBundle/Command/DoctrineCommand.php | 6 +++--- .../DoctrineMongoDBBundle/Command/DoctrineODMCommand.php | 6 +++--- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/src/Symfony/Bundle/DoctrineBundle/Command/DoctrineCommand.php b/src/Symfony/Bundle/DoctrineBundle/Command/DoctrineCommand.php index fb5c6b7533..2d163bb347 100644 --- a/src/Symfony/Bundle/DoctrineBundle/Command/DoctrineCommand.php +++ b/src/Symfony/Bundle/DoctrineBundle/Command/DoctrineCommand.php @@ -165,11 +165,11 @@ abstract class DoctrineCommand extends Command protected function findBasePathForBundle($bundle) { $path = str_replace('\\', '/', $bundle->getNamespace()); - $search = str_replace('\\','/',$bundle->getPath()); - $destination = str_replace('/'.$path, "", $search, $c); + $search = str_replace('\\', '/', $bundle->getPath()); + $destination = str_replace('/'.$path, '', $search, $c); if ($c != 1) { - throw new \RuntimeException("Can't find base path for bundle. Path: $path , Destination: $destination"); + throw new \RuntimeException('Can\'t find base path for bundle (path: "$path", destination: "$destination").'); } return $destination; diff --git a/src/Symfony/Bundle/DoctrineMongoDBBundle/Command/DoctrineODMCommand.php b/src/Symfony/Bundle/DoctrineMongoDBBundle/Command/DoctrineODMCommand.php index 5705f0f1c1..8b13d6012c 100644 --- a/src/Symfony/Bundle/DoctrineMongoDBBundle/Command/DoctrineODMCommand.php +++ b/src/Symfony/Bundle/DoctrineMongoDBBundle/Command/DoctrineODMCommand.php @@ -109,11 +109,11 @@ abstract class DoctrineODMCommand extends Command protected function findBasePathForBundle($bundle) { $path = str_replace('\\', '/', $bundle->getNamespace()); - $search = str_replace('\\','/',$bundle->getPath()); - $destination = str_replace('/'.$path, "", $search, $c); + $search = str_replace('\\', '/', $bundle->getPath()); + $destination = str_replace('/'.$path, '', $search, $c); if ($c != 1) { - throw new \RuntimeException("Can't find base path for bundle. Path: $path , Destination: $destination"); + throw new \RuntimeException('Can\'t find base path for bundle (path: "$path", destination: "$destination").'); } return $destination; From c660fcd2f2310649eabe94a14d28ce14a1a8b760 Mon Sep 17 00:00:00 2001 From: "Johannes M. Schmitt" Date: Tue, 19 Apr 2011 12:12:29 +0200 Subject: [PATCH 37/91] fixes a bug in the SwitchUserListener --- UPDATE.md | 4 ++++ .../Component/Security/Http/Firewall/SwitchUserListener.php | 5 ++++- 2 files changed, 8 insertions(+), 1 deletion(-) diff --git a/UPDATE.md b/UPDATE.md index 469931e4fa..35163b4a69 100644 --- a/UPDATE.md +++ b/UPDATE.md @@ -26,6 +26,10 @@ PR11 to PR12 twig twig.extension.debug +* Fixes a critical security issue which allowed all users to switch to + arbitrary accounts when the SwitchUserListener was activated. Configurations + which do not use the SwitchUserListener are not affected. + PR10 to PR11 ------------ diff --git a/src/Symfony/Component/Security/Http/Firewall/SwitchUserListener.php b/src/Symfony/Component/Security/Http/Firewall/SwitchUserListener.php index 5d69aa25d4..0977cb16fe 100644 --- a/src/Symfony/Component/Security/Http/Firewall/SwitchUserListener.php +++ b/src/Symfony/Component/Security/Http/Firewall/SwitchUserListener.php @@ -11,6 +11,7 @@ namespace Symfony\Component\Security\Http\Firewall; +use Symfony\Component\Security\Core\Exception\AccessDeniedException; use Symfony\Component\Security\Core\SecurityContextInterface; use Symfony\Component\Security\Core\User\UserProviderInterface; use Symfony\Component\Security\Core\User\UserCheckerInterface; @@ -112,7 +113,9 @@ class SwitchUserListener implements ListenerInterface throw new \LogicException(sprintf('You are already switched to "%s" user.', $token->getUsername())); } - $this->accessDecisionManager->decide($token, array($this->role)); + if (false === $this->accessDecisionManager->decide($token, array($this->role))) { + throw new AccessDeniedException(); + } $username = $request->get($this->usernameParameter); From f1ab7da36f5ad4ec71f45c704704c55e26f123d7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Krzysztof=20Men=C5=BCyk?= Date: Tue, 19 Apr 2011 14:40:27 +0200 Subject: [PATCH 38/91] [DoctrineBundle] Fix data:load command (--append w/o value) --- .../DoctrineBundle/Command/LoadDataFixturesDoctrineCommand.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Symfony/Bundle/DoctrineBundle/Command/LoadDataFixturesDoctrineCommand.php b/src/Symfony/Bundle/DoctrineBundle/Command/LoadDataFixturesDoctrineCommand.php index 99b5af1893..5a21e5169c 100644 --- a/src/Symfony/Bundle/DoctrineBundle/Command/LoadDataFixturesDoctrineCommand.php +++ b/src/Symfony/Bundle/DoctrineBundle/Command/LoadDataFixturesDoctrineCommand.php @@ -40,7 +40,7 @@ class LoadDataFixturesDoctrineCommand extends DoctrineCommand ->setName('doctrine:data:load') ->setDescription('Load data fixtures to your database.') ->addOption('fixtures', null, InputOption::VALUE_OPTIONAL | InputOption::VALUE_IS_ARRAY, 'The directory or file to load data fixtures from.') - ->addOption('append', null, InputOption::VALUE_OPTIONAL, 'Whether or not to append the data fixtures.', false) + ->addOption('append', null, InputOption::VALUE_NONE, 'Append the data fixtures instead of flushing the database first.') ->addOption('em', null, InputOption::VALUE_REQUIRED, 'The entity manager to use for this command.') ->setHelp(<<doctrine:data:load command loads data fixtures from your bundles: From 570a10086079c01bb687f37b79492009899c0e2d Mon Sep 17 00:00:00 2001 From: Fabien Potencier Date: Tue, 19 Apr 2011 14:52:15 +0200 Subject: [PATCH 39/91] fixed typos --- src/Symfony/Bundle/DoctrineBundle/Command/DoctrineCommand.php | 2 +- .../Bundle/DoctrineMongoDBBundle/Command/DoctrineODMCommand.php | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/Symfony/Bundle/DoctrineBundle/Command/DoctrineCommand.php b/src/Symfony/Bundle/DoctrineBundle/Command/DoctrineCommand.php index 2d163bb347..041f7b472a 100644 --- a/src/Symfony/Bundle/DoctrineBundle/Command/DoctrineCommand.php +++ b/src/Symfony/Bundle/DoctrineBundle/Command/DoctrineCommand.php @@ -169,7 +169,7 @@ abstract class DoctrineCommand extends Command $destination = str_replace('/'.$path, '', $search, $c); if ($c != 1) { - throw new \RuntimeException('Can\'t find base path for bundle (path: "$path", destination: "$destination").'); + throw new \RuntimeException(sprintf('Can\'t find base path for bundle (path: "%s", destination: "%s").', $path, $destination)); } return $destination; diff --git a/src/Symfony/Bundle/DoctrineMongoDBBundle/Command/DoctrineODMCommand.php b/src/Symfony/Bundle/DoctrineMongoDBBundle/Command/DoctrineODMCommand.php index 8b13d6012c..d0f8241785 100644 --- a/src/Symfony/Bundle/DoctrineMongoDBBundle/Command/DoctrineODMCommand.php +++ b/src/Symfony/Bundle/DoctrineMongoDBBundle/Command/DoctrineODMCommand.php @@ -113,7 +113,7 @@ abstract class DoctrineODMCommand extends Command $destination = str_replace('/'.$path, '', $search, $c); if ($c != 1) { - throw new \RuntimeException('Can\'t find base path for bundle (path: "$path", destination: "$destination").'); + throw new \RuntimeException(sprintf('Can\'t find base path for bundle (path: "%s", destination: "%s").', $path, $destination)); } return $destination; From 1a07ded639aca3ade24b4b2dfe608bdc55323e8f Mon Sep 17 00:00:00 2001 From: hidenorigoto Date: Tue, 19 Apr 2011 22:10:11 +0900 Subject: [PATCH 40/91] updated translation UPDATE.ja file (vPR11 to vPR12) --- UPDATE.ja.md | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) diff --git a/UPDATE.ja.md b/UPDATE.ja.md index fa54373f85..3c4adc6f22 100644 --- a/UPDATE.ja.md +++ b/UPDATE.ja.md @@ -5,11 +5,34 @@ このドキュメントでは、フレームワークの "パブリックな" APIを使っている場合に必要な変更点についてのみ説明しています。 フレームワークのコアコードを "ハック" している場合は、変更履歴を注意深く追跡する必要があるでしょう。 +PR11 to PR12 +------------ + +* HttpFoundation\Cookie::getExpire() は getExpiresTime() に名前が変更されました。 + +* XMLのコンフィギュレーションの記述方法が変更されました。属性が1つしかないタグは、すべてタグのコンテンツとして記述するように変更されました。 + + 変更前: + + + + + + 変更後: + + MyBundle + twig + twig.extension.debug + +* SwitchUserListenerが有効な場合に、すべてのユーザーが任意のアカウントになりすませる致命的な脆弱性を修正しました。SwitchUserListenerを利用しない設定にしている場合は影響はありません。 + PR10 から PR11 -------------- * エクステンションのコンフィギュレーションクラスには、\ `Symfony\Component\Config\Definition\ConfigurationInterface`\ インターフェイスを実装する必要があります。この部分の後方互換性は維持されていますが、今後の開発のために、エクステンションにこのインターフェイスを実装しておいてください。 +* Monologのオプション "fingerscrossed" は "fingers_crossed" に名前が変更されました。 + PR9 から PR10 ------------- From 06c331d04916bdf37edcbfdab2ef8cb05742a010 Mon Sep 17 00:00:00 2001 From: Fabien Potencier Date: Tue, 19 Apr 2011 15:26:51 +0200 Subject: [PATCH 41/91] fixed typo --- .../Resources/views/Collector/request.html.twig | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Symfony/Bundle/WebProfilerBundle/Resources/views/Collector/request.html.twig b/src/Symfony/Bundle/WebProfilerBundle/Resources/views/Collector/request.html.twig index d37ac01ab9..b3752b7729 100644 --- a/src/Symfony/Bundle/WebProfilerBundle/Resources/views/Collector/request.html.twig +++ b/src/Symfony/Bundle/WebProfilerBundle/Resources/views/Collector/request.html.twig @@ -78,7 +78,7 @@

Request Content

- {% if collector.content is false %} + {% if collector.content == false %} Request content not available (it was retrieved as a resource). {% elseif collector.content %}

{{ collector.content }}
From 4724af10f6abffc4f6c55a47d05418e4b8ff293a Mon Sep 17 00:00:00 2001 From: Fabien Potencier Date: Tue, 19 Apr 2011 15:36:40 +0200 Subject: [PATCH 42/91] [DoctrineMongoDbBundle] fixed data:load command (--append does not need a value) --- .../Command/LoadDataFixturesDoctrineODMCommand.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Symfony/Bundle/DoctrineMongoDBBundle/Command/LoadDataFixturesDoctrineODMCommand.php b/src/Symfony/Bundle/DoctrineMongoDBBundle/Command/LoadDataFixturesDoctrineODMCommand.php index f7ec8481db..6d88b9c781 100644 --- a/src/Symfony/Bundle/DoctrineMongoDBBundle/Command/LoadDataFixturesDoctrineODMCommand.php +++ b/src/Symfony/Bundle/DoctrineMongoDBBundle/Command/LoadDataFixturesDoctrineODMCommand.php @@ -40,7 +40,7 @@ class LoadDataFixturesDoctrineODMCommand extends DoctrineODMCommand ->setName('doctrine:mongodb:data:load') ->setDescription('Load data fixtures to your database.') ->addOption('fixtures', null, InputOption::VALUE_OPTIONAL | InputOption::VALUE_IS_ARRAY, 'The directory or file to load data fixtures from.') - ->addOption('append', null, InputOption::VALUE_OPTIONAL, 'Whether or not to append the data fixtures.', false) + ->addOption('append', null, InputOption::VALUE_NONE, 'Append the data fixtures instead of flushing the database first.') ->addOption('dm', null, InputOption::VALUE_REQUIRED, 'The document manager to use for this command.') ->setHelp(<<doctrine:mongodb:data:load command loads data fixtures from your bundles: From defb0218fb1c1ff59b35ac7bbb1d92a84a67fe1a Mon Sep 17 00:00:00 2001 From: Kris Wallsmith Date: Tue, 19 Apr 2011 07:33:51 -0700 Subject: [PATCH 43/91] [DoctrineMongoDBBundle] set annotation constraint namespace alias to assertMongoDB --- .../AddValidatorNamespaceAliasPass.php | 22 +++++++++++++++++ .../DoctrineMongoDBExtension.php | 15 ------------ .../DoctrineMongoDBBundle.php | 2 ++ .../AbstractMongoDBExtensionTest.php | 24 ++++++++++--------- 4 files changed, 37 insertions(+), 26 deletions(-) create mode 100644 src/Symfony/Bundle/DoctrineMongoDBBundle/DependencyInjection/Compiler/AddValidatorNamespaceAliasPass.php diff --git a/src/Symfony/Bundle/DoctrineMongoDBBundle/DependencyInjection/Compiler/AddValidatorNamespaceAliasPass.php b/src/Symfony/Bundle/DoctrineMongoDBBundle/DependencyInjection/Compiler/AddValidatorNamespaceAliasPass.php new file mode 100644 index 0000000000..03c4a6f02e --- /dev/null +++ b/src/Symfony/Bundle/DoctrineMongoDBBundle/DependencyInjection/Compiler/AddValidatorNamespaceAliasPass.php @@ -0,0 +1,22 @@ +hasDefinition('validator.mapping.loader.annotation_loader')) { + return; + } + + $loader = $container->getDefinition('validator.mapping.loader.annotation_loader'); + $args = $loader->getArguments(); + + $args[0]['assertMongoDB'] = 'Symfony\\Bundle\\DoctrineMongoDBBundle\\Validator\\Constraints\\'; + $loader->setArgument(0, $args[0]); + } +} diff --git a/src/Symfony/Bundle/DoctrineMongoDBBundle/DependencyInjection/DoctrineMongoDBExtension.php b/src/Symfony/Bundle/DoctrineMongoDBBundle/DependencyInjection/DoctrineMongoDBExtension.php index aa61fddd22..7d0f002dc7 100644 --- a/src/Symfony/Bundle/DoctrineMongoDBBundle/DependencyInjection/DoctrineMongoDBExtension.php +++ b/src/Symfony/Bundle/DoctrineMongoDBBundle/DependencyInjection/DoctrineMongoDBExtension.php @@ -71,8 +71,6 @@ class DoctrineMongoDBExtension extends AbstractDoctrineExtension $config['metadata_cache_driver'], $container ); - - $this->loadConstraints($container); } /** @@ -311,19 +309,6 @@ class DoctrineMongoDBExtension extends AbstractDoctrineExtension $odmConfigDef->addMethodCall('setDocumentNamespaces', array($this->aliasMap)); } - protected function loadConstraints(ContainerBuilder $container) - { - // FIXME: the validator.annotations.namespaces parameter does not exist anymore - // and anyway, it was not available in the FrameworkExtension code - // as each bundle is isolated from the others - if ($container->hasParameter('validator.annotations.namespaces')) { - $container->setParameter('validator.annotations.namespaces', array_merge( - $container->getParameter('validator.annotations.namespaces'), - array('mongodb' => 'Symfony\Bundle\DoctrineMongoDBBundle\Validator\Constraints\\') - )); - } - } - protected function getObjectManagerElementName($name) { return 'doctrine.odm.mongodb.' . $name; diff --git a/src/Symfony/Bundle/DoctrineMongoDBBundle/DoctrineMongoDBBundle.php b/src/Symfony/Bundle/DoctrineMongoDBBundle/DoctrineMongoDBBundle.php index 105267515f..4e85a8aaa1 100755 --- a/src/Symfony/Bundle/DoctrineMongoDBBundle/DoctrineMongoDBBundle.php +++ b/src/Symfony/Bundle/DoctrineMongoDBBundle/DoctrineMongoDBBundle.php @@ -14,6 +14,7 @@ namespace Symfony\Bundle\DoctrineMongoDBBundle; use Symfony\Component\DependencyInjection\Compiler\PassConfig; use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\HttpKernel\Bundle\Bundle; +use Symfony\Bundle\DoctrineMongoDBBundle\DependencyInjection\Compiler\AddValidatorNamespaceAliasPass; use Symfony\Bundle\DoctrineMongoDBBundle\DependencyInjection\Compiler\CreateHydratorDirectoryPass; use Symfony\Bundle\DoctrineMongoDBBundle\DependencyInjection\Compiler\CreateProxyDirectoryPass; use Symfony\Bundle\DoctrineMongoDBBundle\DependencyInjection\Compiler\RegisterEventListenersAndSubscribersPass; @@ -31,6 +32,7 @@ class DoctrineMongoDBBundle extends Bundle { parent::build($container); + $container->addCompilerPass(new AddValidatorNamespaceAliasPass(), PassConfig::TYPE_BEFORE_OPTIMIZATION); $container->addCompilerPass(new RegisterEventListenersAndSubscribersPass(), PassConfig::TYPE_BEFORE_OPTIMIZATION); $container->addCompilerPass(new CreateProxyDirectoryPass(), PassConfig::TYPE_BEFORE_REMOVING); $container->addCompilerPass(new CreateHydratorDirectoryPass(), PassConfig::TYPE_BEFORE_REMOVING); diff --git a/src/Symfony/Bundle/DoctrineMongoDBBundle/Tests/DependencyInjection/AbstractMongoDBExtensionTest.php b/src/Symfony/Bundle/DoctrineMongoDBBundle/Tests/DependencyInjection/AbstractMongoDBExtensionTest.php index 2e9febf99b..82bca769c7 100644 --- a/src/Symfony/Bundle/DoctrineMongoDBBundle/Tests/DependencyInjection/AbstractMongoDBExtensionTest.php +++ b/src/Symfony/Bundle/DoctrineMongoDBBundle/Tests/DependencyInjection/AbstractMongoDBExtensionTest.php @@ -12,6 +12,7 @@ namespace Symfony\Bundle\DoctrineMongoDBBundle\Tests\DependencyInjection; use Symfony\Bundle\DoctrineMongoDBBundle\Tests\TestCase; +use Symfony\Bundle\DoctrineMongoDBBundle\DependencyInjection\Compiler\AddValidatorNamespaceAliasPass; use Symfony\Bundle\DoctrineMongoDBBundle\DependencyInjection\DoctrineMongoDBExtension; use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\DependencyInjection\ParameterBag\ParameterBag; @@ -334,25 +335,26 @@ abstract class AbstractMongoDBExtensionTest extends TestCase public function testRegistersValidatorNamespace() { $container = $this->getContainer(); + $container->register('validator.mapping.loader.annotation_loader') + ->setClass('stdClass') + ->addArgument(array('foo' => 'Foo\\')); + $container->getCompilerPassConfig()->setOptimizationPasses(array()); + $container->getCompilerPassConfig()->setRemovingPasses(array()); + $container->addCompilerPass(new AddValidatorNamespaceAliasPass()); + $container->compile(); - $container->setParameter('validator.annotations.namespaces', array('Namespace1\\', 'Namespace2\\')); - - $loader = new DoctrineMongoDBExtension(); - - $loader->load(array(array()), $container); - + $definition = $container->getDefinition('validator.mapping.loader.annotation_loader'); + $arguments = $definition->getArguments(); $this->assertEquals(array( - 'Namespace1\\', - 'Namespace2\\', - 'mongodb' => 'Symfony\Bundle\DoctrineMongoDBBundle\Validator\Constraints\\', - ), $container->getParameter('validator.annotations.namespaces')); + 'assertMongoDB' => 'Symfony\\Bundle\\DoctrineMongoDBBundle\\Validator\\Constraints\\', + 'foo' => 'Foo\\', + ), $arguments[0], 'compiler adds constraint alias to validator'); } protected function getContainer($bundle = 'YamlBundle') { require_once __DIR__.'/Fixtures/Bundles/'.$bundle.'/'.$bundle.'.php'; - return new ContainerBuilder(new ParameterBag(array( 'kernel.bundles' => array($bundle => 'DoctrineMongoDBBundle\\Tests\\DependencyInjection\\Fixtures\\Bundles\\'.$bundle.'\\'.$bundle), 'kernel.cache_dir' => sys_get_temp_dir(), From 5a9a65701bed2dbb5924415571b8125c14ddfac8 Mon Sep 17 00:00:00 2001 From: Kris Wallsmith Date: Mon, 18 Apr 2011 15:58:18 -0700 Subject: [PATCH 44/91] [AsseticBundle] added factory worker to fix paths when use_controller is on --- .../Worker/PrependControllerWorker.php | 37 +++++++++++++++++++ .../Resources/config/controller.xml | 4 ++ 2 files changed, 41 insertions(+) create mode 100644 src/Symfony/Bundle/AsseticBundle/Factory/Worker/PrependControllerWorker.php diff --git a/src/Symfony/Bundle/AsseticBundle/Factory/Worker/PrependControllerWorker.php b/src/Symfony/Bundle/AsseticBundle/Factory/Worker/PrependControllerWorker.php new file mode 100644 index 0000000000..81862ba17e --- /dev/null +++ b/src/Symfony/Bundle/AsseticBundle/Factory/Worker/PrependControllerWorker.php @@ -0,0 +1,37 @@ + + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace Symfony\Bundle\AsseticBundle\Factory\Worker; + +use Assetic\Asset\AssetInterface; +use Assetic\Factory\Worker\WorkerInterface; + +/** + * Prepends a fake front controller to every asset's target URL. + * + * This worker should only be added when the use_controller configuration + * option is true. It changes the target URL to include the front controller. + * + * @author Kris Wallsmith + */ +class PrependControllerWorker implements WorkerInterface +{ + const CONTROLLER = 'front_controller/'; + + public function process(AssetInterface $asset) + { + $targetUrl = $asset->getTargetUrl(); + + if ($targetUrl && '/' != $targetUrl[0] && 0 !== strpos($targetUrl, self::CONTROLLER)) { + $asset->setTargetUrl(self::CONTROLLER.$targetUrl); + } + } +} diff --git a/src/Symfony/Bundle/AsseticBundle/Resources/config/controller.xml b/src/Symfony/Bundle/AsseticBundle/Resources/config/controller.xml index 65a65732c2..4b56f8fcb6 100644 --- a/src/Symfony/Bundle/AsseticBundle/Resources/config/controller.xml +++ b/src/Symfony/Bundle/AsseticBundle/Resources/config/controller.xml @@ -8,6 +8,7 @@ Symfony\Bundle\AsseticBundle\Controller\AsseticController Symfony\Bundle\AsseticBundle\Routing\AsseticLoader Assetic\Cache\FilesystemCache + Symfony\Bundle\AsseticBundle\Factory\Worker\PrependControllerWorker @@ -23,5 +24,8 @@ %assetic.cache_dir%/assets + + + From 91602dfef4051c400b12cf8f13f403c9e10d61f6 Mon Sep 17 00:00:00 2001 From: Fabien Potencier Date: Tue, 19 Apr 2011 22:55:27 +0200 Subject: [PATCH 45/91] [FrameworkBundle] made possible to interact with the Kernel/Container after a request in functional tests --- src/Symfony/Bundle/FrameworkBundle/Client.php | 28 +++---------------- 1 file changed, 4 insertions(+), 24 deletions(-) diff --git a/src/Symfony/Bundle/FrameworkBundle/Client.php b/src/Symfony/Bundle/FrameworkBundle/Client.php index 91b4b63cf6..9329c21b63 100644 --- a/src/Symfony/Bundle/FrameworkBundle/Client.php +++ b/src/Symfony/Bundle/FrameworkBundle/Client.php @@ -14,8 +14,6 @@ namespace Symfony\Bundle\FrameworkBundle; use Symfony\Component\DependencyInjection\ContainerInterface; use Symfony\Component\HttpKernel\HttpKernelInterface; use Symfony\Component\HttpKernel\Client as BaseClient; -use Symfony\Component\BrowserKit\History; -use Symfony\Component\BrowserKit\CookieJar; use Symfony\Component\HttpKernel\Profiler\Profiler as HttpProfiler; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; @@ -27,23 +25,6 @@ use Symfony\Component\HttpFoundation\Response; */ class Client extends BaseClient { - protected $container; - - /** - * Constructor. - * - * @param HttpKernelInterface $kernel An HttpKernelInterface instance - * @param array $server The server parameters (equivalent of $_SERVER) - * @param History $history A History instance to store the browser history - * @param CookieJar $cookieJar A CookieJar instance to store the cookies - */ - public function __construct(HttpKernelInterface $kernel, array $server = array(), History $history = null, CookieJar $cookieJar = null) - { - parent::__construct($kernel, $server, $history, $cookieJar); - - $this->container = $kernel->getContainer(); - } - /** * Returns the container. * @@ -51,7 +32,7 @@ class Client extends BaseClient */ public function getContainer() { - return $this->container; + return $this->kernel->getContainer(); } /** @@ -71,11 +52,11 @@ class Client extends BaseClient */ public function getProfiler() { - if (!$this->container->has('profiler')) { + if (!$this->kernel->getContainer()->has('profiler')) { return false; } - return $this->container->get('profiler')->loadFromResponse($this->response); + return $this->kernel->getContainer()->get('profiler')->loadFromResponse($this->response); } /** @@ -87,10 +68,9 @@ class Client extends BaseClient */ protected function doRequest($request) { - $returnValue = $this->kernel->handle($request); $this->kernel->shutdown(); - return $returnValue; + return $this->kernel->handle($request); } /** From 7c54518626734748c10656f5d7ed92cfd7641ed0 Mon Sep 17 00:00:00 2001 From: Fabien Potencier Date: Tue, 19 Apr 2011 23:21:22 +0200 Subject: [PATCH 46/91] [Routing] refactored some unit tests --- .../Routing/Generator/UrlGeneratorTest.php | 151 ++++++------------ 1 file changed, 48 insertions(+), 103 deletions(-) diff --git a/tests/Symfony/Tests/Component/Routing/Generator/UrlGeneratorTest.php b/tests/Symfony/Tests/Component/Routing/Generator/UrlGeneratorTest.php index 1f68431e58..1aae9d8792 100644 --- a/tests/Symfony/Tests/Component/Routing/Generator/UrlGeneratorTest.php +++ b/tests/Symfony/Tests/Component/Routing/Generator/UrlGeneratorTest.php @@ -17,150 +17,74 @@ use Symfony\Component\Routing\Generator\UrlGenerator; class UrlGeneratorTest extends \PHPUnit_Framework_TestCase { - /** @var RouteCollection */ - private $routeCollection; - /** @var UrlGenerator */ - private $generator; - - protected function setUp() - { - parent::setUp(); - - $this->routeCollection = new RouteCollection(); - $this->generator = new UrlGenerator($this->routeCollection); - } - public function testAbsoluteUrlWithPort80() { - $this->routeCollection->add('test', new Route('/testing')); - $this->generator->setContext(array( - 'base_url'=>'/app.php', - 'method'=>'GET', - 'host'=>'localhost', - 'port'=>80, - 'is_secure'=>false)); - - $url = $this->generator->generate('test', array(), true); + $routes = $this->getRoutes('test', new Route('/testing')); + $url = $this->getGenerator($routes)->generate('test', array(), true); $this->assertEquals('http://localhost/app.php/testing', $url); } public function testAbsoluteSecureUrlWithPort443() { - $this->routeCollection->add('test', new Route('/testing')); - $this->generator->setContext(array( - 'base_url'=>'/app.php', - 'method'=>'GET', - 'host'=>'localhost', - 'port'=>443, - 'is_secure'=>true)); - - $url = $this->generator->generate('test', array(), true); + $routes = $this->getRoutes('test', new Route('/testing')); + $url = $this->getGenerator($routes, array('port' => 443, 'is_secure' => true))->generate('test', array(), true); $this->assertEquals('https://localhost/app.php/testing', $url); } public function testAbsoluteUrlWithNonStandardPort() { - $this->routeCollection->add('test', new Route('/testing')); - $this->generator->setContext(array( - 'base_url'=>'/app.php', - 'method'=>'GET', - 'host'=>'localhost', - 'port'=>8080, - 'is_secure'=>false)); - - $url = $this->generator->generate('test', array(), true); + $routes = $this->getRoutes('test', new Route('/testing')); + $url = $this->getGenerator($routes, array('port' => 8080))->generate('test', array(), true); $this->assertEquals('http://localhost:8080/app.php/testing', $url); } public function testAbsoluteSecureUrlWithNonStandardPort() { - $this->routeCollection->add('test', new Route('/testing')); - $this->generator->setContext(array( - 'base_url'=>'/app.php', - 'method'=>'GET', - 'host'=>'localhost', - 'port'=>8080, - 'is_secure'=>true)); - - $url = $this->generator->generate('test', array(), true); + $routes = $this->getRoutes('test', new Route('/testing')); + $url = $this->getGenerator($routes, array('port' => 8080, 'is_secure' => true))->generate('test', array(), true); $this->assertEquals('https://localhost:8080/app.php/testing', $url); } public function testRelativeUrlWithoutParameters() { - $this->routeCollection->add('test', new Route('/testing')); - $this->generator->setContext(array( - 'base_url'=>'/app.php', - 'method'=>'GET', - 'host'=>'localhost', - 'port'=>80, - 'is_secure'=>false)); - - $url = $this->generator->generate('test', array(), false); + $routes = $this->getRoutes('test', new Route('/testing')); + $url = $this->getGenerator($routes)->generate('test', array(), false); $this->assertEquals('/app.php/testing', $url); } public function testRelativeUrlWithParameter() { - $this->routeCollection->add('test', new Route('/testing/{foo}')); - $this->generator->setContext(array( - 'base_url'=>'/app.php', - 'method'=>'GET', - 'host'=>'localhost', - 'port'=>80, - 'is_secure'=>false)); - - $url = $this->generator->generate('test', array('foo' => 'bar'), false); + $routes = $this->getRoutes('test', new Route('/testing/{foo}')); + $url = $this->getGenerator($routes)->generate('test', array('foo' => 'bar'), false); $this->assertEquals('/app.php/testing/bar', $url); } public function testRelativeUrlWithNullParameter() { - $this->routeCollection->add('test', new Route('/testing.{format}', array('format' => null))); - $this->generator->setContext(array( - 'base_url'=>'/app.php', - 'method'=>'GET', - 'host'=>'localhost', - 'port'=>80, - 'is_secure'=>false)); - - $url = $this->generator->generate('test', array(), false); + $routes = $this->getRoutes('test', new Route('/testing.{format}', array('format' => null))); + $url = $this->getGenerator($routes)->generate('test', array(), false); $this->assertEquals('/app.php/testing', $url); } public function testRelativeUrlWithExtraParameters() { - $this->routeCollection->add('test', new Route('/testing')); - $this->generator->setContext(array( - 'base_url'=>'/app.php', - 'method'=>'GET', - 'host'=>'localhost', - 'port'=>80, - 'is_secure'=>false)); - - $url = $this->generator->generate('test', array('foo' => 'bar'), false); + $routes = $this->getRoutes('test', new Route('/testing')); + $url = $this->getGenerator($routes)->generate('test', array('foo' => 'bar'), false); $this->assertEquals('/app.php/testing?foo=bar', $url); } public function testAbsoluteUrlWithExtraParameters() { - $this->routeCollection->add('test', new Route('/testing')); - $this->generator->setContext(array( - 'base_url'=>'/app.php', - 'method'=>'GET', - 'host'=>'localhost', - 'port'=>80, - 'is_secure'=>false)); - - $url = $this->generator->generate('test', array('foo' => 'bar'), true); + $routes = $this->getRoutes('test', new Route('/testing')); + $url = $this->getGenerator($routes)->generate('test', array('foo' => 'bar'), true); $this->assertEquals('http://localhost/app.php/testing?foo=bar', $url); } @@ -170,7 +94,8 @@ class UrlGeneratorTest extends \PHPUnit_Framework_TestCase */ public function testGenerateWithoutRoutes() { - $this->generator->generate('test', array(), true); + $routes = $this->getRoutes('foo', new Route('/testing/{foo}')); + $this->getGenerator($routes)->generate('test', array(), true); } /** @@ -178,8 +103,8 @@ class UrlGeneratorTest extends \PHPUnit_Framework_TestCase */ public function testGenerateForRouteWithoutManditoryParameter() { - $this->routeCollection->add('test', new Route('/testing/{foo}')); - $this->generator->generate('test', array(), true); + $routes = $this->getRoutes('test', new Route('/testing/{foo}')); + $this->getGenerator($routes)->generate('test', array(), true); } /** @@ -187,9 +112,8 @@ class UrlGeneratorTest extends \PHPUnit_Framework_TestCase */ public function testGenerateForRouteWithInvalidOptionalParameter() { - $route = new Route('/testing/{foo}', array('foo' => '1'), array('foo' => 'd+')); - $this->routeCollection->add('test', $route); - $this->generator->generate('test', array('foo' => 'bar'), true); + $routes = $this->getRoutes('test', new Route('/testing/{foo}', array('foo' => '1'), array('foo' => 'd+'))); + $this->getGenerator($routes)->generate('test', array('foo' => 'bar'), true); } /** @@ -197,8 +121,29 @@ class UrlGeneratorTest extends \PHPUnit_Framework_TestCase */ public function testGenerateForRouteWithInvalidManditoryParameter() { - $route = new Route('/testing/{foo}', array(), array('foo' => 'd+')); - $this->routeCollection->add('test', $route); - $this->generator->generate('test', array('foo' => 'bar'), true); + $routes = $this->getRoutes('test', new Route('/testing/{foo}', array(), array('foo' => 'd+'))); + $this->getGenerator($routes)->generate('test', array('foo' => 'bar'), true); + } + + protected function getGenerator(RouteCollection $routes, array $context = array()) + { + $generator = new UrlGenerator($routes); + $generator->setContext(array_replace(array( + 'base_url' => '/app.php', + 'method' => 'GET', + 'host' => 'localhost', + 'port' => 80, + 'is_secure' => false, + ), $context)); + + return $generator; + } + + protected function getRoutes($name, Route $route) + { + $routes = new RouteCollection(); + $routes->add($name, $route); + + return $routes; } } From 6f16820328f843b10a35ee04d239e4a7fc2c570f Mon Sep 17 00:00:00 2001 From: Ryan Weaver Date: Tue, 19 Apr 2011 17:01:22 -0500 Subject: [PATCH 47/91] [FrameworkBundle] Removing unnecessary and buggy functionality from ContainerDebugCommand --- .../Command/ContainerDebugCommand.php | 96 ++----------------- 1 file changed, 10 insertions(+), 86 deletions(-) diff --git a/src/Symfony/Bundle/FrameworkBundle/Command/ContainerDebugCommand.php b/src/Symfony/Bundle/FrameworkBundle/Command/ContainerDebugCommand.php index 0195ff4648..8aeb8193ce 100644 --- a/src/Symfony/Bundle/FrameworkBundle/Command/ContainerDebugCommand.php +++ b/src/Symfony/Bundle/FrameworkBundle/Command/ContainerDebugCommand.php @@ -49,13 +49,7 @@ The container:debug displays all configured publiccontainer:debug -You can also search for specific services using wildcards (*): - - container:debug doctrine.* - - container:debug *event_manager - -To get specific information about a service, use specify its name exactly: +To get specific information about a service, specify its name: container:debug validator @@ -73,20 +67,23 @@ EOF */ protected function execute(InputInterface $input, OutputInterface $output) { - $filter = $input->getArgument('name'); + $name = $input->getArgument('name'); $this->containerBuilder = $this->getContainerBuilder(); - $serviceIds = $this->filterServices($this->containerBuilder->getServiceIds(), $filter); + $serviceIds = $this->containerBuilder->getServiceIds(); - if (1 == count($serviceIds) && false === strpos($filter, '*')) { - $this->outputService($output, $serviceIds[0]); + // sort so that it reads like an index of services + asort($serviceIds); + + if ($name) { + $this->outputService($output, $name); } else { $showPrivate = $input->getOption('show-private'); - $this->outputServices($output, $serviceIds, $filter, $showPrivate); + $this->outputServices($output, $serviceIds, $showPrivate); } } - protected function outputServices(OutputInterface $output, $serviceIds, $filter, $showPrivate = false) + protected function outputServices(OutputInterface $output, $serviceIds, $showPrivate = false) { // set the label to specify public or public+private if ($showPrivate) { @@ -95,9 +92,6 @@ EOF $label = 'Public services'; } - if ($filter) { - $label .= sprintf(' matching %s', $filter); - } $output->writeln($this->getHelper('formatter')->formatSection('container', $label)); // loop through to find get space needed and filter private services @@ -215,74 +209,4 @@ EOF // the service has been injected in some special way, just return the service return $this->containerBuilder->get($serviceId); } - - /** - * Filters the given array of service ids by the given string filter: - * - * * An exact filter, "foo", will return *only* the "foo" service - * * A wildcard filter, "foo*", will return all services matching the wildcard - * - * @param array $serviceIds The array of service ids - * @param string $filter The given filter. If ending in *, a wildcard - * @return array - */ - private function filterServices($serviceIds, $filter, $onlyPublic = true) - { - // alphabetical so that this reads like an index of services - asort($serviceIds); - - if (!$filter) { - return $serviceIds; - } - - $regex = $this->buildFilterRegularExpression($filter); - $filteredIds = array(); - foreach ($serviceIds as $serviceId) { - if (preg_match($regex, $serviceId)) { - $filteredIds[] = $serviceId; - } - } - - if (!$filteredIds) { - // give a different message if the use was searching for an exact service - if (false === strpos($filter, '*')) { - $message = sprintf('The service "%s" does not exist.', $filter); - } else { - $message = sprintf('No services matched the pattern "%s"', $filter); - } - - throw new \InvalidArgumentException($message); - } - - return $filteredIds; - } - - /** - * Given a string with wildcards denoted as asterisks (*), this returns - * the regular expression that can be used to match on the string. - * - * For example, *foo* would equate to: - * - * /^(.+?)*foo(.+?)*$/ - * - * @param string $filter The raw filter - * @return string The regular expression - */ - private function buildFilterRegularExpression($filter) - { - $regex = preg_quote(str_replace('*', '', $filter)); - - // process the "front" wildcard - if ('*' === substr($filter, 0, 1)) { - $regex = '(.+?)*'.$regex; - } - - // process the "end" wildcard - if ('*' === substr($filter, -1, 1)) { - $regex .= '(.+?)*'; - } - $regex = sprintf('/^%s$/', $regex); - - return $regex; - } } From b45d117fbf51429928e8a2ffe8a232ea07a53569 Mon Sep 17 00:00:00 2001 From: Victor Berchet Date: Mon, 18 Apr 2011 14:52:50 +0200 Subject: [PATCH 48/91] [FrameworkBundle] Initialize the listenerId property in the ContainerAwareEventDispatcher class --- .../Bundle/FrameworkBundle/ContainerAwareEventDispatcher.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Symfony/Bundle/FrameworkBundle/ContainerAwareEventDispatcher.php b/src/Symfony/Bundle/FrameworkBundle/ContainerAwareEventDispatcher.php index b0cfe53a59..2732525e13 100644 --- a/src/Symfony/Bundle/FrameworkBundle/ContainerAwareEventDispatcher.php +++ b/src/Symfony/Bundle/FrameworkBundle/ContainerAwareEventDispatcher.php @@ -34,7 +34,7 @@ class ContainerAwareEventDispatcher extends EventDispatcher * The service IDs of the event listeners and subscribers * @var array */ - private $listenerIds; + private $listenerIds = array(); /** * Constructor. From a4c41179e04ff77994cac6456934b508737bd26a Mon Sep 17 00:00:00 2001 From: Victor Berchet Date: Mon, 18 Apr 2011 13:45:15 +0200 Subject: [PATCH 49/91] [FrameworkBundle] Add unit tests for ContainerAwareEventDispatcher --- .../ContainerAwareEventDispatcher.php | 4 +- .../ContainerAwareEventDispatcherTest.php | 61 +++++++++++++++++++ 2 files changed, 63 insertions(+), 2 deletions(-) create mode 100644 src/Symfony/Bundle/FrameworkBundle/Tests/ContainerAwareEventDispatcherTest.php diff --git a/src/Symfony/Bundle/FrameworkBundle/ContainerAwareEventDispatcher.php b/src/Symfony/Bundle/FrameworkBundle/ContainerAwareEventDispatcher.php index 2732525e13..cb9d4b0da8 100644 --- a/src/Symfony/Bundle/FrameworkBundle/ContainerAwareEventDispatcher.php +++ b/src/Symfony/Bundle/FrameworkBundle/ContainerAwareEventDispatcher.php @@ -61,9 +61,9 @@ class ContainerAwareEventDispatcher extends EventDispatcher throw new \InvalidArgumentException('Expected a string argument'); } - foreach ((array) $eventNames as $event) { + foreach ((array) $eventNames as $eventName) { // Prevent duplicate entries - $this->listenerIds[$event][$serviceId] = $priority; + $this->listenerIds[$eventName][$serviceId] = $priority; } } diff --git a/src/Symfony/Bundle/FrameworkBundle/Tests/ContainerAwareEventDispatcherTest.php b/src/Symfony/Bundle/FrameworkBundle/Tests/ContainerAwareEventDispatcherTest.php new file mode 100644 index 0000000000..9fb9a6e271 --- /dev/null +++ b/src/Symfony/Bundle/FrameworkBundle/Tests/ContainerAwareEventDispatcherTest.php @@ -0,0 +1,61 @@ +getMock('Symfony\Bundle\FrameworkBundle\Tests\Service'); + + $service + ->expects($this->once()) + ->method('onEvent') + ->with($event) + ; + + $container = new Container(); + $container->set('service.listener', $service); + + $dispatcher = new ContainerAwareEventDispatcher($container); + $dispatcher->addListenerService('onEvent', 'service.listener'); + + $dispatcher->dispatch('onEvent', $event); + } + + public function testPreventDuplicateListenerService() + { + $event = new Event(); + + $service = $this->getMock('Symfony\Bundle\FrameworkBundle\Tests\Service'); + + $service + ->expects($this->once()) + ->method('onEvent') + ->with($event) + ; + + $container = new Container(); + $container->set('service.listener', $service); + + $dispatcher = new ContainerAwareEventDispatcher($container); + $dispatcher->addListenerService('onEvent', 'service.listener', 5); + $dispatcher->addListenerService('onEvent', 'service.listener', 10); + + $dispatcher->dispatch('onEvent', $event); + } + +} + +class Service +{ + function onEvent(Event $e) + { + } +} \ No newline at end of file From b4df0ea9eddc3e51eb067327a210567e8a98582f Mon Sep 17 00:00:00 2001 From: Victor Berchet Date: Mon, 18 Apr 2011 15:05:53 +0200 Subject: [PATCH 50/91] [FrameworkBundle] Added a test for listener services not available in the current scope --- .../ContainerAwareEventDispatcher.php | 2 ++ .../ContainerAwareEventDispatcherTest.php | 21 +++++++++++++++++++ 2 files changed, 23 insertions(+) diff --git a/src/Symfony/Bundle/FrameworkBundle/ContainerAwareEventDispatcher.php b/src/Symfony/Bundle/FrameworkBundle/ContainerAwareEventDispatcher.php index cb9d4b0da8..87479a0aa6 100644 --- a/src/Symfony/Bundle/FrameworkBundle/ContainerAwareEventDispatcher.php +++ b/src/Symfony/Bundle/FrameworkBundle/ContainerAwareEventDispatcher.php @@ -72,6 +72,8 @@ class ContainerAwareEventDispatcher extends EventDispatcher * * Lazily loads listeners for this event from the dependency injection * container. + * + * @throws \InvalidArgumentException if the service is not defined */ public function dispatch($eventName, Event $event = null) { diff --git a/src/Symfony/Bundle/FrameworkBundle/Tests/ContainerAwareEventDispatcherTest.php b/src/Symfony/Bundle/FrameworkBundle/Tests/ContainerAwareEventDispatcherTest.php index 9fb9a6e271..ea06810311 100644 --- a/src/Symfony/Bundle/FrameworkBundle/Tests/ContainerAwareEventDispatcherTest.php +++ b/src/Symfony/Bundle/FrameworkBundle/Tests/ContainerAwareEventDispatcherTest.php @@ -5,6 +5,7 @@ namespace Symfony\Bundle\FrameworkBundle\Tests; use Symfony\Component\DependencyInjection\Container; use Symfony\Bundle\FrameworkBundle\ContainerAwareEventDispatcher; use Symfony\Component\EventDispatcher\Event; +use Symfony\Component\DependencyInjection\Scope; class ContainerAwareEventDispatcherTest extends \PHPUnit_Framework_TestCase { @@ -51,6 +52,26 @@ class ContainerAwareEventDispatcherTest extends \PHPUnit_Framework_TestCase $dispatcher->dispatch('onEvent', $event); } + /** + * @expectedException \InvalidArgumentException + */ + public function testTriggerAListenerServiceOutOfScope() + { + $service = $this->getMock('Symfony\Bundle\FrameworkBundle\Tests\Service'); + + $scope = new Scope('scope'); + + $container = new Container(); + $container->addScope($scope); + $container->enterScope('scope'); + $container->set('service.listener', $service, 'scope'); + + $dispatcher = new ContainerAwareEventDispatcher($container); + $dispatcher->addListenerService('onEvent', 'service.listener'); + + $container->leaveScope('scope'); + $dispatcher->dispatch('onEvent'); + } } class Service From d993a9160a6f788ffd4ad6e113c1cefa83eb54fd Mon Sep 17 00:00:00 2001 From: Fabien Potencier Date: Wed, 20 Apr 2011 10:49:08 +0200 Subject: [PATCH 51/91] [HttpFoundation] fixed getScheme() method --- src/Symfony/Component/HttpFoundation/Request.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Symfony/Component/HttpFoundation/Request.php b/src/Symfony/Component/HttpFoundation/Request.php index 05af73444a..a2b964bd80 100644 --- a/src/Symfony/Component/HttpFoundation/Request.php +++ b/src/Symfony/Component/HttpFoundation/Request.php @@ -408,7 +408,7 @@ class Request public function getScheme() { - return ($this->server->get('HTTPS') == 'on') ? 'https' : 'http'; + return $this->isSecure() ? 'https' : 'http'; } public function getPort() From 07aae9849536cb5fdd0d901aa7eb113b5a8c054e Mon Sep 17 00:00:00 2001 From: Fabien Potencier Date: Wed, 20 Apr 2011 00:25:45 +0200 Subject: [PATCH 52/91] [Routing] added support for _scheme requirement The _scheme requirement can be used to force routes to always match one given scheme and to always be generated with the given scheme. So, if _scheme is set to https, URL generation will force an absolute URL if the current scheme is http. And if you request the URL with http, you will be redirected to the https URL. --- .../Controller/RedirectController.php | 32 ++++++++++++--- .../DependencyInjection/Configuration.php | 2 + .../FrameworkExtension.php | 4 ++ .../FrameworkBundle/RequestListener.php | 23 +++++++---- .../FrameworkBundle/Resources/config/web.xml | 2 + .../Routing/RedirectableUrlMatcher.php | 16 +++++++- .../Routing/Generator/UrlGenerator.php | 23 +++++++---- .../Matcher/Dumper/PhpMatcherDumper.php | 23 ++++++++--- .../RedirectableUrlMatcherInterface.php | 14 ++----- .../Fixtures/RedirectableUrlMatcher.php | 5 ++- .../Routing/Fixtures/dumper/url_matcher2.php | 16 ++++++++ .../Dumper/PhpGeneratorDumperTest.php | 6 +-- .../Routing/Generator/UrlGeneratorTest.php | 29 ++++++++++--- .../Matcher/Dumper/PhpMatcherDumperTest.php | 41 +++++++++++++++---- 14 files changed, 177 insertions(+), 59 deletions(-) diff --git a/src/Symfony/Bundle/FrameworkBundle/Controller/RedirectController.php b/src/Symfony/Bundle/FrameworkBundle/Controller/RedirectController.php index 81d40ce8da..40f9a729b2 100644 --- a/src/Symfony/Bundle/FrameworkBundle/Controller/RedirectController.php +++ b/src/Symfony/Bundle/FrameworkBundle/Controller/RedirectController.php @@ -51,23 +51,43 @@ class RedirectController extends ContainerAware /** * Redirects to a URL. * - * It expects a url path parameter. * By default, the response status code is 301. * - * If the url is empty, the status code will be 410. - * If the permanent path parameter is set, the status code will be 302. + * If the path is empty, the status code will be 410. + * If the permanent flag is set, the status code will be 302. * - * @param string $url The url to redirect to + * @param string $path The path to redirect to * @param Boolean $permanent Whether the redirect is permanent or not + * @param Boolean $scheme The URL scheme (null to keep the current one) + * @param integer $httpPort The HTTP port + * @param integer $httpsPort The HTTPS port * * @return Response A Response instance */ - public function urlRedirectAction($url, $permanent = false) + public function urlRedirectAction($path, $permanent = false, $scheme = null, $httpPort = 80, $httpsPort = 443) { - if (!$url) { + if (!$path) { return new Response(null, 410); } + $request = $this->container->get('request'); + if (null === $scheme) { + $scheme = $request->getScheme(); + } + $qs = $request->getQueryString(); + if ($qs) { + $qs = '?'.$qs; + } + + $port = ''; + if ('http' === $scheme && 80 != $httpPort) { + $port = ':'.$httpPort; + } elseif ('https' === $scheme && 443 != $httpPort) { + $port = ':'.$httpsPort; + } + + $url = $scheme.'://'.$request->getHttpHost().$port.$request->getBaseUrl().$path.$qs; + return new RedirectResponse($url, $permanent ? 301 : 302); } } diff --git a/src/Symfony/Bundle/FrameworkBundle/DependencyInjection/Configuration.php b/src/Symfony/Bundle/FrameworkBundle/DependencyInjection/Configuration.php index dce083d225..b45e2d4582 100644 --- a/src/Symfony/Bundle/FrameworkBundle/DependencyInjection/Configuration.php +++ b/src/Symfony/Bundle/FrameworkBundle/DependencyInjection/Configuration.php @@ -131,6 +131,8 @@ class Configuration implements ConfigurationInterface ->scalarNode('cache_warmer')->defaultFalse()->end() ->scalarNode('resource')->isRequired()->end() ->scalarNode('type')->end() + ->scalarNode('http_port')->defaultValue(80)->end() + ->scalarNode('https_port')->defaultValue(443)->end() ->end() ->end() ->end() diff --git a/src/Symfony/Bundle/FrameworkBundle/DependencyInjection/FrameworkExtension.php b/src/Symfony/Bundle/FrameworkBundle/DependencyInjection/FrameworkExtension.php index bb690d064e..ac0025ef62 100644 --- a/src/Symfony/Bundle/FrameworkBundle/DependencyInjection/FrameworkExtension.php +++ b/src/Symfony/Bundle/FrameworkBundle/DependencyInjection/FrameworkExtension.php @@ -256,6 +256,10 @@ class FrameworkExtension extends Extension $container->setAlias('router', 'router.cached'); } + $def = $container->getDefinition('request_listener'); + $def->setArgument(2, $config['http_port']); + $def->setArgument(3, $config['https_port']); + $this->addClassesToCompile(array( 'Symfony\\Component\\Routing\\RouterInterface', 'Symfony\\Component\\Routing\\Matcher\\UrlMatcherInterface', diff --git a/src/Symfony/Bundle/FrameworkBundle/RequestListener.php b/src/Symfony/Bundle/FrameworkBundle/RequestListener.php index 04fb40a424..57bf590e52 100644 --- a/src/Symfony/Bundle/FrameworkBundle/RequestListener.php +++ b/src/Symfony/Bundle/FrameworkBundle/RequestListener.php @@ -29,14 +29,18 @@ use Symfony\Component\Routing\RouterInterface; */ class RequestListener { - protected $router; - protected $logger; - protected $container; + private $router; + private $logger; + private $container; + private $httpPort; + private $httpsPort; - public function __construct(ContainerInterface $container, RouterInterface $router, LoggerInterface $logger = null) + public function __construct(ContainerInterface $container, RouterInterface $router, $httpPort = 80, $httpsPort = 443, LoggerInterface $logger = null) { $this->container = $container; $this->router = $router; + $this->httpPort = $httpPort; + $this->httpsPort = $httpsPort; $this->logger = $logger; } @@ -73,11 +77,12 @@ class RequestListener // set the context even if the parsing does not need to be done // to have correct link generation $this->router->setContext(array( - 'base_url' => $request->getBaseUrl(), - 'method' => $request->getMethod(), - 'host' => $request->getHost(), - 'port' => $request->getPort(), - 'is_secure' => $request->isSecure(), + 'base_url' => $request->getBaseUrl(), + 'method' => $request->getMethod(), + 'host' => $request->getHost(), + 'scheme' => $request->getScheme(), + 'http_port' => $this->httpPort, + 'https_port' => $this->httpsPort, )); } diff --git a/src/Symfony/Bundle/FrameworkBundle/Resources/config/web.xml b/src/Symfony/Bundle/FrameworkBundle/Resources/config/web.xml index 217de8192c..9fae044bd5 100755 --- a/src/Symfony/Bundle/FrameworkBundle/Resources/config/web.xml +++ b/src/Symfony/Bundle/FrameworkBundle/Resources/config/web.xml @@ -31,6 +31,8 @@ + +
diff --git a/src/Symfony/Bundle/FrameworkBundle/Routing/RedirectableUrlMatcher.php b/src/Symfony/Bundle/FrameworkBundle/Routing/RedirectableUrlMatcher.php index 54b65ce1ce..e49e5e7e14 100644 --- a/src/Symfony/Bundle/FrameworkBundle/Routing/RedirectableUrlMatcher.php +++ b/src/Symfony/Bundle/FrameworkBundle/Routing/RedirectableUrlMatcher.php @@ -19,12 +19,24 @@ use Symfony\Component\Routing\Matcher\RedirectableUrlMatcherInterface; */ class RedirectableUrlMatcher extends UrlMatcher implements RedirectableUrlMatcherInterface { - public function redirect($pathinfo, $route) + /** + * Redirects the user to another URL. + * + * @param string $path The path info to redirect to. + * @param string $route The route that matched + * @param string $scheme The URL scheme (null to keep the current one) + * + * @return array An array of parameters + */ + public function redirect($path, $route, $scheme = null) { return array( '_controller' => 'Symfony\\Bundle\\FrameworkBundle\\Controller\\RedirectController::urlRedirectAction', - 'url' => $this->context['base_url'].$pathinfo, + 'path' => $path, 'permanent' => true, + 'scheme' => $scheme, + 'httpPort' => isset($this->context['http_port']) ? $this->context['http_port'] : 80, + 'httpsPort' => isset($this->context['https_port']) ? $this->context['https_port'] : 443, '_route' => $route, ); } diff --git a/src/Symfony/Component/Routing/Generator/UrlGenerator.php b/src/Symfony/Component/Routing/Generator/UrlGenerator.php index 79fea790fb..c0d3d6f254 100644 --- a/src/Symfony/Component/Routing/Generator/UrlGenerator.php +++ b/src/Symfony/Component/Routing/Generator/UrlGenerator.php @@ -129,14 +129,23 @@ class UrlGenerator implements UrlGeneratorInterface $url = (isset($this->context['base_url']) ? $this->context['base_url'] : '').$url; - if ($absolute && isset($this->context['host'])) { - $isSecure = (isset($this->context['is_secure']) && $this->context['is_secure']); - $port = isset($this->context['port']) ? $this->context['port'] : 80; - $urlBeginning = 'http'.($isSecure ? 's' : '').'://'.$this->context['host']; - if (($isSecure && $port != 443) || (!$isSecure && $port != 80)) { - $urlBeginning .= ':'.$port; + if (isset($this->context['host'])) { + $scheme = isset($this->context['scheme']) ? $this->context['scheme'] : 'http'; + if (isset($requirements['_scheme']) && ($req = strtolower($requirements['_scheme'])) && $scheme != $req) { + $absolute = true; + $scheme = $req; + } + + if ($absolute) { + $port = ''; + if ('http' === $scheme && 80 != ($httpPort = isset($this->context['http_port']) ? $this->context['http_port'] : 80)) { + $port = ':'.$httpPort; + } elseif ('https' === $scheme && 443 != ($httpsPort = isset($this->context['https_port']) ? $this->context['https_port'] : 443)) { + $port = ':'.$httpsPort; + } + + $url = $scheme.'://'.$this->context['host'].$port.$url; } - $url = $urlBeginning.$url; } return $url; diff --git a/src/Symfony/Component/Routing/Matcher/Dumper/PhpMatcherDumper.php b/src/Symfony/Component/Routing/Matcher/Dumper/PhpMatcherDumper.php index b882ad57de..bbcf1edcff 100644 --- a/src/Symfony/Component/Routing/Matcher/Dumper/PhpMatcherDumper.php +++ b/src/Symfony/Component/Routing/Matcher/Dumper/PhpMatcherDumper.php @@ -41,17 +41,17 @@ class PhpMatcherDumper extends MatcherDumper // trailing slash support is only enabled if we know how to redirect the user $interfaces = class_implements($options['base_class']); - $supportsTrailingSlash = isset($interfaces['Symfony\Component\Routing\Matcher\RedirectableUrlMatcherInterface']); + $supportsRedirections = isset($interfaces['Symfony\Component\Routing\Matcher\RedirectableUrlMatcherInterface']); return $this->startClass($options['class'], $options['base_class']). $this->addConstructor(). - $this->addMatcher($supportsTrailingSlash). + $this->addMatcher($supportsRedirections). $this->endClass() ; } - private function addMatcher($supportsTrailingSlash) + private function addMatcher($supportsRedirections) { $code = array(); @@ -61,7 +61,7 @@ class PhpMatcherDumper extends MatcherDumper $hasTrailingSlash = false; $matches = false; if (!count($compiledRoute->getVariables()) && false !== preg_match('#^(.)\^(?P.*?)\$\1#', $compiledRoute->getRegex(), $m)) { - if ($supportsTrailingSlash && substr($m['url'], -1) === '/') { + if ($supportsRedirections && substr($m['url'], -1) === '/') { $conditions[] = sprintf("rtrim(\$pathinfo, '/') === '%s'", rtrim(str_replace('\\', '', $m['url']), '/')); $hasTrailingSlash = true; } else { @@ -73,7 +73,7 @@ class PhpMatcherDumper extends MatcherDumper } $regex = $compiledRoute->getRegex(); - if ($supportsTrailingSlash && $pos = strpos($regex, '/$')) { + if ($supportsRedirections && $pos = strpos($regex, '/$')) { $regex = substr($regex, 0, $pos).'/?$'.substr($regex, $pos + 2); $hasTrailingSlash = true; } @@ -110,6 +110,19 @@ EOF , $name); } + if ($scheme = $route->getRequirement('_scheme')) { + if (!$supportsRedirections) { + throw new \LogicException('The "_scheme" requirement is only supported for route dumper that implements RedirectableUrlMatcherInterface.'); + } + + $code[] = sprintf(<<context['scheme']) && \$this->context['scheme'] !== '$scheme') { + return \$this->redirect(\$pathinfo, '%s', '$scheme'); + } +EOF + , $name); + } + // optimize parameters array if (true === $matches && $compiledRoute->getDefaults()) { $code[] = sprintf(" return array_merge(\$this->mergeDefaults(\$matches, %s), array('_route' => '%s'));" diff --git a/src/Symfony/Component/Routing/Matcher/RedirectableUrlMatcherInterface.php b/src/Symfony/Component/Routing/Matcher/RedirectableUrlMatcherInterface.php index b1e4cd4b41..3ed93e7a52 100644 --- a/src/Symfony/Component/Routing/Matcher/RedirectableUrlMatcherInterface.php +++ b/src/Symfony/Component/Routing/Matcher/RedirectableUrlMatcherInterface.php @@ -21,17 +21,11 @@ interface RedirectableUrlMatcherInterface /** * Redirects the user to another URL. * - * As the Routing component does not know know to redirect the user, - * the default implementation throw an exception. - * - * Override this method to implement your own logic. - * - * If you are using a Dumper, don't forget to change the default base. - * - * @param string $pathinfo The path info to redirect to. - * @param string $route The route that matched + * @param string $path The path info to redirect to. + * @param string $route The route that matched + * @param string $scheme The URL scheme (null to keep the current one) * * @return array An array of parameters */ - function redirect($pathinfo, $route); + function redirect($path, $route, $scheme = null); } diff --git a/tests/Symfony/Tests/Component/Routing/Fixtures/RedirectableUrlMatcher.php b/tests/Symfony/Tests/Component/Routing/Fixtures/RedirectableUrlMatcher.php index c1d4e34c90..81f021afee 100644 --- a/tests/Symfony/Tests/Component/Routing/Fixtures/RedirectableUrlMatcher.php +++ b/tests/Symfony/Tests/Component/Routing/Fixtures/RedirectableUrlMatcher.php @@ -19,11 +19,12 @@ use Symfony\Component\Routing\Matcher\RedirectableUrlMatcherInterface; */ class RedirectableUrlMatcher extends UrlMatcher implements RedirectableUrlMatcherInterface { - public function redirect($pathinfo, $route) + public function redirect($path, $route, $scheme = null) { return array( '_controller' => 'Some controller reference...', - 'url' => $this->context['base_url'].$pathinfo, + 'path' => $path, + 'scheme' => $scheme, ); } } diff --git a/tests/Symfony/Tests/Component/Routing/Fixtures/dumper/url_matcher2.php b/tests/Symfony/Tests/Component/Routing/Fixtures/dumper/url_matcher2.php index 370ba5ba71..5c6fdbd3cb 100644 --- a/tests/Symfony/Tests/Component/Routing/Fixtures/dumper/url_matcher2.php +++ b/tests/Symfony/Tests/Component/Routing/Fixtures/dumper/url_matcher2.php @@ -100,6 +100,22 @@ class ProjectUrlMatcher extends Symfony\Tests\Component\Routing\Fixtures\Redirec return array ( 'def' => 'test', '_route' => 'foofoo',); } + // secure + if ($pathinfo === '/secure') { + if (isset($this->context['scheme']) && $this->context['scheme'] !== 'https') { + return $this->redirect($pathinfo, 'secure', 'https'); + } + return array('_route' => 'secure'); + } + + // nonsecure + if ($pathinfo === '/nonsecure') { + if (isset($this->context['scheme']) && $this->context['scheme'] !== 'http') { + return $this->redirect($pathinfo, 'nonsecure', 'http'); + } + return array('_route' => 'nonsecure'); + } + throw 0 < count($allow) ? new MethodNotAllowedException(array_unique($allow)) : new NotFoundException(); } } diff --git a/tests/Symfony/Tests/Component/Routing/Generator/Dumper/PhpGeneratorDumperTest.php b/tests/Symfony/Tests/Component/Routing/Generator/Dumper/PhpGeneratorDumperTest.php index ca43691ba5..0ec8be010e 100644 --- a/tests/Symfony/Tests/Component/Routing/Generator/Dumper/PhpGeneratorDumperTest.php +++ b/tests/Symfony/Tests/Component/Routing/Generator/Dumper/PhpGeneratorDumperTest.php @@ -61,8 +61,7 @@ class PhpGeneratorDumperTest extends \PHPUnit_Framework_TestCase 'base_url' => '/app.php', 'method' => 'GET', 'host' => 'localhost', - 'port' => 80, - 'is_secure' => false + 'scheme' => 'http', )); $absoluteUrlWithParameter = $projectUrlGenerator->generate('Test', array('foo' => 'bar'), true); @@ -88,8 +87,7 @@ class PhpGeneratorDumperTest extends \PHPUnit_Framework_TestCase 'base_url' => '/app.php', 'method' => 'GET', 'host' => 'localhost', - 'port' => 80, - 'is_secure' => false + 'scheme' => 'http', )); $projectUrlGenerator->generate('Test', array()); diff --git a/tests/Symfony/Tests/Component/Routing/Generator/UrlGeneratorTest.php b/tests/Symfony/Tests/Component/Routing/Generator/UrlGeneratorTest.php index 1aae9d8792..bda8dad448 100644 --- a/tests/Symfony/Tests/Component/Routing/Generator/UrlGeneratorTest.php +++ b/tests/Symfony/Tests/Component/Routing/Generator/UrlGeneratorTest.php @@ -28,7 +28,7 @@ class UrlGeneratorTest extends \PHPUnit_Framework_TestCase public function testAbsoluteSecureUrlWithPort443() { $routes = $this->getRoutes('test', new Route('/testing')); - $url = $this->getGenerator($routes, array('port' => 443, 'is_secure' => true))->generate('test', array(), true); + $url = $this->getGenerator($routes, array('scheme' => 'https'))->generate('test', array(), true); $this->assertEquals('https://localhost/app.php/testing', $url); } @@ -36,7 +36,7 @@ class UrlGeneratorTest extends \PHPUnit_Framework_TestCase public function testAbsoluteUrlWithNonStandardPort() { $routes = $this->getRoutes('test', new Route('/testing')); - $url = $this->getGenerator($routes, array('port' => 8080))->generate('test', array(), true); + $url = $this->getGenerator($routes, array('http_port' => 8080))->generate('test', array(), true); $this->assertEquals('http://localhost:8080/app.php/testing', $url); } @@ -44,7 +44,7 @@ class UrlGeneratorTest extends \PHPUnit_Framework_TestCase public function testAbsoluteSecureUrlWithNonStandardPort() { $routes = $this->getRoutes('test', new Route('/testing')); - $url = $this->getGenerator($routes, array('port' => 8080, 'is_secure' => true))->generate('test', array(), true); + $url = $this->getGenerator($routes, array('https_port' => 8080, 'scheme' => 'https'))->generate('test', array(), true); $this->assertEquals('https://localhost:8080/app.php/testing', $url); } @@ -125,6 +125,24 @@ class UrlGeneratorTest extends \PHPUnit_Framework_TestCase $this->getGenerator($routes)->generate('test', array('foo' => 'bar'), true); } + public function testSchemeRequirementDoesNothingIfSameCurrentScheme() + { + $routes = $this->getRoutes('test', new Route('/', array(), array('_scheme' => 'http'))); + $this->assertEquals('/app.php/', $this->getGenerator($routes)->generate('test')); + + $routes = $this->getRoutes('test', new Route('/', array(), array('_scheme' => 'https'))); + $this->assertEquals('/app.php/', $this->getGenerator($routes, array('scheme' => 'https'))->generate('test')); + } + + public function testSchemeRequirementForcesAbsoluteUrl() + { + $routes = $this->getRoutes('test', new Route('/', array(), array('_scheme' => 'https'))); + $this->assertEquals('https://localhost/app.php/', $this->getGenerator($routes)->generate('test')); + + $routes = $this->getRoutes('test', new Route('/', array(), array('_scheme' => 'http'))); + $this->assertEquals('http://localhost/app.php/', $this->getGenerator($routes, array('scheme' => 'https'))->generate('test')); + } + protected function getGenerator(RouteCollection $routes, array $context = array()) { $generator = new UrlGenerator($routes); @@ -132,8 +150,9 @@ class UrlGeneratorTest extends \PHPUnit_Framework_TestCase 'base_url' => '/app.php', 'method' => 'GET', 'host' => 'localhost', - 'port' => 80, - 'is_secure' => false, + 'http_port' => 80, + 'https_port' => 443, + 'scheme' => 'http', ), $context)); return $generator; diff --git a/tests/Symfony/Tests/Component/Routing/Matcher/Dumper/PhpMatcherDumperTest.php b/tests/Symfony/Tests/Component/Routing/Matcher/Dumper/PhpMatcherDumperTest.php index 138425fba9..c61af52e70 100644 --- a/tests/Symfony/Tests/Component/Routing/Matcher/Dumper/PhpMatcherDumperTest.php +++ b/tests/Symfony/Tests/Component/Routing/Matcher/Dumper/PhpMatcherDumperTest.php @@ -17,13 +17,6 @@ use Symfony\Component\Routing\RouteCollection; class PhpMatcherDumperTest extends \PHPUnit_Framework_TestCase { - static protected $fixturesPath; - - static public function setUpBeforeClass() - { - self::$fixturesPath = realpath(__DIR__.'/../../Fixtures/'); - } - public function testDump() { $collection = new RouteCollection(); @@ -75,7 +68,37 @@ class PhpMatcherDumperTest extends \PHPUnit_Framework_TestCase )); $dumper = new PhpMatcherDumper($collection); - $this->assertStringEqualsFile(self::$fixturesPath.'/dumper/url_matcher1.php', $dumper->dump(), '->dump() dumps basic routes to the correct PHP file.'); - $this->assertStringEqualsFile(self::$fixturesPath.'/dumper/url_matcher2.php', $dumper->dump(array('base_class' => 'Symfony\Tests\Component\Routing\Fixtures\RedirectableUrlMatcher')), '->dump() dumps basic routes to the correct PHP file.'); + $this->assertStringEqualsFile(__DIR__.'/../../Fixtures/dumper/url_matcher1.php', $dumper->dump(), '->dump() dumps basic routes to the correct PHP file.'); + + // force HTTPS redirection + $collection->add('secure', new Route( + '/secure', + array(), + array('_scheme' => 'https') + )); + + // force HTTP redirection + $collection->add('nonsecure', new Route( + '/nonsecure', + array(), + array('_scheme' => 'http') + )); + + $this->assertStringEqualsFile(__DIR__.'/../../Fixtures/dumper/url_matcher2.php', $dumper->dump(array('base_class' => 'Symfony\Tests\Component\Routing\Fixtures\RedirectableUrlMatcher')), '->dump() dumps basic routes to the correct PHP file.'); + } + + /** + * @expectedException \LogicException + */ + public function testDumpWhenSchemeIsUsedWithoutAProperDumper() + { + $collection = new RouteCollection(); + $collection->add('secure', new Route( + '/secure', + array(), + array('_scheme' => 'https') + )); + $dumper = new PhpMatcherDumper($collection); + $dumper->dump(); } } From cdf706d357b8f74acae5e7a29b4982010a854bf9 Mon Sep 17 00:00:00 2001 From: Kris Wallsmith Date: Tue, 19 Apr 2011 14:29:10 -0700 Subject: [PATCH 53/91] [DependencyInjection] renamed Definition::setArgument() as replaceArgument() to be more specific --- .../Compiler/AssetManagerPass.php | 2 +- .../Compiler/FilterManagerPass.php | 2 +- .../AddValidatorNamespaceAliasPass.php | 2 +- .../Compiler/AddCacheWarmerPass.php | 2 +- .../Compiler/AddConstraintValidatorsPass.php | 2 +- .../Compiler/AddFieldFactoryGuessersPass.php | 2 +- .../FrameworkExtension.php | 38 +++++++++---------- .../Compiler/LoggerChannelPass.php | 4 +- .../Compiler/AddSecurityVotersPass.php | 2 +- .../Security/Factory/AbstractFactory.php | 8 ++-- .../Security/Factory/FormLoginFactory.php | 4 +- .../Security/Factory/HttpBasicFactory.php | 8 ++-- .../Security/Factory/HttpDigestFactory.php | 10 ++--- .../Security/Factory/RememberMeFactory.php | 10 ++--- .../Security/Factory/X509Factory.php | 8 ++-- .../DependencyInjection/SecurityExtension.php | 36 +++++++++--------- .../WebProfilerExtension.php | 4 +- .../ResolveDefinitionTemplatesPass.php | 2 +- .../DependencyInjection/Definition.php | 2 +- .../DefinitionDecorator.php | 2 +- .../ResolveDefinitionTemplatesPassTest.php | 6 +-- .../DefinitionDecoratorTest.php | 2 +- .../DependencyInjection/DefinitionTest.php | 8 ++-- 23 files changed, 83 insertions(+), 83 deletions(-) diff --git a/src/Symfony/Bundle/AsseticBundle/DependencyInjection/Compiler/AssetManagerPass.php b/src/Symfony/Bundle/AsseticBundle/DependencyInjection/Compiler/AssetManagerPass.php index 22454b83af..154f2ce553 100644 --- a/src/Symfony/Bundle/AsseticBundle/DependencyInjection/Compiler/AssetManagerPass.php +++ b/src/Symfony/Bundle/AsseticBundle/DependencyInjection/Compiler/AssetManagerPass.php @@ -48,7 +48,7 @@ class AssetManagerPass implements CompilerPassInterface } } } - $am->setArgument(1, $loaders); + $am->replaceArgument(1, $loaders); // add resources foreach ($container->findTaggedServiceIds('assetic.formula_resource') as $id => $attributes) { diff --git a/src/Symfony/Bundle/AsseticBundle/DependencyInjection/Compiler/FilterManagerPass.php b/src/Symfony/Bundle/AsseticBundle/DependencyInjection/Compiler/FilterManagerPass.php index b9c258774b..af04a6e214 100644 --- a/src/Symfony/Bundle/AsseticBundle/DependencyInjection/Compiler/FilterManagerPass.php +++ b/src/Symfony/Bundle/AsseticBundle/DependencyInjection/Compiler/FilterManagerPass.php @@ -39,6 +39,6 @@ class FilterManagerPass implements CompilerPassInterface $container ->getDefinition('assetic.filter_manager') - ->setArgument(1, $mapping); + ->replaceArgument(1, $mapping); } } diff --git a/src/Symfony/Bundle/DoctrineMongoDBBundle/DependencyInjection/Compiler/AddValidatorNamespaceAliasPass.php b/src/Symfony/Bundle/DoctrineMongoDBBundle/DependencyInjection/Compiler/AddValidatorNamespaceAliasPass.php index 03c4a6f02e..3cfd2e93ac 100644 --- a/src/Symfony/Bundle/DoctrineMongoDBBundle/DependencyInjection/Compiler/AddValidatorNamespaceAliasPass.php +++ b/src/Symfony/Bundle/DoctrineMongoDBBundle/DependencyInjection/Compiler/AddValidatorNamespaceAliasPass.php @@ -17,6 +17,6 @@ class AddValidatorNamespaceAliasPass implements CompilerPassInterface $args = $loader->getArguments(); $args[0]['assertMongoDB'] = 'Symfony\\Bundle\\DoctrineMongoDBBundle\\Validator\\Constraints\\'; - $loader->setArgument(0, $args[0]); + $loader->replaceArgument(0, $args[0]); } } diff --git a/src/Symfony/Bundle/FrameworkBundle/DependencyInjection/Compiler/AddCacheWarmerPass.php b/src/Symfony/Bundle/FrameworkBundle/DependencyInjection/Compiler/AddCacheWarmerPass.php index b69e79a159..170c33e360 100644 --- a/src/Symfony/Bundle/FrameworkBundle/DependencyInjection/Compiler/AddCacheWarmerPass.php +++ b/src/Symfony/Bundle/FrameworkBundle/DependencyInjection/Compiler/AddCacheWarmerPass.php @@ -41,7 +41,7 @@ class AddCacheWarmerPass implements CompilerPassInterface krsort($warmers); $warmers = call_user_func_array('array_merge', $warmers); - $container->getDefinition('cache_warmer')->setArgument(0, $warmers); + $container->getDefinition('cache_warmer')->replaceArgument(0, $warmers); if ('full' === $container->getParameter('kernel.cache_warmup')) { $container->getDefinition('cache_warmer')->addMethodCall('enableOptionalWarmers', array()); diff --git a/src/Symfony/Bundle/FrameworkBundle/DependencyInjection/Compiler/AddConstraintValidatorsPass.php b/src/Symfony/Bundle/FrameworkBundle/DependencyInjection/Compiler/AddConstraintValidatorsPass.php index 574282ea34..99ee9d6280 100644 --- a/src/Symfony/Bundle/FrameworkBundle/DependencyInjection/Compiler/AddConstraintValidatorsPass.php +++ b/src/Symfony/Bundle/FrameworkBundle/DependencyInjection/Compiler/AddConstraintValidatorsPass.php @@ -29,6 +29,6 @@ class AddConstraintValidatorsPass implements CompilerPassInterface } } - $container->getDefinition('validator.validator_factory')->setArgument(1, $validators); + $container->getDefinition('validator.validator_factory')->replaceArgument(1, $validators); } } \ No newline at end of file diff --git a/src/Symfony/Bundle/FrameworkBundle/DependencyInjection/Compiler/AddFieldFactoryGuessersPass.php b/src/Symfony/Bundle/FrameworkBundle/DependencyInjection/Compiler/AddFieldFactoryGuessersPass.php index 0a0a977147..ef88acf730 100644 --- a/src/Symfony/Bundle/FrameworkBundle/DependencyInjection/Compiler/AddFieldFactoryGuessersPass.php +++ b/src/Symfony/Bundle/FrameworkBundle/DependencyInjection/Compiler/AddFieldFactoryGuessersPass.php @@ -33,6 +33,6 @@ class AddFieldFactoryGuessersPass implements CompilerPassInterface return new Reference($id); }, array_keys($container->findTaggedServiceIds('form.field_factory.guesser'))); - $container->getDefinition('form.field_factory')->setArgument(0, $guessers); + $container->getDefinition('form.field_factory')->replaceArgument(0, $guessers); } } \ No newline at end of file diff --git a/src/Symfony/Bundle/FrameworkBundle/DependencyInjection/FrameworkExtension.php b/src/Symfony/Bundle/FrameworkBundle/DependencyInjection/FrameworkExtension.php index bb690d064e..6302e0ed9c 100644 --- a/src/Symfony/Bundle/FrameworkBundle/DependencyInjection/FrameworkExtension.php +++ b/src/Symfony/Bundle/FrameworkBundle/DependencyInjection/FrameworkExtension.php @@ -75,12 +75,12 @@ class FrameworkExtension extends Extension } else { $container ->getDefinition('error_handler')->addMethodCall('register', array()) - ->setArgument(0, $config['error_handler']) + ->replaceArgument(0, $config['error_handler']) ; } } - $container->getDefinition('exception_listener')->setArgument(0, $config['exception_controller']); + $container->getDefinition('exception_listener')->replaceArgument(0, $config['exception_controller']); if (!empty($config['test'])) { $loader->load('test.xml'); @@ -194,8 +194,8 @@ class FrameworkExtension extends Extension $loader->load('collectors.xml'); $container->getDefinition('profiler_listener') - ->setArgument(2, $config['only_exceptions']) - ->setArgument(3, $config['only_master_requests']) + ->replaceArgument(2, $config['only_exceptions']) + ->replaceArgument(3, $config['only_master_requests']) ; // Choose storage class based on the DSN @@ -209,10 +209,10 @@ class FrameworkExtension extends Extension } $container->getDefinition('profiler.storage') - ->setArgument(0, $config['dsn']) - ->setArgument(1, $config['username']) - ->setArgument(2, $config['password']) - ->setArgument(3, $config['lifetime']) + ->replaceArgument(0, $config['dsn']) + ->replaceArgument(1, $config['username']) + ->replaceArgument(2, $config['password']) + ->replaceArgument(3, $config['lifetime']) ->setClass($supported[$class]) ; @@ -285,7 +285,7 @@ class FrameworkExtension extends Extension $container->setParameter('session.class', $config['class']); } - $container->getDefinition('session')->setArgument(1, $config['default_locale']); + $container->getDefinition('session')->replaceArgument(1, $config['default_locale']); $container->setAlias('session.storage', 'session.storage.'.$config['storage_id']); @@ -323,7 +323,7 @@ class FrameworkExtension extends Extension $container ->getDefinition('templating.helper.code') - ->setArgument(0, str_replace('%', '%%', isset($links[$ide]) ? $links[$ide] : $ide)) + ->replaceArgument(0, str_replace('%', '%%', isset($links[$ide]) ? $links[$ide] : $ide)) ; if ($container->getParameter('kernel.debug')) { @@ -339,9 +339,9 @@ class FrameworkExtension extends Extension } $container ->getDefinition('templating.helper.assets') - ->setArgument(1, isset($config['assets_base_urls']) ? $config['assets_base_urls'] : array()) - ->setArgument(2, $config['assets_version']) - ->setArgument(3, $packages) + ->replaceArgument(1, isset($config['assets_base_urls']) ? $config['assets_base_urls'] : array()) + ->replaceArgument(2, $config['assets_version']) + ->replaceArgument(3, $packages) ; if (!empty($config['loaders'])) { @@ -360,7 +360,7 @@ class FrameworkExtension extends Extension // Wrap the existing loader with cache (must happen after loaders are registered) $container->setDefinition('templating.loader.wrapped', $container->findDefinition('templating.loader')); $loaderCache = $container->getDefinition('templating.loader.cache'); - $loaderCache->setArgument(1, $config['cache']); + $loaderCache->replaceArgument(1, $config['cache']); $container->setDefinition('templating.loader', $loaderCache); } @@ -403,7 +403,7 @@ class FrameworkExtension extends Extension if (1 === count($engines)) { $container->setAlias('templating', (string) reset($engines)); } else { - $container->getDefinition('templating.engine.delegating')->setArgument(1, $engines); + $container->getDefinition('templating.engine.delegating')->replaceArgument(1, $engines); $container->setAlias('templating', 'templating.engine.delegating'); } } @@ -466,12 +466,12 @@ class FrameworkExtension extends Extension $container ->getDefinition('validator.mapping.loader.xml_files_loader') - ->setArgument(0, $this->getValidatorXmlMappingFiles($container)) + ->replaceArgument(0, $this->getValidatorXmlMappingFiles($container)) ; $container ->getDefinition('validator.mapping.loader.yaml_files_loader') - ->setArgument(0, $this->getValidatorYamlMappingFiles($container)) + ->replaceArgument(0, $this->getValidatorYamlMappingFiles($container)) ; if (isset($config['annotations'])) { @@ -484,7 +484,7 @@ class FrameworkExtension extends Extension // Register annotation loader $container ->getDefinition('validator.mapping.loader.annotation_loader') - ->setArgument(0, $namespaces) + ->replaceArgument(0, $namespaces) ; $loaderChain = $container->getDefinition('validator.mapping.loader.loader_chain'); @@ -495,7 +495,7 @@ class FrameworkExtension extends Extension if (isset($config['cache'])) { $container->getDefinition('validator.mapping.class_metadata_factory') - ->setArgument(1, new Reference('validator.mapping.cache.'.$config['cache'])); + ->replaceArgument(1, new Reference('validator.mapping.cache.'.$config['cache'])); $container->setParameter( 'validator.mapping.cache.prefix', 'validator_'.md5($container->getParameter('kernel.root_dir')) diff --git a/src/Symfony/Bundle/MonologBundle/DependencyInjection/Compiler/LoggerChannelPass.php b/src/Symfony/Bundle/MonologBundle/DependencyInjection/Compiler/LoggerChannelPass.php index dd1a17f462..f957467966 100644 --- a/src/Symfony/Bundle/MonologBundle/DependencyInjection/Compiler/LoggerChannelPass.php +++ b/src/Symfony/Bundle/MonologBundle/DependencyInjection/Compiler/LoggerChannelPass.php @@ -39,7 +39,7 @@ class LoggerChannelPass implements CompilerPassInterface $this->createLogger($tag['channel'], $loggerId, $container); foreach ($definition->getArguments() as $index => $argument) { if ($argument instanceof Reference && 'logger' === (string) $argument) { - $definition->setArgument($index, new Reference($loggerId, $argument->getInvalidBehavior(), $argument->isStrict())); + $definition->replaceArgument($index, new Reference($loggerId, $argument->getInvalidBehavior(), $argument->isStrict())); } } } @@ -51,7 +51,7 @@ class LoggerChannelPass implements CompilerPassInterface { if (!in_array($channel, $this->channels)) { $logger = new DefinitionDecorator('monolog.logger_prototype'); - $logger->setArgument(0, $channel); + $logger->replaceArgument(0, $channel); $container->setDefinition($loggerId, $logger); array_push($this->channels, $channel); } diff --git a/src/Symfony/Bundle/SecurityBundle/DependencyInjection/Compiler/AddSecurityVotersPass.php b/src/Symfony/Bundle/SecurityBundle/DependencyInjection/Compiler/AddSecurityVotersPass.php index 19d1319cec..a856584da4 100644 --- a/src/Symfony/Bundle/SecurityBundle/DependencyInjection/Compiler/AddSecurityVotersPass.php +++ b/src/Symfony/Bundle/SecurityBundle/DependencyInjection/Compiler/AddSecurityVotersPass.php @@ -40,6 +40,6 @@ class AddSecurityVotersPass implements CompilerPassInterface $voters = iterator_to_array($voters); ksort($voters); - $container->getDefinition('security.access.decision_manager')->setArgument(0, array_values($voters)); + $container->getDefinition('security.access.decision_manager')->replaceArgument(0, array_values($voters)); } } \ No newline at end of file diff --git a/src/Symfony/Bundle/SecurityBundle/DependencyInjection/Security/Factory/AbstractFactory.php b/src/Symfony/Bundle/SecurityBundle/DependencyInjection/Security/Factory/AbstractFactory.php index 4e91baff24..703821fdaf 100644 --- a/src/Symfony/Bundle/SecurityBundle/DependencyInjection/Security/Factory/AbstractFactory.php +++ b/src/Symfony/Bundle/SecurityBundle/DependencyInjection/Security/Factory/AbstractFactory.php @@ -148,17 +148,17 @@ abstract class AbstractFactory implements SecurityFactoryInterface { $listenerId = $this->getListenerId(); $listener = new DefinitionDecorator($listenerId); - $listener->setArgument(3, $id); - $listener->setArgument(4, array_intersect_key($config, $this->options)); + $listener->replaceArgument(3, $id); + $listener->replaceArgument(4, array_intersect_key($config, $this->options)); // success handler if (isset($config['success_handler'])) { - $listener->setArgument(5, new Reference($config['success_handler'])); + $listener->replaceArgument(5, new Reference($config['success_handler'])); } // failure handler if (isset($config['failure_handler'])) { - $listener->setArgument(6, new Reference($config['failure_handler'])); + $listener->replaceArgument(6, new Reference($config['failure_handler'])); } $listenerId .= '.'.$id; diff --git a/src/Symfony/Bundle/SecurityBundle/DependencyInjection/Security/Factory/FormLoginFactory.php b/src/Symfony/Bundle/SecurityBundle/DependencyInjection/Security/Factory/FormLoginFactory.php index 53296e5862..e23b4d52b9 100644 --- a/src/Symfony/Bundle/SecurityBundle/DependencyInjection/Security/Factory/FormLoginFactory.php +++ b/src/Symfony/Bundle/SecurityBundle/DependencyInjection/Security/Factory/FormLoginFactory.php @@ -65,8 +65,8 @@ class FormLoginFactory extends AbstractFactory $provider = 'security.authentication.provider.dao.'.$id; $container ->setDefinition($provider, new DefinitionDecorator('security.authentication.provider.dao')) - ->setArgument(0, new Reference($userProviderId)) - ->setArgument(2, $id) + ->replaceArgument(0, new Reference($userProviderId)) + ->replaceArgument(2, $id) ; return $provider; diff --git a/src/Symfony/Bundle/SecurityBundle/DependencyInjection/Security/Factory/HttpBasicFactory.php b/src/Symfony/Bundle/SecurityBundle/DependencyInjection/Security/Factory/HttpBasicFactory.php index 8a5a17b0cf..c87f68c38f 100644 --- a/src/Symfony/Bundle/SecurityBundle/DependencyInjection/Security/Factory/HttpBasicFactory.php +++ b/src/Symfony/Bundle/SecurityBundle/DependencyInjection/Security/Factory/HttpBasicFactory.php @@ -29,8 +29,8 @@ class HttpBasicFactory implements SecurityFactoryInterface $provider = 'security.authentication.provider.dao.'.$id; $container ->setDefinition($provider, new DefinitionDecorator('security.authentication.provider.dao')) - ->setArgument(0, new Reference($userProvider)) - ->setArgument(2, $id) + ->replaceArgument(0, new Reference($userProvider)) + ->replaceArgument(2, $id) ; // entry point @@ -39,8 +39,8 @@ class HttpBasicFactory implements SecurityFactoryInterface // listener $listenerId = 'security.authentication.listener.basic.'.$id; $listener = $container->setDefinition($listenerId, new DefinitionDecorator('security.authentication.listener.basic')); - $listener->setArgument(2, $id); - $listener->setArgument(3, new Reference($entryPointId)); + $listener->replaceArgument(2, $id); + $listener->replaceArgument(3, new Reference($entryPointId)); return array($provider, $listenerId, $entryPointId); } diff --git a/src/Symfony/Bundle/SecurityBundle/DependencyInjection/Security/Factory/HttpDigestFactory.php b/src/Symfony/Bundle/SecurityBundle/DependencyInjection/Security/Factory/HttpDigestFactory.php index cdeaeb43a4..2f09be07af 100644 --- a/src/Symfony/Bundle/SecurityBundle/DependencyInjection/Security/Factory/HttpDigestFactory.php +++ b/src/Symfony/Bundle/SecurityBundle/DependencyInjection/Security/Factory/HttpDigestFactory.php @@ -29,8 +29,8 @@ class HttpDigestFactory implements SecurityFactoryInterface $provider = 'security.authentication.provider.dao.'.$id; $container ->setDefinition($provider, new DefinitionDecorator('security.authentication.provider.dao')) - ->setArgument(0, new Reference($userProvider)) - ->setArgument(2, $id) + ->replaceArgument(0, new Reference($userProvider)) + ->replaceArgument(2, $id) ; // entry point @@ -39,9 +39,9 @@ class HttpDigestFactory implements SecurityFactoryInterface // listener $listenerId = 'security.authentication.listener.digest.'.$id; $listener = $container->setDefinition($listenerId, new DefinitionDecorator('security.authentication.listener.digest')); - $listener->setArgument(1, new Reference($userProvider)); - $listener->setArgument(2, $id); - $listener->setArgument(3, new Reference($entryPointId)); + $listener->replaceArgument(1, new Reference($userProvider)); + $listener->replaceArgument(2, $id); + $listener->replaceArgument(3, new Reference($entryPointId)); return array($provider, $listenerId, $entryPointId); } diff --git a/src/Symfony/Bundle/SecurityBundle/DependencyInjection/Security/Factory/RememberMeFactory.php b/src/Symfony/Bundle/SecurityBundle/DependencyInjection/Security/Factory/RememberMeFactory.php index c9cfb6a788..21f1ee1bc3 100644 --- a/src/Symfony/Bundle/SecurityBundle/DependencyInjection/Security/Factory/RememberMeFactory.php +++ b/src/Symfony/Bundle/SecurityBundle/DependencyInjection/Security/Factory/RememberMeFactory.php @@ -53,8 +53,8 @@ class RememberMeFactory implements SecurityFactoryInterface } $rememberMeServices = $container->setDefinition($rememberMeServicesId, new DefinitionDecorator($templateId)); - $rememberMeServices->setArgument(1, $config['key']); - $rememberMeServices->setArgument(2, $id); + $rememberMeServices->replaceArgument(1, $config['key']); + $rememberMeServices->replaceArgument(2, $id); if (isset($config['token-provider'])) { // FIXME: make the naming assumption more flexible @@ -64,7 +64,7 @@ class RememberMeFactory implements SecurityFactoryInterface } // remember-me options - $rememberMeServices->setArgument(3, array_intersect_key($config, $this->options)); + $rememberMeServices->replaceArgument(3, array_intersect_key($config, $this->options)); // attach to remember-me aware listeners $userProviders = array(); @@ -88,12 +88,12 @@ class RememberMeFactory implements SecurityFactoryInterface if (count($userProviders) === 0) { throw new \RuntimeException('You must configure at least one remember-me aware listener (such as form-login) for each firewall that has remember-me enabled.'); } - $rememberMeServices->setArgument(0, $userProviders); + $rememberMeServices->replaceArgument(0, $userProviders); // remember-me listener $listenerId = 'security.authentication.listener.rememberme.'.$id; $listener = $container->setDefinition($listenerId, new DefinitionDecorator('security.authentication.listener.rememberme')); - $listener->setArgument(1, new Reference($rememberMeServicesId)); + $listener->replaceArgument(1, new Reference($rememberMeServicesId)); return array($authProviderId, $listenerId, $defaultEntryPoint); } diff --git a/src/Symfony/Bundle/SecurityBundle/DependencyInjection/Security/Factory/X509Factory.php b/src/Symfony/Bundle/SecurityBundle/DependencyInjection/Security/Factory/X509Factory.php index 87625cc2cd..d24942b672 100644 --- a/src/Symfony/Bundle/SecurityBundle/DependencyInjection/Security/Factory/X509Factory.php +++ b/src/Symfony/Bundle/SecurityBundle/DependencyInjection/Security/Factory/X509Factory.php @@ -30,16 +30,16 @@ class X509Factory implements SecurityFactoryInterface $provider = 'security.authentication.provider.pre_authenticated.'.$id; $container ->setDefinition($provider, new DefinitionDecorator('security.authentication.provider.pre_authenticated')) - ->setArgument(0, new Reference($userProvider)) + ->replaceArgument(0, new Reference($userProvider)) ->addArgument($id) ; // listener $listenerId = 'security.authentication.listener.x509.'.$id; $listener = $container->setDefinition($listenerId, new DefinitionDecorator('security.authentication.listener.x509')); - $listener->setArgument(2, $id); - $listener->setArgument(3, $config['user']); - $listener->setArgument(4, $config['credentials']); + $listener->replaceArgument(2, $id); + $listener->replaceArgument(3, $config['user']); + $listener->replaceArgument(4, $config['credentials']); return array($provider, $listenerId, $defaultEntryPoint); } diff --git a/src/Symfony/Bundle/SecurityBundle/DependencyInjection/SecurityExtension.php b/src/Symfony/Bundle/SecurityBundle/DependencyInjection/SecurityExtension.php index 35c69b2cb1..b484f37512 100644 --- a/src/Symfony/Bundle/SecurityBundle/DependencyInjection/SecurityExtension.php +++ b/src/Symfony/Bundle/SecurityBundle/DependencyInjection/SecurityExtension.php @@ -62,7 +62,7 @@ class SecurityExtension extends Extension // set some global scalars $container->setParameter('security.access.denied_url', $config['access_denied_url']); - $container->getDefinition('security.authentication.session_strategy')->setArgument(0, $config['session_fixation_strategy']); + $container->getDefinition('security.authentication.session_strategy')->replaceArgument(0, $config['session_fixation_strategy']); $container ->getDefinition('security.access.decision_manager') ->addArgument($config['access_decision_manager']['strategy']) @@ -202,12 +202,12 @@ class SecurityExtension extends Extension $contextId = 'security.firewall.map.context.'.$name; $context = $container->setDefinition($contextId, new DefinitionDecorator('security.firewall.context')); $context - ->setArgument(0, $listeners) - ->setArgument(1, $exceptionListener) + ->replaceArgument(0, $listeners) + ->replaceArgument(1, $exceptionListener) ; $map[$contextId] = $matcher; } - $mapDef->setArgument(1, $map); + $mapDef->replaceArgument(1, $map); // add authentication providers to authentication manager $authenticationProviders = array_map(function($id) { @@ -215,7 +215,7 @@ class SecurityExtension extends Extension }, array_values(array_unique($authenticationProviders))); $container ->getDefinition('security.authentication.manager') - ->setArgument(0, $authenticationProviders) + ->replaceArgument(0, $authenticationProviders) ; } @@ -263,13 +263,13 @@ class SecurityExtension extends Extension if (isset($firewall['logout'])) { $listenerId = 'security.logout_listener.'.$id; $listener = $container->setDefinition($listenerId, new DefinitionDecorator('security.logout_listener')); - $listener->setArgument(1, $firewall['logout']['path']); - $listener->setArgument(2, $firewall['logout']['target']); + $listener->replaceArgument(1, $firewall['logout']['path']); + $listener->replaceArgument(2, $firewall['logout']['target']); $listeners[] = new Reference($listenerId); // add logout success handler if (isset($firewall['logout']['success_handler'])) { - $listener->setArgument(3, new Reference($firewall['logout']['success_handler'])); + $listener->replaceArgument(3, new Reference($firewall['logout']['success_handler'])); } // add session logout handler @@ -324,7 +324,7 @@ class SecurityExtension extends Extension $listenerId = 'security.context_listener.'.count($this->contextListeners); $listener = $container->setDefinition($listenerId, new DefinitionDecorator('security.context_listener')); - $listener->setArgument(2, $contextKey); + $listener->replaceArgument(2, $contextKey); return $this->contextListeners[$contextKey] = $listenerId; } @@ -356,7 +356,7 @@ class SecurityExtension extends Extension $listenerId = 'security.authentication.listener.anonymous.'.$id; $container ->setDefinition($listenerId, new DefinitionDecorator('security.authentication.listener.anonymous')) - ->setArgument(1, $firewall['anonymous']['key']) + ->replaceArgument(1, $firewall['anonymous']['key']) ; $listeners[] = new Reference($listenerId); @@ -364,7 +364,7 @@ class SecurityExtension extends Extension $providerId = 'security.authentication.provider.anonymous.'.$id; $container ->setDefinition($providerId, new DefinitionDecorator('security.authentication.provider.anonymous')) - ->setArgument(0, $firewall['anonymous']['key']) + ->replaceArgument(0, $firewall['anonymous']['key']) ; $authenticationProviders[] = $providerId; @@ -496,13 +496,13 @@ class SecurityExtension extends Extension { $exceptionListenerId = 'security.exception_listener.'.$id; $listener = $container->setDefinition($exceptionListenerId, new DefinitionDecorator('security.exception_listener')); - $listener->setArgument(2, null === $defaultEntryPoint ? null : new Reference($defaultEntryPoint)); + $listener->replaceArgument(2, null === $defaultEntryPoint ? null : new Reference($defaultEntryPoint)); // access denied handler setup if (isset($config['access_denied_handler'])) { - $listener->setArgument(4, new Reference($config['access_denied_handler'])); + $listener->replaceArgument(4, new Reference($config['access_denied_handler'])); } else if (isset($config['access_denied_url'])) { - $listener->setArgument(3, $config['access_denied_url']); + $listener->replaceArgument(3, $config['access_denied_url']); } return $exceptionListenerId; @@ -514,10 +514,10 @@ class SecurityExtension extends Extension $switchUserListenerId = 'security.authentication.switchuser_listener.'.$id; $listener = $container->setDefinition($switchUserListenerId, new DefinitionDecorator('security.authentication.switchuser_listener')); - $listener->setArgument(1, new Reference($userProvider)); - $listener->setArgument(3, $id); - $listener->setArgument(6, $config['parameter']); - $listener->setArgument(7, $config['role']); + $listener->replaceArgument(1, new Reference($userProvider)); + $listener->replaceArgument(3, $id); + $listener->replaceArgument(6, $config['parameter']); + $listener->replaceArgument(7, $config['role']); return $switchUserListenerId; } diff --git a/src/Symfony/Bundle/WebProfilerBundle/DependencyInjection/WebProfilerExtension.php b/src/Symfony/Bundle/WebProfilerBundle/DependencyInjection/WebProfilerExtension.php index 3be5ef7e97..2217e72679 100644 --- a/src/Symfony/Bundle/WebProfilerBundle/DependencyInjection/WebProfilerExtension.php +++ b/src/Symfony/Bundle/WebProfilerBundle/DependencyInjection/WebProfilerExtension.php @@ -48,8 +48,8 @@ class WebProfilerExtension extends Extension $loader->load('toolbar.xml'); $container->getDefinition('web_profiler.debug.toolbar') - ->setArgument(1, $config['intercept_redirects']) - ->setArgument(2, $config['verbose']) + ->replaceArgument(1, $config['intercept_redirects']) + ->replaceArgument(2, $config['verbose']) ; } } diff --git a/src/Symfony/Component/DependencyInjection/Compiler/ResolveDefinitionTemplatesPass.php b/src/Symfony/Component/DependencyInjection/Compiler/ResolveDefinitionTemplatesPass.php index f253a8f94e..ca263d3a5c 100644 --- a/src/Symfony/Component/DependencyInjection/Compiler/ResolveDefinitionTemplatesPass.php +++ b/src/Symfony/Component/DependencyInjection/Compiler/ResolveDefinitionTemplatesPass.php @@ -111,7 +111,7 @@ class ResolveDefinitionTemplatesPass implements CompilerPassInterface } $index = (integer) substr($k, strlen('index_')); - $def->setArgument($index, $v); + $def->replaceArgument($index, $v); } // merge properties diff --git a/src/Symfony/Component/DependencyInjection/Definition.php b/src/Symfony/Component/DependencyInjection/Definition.php index 550aa59b20..b44983d61d 100644 --- a/src/Symfony/Component/DependencyInjection/Definition.php +++ b/src/Symfony/Component/DependencyInjection/Definition.php @@ -205,7 +205,7 @@ class Definition * * @return Definition The current instance */ - public function setArgument($index, $argument) + public function replaceArgument($index, $argument) { if ($index < 0 || $index > count($this->arguments) - 1) { throw new \OutOfBoundsException(sprintf('The index "%d" is not in the range [0, %d].', $index, count($this->arguments) - 1)); diff --git a/src/Symfony/Component/DependencyInjection/DefinitionDecorator.php b/src/Symfony/Component/DependencyInjection/DefinitionDecorator.php index 50395cc5e0..53ac89a3b6 100644 --- a/src/Symfony/Component/DependencyInjection/DefinitionDecorator.php +++ b/src/Symfony/Component/DependencyInjection/DefinitionDecorator.php @@ -129,7 +129,7 @@ class DefinitionDecorator extends Definition * @return DefinitionDecorator the current instance * @throws \InvalidArgumentException when $index isnt an integer */ - public function setArgument($index, $value) + public function replaceArgument($index, $value) { if (!is_int($index)) { throw new \InvalidArgumentException('$index must be an integer.'); diff --git a/tests/Symfony/Tests/Component/DependencyInjection/Compiler/ResolveDefinitionTemplatesPassTest.php b/tests/Symfony/Tests/Component/DependencyInjection/Compiler/ResolveDefinitionTemplatesPassTest.php index 4e29373e22..3ae83af9d5 100644 --- a/tests/Symfony/Tests/Component/DependencyInjection/Compiler/ResolveDefinitionTemplatesPassTest.php +++ b/tests/Symfony/Tests/Component/DependencyInjection/Compiler/ResolveDefinitionTemplatesPassTest.php @@ -14,7 +14,7 @@ class ResolveDefinitionTemplatesPassTest extends \PHPUnit_Framework_TestCase $container = new ContainerBuilder(); $container->register('parent', 'foo')->setArguments(array('moo', 'b'))->setProperty('foo', 'moo'); $container->setDefinition('child', new DefinitionDecorator('parent')) - ->setArgument(0, 'a') + ->replaceArgument(0, 'a') ->setProperty('foo', 'bar') ->setClass('bar') ; @@ -119,12 +119,12 @@ class ResolveDefinitionTemplatesPassTest extends \PHPUnit_Framework_TestCase $container ->setDefinition('child2', new DefinitionDecorator('child1')) - ->setArgument(1, 'b') + ->replaceArgument(1, 'b') ; $container ->setDefinition('child1', new DefinitionDecorator('parent')) - ->setArgument(0, 'a') + ->replaceArgument(0, 'a') ; $this->process($container); diff --git a/tests/Symfony/Tests/Component/DependencyInjection/DefinitionDecoratorTest.php b/tests/Symfony/Tests/Component/DependencyInjection/DefinitionDecoratorTest.php index 6c74adfe4a..165d26df63 100644 --- a/tests/Symfony/Tests/Component/DependencyInjection/DefinitionDecoratorTest.php +++ b/tests/Symfony/Tests/Component/DependencyInjection/DefinitionDecoratorTest.php @@ -57,7 +57,7 @@ class DefinitionDecoratorTest extends \PHPUnit_Framework_TestCase $def = new DefinitionDecorator('foo'); $this->assertEquals(array(), $def->getArguments()); - $this->assertSame($def, $def->setArgument(0, 'foo')); + $this->assertSame($def, $def->replaceArgument(0, 'foo')); $this->assertEquals(array('index_0' => 'foo'), $def->getArguments()); } } \ No newline at end of file diff --git a/tests/Symfony/Tests/Component/DependencyInjection/DefinitionTest.php b/tests/Symfony/Tests/Component/DependencyInjection/DefinitionTest.php index d1880d706b..9ff87e09b7 100644 --- a/tests/Symfony/Tests/Component/DependencyInjection/DefinitionTest.php +++ b/tests/Symfony/Tests/Component/DependencyInjection/DefinitionTest.php @@ -201,7 +201,7 @@ class DefinitionTest extends \PHPUnit_Framework_TestCase } /** - * @covers Symfony\Component\DependencyInjection\Definition::setArgument + * @covers Symfony\Component\DependencyInjection\Definition::replaceArgument */ public function testSetArgument() { @@ -210,13 +210,13 @@ class DefinitionTest extends \PHPUnit_Framework_TestCase $def->addArgument('foo'); $this->assertSame(array('foo'), $def->getArguments()); - $this->assertSame($def, $def->setArgument(0, 'moo')); + $this->assertSame($def, $def->replaceArgument(0, 'moo')); $this->assertSame(array('moo'), $def->getArguments()); $def->addArgument('moo'); $def - ->setArgument(0, 'foo') - ->setArgument(1, 'bar') + ->replaceArgument(0, 'foo') + ->replaceArgument(1, 'bar') ; $this->assertSame(array('foo', 'bar'), $def->getArguments()); } From 470baaab9f9082c1339a23bf014408040331ea67 Mon Sep 17 00:00:00 2001 From: Kris Wallsmith Date: Tue, 19 Apr 2011 14:40:18 -0700 Subject: [PATCH 54/91] [DependencyInjection] renamed ContainerBuilder::remove() as removeDefinition() to be more consistent with other definition-related methods --- .../AsseticBundle/DependencyInjection/AsseticExtension.php | 4 ++-- .../DependencyInjection/Compiler/CheckClosureFilterPass.php | 4 ++-- .../DependencyInjection/Compiler/TemplatingPass.php | 4 ++-- .../SecurityBundle/DependencyInjection/SecurityExtension.php | 4 ++-- .../Compiler/RemoveAbstractDefinitionsPass.php | 2 +- .../Compiler/RemoveUnusedDefinitionsPass.php | 4 ++-- .../Compiler/ReplaceAliasByActualDefinitionPass.php | 2 +- .../Component/DependencyInjection/ContainerBuilder.php | 4 ++-- 8 files changed, 14 insertions(+), 14 deletions(-) diff --git a/src/Symfony/Bundle/AsseticBundle/DependencyInjection/AsseticExtension.php b/src/Symfony/Bundle/AsseticBundle/DependencyInjection/AsseticExtension.php index 0b4e5faac1..19213c6aee 100644 --- a/src/Symfony/Bundle/AsseticBundle/DependencyInjection/AsseticExtension.php +++ b/src/Symfony/Bundle/AsseticBundle/DependencyInjection/AsseticExtension.php @@ -76,12 +76,12 @@ class AsseticExtension extends Extension $loader->load('controller.xml'); $container->setParameter('assetic.twig_extension.class', '%assetic.twig_extension.dynamic.class%'); $container->getDefinition('assetic.helper.dynamic')->addTag('templating.helper', array('alias' => 'assetic')); - $container->remove('assetic.helper.static'); + $container->removeDefinition('assetic.helper.static'); } else { $loader->load('asset_writer.xml'); $container->setParameter('assetic.twig_extension.class', '%assetic.twig_extension.static.class%'); $container->getDefinition('assetic.helper.static')->addTag('templating.helper', array('alias' => 'assetic')); - $container->remove('assetic.helper.dynamic'); + $container->removeDefinition('assetic.helper.dynamic'); } // register config resources diff --git a/src/Symfony/Bundle/AsseticBundle/DependencyInjection/Compiler/CheckClosureFilterPass.php b/src/Symfony/Bundle/AsseticBundle/DependencyInjection/Compiler/CheckClosureFilterPass.php index fd14b0b400..251fb758f8 100644 --- a/src/Symfony/Bundle/AsseticBundle/DependencyInjection/Compiler/CheckClosureFilterPass.php +++ b/src/Symfony/Bundle/AsseticBundle/DependencyInjection/Compiler/CheckClosureFilterPass.php @@ -25,9 +25,9 @@ class CheckClosureFilterPass implements CompilerPassInterface { if ($container->hasDefinition('assetic.filter.closure.jar') && $container->getParameterBag()->resolveValue($container->getParameter('assetic.filter.closure.jar'))) { - $container->remove('assetic.filter.closure.api'); + $container->removeDefinition('assetic.filter.closure.api'); } elseif ($container->hasDefinition('assetic.filter.closure.api')) { - $container->remove('assetic.filter.closure.jar'); + $container->removeDefinition('assetic.filter.closure.jar'); } } } diff --git a/src/Symfony/Bundle/AsseticBundle/DependencyInjection/Compiler/TemplatingPass.php b/src/Symfony/Bundle/AsseticBundle/DependencyInjection/Compiler/TemplatingPass.php index 852b488551..b0281261a7 100644 --- a/src/Symfony/Bundle/AsseticBundle/DependencyInjection/Compiler/TemplatingPass.php +++ b/src/Symfony/Bundle/AsseticBundle/DependencyInjection/Compiler/TemplatingPass.php @@ -31,13 +31,13 @@ class TemplatingPass implements CompilerPassInterface if (!in_array('twig', $engines)) { foreach ($container->findTaggedServiceIds('assetic.templating.twig') as $id => $attr) { - $container->remove($id); + $container->removeDefinition($id); } } if (!in_array('php', $engines)) { foreach ($container->findTaggedServiceIds('assetic.templating.php') as $id => $attr) { - $container->remove($id); + $container->removeDefinition($id); } } } diff --git a/src/Symfony/Bundle/SecurityBundle/DependencyInjection/SecurityExtension.php b/src/Symfony/Bundle/SecurityBundle/DependencyInjection/SecurityExtension.php index b484f37512..689678cdaf 100644 --- a/src/Symfony/Bundle/SecurityBundle/DependencyInjection/SecurityExtension.php +++ b/src/Symfony/Bundle/SecurityBundle/DependencyInjection/SecurityExtension.php @@ -138,13 +138,13 @@ class SecurityExtension extends Extension private function createRoleHierarchy($config, ContainerBuilder $container) { if (!isset($config['role_hierarchy'])) { - $container->remove('security.access.role_hierarchy_voter'); + $container->removeDefinition('security.access.role_hierarchy_voter'); return; } $container->setParameter('security.role_hierarchy.roles', $config['role_hierarchy']); - $container->remove('security.access.simple_role_voter'); + $container->removeDefinition('security.access.simple_role_voter'); } private function createAuthorization($config, ContainerBuilder $container) diff --git a/src/Symfony/Component/DependencyInjection/Compiler/RemoveAbstractDefinitionsPass.php b/src/Symfony/Component/DependencyInjection/Compiler/RemoveAbstractDefinitionsPass.php index c0657b3789..45857a1712 100644 --- a/src/Symfony/Component/DependencyInjection/Compiler/RemoveAbstractDefinitionsPass.php +++ b/src/Symfony/Component/DependencyInjection/Compiler/RemoveAbstractDefinitionsPass.php @@ -22,7 +22,7 @@ class RemoveAbstractDefinitionsPass implements CompilerPassInterface foreach ($container->getDefinitions() as $id => $definition) { if ($definition->isAbstract()) { - $container->remove($id); + $container->removeDefinition($id); $compiler->addLogMessage($formatter->formatRemoveService($this, $id, 'abstract')); } } diff --git a/src/Symfony/Component/DependencyInjection/Compiler/RemoveUnusedDefinitionsPass.php b/src/Symfony/Component/DependencyInjection/Compiler/RemoveUnusedDefinitionsPass.php index 1ad361d612..7c7974e4b1 100644 --- a/src/Symfony/Component/DependencyInjection/Compiler/RemoveUnusedDefinitionsPass.php +++ b/src/Symfony/Component/DependencyInjection/Compiler/RemoveUnusedDefinitionsPass.php @@ -72,10 +72,10 @@ class RemoveUnusedDefinitionsPass implements RepeatablePassInterface if (1 === count($referencingAliases) && false === $isReferenced) { $container->setDefinition((string) reset($referencingAliases), $definition); $definition->setPublic(true); - $container->remove($id); + $container->removeDefinition($id); $compiler->addLogMessage($formatter->formatRemoveService($this, $id, 'replaces alias '.reset($referencingAliases))); } else if (0 === count($referencingAliases) && false === $isReferenced) { - $container->remove($id); + $container->removeDefinition($id); $compiler->addLogMessage($formatter->formatRemoveService($this, $id, 'unused')); $hasChanged = true; } diff --git a/src/Symfony/Component/DependencyInjection/Compiler/ReplaceAliasByActualDefinitionPass.php b/src/Symfony/Component/DependencyInjection/Compiler/ReplaceAliasByActualDefinitionPass.php index 61c4a1f2db..17ccc9fa13 100644 --- a/src/Symfony/Component/DependencyInjection/Compiler/ReplaceAliasByActualDefinitionPass.php +++ b/src/Symfony/Component/DependencyInjection/Compiler/ReplaceAliasByActualDefinitionPass.php @@ -47,7 +47,7 @@ class ReplaceAliasByActualDefinitionPass implements CompilerPassInterface $definition->setPublic(true); $container->setDefinition($id, $definition); - $container->remove($aliasId); + $container->removeDefinition($aliasId); $this->updateReferences($container, $aliasId, $id); diff --git a/src/Symfony/Component/DependencyInjection/ContainerBuilder.php b/src/Symfony/Component/DependencyInjection/ContainerBuilder.php index 40a2a0affd..89408969ba 100644 --- a/src/Symfony/Component/DependencyInjection/ContainerBuilder.php +++ b/src/Symfony/Component/DependencyInjection/ContainerBuilder.php @@ -241,11 +241,11 @@ class ContainerBuilder extends Container implements TaggedContainerInterface } /** - * Removes a service. + * Removes a service definition. * * @param string $id The service identifier */ - public function remove($id) + public function removeDefinition($id) { unset($this->definitions[strtolower($id)]); } From 022728fda5533c44598e92794ccbdf2d445b9523 Mon Sep 17 00:00:00 2001 From: Kris Wallsmith Date: Wed, 20 Apr 2011 04:48:32 -0700 Subject: [PATCH 55/91] added method renames to UPDATE --- UPDATE.md | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/UPDATE.md b/UPDATE.md index 35163b4a69..54d339d237 100644 --- a/UPDATE.md +++ b/UPDATE.md @@ -6,6 +6,22 @@ one. It only discusses changes that need to be done when using the "public" API of the framework. If you "hack" the core, you should probably follow the timeline closely anyway. +PR12 to PR13 +------------ + +* Some methods in the DependencyInjection component's ContainerBuilder and + Definition classes have been renamed to be more specific and consistent: + + Before: + + $container->remove('my_definition'); + $definition->setArgument(0, 'foo'); + + After: + + $container->removeDefinition('my_definition'); + $definition->replaceArgument(0, 'foo'); + PR11 to PR12 ------------ From 117321d3c651a0563ed92871be5a732a1a0c4b79 Mon Sep 17 00:00:00 2001 From: Fabien Potencier Date: Wed, 20 Apr 2011 13:54:39 +0200 Subject: [PATCH 56/91] replaced array for request context in Routing by a RequestContext class --- .../FrameworkBundle/RequestListener.php | 15 +- .../Routing/RedirectableUrlMatcher.php | 4 +- .../Generator/Dumper/PhpGeneratorDumper.php | 4 +- .../Routing/Generator/UrlGenerator.php | 25 +-- .../Matcher/Dumper/PhpMatcherDumper.php | 7 +- .../Component/Routing/Matcher/UrlMatcher.php | 11 +- .../Component/Routing/RequestContext.php | 167 ++++++++++++++++++ src/Symfony/Component/Routing/Router.php | 8 +- .../Routing/Fixtures/dumper/url_matcher1.php | 9 +- .../Routing/Fixtures/dumper/url_matcher2.php | 13 +- .../Dumper/PhpGeneratorDumperTest.php | 19 +- .../Routing/Generator/UrlGeneratorTest.php | 22 ++- .../Matcher/Dumper/PhpMatcherDumperTest.php | 5 +- .../Routing/Matcher/UrlMatcherTest.php | 19 +- 14 files changed, 247 insertions(+), 81 deletions(-) create mode 100644 src/Symfony/Component/Routing/RequestContext.php diff --git a/src/Symfony/Bundle/FrameworkBundle/RequestListener.php b/src/Symfony/Bundle/FrameworkBundle/RequestListener.php index 57bf590e52..80eec52471 100644 --- a/src/Symfony/Bundle/FrameworkBundle/RequestListener.php +++ b/src/Symfony/Bundle/FrameworkBundle/RequestListener.php @@ -21,6 +21,7 @@ use Symfony\Component\DependencyInjection\ContainerInterface; use Symfony\Component\Routing\Matcher\Exception\MethodNotAllowedException; use Symfony\Component\Routing\Matcher\Exception\NotFoundException; use Symfony\Component\Routing\RouterInterface; +use Symfony\Component\Routing\RequestContext; /** * RequestListener. @@ -76,13 +77,13 @@ class RequestListener if ($master) { // set the context even if the parsing does not need to be done // to have correct link generation - $this->router->setContext(array( - 'base_url' => $request->getBaseUrl(), - 'method' => $request->getMethod(), - 'host' => $request->getHost(), - 'scheme' => $request->getScheme(), - 'http_port' => $this->httpPort, - 'https_port' => $this->httpsPort, + $this->router->setContext(new RequestContext( + $request->getBaseUrl(), + $request->getMethod(), + $request->getHost(), + $request->getScheme(), + $this->httpPort, + $this->httpsPort )); } diff --git a/src/Symfony/Bundle/FrameworkBundle/Routing/RedirectableUrlMatcher.php b/src/Symfony/Bundle/FrameworkBundle/Routing/RedirectableUrlMatcher.php index e49e5e7e14..c08badac42 100644 --- a/src/Symfony/Bundle/FrameworkBundle/Routing/RedirectableUrlMatcher.php +++ b/src/Symfony/Bundle/FrameworkBundle/Routing/RedirectableUrlMatcher.php @@ -35,8 +35,8 @@ class RedirectableUrlMatcher extends UrlMatcher implements RedirectableUrlMatche 'path' => $path, 'permanent' => true, 'scheme' => $scheme, - 'httpPort' => isset($this->context['http_port']) ? $this->context['http_port'] : 80, - 'httpsPort' => isset($this->context['https_port']) ? $this->context['https_port'] : 443, + 'httpPort' => $this->context->getHttpPort(), + 'httpsPort' => $this->context->getHttpsPort(), '_route' => $route, ); } diff --git a/src/Symfony/Component/Routing/Generator/Dumper/PhpGeneratorDumper.php b/src/Symfony/Component/Routing/Generator/Dumper/PhpGeneratorDumper.php index 87e85dad3a..51d8466ca9 100644 --- a/src/Symfony/Component/Routing/Generator/Dumper/PhpGeneratorDumper.php +++ b/src/Symfony/Component/Routing/Generator/Dumper/PhpGeneratorDumper.php @@ -107,6 +107,8 @@ EOF; return <<context = \$context; \$this->defaults = \$defaults; diff --git a/src/Symfony/Component/Routing/Generator/UrlGenerator.php b/src/Symfony/Component/Routing/Generator/UrlGenerator.php index c0d3d6f254..0c5ba32c95 100644 --- a/src/Symfony/Component/Routing/Generator/UrlGenerator.php +++ b/src/Symfony/Component/Routing/Generator/UrlGenerator.php @@ -13,6 +13,7 @@ namespace Symfony\Component\Routing\Generator; use Symfony\Component\Routing\Route; use Symfony\Component\Routing\RouteCollection; +use Symfony\Component\Routing\RequestContext; /** * UrlGenerator generates URL based on a set of routes. @@ -31,10 +32,10 @@ class UrlGenerator implements UrlGeneratorInterface * Constructor. * * @param RouteCollection $routes A RouteCollection instance - * @param array $context The context + * @param RequestContext $context The context * @param array $defaults The default values */ - public function __construct(RouteCollection $routes, array $context = array(), array $defaults = array()) + public function __construct(RouteCollection $routes, RequestContext $context, array $defaults = array()) { $this->routes = $routes; $this->context = $context; @@ -45,9 +46,9 @@ class UrlGenerator implements UrlGeneratorInterface /** * Sets the request context. * - * @param array $context The context + * @param RequestContext $context The context */ - public function setContext(array $context = array()) + public function setContext(RequestContext $context) { $this->context = $context; } @@ -127,10 +128,10 @@ class UrlGenerator implements UrlGeneratorInterface $url .= '?'.http_build_query($extra); } - $url = (isset($this->context['base_url']) ? $this->context['base_url'] : '').$url; + $url = $this->context->getBaseUrl().$url; - if (isset($this->context['host'])) { - $scheme = isset($this->context['scheme']) ? $this->context['scheme'] : 'http'; + if ($this->context->getHost()) { + $scheme = $this->context->getScheme(); if (isset($requirements['_scheme']) && ($req = strtolower($requirements['_scheme'])) && $scheme != $req) { $absolute = true; $scheme = $req; @@ -138,13 +139,13 @@ class UrlGenerator implements UrlGeneratorInterface if ($absolute) { $port = ''; - if ('http' === $scheme && 80 != ($httpPort = isset($this->context['http_port']) ? $this->context['http_port'] : 80)) { - $port = ':'.$httpPort; - } elseif ('https' === $scheme && 443 != ($httpsPort = isset($this->context['https_port']) ? $this->context['https_port'] : 443)) { - $port = ':'.$httpsPort; + if ('http' === $scheme && 80 != $this->context->getHttpPort()) { + $port = ':'.$this->context->getHttpPort(); + } elseif ('https' === $scheme && 443 != $this->context->getHttpsPort()) { + $port = ':'.$this->context->getHttpsPort(); } - $url = $scheme.'://'.$this->context['host'].$port.$url; + $url = $scheme.'://'.$this->context->getHost().$port.$url; } } diff --git a/src/Symfony/Component/Routing/Matcher/Dumper/PhpMatcherDumper.php b/src/Symfony/Component/Routing/Matcher/Dumper/PhpMatcherDumper.php index bbcf1edcff..0c61139019 100644 --- a/src/Symfony/Component/Routing/Matcher/Dumper/PhpMatcherDumper.php +++ b/src/Symfony/Component/Routing/Matcher/Dumper/PhpMatcherDumper.php @@ -94,7 +94,7 @@ EOF; if ($req = $route->getRequirement('_method')) { $req = implode('\', \'', array_map('strtolower', explode('|', $req))); $code[] = <<context['method']) && !in_array(strtolower(\$this->context['method']), array('$req'))) { + if (!in_array(\$this->context->getMethod(), array('$req'))) { \$allow = array_merge(\$allow, array('$req')); goto $gotoname; } @@ -116,7 +116,7 @@ EOF } $code[] = sprintf(<<context['scheme']) && \$this->context['scheme'] !== '$scheme') { + if (\$this->context->getScheme() !== '$scheme') { return \$this->redirect(\$pathinfo, '%s', '$scheme'); } EOF @@ -165,6 +165,7 @@ EOF; use Symfony\Component\Routing\Matcher\Exception\MethodNotAllowedException; use Symfony\Component\Routing\Matcher\Exception\NotFoundException; +use Symfony\Component\Routing\RequestContext; /** * $class @@ -184,7 +185,7 @@ EOF; /** * Constructor. */ - public function __construct(array \$context = array(), array \$defaults = array()) + public function __construct(RequestContext \$context, array \$defaults = array()) { \$this->context = \$context; \$this->defaults = \$defaults; diff --git a/src/Symfony/Component/Routing/Matcher/UrlMatcher.php b/src/Symfony/Component/Routing/Matcher/UrlMatcher.php index ab47ed1bf2..c43c339291 100644 --- a/src/Symfony/Component/Routing/Matcher/UrlMatcher.php +++ b/src/Symfony/Component/Routing/Matcher/UrlMatcher.php @@ -15,6 +15,7 @@ use Symfony\Component\Routing\Matcher\Exception\MethodNotAllowedException; use Symfony\Component\Routing\Matcher\Exception\NotFoundException; use Symfony\Component\Routing\Route; use Symfony\Component\Routing\RouteCollection; +use Symfony\Component\Routing\RequestContext; /** * UrlMatcher matches URL based on a set of routes. @@ -32,10 +33,10 @@ class UrlMatcher implements UrlMatcherInterface * Constructor. * * @param RouteCollection $routes A RouteCollection instance - * @param array $context The context + * @param RequestContext $context The context * @param array $defaults The default values */ - public function __construct(RouteCollection $routes, array $context = array(), array $defaults = array()) + public function __construct(RouteCollection $routes, RequestContext $context, array $defaults = array()) { $this->routes = $routes; $this->context = $context; @@ -45,9 +46,9 @@ class UrlMatcher implements UrlMatcherInterface /** * Sets the request context. * - * @param array $context The context + * @param RequestContext $context The context */ - public function setContext(array $context = array()) + public function setContext(RequestContext $context) { $this->context = $context; } @@ -79,7 +80,7 @@ class UrlMatcher implements UrlMatcherInterface } // check HTTP method requirement - if (isset($this->context['method']) && $route->getRequirement('_method') && ($req = explode('|', $route->getRequirement('_method'))) && !in_array(strtolower($this->context['method']), array_map('strtolower', $req))) { + if ($route->getRequirement('_method') && ($req = explode('|', $route->getRequirement('_method'))) && !in_array($this->context->getMethod(), array_map('strtolower', $req))) { $allow = array_merge($allow, $req); continue; } diff --git a/src/Symfony/Component/Routing/RequestContext.php b/src/Symfony/Component/Routing/RequestContext.php new file mode 100644 index 0000000000..6406f75ab1 --- /dev/null +++ b/src/Symfony/Component/Routing/RequestContext.php @@ -0,0 +1,167 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Routing; + +/** + * Holds information about the current request. + * + * @author Fabien Potencier + */ +class RequestContext +{ + private $baseUrl; + private $method; + private $host; + private $scheme; + private $httpPort; + private $httpsPort; + + /** + * Constructor. + * + * @param string $baseUrl The base URL + * @param string $method The HTTP method + * @param string $host The HTTP host name + * @param string $scheme The HTTP scheme + * @param integer $httpPort The HTTP port + * @param integer $httpsPort The HTTPS port + */ + public function __construct($baseUrl = '', $method = 'get', $host = 'localhost', $scheme = 'http', $httpPort = 80, $httpsPort = 443) + { + $this->baseUrl = $baseUrl; + $this->method = strtolower($method); + $this->host = $host; + $this->scheme = strtolower($scheme); + $this->httpPort = $httpPort; + $this->httpsPort = $httpsPort; + } + + /** + * Gets the base URL. + * + * @return string The base URL + */ + public function getBaseUrl() + { + return $this->baseUrl; + } + + /** + * Sets the base URL. + * + * @param string $baseUrl The base URL + */ + public function setBaseUrl($baseUrl) + { + $this->baseUrl = $baseUrl; + } + + /** + * Gets the HTTP method. + * + * @return string The HTTP method + */ + public function getMethod() + { + return $this->method; + } + + /** + * Sets the HTTP method. + * + * @param string $method The HTTP method + */ + public function setMethod($method) + { + $this->method = strtolower($method); + } + + /** + * Gets the HTTP host. + * + * @return string The HTTP host + */ + public function getHost() + { + return $this->host; + } + + /** + * Sets the HTTP host. + * + * @param string $host The HTTP host + */ + public function setHost($host) + { + $this->host = $host; + } + + /** + * Gets the HTTP scheme. + * + * @return string The HTTP scheme + */ + public function getScheme() + { + return $this->scheme; + } + + /** + * Sets the HTTP scheme. + * + * @param string $scheme The HTTP scheme + */ + public function setScheme($scheme) + { + $this->scheme = strtolower($scheme); + } + + /** + * Gets the HTTP port. + * + * @return string The HTTP port + */ + public function getHttpPort() + { + return $this->httpPort; + } + + /** + * Sets the HTTP port. + * + * @param string $httpPort The HTTP port + */ + public function setHttpPort($httpPort) + { + $this->httpPort = $httpPort; + } + + /** + * Gets the HTTPS port. + * + * @return string The HTTPS port + */ + public function getHttpsPort() + { + return $this->httpsPort; + } + + /** + * Sets the HTTPS port. + * + * @param string $httpsPort The HTTPS port + */ + public function setHttpsPort($httpsPort) + { + $this->httpsPort = $httpsPort; + } +} diff --git a/src/Symfony/Component/Routing/Router.php b/src/Symfony/Component/Routing/Router.php index 5e5961d5e4..74a6889b70 100644 --- a/src/Symfony/Component/Routing/Router.php +++ b/src/Symfony/Component/Routing/Router.php @@ -48,11 +48,11 @@ class Router implements RouterInterface * * @throws \InvalidArgumentException When unsupported option is provided */ - public function __construct(LoaderInterface $loader, $resource, array $options = array(), array $context = array(), array $defaults = array()) + public function __construct(LoaderInterface $loader, $resource, array $options = array(), RequestContext $context = null, array $defaults = array()) { $this->loader = $loader; $this->resource = $resource; - $this->context = $context; + $this->context = null === $context ? new RequestContext() : $context; $this->defaults = $defaults; $this->options = array( 'cache_dir' => null, @@ -102,9 +102,9 @@ class Router implements RouterInterface /** * Sets the request context. * - * @param array $context The context + * @param RequestContext $context The context */ - public function setContext(array $context = array()) + public function setContext(RequestContext $context) { $this->getMatcher()->setContext($context); $this->getGenerator()->setContext($context); diff --git a/tests/Symfony/Tests/Component/Routing/Fixtures/dumper/url_matcher1.php b/tests/Symfony/Tests/Component/Routing/Fixtures/dumper/url_matcher1.php index 26395f0bb9..19414f48cd 100644 --- a/tests/Symfony/Tests/Component/Routing/Fixtures/dumper/url_matcher1.php +++ b/tests/Symfony/Tests/Component/Routing/Fixtures/dumper/url_matcher1.php @@ -2,6 +2,7 @@ use Symfony\Component\Routing\Matcher\Exception\MethodNotAllowedException; use Symfony\Component\Routing\Matcher\Exception\NotFoundException; +use Symfony\Component\Routing\RequestContext; /** * ProjectUrlMatcher @@ -14,7 +15,7 @@ class ProjectUrlMatcher extends Symfony\Component\Routing\Matcher\UrlMatcher /** * Constructor. */ - public function __construct(array $context = array(), array $defaults = array()) + public function __construct(RequestContext $context, array $defaults = array()) { $this->context = $context; $this->defaults = $defaults; @@ -31,7 +32,7 @@ class ProjectUrlMatcher extends Symfony\Component\Routing\Matcher\UrlMatcher // bar if (0 === strpos($pathinfo, '/bar') && preg_match('#^/bar/(?P[^/\.]+?)$#x', $pathinfo, $matches)) { - if (isset($this->context['method']) && !in_array(strtolower($this->context['method']), array('get', 'head'))) { + if (!in_array($this->context->getMethod(), array('get', 'head'))) { $allow = array_merge($allow, array('get', 'head')); goto not_bar; } @@ -63,7 +64,7 @@ class ProjectUrlMatcher extends Symfony\Component\Routing\Matcher\UrlMatcher // baz5 if (0 === strpos($pathinfo, '/test') && preg_match('#^/test/(?P[^/\.]+?)/$#x', $pathinfo, $matches)) { - if (isset($this->context['method']) && !in_array(strtolower($this->context['method']), array('post'))) { + if (!in_array($this->context->getMethod(), array('post'))) { $allow = array_merge($allow, array('post')); goto not_baz5; } @@ -74,7 +75,7 @@ class ProjectUrlMatcher extends Symfony\Component\Routing\Matcher\UrlMatcher // baz.baz6 if (0 === strpos($pathinfo, '/test') && preg_match('#^/test/(?P[^/\.]+?)/$#x', $pathinfo, $matches)) { - if (isset($this->context['method']) && !in_array(strtolower($this->context['method']), array('put'))) { + if (!in_array($this->context->getMethod(), array('put'))) { $allow = array_merge($allow, array('put')); goto not_bazbaz6; } diff --git a/tests/Symfony/Tests/Component/Routing/Fixtures/dumper/url_matcher2.php b/tests/Symfony/Tests/Component/Routing/Fixtures/dumper/url_matcher2.php index 5c6fdbd3cb..aaafee1730 100644 --- a/tests/Symfony/Tests/Component/Routing/Fixtures/dumper/url_matcher2.php +++ b/tests/Symfony/Tests/Component/Routing/Fixtures/dumper/url_matcher2.php @@ -2,6 +2,7 @@ use Symfony\Component\Routing\Matcher\Exception\MethodNotAllowedException; use Symfony\Component\Routing\Matcher\Exception\NotFoundException; +use Symfony\Component\Routing\RequestContext; /** * ProjectUrlMatcher @@ -14,7 +15,7 @@ class ProjectUrlMatcher extends Symfony\Tests\Component\Routing\Fixtures\Redirec /** * Constructor. */ - public function __construct(array $context = array(), array $defaults = array()) + public function __construct(RequestContext $context, array $defaults = array()) { $this->context = $context; $this->defaults = $defaults; @@ -31,7 +32,7 @@ class ProjectUrlMatcher extends Symfony\Tests\Component\Routing\Fixtures\Redirec // bar if (0 === strpos($pathinfo, '/bar') && preg_match('#^/bar/(?P[^/\.]+?)$#x', $pathinfo, $matches)) { - if (isset($this->context['method']) && !in_array(strtolower($this->context['method']), array('get', 'head'))) { + if (!in_array($this->context->getMethod(), array('get', 'head'))) { $allow = array_merge($allow, array('get', 'head')); goto not_bar; } @@ -69,7 +70,7 @@ class ProjectUrlMatcher extends Symfony\Tests\Component\Routing\Fixtures\Redirec // baz5 if (0 === strpos($pathinfo, '/test') && preg_match('#^/test/(?P[^/\.]+?)/?$#x', $pathinfo, $matches)) { - if (isset($this->context['method']) && !in_array(strtolower($this->context['method']), array('post'))) { + if (!in_array($this->context->getMethod(), array('post'))) { $allow = array_merge($allow, array('post')); goto not_baz5; } @@ -83,7 +84,7 @@ class ProjectUrlMatcher extends Symfony\Tests\Component\Routing\Fixtures\Redirec // baz.baz6 if (0 === strpos($pathinfo, '/test') && preg_match('#^/test/(?P[^/\.]+?)/?$#x', $pathinfo, $matches)) { - if (isset($this->context['method']) && !in_array(strtolower($this->context['method']), array('put'))) { + if (!in_array($this->context->getMethod(), array('put'))) { $allow = array_merge($allow, array('put')); goto not_bazbaz6; } @@ -102,7 +103,7 @@ class ProjectUrlMatcher extends Symfony\Tests\Component\Routing\Fixtures\Redirec // secure if ($pathinfo === '/secure') { - if (isset($this->context['scheme']) && $this->context['scheme'] !== 'https') { + if ($this->context->getScheme() !== 'https') { return $this->redirect($pathinfo, 'secure', 'https'); } return array('_route' => 'secure'); @@ -110,7 +111,7 @@ class ProjectUrlMatcher extends Symfony\Tests\Component\Routing\Fixtures\Redirec // nonsecure if ($pathinfo === '/nonsecure') { - if (isset($this->context['scheme']) && $this->context['scheme'] !== 'http') { + if ($this->context->getScheme() !== 'http') { return $this->redirect($pathinfo, 'nonsecure', 'http'); } return array('_route' => 'nonsecure'); diff --git a/tests/Symfony/Tests/Component/Routing/Generator/Dumper/PhpGeneratorDumperTest.php b/tests/Symfony/Tests/Component/Routing/Generator/Dumper/PhpGeneratorDumperTest.php index 0ec8be010e..5d5466de67 100644 --- a/tests/Symfony/Tests/Component/Routing/Generator/Dumper/PhpGeneratorDumperTest.php +++ b/tests/Symfony/Tests/Component/Routing/Generator/Dumper/PhpGeneratorDumperTest.php @@ -14,6 +14,7 @@ namespace Symfony\Tests\Component\Routing\Generator\Dumper\PhpGeneratorDumper; use Symfony\Component\Routing\RouteCollection; use Symfony\Component\Routing\Route; use Symfony\Component\Routing\Generator\Dumper\PhpGeneratorDumper; +use Symfony\Component\Routing\RequestContext; class PhpGeneratorDumperTest extends \PHPUnit_Framework_TestCase { @@ -37,7 +38,7 @@ class PhpGeneratorDumperTest extends \PHPUnit_Framework_TestCase parent::setUp(); $this->routeCollection = new RouteCollection(); - $this->generatorDumper = new PhpGeneratorDumper($this->routeCollection); + $this->generatorDumper = new PhpGeneratorDumper($this->routeCollection, new RequestContext()); $this->testTmpFilepath = sys_get_temp_dir().DIRECTORY_SEPARATOR.'php_generator.php'; @unlink($this->testTmpFilepath); } @@ -57,12 +58,7 @@ class PhpGeneratorDumperTest extends \PHPUnit_Framework_TestCase file_put_contents($this->testTmpFilepath, $this->generatorDumper->dump()); include ($this->testTmpFilepath); - $projectUrlGenerator = new \ProjectUrlGenerator(array( - 'base_url' => '/app.php', - 'method' => 'GET', - 'host' => 'localhost', - 'scheme' => 'http', - )); + $projectUrlGenerator = new \ProjectUrlGenerator(new RequestContext('/app.php')); $absoluteUrlWithParameter = $projectUrlGenerator->generate('Test', array('foo' => 'bar'), true); $absoluteUrlWithoutParameter = $projectUrlGenerator->generate('Test2', array(), true); @@ -83,12 +79,7 @@ class PhpGeneratorDumperTest extends \PHPUnit_Framework_TestCase file_put_contents($this->testTmpFilepath, $this->generatorDumper->dump(array('class' => 'WithoutRoutesUrlGenerator'))); include ($this->testTmpFilepath); - $projectUrlGenerator = new \WithoutRoutesUrlGenerator(array( - 'base_url' => '/app.php', - 'method' => 'GET', - 'host' => 'localhost', - 'scheme' => 'http', - )); + $projectUrlGenerator = new \WithoutRoutesUrlGenerator(new RequestContext('/app.php')); $projectUrlGenerator->generate('Test', array()); } @@ -100,7 +91,7 @@ class PhpGeneratorDumperTest extends \PHPUnit_Framework_TestCase file_put_contents($this->testTmpFilepath, $this->generatorDumper->dump(array('class' => 'DefaultRoutesUrlGenerator'))); include ($this->testTmpFilepath); - $projectUrlGenerator = new \DefaultRoutesUrlGenerator(array()); + $projectUrlGenerator = new \DefaultRoutesUrlGenerator(new RequestContext()); $url = $projectUrlGenerator->generate('Test', array()); $this->assertEquals($url, '/testing'); diff --git a/tests/Symfony/Tests/Component/Routing/Generator/UrlGeneratorTest.php b/tests/Symfony/Tests/Component/Routing/Generator/UrlGeneratorTest.php index bda8dad448..32015e7aa8 100644 --- a/tests/Symfony/Tests/Component/Routing/Generator/UrlGeneratorTest.php +++ b/tests/Symfony/Tests/Component/Routing/Generator/UrlGeneratorTest.php @@ -14,6 +14,7 @@ namespace Symfony\Tests\Component\Routing\Generator; use Symfony\Component\Routing\RouteCollection; use Symfony\Component\Routing\Route; use Symfony\Component\Routing\Generator\UrlGenerator; +use Symfony\Component\Routing\RequestContext; class UrlGeneratorTest extends \PHPUnit_Framework_TestCase { @@ -36,7 +37,7 @@ class UrlGeneratorTest extends \PHPUnit_Framework_TestCase public function testAbsoluteUrlWithNonStandardPort() { $routes = $this->getRoutes('test', new Route('/testing')); - $url = $this->getGenerator($routes, array('http_port' => 8080))->generate('test', array(), true); + $url = $this->getGenerator($routes, array('httpPort' => 8080))->generate('test', array(), true); $this->assertEquals('http://localhost:8080/app.php/testing', $url); } @@ -44,7 +45,7 @@ class UrlGeneratorTest extends \PHPUnit_Framework_TestCase public function testAbsoluteSecureUrlWithNonStandardPort() { $routes = $this->getRoutes('test', new Route('/testing')); - $url = $this->getGenerator($routes, array('https_port' => 8080, 'scheme' => 'https'))->generate('test', array(), true); + $url = $this->getGenerator($routes, array('httpsPort' => 8080, 'scheme' => 'https'))->generate('test', array(), true); $this->assertEquals('https://localhost:8080/app.php/testing', $url); } @@ -143,17 +144,14 @@ class UrlGeneratorTest extends \PHPUnit_Framework_TestCase $this->assertEquals('http://localhost/app.php/', $this->getGenerator($routes, array('scheme' => 'https'))->generate('test')); } - protected function getGenerator(RouteCollection $routes, array $context = array()) + protected function getGenerator(RouteCollection $routes, array $parameters = array()) { - $generator = new UrlGenerator($routes); - $generator->setContext(array_replace(array( - 'base_url' => '/app.php', - 'method' => 'GET', - 'host' => 'localhost', - 'http_port' => 80, - 'https_port' => 443, - 'scheme' => 'http', - ), $context)); + $context = new RequestContext('/app.php'); + foreach ($parameters as $key => $value) { + $method = 'set'.$key; + $context->$method($value); + } + $generator = new UrlGenerator($routes, $context); return $generator; } diff --git a/tests/Symfony/Tests/Component/Routing/Matcher/Dumper/PhpMatcherDumperTest.php b/tests/Symfony/Tests/Component/Routing/Matcher/Dumper/PhpMatcherDumperTest.php index c61af52e70..5286a9a851 100644 --- a/tests/Symfony/Tests/Component/Routing/Matcher/Dumper/PhpMatcherDumperTest.php +++ b/tests/Symfony/Tests/Component/Routing/Matcher/Dumper/PhpMatcherDumperTest.php @@ -14,6 +14,7 @@ namespace Symfony\Tests\Component\Routing; use Symfony\Component\Routing\Matcher\Dumper\PhpMatcherDumper; use Symfony\Component\Routing\Route; use Symfony\Component\Routing\RouteCollection; +use Symfony\Component\Routing\RequestContext; class PhpMatcherDumperTest extends \PHPUnit_Framework_TestCase { @@ -67,7 +68,7 @@ class PhpMatcherDumperTest extends \PHPUnit_Framework_TestCase array('def' => 'test') )); - $dumper = new PhpMatcherDumper($collection); + $dumper = new PhpMatcherDumper($collection, new RequestContext()); $this->assertStringEqualsFile(__DIR__.'/../../Fixtures/dumper/url_matcher1.php', $dumper->dump(), '->dump() dumps basic routes to the correct PHP file.'); // force HTTPS redirection @@ -98,7 +99,7 @@ class PhpMatcherDumperTest extends \PHPUnit_Framework_TestCase array(), array('_scheme' => 'https') )); - $dumper = new PhpMatcherDumper($collection); + $dumper = new PhpMatcherDumper($collection, new RequestContext()); $dumper->dump(); } } diff --git a/tests/Symfony/Tests/Component/Routing/Matcher/UrlMatcherTest.php b/tests/Symfony/Tests/Component/Routing/Matcher/UrlMatcherTest.php index 7efbef6bda..034ecfcc4e 100644 --- a/tests/Symfony/Tests/Component/Routing/Matcher/UrlMatcherTest.php +++ b/tests/Symfony/Tests/Component/Routing/Matcher/UrlMatcherTest.php @@ -16,6 +16,7 @@ use Symfony\Component\Routing\Matcher\Exception\NotFoundException; use Symfony\Component\Routing\Matcher\UrlMatcher; use Symfony\Component\Routing\Route; use Symfony\Component\Routing\RouteCollection; +use Symfony\Component\Routing\RequestContext; class UrlMatcherTest extends \PHPUnit_Framework_TestCase { @@ -24,7 +25,7 @@ class UrlMatcherTest extends \PHPUnit_Framework_TestCase $coll = new RouteCollection(); $coll->add('foo', new Route('/foo')); - $matcher = new UrlMatcher($coll, array('method' => 'get')); + $matcher = new UrlMatcher($coll, new RequestContext()); $matcher->match('/foo'); } @@ -33,7 +34,7 @@ class UrlMatcherTest extends \PHPUnit_Framework_TestCase $coll = new RouteCollection(); $coll->add('foo', new Route('/foo', array(), array('_method' => 'post'))); - $matcher = new UrlMatcher($coll, array('method' => 'get')); + $matcher = new UrlMatcher($coll, new RequestContext()); try { $matcher->match('/foo'); @@ -49,7 +50,7 @@ class UrlMatcherTest extends \PHPUnit_Framework_TestCase $coll->add('foo1', new Route('/foo', array(), array('_method' => 'post'))); $coll->add('foo2', new Route('/foo', array(), array('_method' => 'put|delete'))); - $matcher = new UrlMatcher($coll, array('method' => 'get')); + $matcher = new UrlMatcher($coll, new RequestContext()); try { $matcher->match('/foo'); @@ -64,7 +65,7 @@ class UrlMatcherTest extends \PHPUnit_Framework_TestCase // test the patterns are matched are parameters are returned $collection = new RouteCollection(); $collection->add('foo', new Route('/foo/{bar}')); - $matcher = new UrlMatcher($collection, array(), array()); + $matcher = new UrlMatcher($collection, new RequestContext(), array()); try { $matcher->match('/no-match'); $this->fail(); @@ -74,26 +75,26 @@ class UrlMatcherTest extends \PHPUnit_Framework_TestCase // test that defaults are merged $collection = new RouteCollection(); $collection->add('foo', new Route('/foo/{bar}', array('def' => 'test'))); - $matcher = new UrlMatcher($collection, array(), array()); + $matcher = new UrlMatcher($collection, new RequestContext(), array()); $this->assertEquals(array('_route' => 'foo', 'bar' => 'baz', 'def' => 'test'), $matcher->match('/foo/baz')); // test that route "method" is ignored if no method is given in the context $collection = new RouteCollection(); $collection->add('foo', new Route('/foo', array(), array('_method' => 'GET|head'))); - $matcher = new UrlMatcher($collection, array(), array()); + $matcher = new UrlMatcher($collection, new RequestContext(), array()); $this->assertInternalType('array', $matcher->match('/foo')); // route does not match with POST method context - $matcher = new UrlMatcher($collection, array('method' => 'POST'), array()); + $matcher = new UrlMatcher($collection, new RequestContext('', 'post'), array()); try { $matcher->match('/foo'); $this->fail(); } catch (MethodNotAllowedException $e) {} // route does match with GET or HEAD method context - $matcher = new UrlMatcher($collection, array('method' => 'GET'), array()); + $matcher = new UrlMatcher($collection, new RequestContext(), array()); $this->assertInternalType('array', $matcher->match('/foo')); - $matcher = new UrlMatcher($collection, array('method' => 'HEAD'), array()); + $matcher = new UrlMatcher($collection, new RequestContext('', 'head'), array()); $this->assertInternalType('array', $matcher->match('/foo')); } } From 0dbfa18c46e241b1532bef376e3dc82089685368 Mon Sep 17 00:00:00 2001 From: Fabien Potencier Date: Wed, 20 Apr 2011 14:04:53 +0200 Subject: [PATCH 57/91] [Routing] made a small optimization to the route dumper --- .../Matcher/Dumper/PhpMatcherDumper.php | 18 ++++++++++++++---- .../Routing/Fixtures/dumper/url_matcher1.php | 8 ++++---- .../Routing/Fixtures/dumper/url_matcher2.php | 8 ++++---- 3 files changed, 22 insertions(+), 12 deletions(-) diff --git a/src/Symfony/Component/Routing/Matcher/Dumper/PhpMatcherDumper.php b/src/Symfony/Component/Routing/Matcher/Dumper/PhpMatcherDumper.php index 0c61139019..874c59c4ab 100644 --- a/src/Symfony/Component/Routing/Matcher/Dumper/PhpMatcherDumper.php +++ b/src/Symfony/Component/Routing/Matcher/Dumper/PhpMatcherDumper.php @@ -92,13 +92,23 @@ class PhpMatcherDumper extends MatcherDumper EOF; if ($req = $route->getRequirement('_method')) { - $req = implode('\', \'', array_map('strtolower', explode('|', $req))); - $code[] = <<context->getMethod(), array('$req'))) { - \$allow = array_merge(\$allow, array('$req')); + $methods = array_map('strtolower', explode('|', $req)); + if (1 === count($methods)) { + $code[] = <<context->getMethod() != '$methods[0]') { + \$allow[] = '$methods[0]'; goto $gotoname; } EOF; + } else { + $methods = implode('\', \'', $methods); + $code[] = <<context->getMethod(), array('$methods'))) { + \$allow = array_merge(\$allow, array('$methods')); + goto $gotoname; + } +EOF; + } } if ($hasTrailingSlash) { diff --git a/tests/Symfony/Tests/Component/Routing/Fixtures/dumper/url_matcher1.php b/tests/Symfony/Tests/Component/Routing/Fixtures/dumper/url_matcher1.php index 19414f48cd..b3fe2bd3b8 100644 --- a/tests/Symfony/Tests/Component/Routing/Fixtures/dumper/url_matcher1.php +++ b/tests/Symfony/Tests/Component/Routing/Fixtures/dumper/url_matcher1.php @@ -64,8 +64,8 @@ class ProjectUrlMatcher extends Symfony\Component\Routing\Matcher\UrlMatcher // baz5 if (0 === strpos($pathinfo, '/test') && preg_match('#^/test/(?P[^/\.]+?)/$#x', $pathinfo, $matches)) { - if (!in_array($this->context->getMethod(), array('post'))) { - $allow = array_merge($allow, array('post')); + if ($this->context->getMethod() != 'post') { + $allow[] = 'post'; goto not_baz5; } $matches['_route'] = 'baz5'; @@ -75,8 +75,8 @@ class ProjectUrlMatcher extends Symfony\Component\Routing\Matcher\UrlMatcher // baz.baz6 if (0 === strpos($pathinfo, '/test') && preg_match('#^/test/(?P[^/\.]+?)/$#x', $pathinfo, $matches)) { - if (!in_array($this->context->getMethod(), array('put'))) { - $allow = array_merge($allow, array('put')); + if ($this->context->getMethod() != 'put') { + $allow[] = 'put'; goto not_bazbaz6; } $matches['_route'] = 'baz.baz6'; diff --git a/tests/Symfony/Tests/Component/Routing/Fixtures/dumper/url_matcher2.php b/tests/Symfony/Tests/Component/Routing/Fixtures/dumper/url_matcher2.php index aaafee1730..60c3ed8fea 100644 --- a/tests/Symfony/Tests/Component/Routing/Fixtures/dumper/url_matcher2.php +++ b/tests/Symfony/Tests/Component/Routing/Fixtures/dumper/url_matcher2.php @@ -70,8 +70,8 @@ class ProjectUrlMatcher extends Symfony\Tests\Component\Routing\Fixtures\Redirec // baz5 if (0 === strpos($pathinfo, '/test') && preg_match('#^/test/(?P[^/\.]+?)/?$#x', $pathinfo, $matches)) { - if (!in_array($this->context->getMethod(), array('post'))) { - $allow = array_merge($allow, array('post')); + if ($this->context->getMethod() != 'post') { + $allow[] = 'post'; goto not_baz5; } if (substr($pathinfo, -1) !== '/') { @@ -84,8 +84,8 @@ class ProjectUrlMatcher extends Symfony\Tests\Component\Routing\Fixtures\Redirec // baz.baz6 if (0 === strpos($pathinfo, '/test') && preg_match('#^/test/(?P[^/\.]+?)/?$#x', $pathinfo, $matches)) { - if (!in_array($this->context->getMethod(), array('put'))) { - $allow = array_merge($allow, array('put')); + if ($this->context->getMethod() != 'put') { + $allow[] = 'put'; goto not_bazbaz6; } if (substr($pathinfo, -1) !== '/') { From 1df8b2ee3723caed174947ca983eee6974480219 Mon Sep 17 00:00:00 2001 From: Fabien Potencier Date: Wed, 20 Apr 2011 14:31:42 +0200 Subject: [PATCH 58/91] [FrameworkBundle] fixed methods that have been renamed in the previous commit --- .../DependencyInjection/FrameworkExtension.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/Symfony/Bundle/FrameworkBundle/DependencyInjection/FrameworkExtension.php b/src/Symfony/Bundle/FrameworkBundle/DependencyInjection/FrameworkExtension.php index b25641afdf..32c9474dac 100644 --- a/src/Symfony/Bundle/FrameworkBundle/DependencyInjection/FrameworkExtension.php +++ b/src/Symfony/Bundle/FrameworkBundle/DependencyInjection/FrameworkExtension.php @@ -257,8 +257,8 @@ class FrameworkExtension extends Extension } $def = $container->getDefinition('request_listener'); - $def->setArgument(2, $config['http_port']); - $def->setArgument(3, $config['https_port']); + $def->replaceArgument(2, $config['http_port']); + $def->replaceArgument(3, $config['https_port']); $this->addClassesToCompile(array( 'Symfony\\Component\\Routing\\RouterInterface', From 03bb3580a69150948ab37d8418aab9f759682c88 Mon Sep 17 00:00:00 2001 From: Tim Nagel Date: Wed, 20 Apr 2011 23:52:17 +1000 Subject: [PATCH 59/91] [HttpFoundation\File] Removed realpath() --- src/Symfony/Component/HttpFoundation/File/File.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Symfony/Component/HttpFoundation/File/File.php b/src/Symfony/Component/HttpFoundation/File/File.php index 4675332e17..bda63e9a6b 100644 --- a/src/Symfony/Component/HttpFoundation/File/File.php +++ b/src/Symfony/Component/HttpFoundation/File/File.php @@ -491,7 +491,7 @@ class File throw new FileNotFoundException($path); } - $this->path = realpath($path); + $this->path = $path; } /** From fd1636b324b245bd632b67c263a5810672663349 Mon Sep 17 00:00:00 2001 From: Fabien Potencier Date: Wed, 20 Apr 2011 15:54:48 +0200 Subject: [PATCH 60/91] [Routing] added RedirectableUrlMatcher --- .../Matcher/RedirectableUrlMatcher.php | 49 +++++++++++++++++++ .../Matcher/RedirectableUrlMatcherTest.php | 29 +++++++++++ 2 files changed, 78 insertions(+) create mode 100644 src/Symfony/Component/Routing/Matcher/RedirectableUrlMatcher.php create mode 100644 tests/Symfony/Tests/Component/Routing/Matcher/RedirectableUrlMatcherTest.php diff --git a/src/Symfony/Component/Routing/Matcher/RedirectableUrlMatcher.php b/src/Symfony/Component/Routing/Matcher/RedirectableUrlMatcher.php new file mode 100644 index 0000000000..e18ea8df2f --- /dev/null +++ b/src/Symfony/Component/Routing/Matcher/RedirectableUrlMatcher.php @@ -0,0 +1,49 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Routing\Matcher; + +use Symfony\Component\Routing\Matcher\Exception\NotFoundException; + +/** + * @author Fabien Potencier + */ +abstract class RedirectableUrlMatcher extends UrlMatcher implements RedirectableUrlMatcherInterface +{ + private $trailingSlashTest = false; + + /** + * @see UrlMatcher::match() + */ + public function match($pathinfo) + { + try { + $parameters = parent::match($pathinfo); + } catch (NotFoundException $e) { + if ('/' === substr($pathinfo, -1)) { + throw $e; + } + + // try with a / at the end + $this->trailingSlashTest = true; + + return $this->match($pathinfo.'/'); + } + + if ($this->trailingSlashTest) { + $this->trailingSlashTest = false; + + return $this->redirect($pathinfo, null); + } + + return $parameters; + } +} diff --git a/tests/Symfony/Tests/Component/Routing/Matcher/RedirectableUrlMatcherTest.php b/tests/Symfony/Tests/Component/Routing/Matcher/RedirectableUrlMatcherTest.php new file mode 100644 index 0000000000..20ff970649 --- /dev/null +++ b/tests/Symfony/Tests/Component/Routing/Matcher/RedirectableUrlMatcherTest.php @@ -0,0 +1,29 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Tests\Component\Routing\Matcher; + +use Symfony\Component\Routing\Route; +use Symfony\Component\Routing\RouteCollection; +use Symfony\Component\Routing\RequestContext; + +class RedirectableUrlMatcherTest extends \PHPUnit_Framework_TestCase +{ + public function testNoMethodSoAllowed() + { + $coll = new RouteCollection(); + $coll->add('foo', new Route('/foo/')); + + $matcher = $this->getMockForAbstractClass('Symfony\Component\Routing\Matcher\RedirectableUrlMatcher', array($coll, new RequestContext())); + $matcher->expects($this->once())->method('redirect'); + $matcher->match('/foo'); + } +} From 1191e3aa666662027a1df66381061ff70149c766 Mon Sep 17 00:00:00 2001 From: Victor Berchet Date: Wed, 20 Apr 2011 17:37:21 +0200 Subject: [PATCH 61/91] [AsseticBundle] Fix the cache warmers --- .../CacheWarmer/AssetManagerCacheWarmer.php | 11 ++++++----- .../CacheWarmer/AssetWriterCacheWarmer.php | 13 +++++++------ .../AsseticBundle/Resources/config/asset_writer.xml | 2 +- .../AsseticBundle/Resources/config/assetic.xml | 2 +- .../DependencyInjection/FrameworkExtension.php | 5 ++++- 5 files changed, 19 insertions(+), 14 deletions(-) diff --git a/src/Symfony/Bundle/AsseticBundle/CacheWarmer/AssetManagerCacheWarmer.php b/src/Symfony/Bundle/AsseticBundle/CacheWarmer/AssetManagerCacheWarmer.php index 6adf66f2a2..35e7e8dc67 100644 --- a/src/Symfony/Bundle/AsseticBundle/CacheWarmer/AssetManagerCacheWarmer.php +++ b/src/Symfony/Bundle/AsseticBundle/CacheWarmer/AssetManagerCacheWarmer.php @@ -11,21 +11,22 @@ namespace Symfony\Bundle\AsseticBundle\CacheWarmer; -use Assetic\Factory\LazyAssetManager; use Symfony\Component\HttpKernel\CacheWarmer\CacheWarmer; +use Symfony\Component\DependencyInjection\ContainerInterface; class AssetManagerCacheWarmer extends CacheWarmer { - protected $am; + private $container; - public function __construct(LazyAssetManager $am) + public function __construct(ContainerInterface $container) { - $this->am = $am; + $this->container = $container; } public function warmUp($cacheDir) { - $this->am->load(); + $am = $this->container->get('assetic.asset_manager'); + $am->load(); } public function isOptional() diff --git a/src/Symfony/Bundle/AsseticBundle/CacheWarmer/AssetWriterCacheWarmer.php b/src/Symfony/Bundle/AsseticBundle/CacheWarmer/AssetWriterCacheWarmer.php index 034a45a6e0..298ffd235d 100644 --- a/src/Symfony/Bundle/AsseticBundle/CacheWarmer/AssetWriterCacheWarmer.php +++ b/src/Symfony/Bundle/AsseticBundle/CacheWarmer/AssetWriterCacheWarmer.php @@ -11,24 +11,25 @@ namespace Symfony\Bundle\AsseticBundle\CacheWarmer; -use Assetic\AssetManager; use Assetic\AssetWriter; use Symfony\Component\HttpKernel\CacheWarmer\CacheWarmer; +use Symfony\Component\DependencyInjection\ContainerInterface; class AssetWriterCacheWarmer extends CacheWarmer { - protected $am; - protected $writer; + private $container; + private $writer; - public function __construct(AssetManager $am, AssetWriter $writer) + public function __construct(ContainerInterface $container, AssetWriter $writer) { - $this->am = $am; + $this->container = $container; $this->writer = $writer; } public function warmUp($cacheDir) { - $this->writer->writeManagerAssets($this->am); + $am = $this->container->get('assetic.asset_manager'); + $this->writer->writeManagerAssets($am); } public function isOptional() diff --git a/src/Symfony/Bundle/AsseticBundle/Resources/config/asset_writer.xml b/src/Symfony/Bundle/AsseticBundle/Resources/config/asset_writer.xml index 855caa06ec..c4a9515396 100644 --- a/src/Symfony/Bundle/AsseticBundle/Resources/config/asset_writer.xml +++ b/src/Symfony/Bundle/AsseticBundle/Resources/config/asset_writer.xml @@ -12,7 +12,7 @@ - + diff --git a/src/Symfony/Bundle/AsseticBundle/Resources/config/assetic.xml b/src/Symfony/Bundle/AsseticBundle/Resources/config/assetic.xml index 2ef38f2616..23d67202d6 100644 --- a/src/Symfony/Bundle/AsseticBundle/Resources/config/assetic.xml +++ b/src/Symfony/Bundle/AsseticBundle/Resources/config/assetic.xml @@ -42,7 +42,7 @@ - + diff --git a/src/Symfony/Bundle/FrameworkBundle/DependencyInjection/FrameworkExtension.php b/src/Symfony/Bundle/FrameworkBundle/DependencyInjection/FrameworkExtension.php index 32c9474dac..f2297d3f4e 100644 --- a/src/Symfony/Bundle/FrameworkBundle/DependencyInjection/FrameworkExtension.php +++ b/src/Symfony/Bundle/FrameworkBundle/DependencyInjection/FrameworkExtension.php @@ -370,7 +370,10 @@ class FrameworkExtension extends Extension } if ($config['cache_warmer']) { - $container->getDefinition('templating.cache_warmer.template_paths')->addTag('kernel.cache_warmer'); + $container + ->getDefinition('templating.cache_warmer.template_paths') + ->addTag('kernel.cache_warmer', array('priority' => 20)) + ; $container->setAlias('templating.locator', 'templating.locator.cached'); } else { $container->setAlias('templating.locator', 'templating.locator.uncached'); From 30511d29658b994c15622a969fe50d9982588c4d Mon Sep 17 00:00:00 2001 From: Kris Wallsmith Date: Wed, 20 Apr 2011 13:20:21 -0700 Subject: [PATCH 62/91] [HttpFoundation] fixed FilesystemSessionStorage --- .../FilesystemSessionStorage.php | 15 ++++- .../FilesystemSessionStorageTest.php | 59 +++++++++++++++++++ 2 files changed, 73 insertions(+), 1 deletion(-) create mode 100644 tests/Symfony/Tests/Component/HttpFoundation/SessionStorage/FilesystemSessionStorageTest.php diff --git a/src/Symfony/Component/HttpFoundation/SessionStorage/FilesystemSessionStorage.php b/src/Symfony/Component/HttpFoundation/SessionStorage/FilesystemSessionStorage.php index e174be7a94..5cc70ff452 100644 --- a/src/Symfony/Component/HttpFoundation/SessionStorage/FilesystemSessionStorage.php +++ b/src/Symfony/Component/HttpFoundation/SessionStorage/FilesystemSessionStorage.php @@ -20,17 +20,19 @@ class FilesystemSessionStorage extends NativeSessionStorage { private $path; private $data; + private $started; public function __construct($path, array $options = array()) { $this->path = $path; + $this->started = false; parent::__construct($options); } public function start() { - if (self::$sessionStarted) { + if ($this->started) { return; } @@ -57,6 +59,16 @@ class FilesystemSessionStorage extends NativeSessionStorage $file = $this->path.'/'.session_id().'.session'; $this->data = file_exists($file) ? unserialize(file_get_contents($file)) : array(); + $this->started = true; + } + + public function getId() + { + if (!$this->started) { + throw new \RuntimeException('The session must be started before reading its ID'); + } + + return session_id(); } public function read($key, $default = null) @@ -85,6 +97,7 @@ class FilesystemSessionStorage extends NativeSessionStorage if ($destroy) { $this->data = array(); } + return true; } } diff --git a/tests/Symfony/Tests/Component/HttpFoundation/SessionStorage/FilesystemSessionStorageTest.php b/tests/Symfony/Tests/Component/HttpFoundation/SessionStorage/FilesystemSessionStorageTest.php new file mode 100644 index 0000000000..7f4503b405 --- /dev/null +++ b/tests/Symfony/Tests/Component/HttpFoundation/SessionStorage/FilesystemSessionStorageTest.php @@ -0,0 +1,59 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Tests\Component\HttpFoundation\SessionStorage; + +use Symfony\Component\HttpFoundation\SessionStorage\FilesystemSessionStorage; + +class FilesystemSessionStorageTest extends \PHPUnit_Framework_TestCase +{ + private $path; + + protected function setUp() + { + $this->path = sys_get_temp_dir().'/sf2/session_test'; + if (!file_exists($this->path)) { + mkdir($this->path, 0777, true); + } + } + + protected function tearDown() + { + array_map('unlink', glob($this->path.'/*.session')); + rmdir($this->path); + } + + public function testMultipleInstances() + { + $storage = new FilesystemSessionStorage($this->path); + $storage->start(); + $storage->write('foo', 'bar'); + + $storage = new FilesystemSessionStorage($this->path); + $storage->start(); + $this->assertEquals('bar', $storage->read('foo'), 'values persist between instances'); + } + + public function testGetIdThrowsErrorBeforeStart() + { + $this->setExpectedException('RuntimeException'); + + $storage = new FilesystemSessionStorage($this->path); + $storage->getId(); + } + + public function testGetIdWorksAfterStart() + { + $storage = new FilesystemSessionStorage($this->path); + $storage->start(); + $storage->getId(); + } +} From 8ae7a21e30dd20b1099782e9d4e703c22c027374 Mon Sep 17 00:00:00 2001 From: Johannes Schmitt Date: Wed, 20 Apr 2011 22:20:55 +0200 Subject: [PATCH 63/91] [SecurityBundle] changed expected value for token_provider key in the rememberme section --- UPDATE.md | 3 +++ .../Security/Factory/RememberMeFactory.php | 8 ++------ 2 files changed, 5 insertions(+), 6 deletions(-) diff --git a/UPDATE.md b/UPDATE.md index 54d339d237..1d08d5854f 100644 --- a/UPDATE.md +++ b/UPDATE.md @@ -21,6 +21,9 @@ PR12 to PR13 $container->removeDefinition('my_definition'); $definition->replaceArgument(0, 'foo'); + +* In the rememberme configuration, the token_provider key now expects a real + service id instead of only a suffix. PR11 to PR12 ------------ diff --git a/src/Symfony/Bundle/SecurityBundle/DependencyInjection/Security/Factory/RememberMeFactory.php b/src/Symfony/Bundle/SecurityBundle/DependencyInjection/Security/Factory/RememberMeFactory.php index 21f1ee1bc3..13cf66fa39 100644 --- a/src/Symfony/Bundle/SecurityBundle/DependencyInjection/Security/Factory/RememberMeFactory.php +++ b/src/Symfony/Bundle/SecurityBundle/DependencyInjection/Security/Factory/RememberMeFactory.php @@ -35,9 +35,6 @@ class RememberMeFactory implements SecurityFactoryInterface // remember me services if (isset($config['token_provider'])) { - $config['token-provider'] = $config['token_provider']; - } - if (isset($config['token-provider'])) { $templateId = 'security.authentication.rememberme.services.persistent'; $rememberMeServicesId = $templateId.'.'.$id; } else { @@ -56,10 +53,9 @@ class RememberMeFactory implements SecurityFactoryInterface $rememberMeServices->replaceArgument(1, $config['key']); $rememberMeServices->replaceArgument(2, $id); - if (isset($config['token-provider'])) { - // FIXME: make the naming assumption more flexible + if (isset($config['token_provider'])) { $rememberMeServices->addMethodCall('setTokenProvider', array( - new Reference('security.rememberme.token.provider.'.$config['token-provider']) + new Reference($config['token_provider']) )); } From 4d6e239f106146a8db6e47795fe8f81e933995ad Mon Sep 17 00:00:00 2001 From: Johannes Schmitt Date: Wed, 20 Apr 2011 22:25:05 +0200 Subject: [PATCH 64/91] [Security/Acl] removed Doctrine dependency from interfaces and moved them to the actual implementation --- src/Symfony/Component/Security/Acl/Domain/Acl.php | 3 ++- src/Symfony/Component/Security/Acl/Domain/FieldEntry.php | 4 ++-- .../{FieldAwareEntryInterface.php => FieldEntryInterface.php} | 2 +- .../Component/Security/Acl/Model/MutableAclInterface.php | 4 +--- 4 files changed, 6 insertions(+), 7 deletions(-) rename src/Symfony/Component/Security/Acl/Model/{FieldAwareEntryInterface.php => FieldEntryInterface.php} (91%) diff --git a/src/Symfony/Component/Security/Acl/Domain/Acl.php b/src/Symfony/Component/Security/Acl/Domain/Acl.php index 20f300b539..09bcb34390 100644 --- a/src/Symfony/Component/Security/Acl/Domain/Acl.php +++ b/src/Symfony/Component/Security/Acl/Domain/Acl.php @@ -10,6 +10,7 @@ namespace Symfony\Component\Security\Acl\Domain; +use Doctrine\Common\NotifyPropertyChanged; use Doctrine\Common\PropertyChangedListener; use Symfony\Component\Security\Acl\Model\AclInterface; use Symfony\Component\Security\Acl\Model\AuditableAclInterface; @@ -33,7 +34,7 @@ use Symfony\Component\Security\Acl\Model\SecurityIdentityInterface; * * @author Johannes M. Schmitt */ -class Acl implements AuditableAclInterface +class Acl implements AuditableAclInterface, NotifyPropertyChanged { private $parentAcl; private $permissionGrantingStrategy; diff --git a/src/Symfony/Component/Security/Acl/Domain/FieldEntry.php b/src/Symfony/Component/Security/Acl/Domain/FieldEntry.php index 0f71237831..1510df2411 100644 --- a/src/Symfony/Component/Security/Acl/Domain/FieldEntry.php +++ b/src/Symfony/Component/Security/Acl/Domain/FieldEntry.php @@ -12,7 +12,7 @@ namespace Symfony\Component\Security\Acl\Domain; use Symfony\Component\Security\Acl\Model\AclInterface; -use Symfony\Component\Security\Acl\Model\FieldAwareEntryInterface; +use Symfony\Component\Security\Acl\Model\FieldEntryInterface; use Symfony\Component\Security\Acl\Model\SecurityIdentityInterface; /** @@ -20,7 +20,7 @@ use Symfony\Component\Security\Acl\Model\SecurityIdentityInterface; * * @author Johannes M. Schmitt */ -class FieldEntry extends Entry implements FieldAwareEntryInterface +class FieldEntry extends Entry implements FieldEntryInterface { private $field; diff --git a/src/Symfony/Component/Security/Acl/Model/FieldAwareEntryInterface.php b/src/Symfony/Component/Security/Acl/Model/FieldEntryInterface.php similarity index 91% rename from src/Symfony/Component/Security/Acl/Model/FieldAwareEntryInterface.php rename to src/Symfony/Component/Security/Acl/Model/FieldEntryInterface.php index bcf292cdaf..68aa10c9f1 100644 --- a/src/Symfony/Component/Security/Acl/Model/FieldAwareEntryInterface.php +++ b/src/Symfony/Component/Security/Acl/Model/FieldEntryInterface.php @@ -16,7 +16,7 @@ namespace Symfony\Component\Security\Acl\Model; * * @author Johannes M. Schmitt */ -interface FieldAwareEntryInterface +interface FieldEntryInterface extends EntryInterface { /** * Returns the field used for this entry. diff --git a/src/Symfony/Component/Security/Acl/Model/MutableAclInterface.php b/src/Symfony/Component/Security/Acl/Model/MutableAclInterface.php index 4e52e65cef..fdd671236b 100644 --- a/src/Symfony/Component/Security/Acl/Model/MutableAclInterface.php +++ b/src/Symfony/Component/Security/Acl/Model/MutableAclInterface.php @@ -11,8 +11,6 @@ namespace Symfony\Component\Security\Acl\Model; -use Doctrine\Common\NotifyPropertyChanged; - /** * This interface adds mutators for the AclInterface. * @@ -21,7 +19,7 @@ use Doctrine\Common\NotifyPropertyChanged; * * @author Johannes M. Schmitt */ -interface MutableAclInterface extends AclInterface, NotifyPropertyChanged +interface MutableAclInterface extends AclInterface { /** * Deletes a class-based ACE From f697fe3b26beef2d34264972cae7569b6804efac Mon Sep 17 00:00:00 2001 From: Johannes Schmitt Date: Wed, 20 Apr 2011 22:35:17 +0200 Subject: [PATCH 65/91] [Security/Acl] some misc fixes --- .../Acl/Domain/PermissionGrantingStrategy.php | 22 ++++++------------- .../Acl/Exception/NoAceFoundException.php | 4 ++++ 2 files changed, 11 insertions(+), 15 deletions(-) diff --git a/src/Symfony/Component/Security/Acl/Domain/PermissionGrantingStrategy.php b/src/Symfony/Component/Security/Acl/Domain/PermissionGrantingStrategy.php index 8bee157ae4..37bbe4eb0f 100644 --- a/src/Symfony/Component/Security/Acl/Domain/PermissionGrantingStrategy.php +++ b/src/Symfony/Component/Security/Acl/Domain/PermissionGrantingStrategy.php @@ -30,16 +30,8 @@ class PermissionGrantingStrategy implements PermissionGrantingStrategyInterface const ALL = 'all'; const ANY = 'any'; - private static $noAceException; private $auditLogger; - public function __construct() - { - if (null === static::$noAceException) { - static::$noAceException = new NoAceFoundException('No ACE.'); - } - } - /** * Sets the audit logger * @@ -61,7 +53,7 @@ class PermissionGrantingStrategy implements PermissionGrantingStrategyInterface $aces = $acl->getObjectAces(); if (!$aces) { - throw static::$noAceException; + throw new NoAceFoundException(); } return $this->hasSufficientPermissions($acl, $aces, $masks, $sids, $administrativeMode); @@ -69,7 +61,7 @@ class PermissionGrantingStrategy implements PermissionGrantingStrategyInterface $aces = $acl->getClassAces(); if (!$aces) { - throw static::$noAceException; + throw $noObjectAce; } return $this->hasSufficientPermissions($acl, $aces, $masks, $sids, $administrativeMode); @@ -79,7 +71,7 @@ class PermissionGrantingStrategy implements PermissionGrantingStrategyInterface return $parentAcl->isGranted($masks, $sids, $administrativeMode); } - throw new NoAceFoundException('No applicable ACE was found.'); + throw $noClassAce; } } @@ -92,14 +84,14 @@ class PermissionGrantingStrategy implements PermissionGrantingStrategyInterface try { $aces = $acl->getObjectFieldAces($field); if (!$aces) { - throw static::$noAceException; + throw new NoAceFoundException(); } return $this->hasSufficientPermissions($acl, $aces, $masks, $sids, $administrativeMode); } catch (NoAceFoundException $noObjectAces) { $aces = $acl->getClassFieldAces($field); if (!$aces) { - throw static::$noAceException; + throw $noObjectAces; } return $this->hasSufficientPermissions($acl, $aces, $masks, $sids, $administrativeMode); @@ -109,7 +101,7 @@ class PermissionGrantingStrategy implements PermissionGrantingStrategyInterface return $parentAcl->isFieldGranted($field, $masks, $sids, $administrativeMode); } - throw new NoAceFoundException('No applicable ACE was found.'); + throw $noClassAces; } } @@ -177,7 +169,7 @@ class PermissionGrantingStrategy implements PermissionGrantingStrategyInterface return false; } - throw static::$noAceException; + throw new NoAceFoundException(); } /** diff --git a/src/Symfony/Component/Security/Acl/Exception/NoAceFoundException.php b/src/Symfony/Component/Security/Acl/Exception/NoAceFoundException.php index 0ecad61349..994efc012b 100644 --- a/src/Symfony/Component/Security/Acl/Exception/NoAceFoundException.php +++ b/src/Symfony/Component/Security/Acl/Exception/NoAceFoundException.php @@ -19,4 +19,8 @@ namespace Symfony\Component\Security\Acl\Exception; */ class NoAceFoundException extends Exception { + public function __construct() + { + parent::__construct('No applicable ACE was found.'); + } } \ No newline at end of file From 192592ec9b6382e4da72061a0c4571b79bfca0cb Mon Sep 17 00:00:00 2001 From: Johannes Schmitt Date: Wed, 20 Apr 2011 22:38:16 +0200 Subject: [PATCH 66/91] [Security/Core] force implementations to accept null values --- .../Component/Security/Core/SecurityContextInterface.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Symfony/Component/Security/Core/SecurityContextInterface.php b/src/Symfony/Component/Security/Core/SecurityContextInterface.php index a47c89dbcb..c54ca0e3c9 100644 --- a/src/Symfony/Component/Security/Core/SecurityContextInterface.php +++ b/src/Symfony/Component/Security/Core/SecurityContextInterface.php @@ -28,7 +28,7 @@ interface SecurityContextInterface * @param TokenInterface $token * @return void */ - function setToken(TokenInterface $token); + function setToken(TokenInterface $token = null); /** * Checks if the attributes are granted against the current authentication token and optionally supplied object. From f7d44148df19d1564f5ce326e080cca33d805e63 Mon Sep 17 00:00:00 2001 From: Fabien Potencier Date: Wed, 20 Apr 2011 22:49:56 +0200 Subject: [PATCH 67/91] [Routing] removed unused defaults variable --- .../Routing/Generator/Dumper/PhpGeneratorDumper.php | 12 +++--------- .../Component/Routing/Generator/UrlGenerator.php | 6 +----- .../Routing/Matcher/Dumper/PhpMatcherDumper.php | 3 +-- src/Symfony/Component/Routing/Matcher/UrlMatcher.php | 7 ++----- .../Routing/Fixtures/dumper/url_matcher1.php | 3 +-- .../Routing/Fixtures/dumper/url_matcher2.php | 3 +-- 6 files changed, 9 insertions(+), 25 deletions(-) diff --git a/src/Symfony/Component/Routing/Generator/Dumper/PhpGeneratorDumper.php b/src/Symfony/Component/Routing/Generator/Dumper/PhpGeneratorDumper.php index 51d8466ca9..4649ed961e 100644 --- a/src/Symfony/Component/Routing/Generator/Dumper/PhpGeneratorDumper.php +++ b/src/Symfony/Component/Routing/Generator/Dumper/PhpGeneratorDumper.php @@ -54,10 +54,7 @@ class PhpGeneratorDumper extends GeneratorDumper $compiledRoute = $route->compile(); $variables = str_replace("\n", '', var_export($compiledRoute->getVariables(), true)); - $defaultsMerge = ''; - foreach ($compiledRoute->getDefaults() as $key => $value) { - $defaultsMerge .= ' $defaults[\''.$key.'\'] = '.str_replace("\n", '', var_export($value, true)).';'."\n"; - } + $defaults = str_replace("\n", '', var_export($compiledRoute->getDefaults(), true)); $requirements = str_replace("\n", '', var_export($compiledRoute->getRequirements(), true)); $tokens = str_replace("\n", '', var_export($compiledRoute->getTokens(), true)); @@ -66,9 +63,7 @@ class PhpGeneratorDumper extends GeneratorDumper $methods[] = <<defaults; -$defaultsMerge - return array($variables, \$defaults, $requirements, $tokens); + return array($variables, $defaults, $requirements, $tokens); } EOF @@ -131,10 +126,9 @@ EOF; /** * Constructor. */ - public function __construct(RequestContext \$context, array \$defaults = array()) + public function __construct(RequestContext \$context) { \$this->context = \$context; - \$this->defaults = \$defaults; } EOF; diff --git a/src/Symfony/Component/Routing/Generator/UrlGenerator.php b/src/Symfony/Component/Routing/Generator/UrlGenerator.php index 0c5ba32c95..7f76361785 100644 --- a/src/Symfony/Component/Routing/Generator/UrlGenerator.php +++ b/src/Symfony/Component/Routing/Generator/UrlGenerator.php @@ -22,7 +22,6 @@ use Symfony\Component\Routing\RequestContext; */ class UrlGenerator implements UrlGeneratorInterface { - protected $defaults; protected $context; private $routes; @@ -33,13 +32,11 @@ class UrlGenerator implements UrlGeneratorInterface * * @param RouteCollection $routes A RouteCollection instance * @param RequestContext $context The context - * @param array $defaults The default values */ - public function __construct(RouteCollection $routes, RequestContext $context, array $defaults = array()) + public function __construct(RouteCollection $routes, RequestContext $context) { $this->routes = $routes; $this->context = $context; - $this->defaults = $defaults; $this->cache = array(); } @@ -82,7 +79,6 @@ class UrlGenerator implements UrlGeneratorInterface */ protected function doGenerate($variables, $defaults, $requirements, $tokens, $parameters, $name, $absolute) { - $defaults = array_merge($this->defaults, $defaults); $tparams = array_merge($defaults, $parameters); // all params must be given diff --git a/src/Symfony/Component/Routing/Matcher/Dumper/PhpMatcherDumper.php b/src/Symfony/Component/Routing/Matcher/Dumper/PhpMatcherDumper.php index 874c59c4ab..339715be64 100644 --- a/src/Symfony/Component/Routing/Matcher/Dumper/PhpMatcherDumper.php +++ b/src/Symfony/Component/Routing/Matcher/Dumper/PhpMatcherDumper.php @@ -195,10 +195,9 @@ EOF; /** * Constructor. */ - public function __construct(RequestContext \$context, array \$defaults = array()) + public function __construct(RequestContext \$context) { \$this->context = \$context; - \$this->defaults = \$defaults; } EOF; diff --git a/src/Symfony/Component/Routing/Matcher/UrlMatcher.php b/src/Symfony/Component/Routing/Matcher/UrlMatcher.php index c43c339291..41660584dd 100644 --- a/src/Symfony/Component/Routing/Matcher/UrlMatcher.php +++ b/src/Symfony/Component/Routing/Matcher/UrlMatcher.php @@ -24,7 +24,6 @@ use Symfony\Component\Routing\RequestContext; */ class UrlMatcher implements UrlMatcherInterface { - protected $defaults; protected $context; private $routes; @@ -34,13 +33,11 @@ class UrlMatcher implements UrlMatcherInterface * * @param RouteCollection $routes A RouteCollection instance * @param RequestContext $context The context - * @param array $defaults The default values */ - public function __construct(RouteCollection $routes, RequestContext $context, array $defaults = array()) + public function __construct(RouteCollection $routes, RequestContext $context) { $this->routes = $routes; $this->context = $context; - $this->defaults = $defaults; } /** @@ -95,7 +92,7 @@ class UrlMatcher implements UrlMatcherInterface protected function mergeDefaults($params, $defaults) { - $parameters = array_merge($this->defaults, $defaults); + $parameters = $defaults; foreach ($params as $key => $value) { if (!is_int($key)) { $parameters[$key] = urldecode($value); diff --git a/tests/Symfony/Tests/Component/Routing/Fixtures/dumper/url_matcher1.php b/tests/Symfony/Tests/Component/Routing/Fixtures/dumper/url_matcher1.php index b3fe2bd3b8..3250215125 100644 --- a/tests/Symfony/Tests/Component/Routing/Fixtures/dumper/url_matcher1.php +++ b/tests/Symfony/Tests/Component/Routing/Fixtures/dumper/url_matcher1.php @@ -15,10 +15,9 @@ class ProjectUrlMatcher extends Symfony\Component\Routing\Matcher\UrlMatcher /** * Constructor. */ - public function __construct(RequestContext $context, array $defaults = array()) + public function __construct(RequestContext $context) { $this->context = $context; - $this->defaults = $defaults; } public function match($pathinfo) diff --git a/tests/Symfony/Tests/Component/Routing/Fixtures/dumper/url_matcher2.php b/tests/Symfony/Tests/Component/Routing/Fixtures/dumper/url_matcher2.php index 60c3ed8fea..db003bb89d 100644 --- a/tests/Symfony/Tests/Component/Routing/Fixtures/dumper/url_matcher2.php +++ b/tests/Symfony/Tests/Component/Routing/Fixtures/dumper/url_matcher2.php @@ -15,10 +15,9 @@ class ProjectUrlMatcher extends Symfony\Tests\Component\Routing\Fixtures\Redirec /** * Constructor. */ - public function __construct(RequestContext $context, array $defaults = array()) + public function __construct(RequestContext $context) { $this->context = $context; - $this->defaults = $defaults; } public function match($pathinfo) From c6dcf0f8f327adaa5a38033f6b091cf94f47c186 Mon Sep 17 00:00:00 2001 From: Fabien Potencier Date: Wed, 20 Apr 2011 23:01:05 +0200 Subject: [PATCH 68/91] [Routing] added a way to set default parameters that are applied when generating URLs --- .../Routing/Generator/UrlGenerator.php | 3 +- .../Component/Routing/RequestContext.php | 63 +++++++++++++++++++ 2 files changed, 65 insertions(+), 1 deletion(-) diff --git a/src/Symfony/Component/Routing/Generator/UrlGenerator.php b/src/Symfony/Component/Routing/Generator/UrlGenerator.php index 7f76361785..d921a64d76 100644 --- a/src/Symfony/Component/Routing/Generator/UrlGenerator.php +++ b/src/Symfony/Component/Routing/Generator/UrlGenerator.php @@ -79,7 +79,8 @@ class UrlGenerator implements UrlGeneratorInterface */ protected function doGenerate($variables, $defaults, $requirements, $tokens, $parameters, $name, $absolute) { - $tparams = array_merge($defaults, $parameters); + $parameters = array_replace($this->context->getParameters(), $parameters); + $tparams = array_replace($defaults, $parameters); // all params must be given if ($diff = array_diff_key($variables, $tparams)) { diff --git a/src/Symfony/Component/Routing/RequestContext.php b/src/Symfony/Component/Routing/RequestContext.php index 6406f75ab1..1110efe222 100644 --- a/src/Symfony/Component/Routing/RequestContext.php +++ b/src/Symfony/Component/Routing/RequestContext.php @@ -24,6 +24,7 @@ class RequestContext private $scheme; private $httpPort; private $httpsPort; + private $parameters; /** * Constructor. @@ -43,6 +44,7 @@ class RequestContext $this->scheme = strtolower($scheme); $this->httpPort = $httpPort; $this->httpsPort = $httpsPort; + $this->parameters = array(); } /** @@ -164,4 +166,65 @@ class RequestContext { $this->httpsPort = $httpsPort; } + + /** + * Returns the parameters. + * + * @return array The parameters + */ + public function getParameters() + { + return $this->parameters; + } + + /** + * Sets the parameters. + * + * This method implements a fluent interface. + * + * @param array $parameters The parameters + * + * @return Route The current Route instance + */ + public function setParameters(array $parameters) + { + $this->parameters = $parameters; + + return $this; + } + + /** + * Gets a parameter value. + * + * @param string $name A parameter name + * + * @return mixed The parameter value + */ + public function getParameter($name) + { + return isset($this->parameters[$name]) ? $this->parameters[$name] : null; + } + + /** + * Checks if a parameter value is set for the given parameter. + * + * @param string $name A parameter name + * + * @return Boolean true if the parameter value is set, false otherwise + */ + public function hasParameter($name) + { + return array_key_exists($name, $this->parameters); + } + + /** + * Sets a parameter value. + * + * @param string $name A parameter name + * @param mixed $parameter The parameter value + */ + public function setParameter($name, $parameter) + { + $this->parameters[$name] = $parameter; + } } From 7266b41aded2db6a88f980431752f25688cb204b Mon Sep 17 00:00:00 2001 From: Fabien Potencier Date: Wed, 20 Apr 2011 23:01:31 +0200 Subject: [PATCH 69/91] [FrameworkBundle] added the current locale as the default value for _locale when generating routes --- .../FrameworkBundle/RequestListener.php | 19 +++++++++++++------ 1 file changed, 13 insertions(+), 6 deletions(-) diff --git a/src/Symfony/Bundle/FrameworkBundle/RequestListener.php b/src/Symfony/Bundle/FrameworkBundle/RequestListener.php index 80eec52471..ac68a2e57c 100644 --- a/src/Symfony/Bundle/FrameworkBundle/RequestListener.php +++ b/src/Symfony/Bundle/FrameworkBundle/RequestListener.php @@ -77,14 +77,20 @@ class RequestListener if ($master) { // set the context even if the parsing does not need to be done // to have correct link generation - $this->router->setContext(new RequestContext( + $context = new RequestContext( $request->getBaseUrl(), $request->getMethod(), $request->getHost(), $request->getScheme(), $this->httpPort, $this->httpsPort - )); + ); + + if ($session = $request->getSession()) { + $context->setParameter('_locale', $session->getLocale()); + } + + $this->router->setContext($context); } if ($request->attributes->has('_controller')) { @@ -101,10 +107,6 @@ class RequestListener } $request->attributes->add($parameters); - - if ($locale = $request->attributes->get('_locale')) { - $request->getSession()->setLocale($locale); - } } catch (NotFoundException $e) { $message = sprintf('No route found for "%s %s"', $request->getMethod(), $request->getPathInfo()); if (null !== $this->logger) { @@ -118,6 +120,11 @@ class RequestListener } throw new MethodNotAllowedHttpException($e->getAllowedMethods(), $message, $e); } + + if ($master && $locale = $request->attributes->get('_locale')) { + $request->getSession()->setLocale($locale); + $context->setParameter('_locale', $locale); + } } private function parametersToString(array $parameters) From a5aba7dbd7f1b0be75bbc7b4e66da5f3dde993d9 Mon Sep 17 00:00:00 2001 From: Ryan Weaver Date: Wed, 20 Apr 2011 16:08:55 -0500 Subject: [PATCH 70/91] [FrameworkBundle] Upating XML test fixtures for newer namespace This wasn't actually affecting anything (which is why it wasn't caught), but this is more correct. --- .../DependencyInjection/Fixtures/xml/full.xml | 52 +++++++++---------- .../Fixtures/xml/session_pdo.xml | 8 +-- .../Fixtures/xml/validation_annotations.xml | 12 ++--- 3 files changed, 36 insertions(+), 36 deletions(-) diff --git a/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/Fixtures/xml/full.xml b/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/Fixtures/xml/full.xml index 0c4511af8a..481dbfb58a 100644 --- a/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/Fixtures/xml/full.xml +++ b/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/Fixtures/xml/full.xml @@ -2,33 +2,33 @@ - - - - - - - - loader.foo - loader.bar - php - twig - http://cdn.example.com - - http://images1.example.com - http://images2.example.com - - - - http://bar1.example.com - http://bar2.example.com - - - - - + + + + + + + + loader.foo + loader.bar + php + twig + http://cdn.example.com + + http://images1.example.com + http://images2.example.com + + + + http://bar1.example.com + http://bar2.example.com + + + + + diff --git a/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/Fixtures/xml/session_pdo.xml b/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/Fixtures/xml/session_pdo.xml index f54fb261d3..cb088ee787 100644 --- a/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/Fixtures/xml/session_pdo.xml +++ b/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/Fixtures/xml/session_pdo.xml @@ -2,11 +2,11 @@ - - - + + + diff --git a/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/Fixtures/xml/validation_annotations.xml b/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/Fixtures/xml/validation_annotations.xml index aef3e01f09..8980e16a3b 100644 --- a/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/Fixtures/xml/validation_annotations.xml +++ b/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/Fixtures/xml/validation_annotations.xml @@ -2,13 +2,13 @@ - - - Application\Validator\Constraints\ - - + + + Application\Validator\Constraints\ + + From f7b1839296820c1a7868b3736d8ec318b13118f6 Mon Sep 17 00:00:00 2001 From: Victor Berchet Date: Wed, 20 Apr 2011 23:28:19 +0200 Subject: [PATCH 71/91] [AsseticBundle] Update the cache warmer tests --- .../AssetManagerCacheWarmerTest.php | 21 ++++++++++++-- .../AssetWriterCacheWarmerTest.php | 28 +++++++++++++++---- 2 files changed, 41 insertions(+), 8 deletions(-) diff --git a/src/Symfony/Bundle/AsseticBundle/Tests/CacheWarmer/AssetManagerCacheWarmerTest.php b/src/Symfony/Bundle/AsseticBundle/Tests/CacheWarmer/AssetManagerCacheWarmerTest.php index 65b14bff26..02b959890c 100644 --- a/src/Symfony/Bundle/AsseticBundle/Tests/CacheWarmer/AssetManagerCacheWarmerTest.php +++ b/src/Symfony/Bundle/AsseticBundle/Tests/CacheWarmer/AssetManagerCacheWarmerTest.php @@ -24,13 +24,28 @@ class AssetManagerCacheWarmerTest extends \PHPUnit_Framework_TestCase public function testWarmUp() { - $am = $this->getMockBuilder('Assetic\\Factory\\LazyAssetManager') + $am = $this + ->getMockBuilder('Assetic\\Factory\\LazyAssetManager') ->disableOriginalConstructor() - ->getMock(); + ->getMock() + ; $am->expects($this->once())->method('load'); + + $container = $this + ->getMockBuilder('Symfony\\Component\\DependencyInjection\\Container') + ->setConstructorArgs(array()) + ->getMock() + ; + + $container + ->expects($this->once()) + ->method('get') + ->with('assetic.asset_manager') + ->will($this->returnValue($am)) + ; - $warmer = new AssetManagerCacheWarmer($am); + $warmer = new AssetManagerCacheWarmer($container); $warmer->warmUp('/path/to/cache'); } } diff --git a/src/Symfony/Bundle/AsseticBundle/Tests/CacheWarmer/AssetWriterCacheWarmerTest.php b/src/Symfony/Bundle/AsseticBundle/Tests/CacheWarmer/AssetWriterCacheWarmerTest.php index 35e67cd129..d8b78c0e6f 100644 --- a/src/Symfony/Bundle/AsseticBundle/Tests/CacheWarmer/AssetWriterCacheWarmerTest.php +++ b/src/Symfony/Bundle/AsseticBundle/Tests/CacheWarmer/AssetWriterCacheWarmerTest.php @@ -25,15 +25,33 @@ class AssetWriterCacheWarmerTest extends \PHPUnit_Framework_TestCase public function testWarmUp() { $am = $this->getMock('Assetic\\AssetManager'); - $writer = $this->getMockBuilder('Assetic\\AssetWriter') + + $writer = $this + ->getMockBuilder('Assetic\\AssetWriter') ->disableOriginalConstructor() - ->getMock(); + ->getMock() + ; - $writer->expects($this->once()) + $writer + ->expects($this->once()) ->method('writeManagerAssets') - ->with($am); + ->with($am) + ; + + $container = $this + ->getMockBuilder('Symfony\\Component\\DependencyInjection\\Container') + ->setConstructorArgs(array()) + ->getMock() + ; + + $container + ->expects($this->once()) + ->method('get') + ->with('assetic.asset_manager') + ->will($this->returnValue($am)) + ; - $warmer = new AssetWriterCacheWarmer($am, $writer); + $warmer = new AssetWriterCacheWarmer($container, $writer); $warmer->warmUp('/path/to/cache'); } } From 7ed8ea25d873637b8c1c1e19355616dbdf344dc6 Mon Sep 17 00:00:00 2001 From: Bertrand Zuchuat Date: Wed, 20 Apr 2011 23:45:36 +0200 Subject: [PATCH 72/91] [Container] Added function array_unique on getServiceIds to return only one service name --- src/Symfony/Component/DependencyInjection/Container.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Symfony/Component/DependencyInjection/Container.php b/src/Symfony/Component/DependencyInjection/Container.php index 1cd5733aaa..01fdc29fbb 100644 --- a/src/Symfony/Component/DependencyInjection/Container.php +++ b/src/Symfony/Component/DependencyInjection/Container.php @@ -256,7 +256,7 @@ class Container implements ContainerInterface } } - return array_merge($ids, array_keys($this->services)); + return array_unique(array_merge($ids, array_keys($this->services))); } /** From 54b77d24dd7e0119d2a2654407db6fa991a5ab9c Mon Sep 17 00:00:00 2001 From: Fabien Potencier Date: Thu, 21 Apr 2011 09:01:11 +0200 Subject: [PATCH 73/91] made the %count% variable automatically available when using the transchoice filter (similar to how the tag works) --- src/Symfony/Bridge/Twig/Extension/TranslationExtension.php | 2 +- .../Tests/Bridge/Twig/Extension/TranslationExtensionTest.php | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/src/Symfony/Bridge/Twig/Extension/TranslationExtension.php b/src/Symfony/Bridge/Twig/Extension/TranslationExtension.php index 8b6dfa9e60..6dc59f821f 100644 --- a/src/Symfony/Bridge/Twig/Extension/TranslationExtension.php +++ b/src/Symfony/Bridge/Twig/Extension/TranslationExtension.php @@ -70,7 +70,7 @@ class TranslationExtension extends \Twig_Extension public function transchoice($message, $count, array $arguments = array(), $domain = "messages") { - return $this->translator->transChoice($message, $count, $arguments, $domain); + return $this->translator->transChoice($message, $count, array_merge(array('%count%' => $count), $arguments), $domain); } /** diff --git a/tests/Symfony/Tests/Bridge/Twig/Extension/TranslationExtensionTest.php b/tests/Symfony/Tests/Bridge/Twig/Extension/TranslationExtensionTest.php index a3b6cb7df2..cf21647b2c 100644 --- a/tests/Symfony/Tests/Bridge/Twig/Extension/TranslationExtensionTest.php +++ b/tests/Symfony/Tests/Bridge/Twig/Extension/TranslationExtensionTest.php @@ -84,8 +84,8 @@ class TranslationExtensionTest extends TestCase array('{% set vars = { \'%name%\': \'Symfony2\' } %}{{ hello|trans(vars) }}', 'Hello Symfony2', array('hello' => 'Hello %name%')), // transchoice filter - array('{{ "{0} There is no apples|{1} There is one apple|]1,Inf] There is %count% apples"|transchoice(count, {\'%count%\': count}) }}', 'There is 5 apples', array('count' => 5)), - array('{{ text|transchoice(5, {\'%count%\': 5, \'%name%\': \'Symfony2\'}) }}', 'There is 5 apples (Symfony2)', array('text' => '{0} There is no apples|{1} There is one apple|]1,Inf] There is %count% apples (%name%)')), + array('{{ "{0} There is no apples|{1} There is one apple|]1,Inf] There is %count% apples"|transchoice(count) }}', 'There is 5 apples', array('count' => 5)), + array('{{ text|transchoice(5, {\'%name%\': \'Symfony2\'}) }}', 'There is 5 apples (Symfony2)', array('text' => '{0} There is no apples|{1} There is one apple|]1,Inf] There is %count% apples (%name%)')), ); } From cad6643e776193e5a888b6fbd965aa8058e58bff Mon Sep 17 00:00:00 2001 From: Fabien Potencier Date: Thu, 21 Apr 2011 09:03:30 +0200 Subject: [PATCH 74/91] simplified exceptions as Twig is now smart enough to automatically add line information --- .../Bridge/Twig/TokenParser/TransChoiceTokenParser.php | 2 +- src/Symfony/Bridge/Twig/TokenParser/TransTokenParser.php | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/src/Symfony/Bridge/Twig/TokenParser/TransChoiceTokenParser.php b/src/Symfony/Bridge/Twig/TokenParser/TransChoiceTokenParser.php index 2e14c98399..351e660ccd 100644 --- a/src/Symfony/Bridge/Twig/TokenParser/TransChoiceTokenParser.php +++ b/src/Symfony/Bridge/Twig/TokenParser/TransChoiceTokenParser.php @@ -64,7 +64,7 @@ class TransChoiceTokenParser extends TransTokenParser } if (!$body instanceof \Twig_Node_Text && !$body instanceof \Twig_Node_Expression) { - throw new \Twig_Error_Syntax(sprintf('A message must be a simple text (line %s)', $lineno), -1); + throw new \Twig_Error_Syntax('A message must be a simple text.'); } $stream->expect(\Twig_Token::BLOCK_END_TYPE); diff --git a/src/Symfony/Bridge/Twig/TokenParser/TransTokenParser.php b/src/Symfony/Bridge/Twig/TokenParser/TransTokenParser.php index 0814fc1d01..14e15b403e 100644 --- a/src/Symfony/Bridge/Twig/TokenParser/TransTokenParser.php +++ b/src/Symfony/Bridge/Twig/TokenParser/TransTokenParser.php @@ -53,7 +53,7 @@ class TransTokenParser extends \Twig_TokenParser $stream->next(); $domain = $this->parser->getExpressionParser()->parseExpression(); } elseif (!$stream->test(\Twig_Token::BLOCK_END_TYPE)) { - throw new \Twig_Error_Syntax(sprintf('Unexpected token. Twig was looking for the "from" keyword line %s)', $lineno), -1); + throw new \Twig_Error_Syntax('Unexpected token. Twig was looking for the "with" or "from" keyword.'); } } @@ -64,7 +64,7 @@ class TransTokenParser extends \Twig_TokenParser } if (!$body instanceof \Twig_Node_Text && !$body instanceof \Twig_Node_Expression) { - throw new \Twig_Error_Syntax('A message must be a simple text', -1); + throw new \Twig_Error_Syntax('A message must be a simple text'); } $stream->expect(\Twig_Token::BLOCK_END_TYPE); From 286c45733e47d20d0b40e8454492a5fb66d80875 Mon Sep 17 00:00:00 2001 From: Fabien Potencier Date: Thu, 21 Apr 2011 09:04:16 +0200 Subject: [PATCH 75/91] removed the possibility to pass a message to the trans tag The trans tag should only be used with static texts as automatic output escaping does not occur. --- UPDATE.md | 18 ++++++++++++++++-- .../Twig/Extension/TranslationExtension.php | 2 +- .../Twig/TokenParser/TransTokenParser.php | 18 +++++------------- .../Extension/TranslationExtensionTest.php | 7 ------- 4 files changed, 22 insertions(+), 23 deletions(-) diff --git a/UPDATE.md b/UPDATE.md index 1d08d5854f..eef0f78c18 100644 --- a/UPDATE.md +++ b/UPDATE.md @@ -6,8 +6,22 @@ one. It only discusses changes that need to be done when using the "public" API of the framework. If you "hack" the core, you should probably follow the timeline closely anyway. -PR12 to PR13 ------------- +PR12 to beta1 +------------- + +* The `trans` tag does not accept a message as an argument anymore: + + {% trans "foo" %} + {% trans foo %} + + Use the long version the tags or the filter instead: + + {% trans %}foo{% endtrans %} + {{ foo|trans }} + + This has been done to clarify the usage of the tag and filter and also to + make it clearer when the automatic output escaping rules are applied (see + the doc for more information). * Some methods in the DependencyInjection component's ContainerBuilder and Definition classes have been renamed to be more specific and consistent: diff --git a/src/Symfony/Bridge/Twig/Extension/TranslationExtension.php b/src/Symfony/Bridge/Twig/Extension/TranslationExtension.php index 6dc59f821f..7cc5cc6b78 100644 --- a/src/Symfony/Bridge/Twig/Extension/TranslationExtension.php +++ b/src/Symfony/Bridge/Twig/Extension/TranslationExtension.php @@ -53,7 +53,7 @@ class TranslationExtension extends \Twig_Extension public function getTokenParsers() { return array( - // {% trans "Symfony is great!" %} + // {% trans %}Symfony is great!{% endtrans %} new TransTokenParser(), // {% transchoice count %} diff --git a/src/Symfony/Bridge/Twig/TokenParser/TransTokenParser.php b/src/Symfony/Bridge/Twig/TokenParser/TransTokenParser.php index 14e15b403e..c3450f67ab 100644 --- a/src/Symfony/Bridge/Twig/TokenParser/TransTokenParser.php +++ b/src/Symfony/Bridge/Twig/TokenParser/TransTokenParser.php @@ -36,20 +36,14 @@ class TransTokenParser extends \Twig_TokenParser $vars = new \Twig_Node_Expression_Array(array(), $lineno); $domain = new \Twig_Node_Expression_Constant('messages', $lineno); if (!$stream->test(\Twig_Token::BLOCK_END_TYPE)) { - if (!$stream->test('from') && !$stream->test('with')) { - // {% trans "message" %} - // {% trans message %} - $body = $this->parser->getExpressionParser()->parseExpression(); - } - if ($stream->test('with')) { - // {% trans "message" with vars %} + // {% trans with vars %} $stream->next(); $vars = $this->parser->getExpressionParser()->parseExpression(); } if ($stream->test('from')) { - // {% trans "message" from "messages" %} + // {% trans from "messages" %} $stream->next(); $domain = $this->parser->getExpressionParser()->parseExpression(); } elseif (!$stream->test(\Twig_Token::BLOCK_END_TYPE)) { @@ -57,11 +51,9 @@ class TransTokenParser extends \Twig_TokenParser } } - if (null === $body) { - // {% trans %}message{% endtrans %} - $stream->expect(\Twig_Token::BLOCK_END_TYPE); - $body = $this->parser->subparse(array($this, 'decideTransFork'), true); - } + // {% trans %}message{% endtrans %} + $stream->expect(\Twig_Token::BLOCK_END_TYPE); + $body = $this->parser->subparse(array($this, 'decideTransFork'), true); if (!$body instanceof \Twig_Node_Text && !$body instanceof \Twig_Node_Expression) { throw new \Twig_Error_Syntax('A message must be a simple text'); diff --git a/tests/Symfony/Tests/Bridge/Twig/Extension/TranslationExtensionTest.php b/tests/Symfony/Tests/Bridge/Twig/Extension/TranslationExtensionTest.php index cf21647b2c..c141336bff 100644 --- a/tests/Symfony/Tests/Bridge/Twig/Extension/TranslationExtensionTest.php +++ b/tests/Symfony/Tests/Bridge/Twig/Extension/TranslationExtensionTest.php @@ -47,16 +47,9 @@ class TranslationExtensionTest extends TestCase { return array( // trans tag - array('{% trans "Hello" %}', 'Hello'), - array('{% trans "Hello %name%" %}', 'Hello Symfony2', array('name' => 'Symfony2')), - array('{% trans name %}', 'Symfony2', array('name' => 'Symfony2')), - array('{% trans hello with { \'%name%\': \'Symfony2\' } %}', 'Hello Symfony2', array('hello' => 'Hello %name%')), - array('{% set vars = { \'%name%\': \'Symfony2\' } %}{% trans hello with vars %}', 'Hello Symfony2', array('hello' => 'Hello %name%')), - array('{% trans %}Hello{% endtrans %}', 'Hello'), array('{% trans %}%name%{% endtrans %}', 'Symfony2', array('name' => 'Symfony2')), - array('{% trans "Hello" from elsewhere %}', 'Hello'), array('{% trans from elsewhere %}Hello{% endtrans %}', 'Hello'), array('{% trans %}Hello %name%{% endtrans %}', 'Hello Symfony2', array('name' => 'Symfony2')), From 7e3315972383f38608e17b95cc94adf68fdf3a83 Mon Sep 17 00:00:00 2001 From: Fabien Potencier Date: Thu, 21 Apr 2011 09:52:35 +0200 Subject: [PATCH 76/91] [Routing] the global parameters must not be added in the QS when generating URLs --- .../Routing/Generator/UrlGenerator.php | 3 ++- .../Routing/Generator/UrlGeneratorTest.php | 24 +++++++++++++++++++ 2 files changed, 26 insertions(+), 1 deletion(-) diff --git a/src/Symfony/Component/Routing/Generator/UrlGenerator.php b/src/Symfony/Component/Routing/Generator/UrlGenerator.php index d921a64d76..b9e294362d 100644 --- a/src/Symfony/Component/Routing/Generator/UrlGenerator.php +++ b/src/Symfony/Component/Routing/Generator/UrlGenerator.php @@ -79,6 +79,7 @@ class UrlGenerator implements UrlGeneratorInterface */ protected function doGenerate($variables, $defaults, $requirements, $tokens, $parameters, $name, $absolute) { + $originParameters = $parameters; $parameters = array_replace($this->context->getParameters(), $parameters); $tparams = array_replace($defaults, $parameters); @@ -121,7 +122,7 @@ class UrlGenerator implements UrlGeneratorInterface } // add a query string if needed - if ($extra = array_diff_key($parameters, $variables, $defaults)) { + if ($extra = array_diff_key($originParameters, $variables, $defaults)) { $url .= '?'.http_build_query($extra); } diff --git a/tests/Symfony/Tests/Component/Routing/Generator/UrlGeneratorTest.php b/tests/Symfony/Tests/Component/Routing/Generator/UrlGeneratorTest.php index 32015e7aa8..03d9f997da 100644 --- a/tests/Symfony/Tests/Component/Routing/Generator/UrlGeneratorTest.php +++ b/tests/Symfony/Tests/Component/Routing/Generator/UrlGeneratorTest.php @@ -90,6 +90,30 @@ class UrlGeneratorTest extends \PHPUnit_Framework_TestCase $this->assertEquals('http://localhost/app.php/testing?foo=bar', $url); } + public function testUrlWithExtraParametersFromGlobals() + { + $routes = $this->getRoutes('test', new Route('/testing')); + $generator = $this->getGenerator($routes); + $context = new RequestContext('/app.php'); + $context->setParameter('bar', 'bar'); + $generator->setContext($context); + $url = $generator->generate('test', array('foo' => 'bar')); + + $this->assertEquals('/app.php/testing?foo=bar', $url); + } + + public function testUrlWithGlobalParameter() + { + $routes = $this->getRoutes('test', new Route('/testing/{foo}')); + $generator = $this->getGenerator($routes); + $context = new RequestContext('/app.php'); + $context->setParameter('foo', 'bar'); + $generator->setContext($context); + $url = $generator->generate('test', array()); + + $this->assertEquals('/app.php/testing/bar', $url); + } + /** * @expectedException \InvalidArgumentException */ From 8ad93095d489a14969304d9bd30cf2d5337a2198 Mon Sep 17 00:00:00 2001 From: Kris Wallsmith Date: Thu, 21 Apr 2011 05:41:45 -0700 Subject: [PATCH 77/91] [AsseticBundle] updated twig integration to check debug mode at runtime rather than compile time since twig cannot vary its cache by debug mode --- .../Controller/AsseticController.php | 12 +++- .../DependencyInjection/AsseticExtension.php | 2 - .../Resources/config/templating_twig.xml | 4 +- .../AsseticBundle/Routing/AsseticLoader.php | 35 +++++++++--- .../Templating/DynamicAsseticHelper.php | 2 +- .../AsseticBundle/Tests/FunctionalTest.php | 19 +++++-- .../AsseticBundle/Twig/AsseticExtension.php | 49 ++++++++++++++++ .../Bundle/AsseticBundle/Twig/AsseticNode.php | 57 +++++++++++++++++++ .../AsseticBundle/Twig/AsseticTokenParser.php | 28 +++++++++ .../AsseticBundle/Twig/DynamicExtension.php | 32 ----------- .../Bundle/AsseticBundle/Twig/DynamicNode.php | 36 ------------ .../AsseticBundle/Twig/DynamicTokenParser.php | 27 --------- .../AsseticBundle/Twig/StaticExtension.php | 32 ----------- .../Bundle/AsseticBundle/Twig/StaticNode.php | 37 ------------ .../AsseticBundle/Twig/StaticTokenParser.php | 27 --------- 15 files changed, 187 insertions(+), 212 deletions(-) create mode 100644 src/Symfony/Bundle/AsseticBundle/Twig/AsseticExtension.php create mode 100644 src/Symfony/Bundle/AsseticBundle/Twig/AsseticNode.php create mode 100644 src/Symfony/Bundle/AsseticBundle/Twig/AsseticTokenParser.php delete mode 100644 src/Symfony/Bundle/AsseticBundle/Twig/DynamicExtension.php delete mode 100644 src/Symfony/Bundle/AsseticBundle/Twig/DynamicNode.php delete mode 100644 src/Symfony/Bundle/AsseticBundle/Twig/DynamicTokenParser.php delete mode 100644 src/Symfony/Bundle/AsseticBundle/Twig/StaticExtension.php delete mode 100644 src/Symfony/Bundle/AsseticBundle/Twig/StaticNode.php delete mode 100644 src/Symfony/Bundle/AsseticBundle/Twig/StaticTokenParser.php diff --git a/src/Symfony/Bundle/AsseticBundle/Controller/AsseticController.php b/src/Symfony/Bundle/AsseticBundle/Controller/AsseticController.php index b34a845241..136ef133d6 100644 --- a/src/Symfony/Bundle/AsseticBundle/Controller/AsseticController.php +++ b/src/Symfony/Bundle/AsseticBundle/Controller/AsseticController.php @@ -36,13 +36,21 @@ class AsseticController $this->cache = $cache; } - public function render($name) + public function render($name, $pos = null) { if (!$this->am->has($name)) { - throw new NotFoundHttpException('Asset Not Found'); + throw new NotFoundHttpException(sprintf('The "%s" asset could not be found.', $name)); } $asset = $this->getAsset($name); + if (null !== $pos) { + $leaves = array_values(iterator_to_array($asset)); + if (!isset($leaves[$pos])) { + throw new NotFoundHttpException(sprintf('The "%s" asset does not include a leaf at position %d.', $name, $pos)); + } + $asset = $leaves[$pos]; + } + $response = $this->createResponse(); // last-modified diff --git a/src/Symfony/Bundle/AsseticBundle/DependencyInjection/AsseticExtension.php b/src/Symfony/Bundle/AsseticBundle/DependencyInjection/AsseticExtension.php index 19213c6aee..1284628dde 100644 --- a/src/Symfony/Bundle/AsseticBundle/DependencyInjection/AsseticExtension.php +++ b/src/Symfony/Bundle/AsseticBundle/DependencyInjection/AsseticExtension.php @@ -74,12 +74,10 @@ class AsseticExtension extends Extension // choose dynamic or static if ($parameterBag->resolveValue($parameterBag->get('assetic.use_controller'))) { $loader->load('controller.xml'); - $container->setParameter('assetic.twig_extension.class', '%assetic.twig_extension.dynamic.class%'); $container->getDefinition('assetic.helper.dynamic')->addTag('templating.helper', array('alias' => 'assetic')); $container->removeDefinition('assetic.helper.static'); } else { $loader->load('asset_writer.xml'); - $container->setParameter('assetic.twig_extension.class', '%assetic.twig_extension.static.class%'); $container->getDefinition('assetic.helper.static')->addTag('templating.helper', array('alias' => 'assetic')); $container->removeDefinition('assetic.helper.dynamic'); } diff --git a/src/Symfony/Bundle/AsseticBundle/Resources/config/templating_twig.xml b/src/Symfony/Bundle/AsseticBundle/Resources/config/templating_twig.xml index 5e3d070eb4..a2340dc316 100644 --- a/src/Symfony/Bundle/AsseticBundle/Resources/config/templating_twig.xml +++ b/src/Symfony/Bundle/AsseticBundle/Resources/config/templating_twig.xml @@ -5,8 +5,7 @@ xsi:schemaLocation="http://symfony.com/schema/dic/services http://symfony.com/schema/dic/services/services-1.0.xsd"> - Symfony\Bundle\AsseticBundle\Twig\DynamicExtension - Symfony\Bundle\AsseticBundle\Twig\StaticExtension + Symfony\Bundle\AsseticBundle\Twig\AsseticExtension Assetic\Extension\Twig\TwigFormulaLoader @@ -16,6 +15,7 @@ %assetic.debug% + %assetic.use_controller%
diff --git a/src/Symfony/Bundle/AsseticBundle/Routing/AsseticLoader.php b/src/Symfony/Bundle/AsseticBundle/Routing/AsseticLoader.php index 763ef31be4..214c9bc8fe 100644 --- a/src/Symfony/Bundle/AsseticBundle/Routing/AsseticLoader.php +++ b/src/Symfony/Bundle/AsseticBundle/Routing/AsseticLoader.php @@ -11,6 +11,7 @@ namespace Symfony\Bundle\AsseticBundle\Routing; +use Assetic\Asset\AssetInterface; use Assetic\Factory\LazyAssetManager; use Symfony\Component\Config\Loader\Loader; use Symfony\Component\Config\Resource\FileResource; @@ -62,22 +63,40 @@ class AsseticLoader extends Loader // routes foreach ($this->am->getNames() as $name) { $asset = $this->am->get($name); + $formula = $this->am->getFormula($name); - $defaults = array( - '_controller' => 'assetic.controller:render', - 'name' => $name, - ); + $this->loadRouteForAsset($routes, $asset, $name); - if ($extension = pathinfo($asset->getTargetUrl(), PATHINFO_EXTENSION)) { - $defaults['_format'] = $extension; + // add a route for each "leaf" in debug mode + if (isset($formula[2]['debug']) ? $formula[2]['debug'] : $this->am->isDebug()) { + $i = 0; + foreach ($asset as $leaf) { + $pos = $i++; + $this->loadRouteForAsset($routes, $leaf, $name.'_'.$pos, $pos); + } } - - $routes->add('assetic_'.$name, new Route($asset->getTargetUrl(), $defaults)); } return $routes; } + private function loadRouteForAsset(RouteCollection $routes, AssetInterface $asset, $name, $pos = null) + { + $defaults = array( + '_controller' => 'assetic.controller:render', + 'name' => $name, + 'pos' => $pos, + ); + + $pattern = $asset->getTargetUrl(); + + if ($format = pathinfo($pattern, PATHINFO_EXTENSION)) { + $defaults['_format'] = $format; + } + + $routes->add('_assetic_'.$name, new Route($pattern, $defaults)); + } + public function supports($resource, $type = null) { return 'assetic' == $type; diff --git a/src/Symfony/Bundle/AsseticBundle/Templating/DynamicAsseticHelper.php b/src/Symfony/Bundle/AsseticBundle/Templating/DynamicAsseticHelper.php index e1ad188abe..a3dad04501 100644 --- a/src/Symfony/Bundle/AsseticBundle/Templating/DynamicAsseticHelper.php +++ b/src/Symfony/Bundle/AsseticBundle/Templating/DynamicAsseticHelper.php @@ -40,6 +40,6 @@ class DynamicAsseticHelper extends AsseticHelper protected function getAssetUrl(AssetInterface $asset, $options = array()) { - return $this->routerHelper->generate('assetic_'.$options['name']); + return $this->routerHelper->generate('_assetic_'.$options['name']); } } diff --git a/src/Symfony/Bundle/AsseticBundle/Tests/FunctionalTest.php b/src/Symfony/Bundle/AsseticBundle/Tests/FunctionalTest.php index 76a6c600a0..3c9ba424ff 100644 --- a/src/Symfony/Bundle/AsseticBundle/Tests/FunctionalTest.php +++ b/src/Symfony/Bundle/AsseticBundle/Tests/FunctionalTest.php @@ -44,7 +44,7 @@ class FunctionalTest extends \PHPUnit_Framework_TestCase } /** - * @dataProvider provideDebugAndAssetCount + * @dataProvider provideAmDebugAndAssetCount */ public function testKernel($debug, $count) { @@ -55,7 +55,7 @@ class FunctionalTest extends \PHPUnit_Framework_TestCase } /** - * @dataProvider provideDebugAndAssetCount + * @dataProvider provideRouterDebugAndAssetCount */ public function testRoutes($debug, $count) { @@ -64,7 +64,7 @@ class FunctionalTest extends \PHPUnit_Framework_TestCase $matches = 0; foreach (array_keys($kernel->getContainer()->get('router')->getRouteCollection()->all()) as $name) { - if (0 === strpos($name, 'assetic_')) { + if (0 === strpos($name, '_assetic_')) { ++$matches; } } @@ -102,11 +102,18 @@ class FunctionalTest extends \PHPUnit_Framework_TestCase $this->assertEquals(2, count($crawler->filter('script[src$=".js"]'))); } - public function provideDebugAndAssetCount() + public function provideAmDebugAndAssetCount() { - // totals include assets defined in both php and twig templates return array( - array(true, 6), + array(true, 3), + array(false, 3), + ); + } + + public function provideRouterDebugAndAssetCount() + { + return array( + array(true, 9), array(false, 3), ); } diff --git a/src/Symfony/Bundle/AsseticBundle/Twig/AsseticExtension.php b/src/Symfony/Bundle/AsseticBundle/Twig/AsseticExtension.php new file mode 100644 index 0000000000..e5302ed71c --- /dev/null +++ b/src/Symfony/Bundle/AsseticBundle/Twig/AsseticExtension.php @@ -0,0 +1,49 @@ + + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace Symfony\Bundle\AsseticBundle\Twig; + +use Assetic\Extension\Twig\AsseticExtension as BaseAsseticExtension; +use Assetic\Factory\AssetFactory; + +/** + * Assetic extension. + * + * @author Kris Wallsmith + */ +class AsseticExtension extends BaseAsseticExtension +{ + private $useController; + + public function __construct(AssetFactory $factory, $debug = false, $useController = false) + { + parent::__construct($factory, $debug); + + $this->useController = $useController; + } + + public function getTokenParsers() + { + return array( + new AsseticTokenParser($this->factory, 'javascripts', 'js/*.js', false, array('package')), + new AsseticTokenParser($this->factory, 'stylesheets', 'css/*.css', false, array('package')), + new AsseticTokenParser($this->factory, 'image', 'images/*', true, array('package')), + ); + } + + public function getGlobals() + { + $globals = parent::getGlobals(); + $globals['assetic']['use_controller'] = $this->useController; + + return $globals; + } +} diff --git a/src/Symfony/Bundle/AsseticBundle/Twig/AsseticNode.php b/src/Symfony/Bundle/AsseticBundle/Twig/AsseticNode.php new file mode 100644 index 0000000000..1202b4abe0 --- /dev/null +++ b/src/Symfony/Bundle/AsseticBundle/Twig/AsseticNode.php @@ -0,0 +1,57 @@ + + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace Symfony\Bundle\AsseticBundle\Twig; + +use Assetic\Asset\AssetInterface; +use Assetic\Extension\Twig\AsseticNode as BaseAsseticNode; + +/** + * Assetic node. + * + * @author Kris Wallsmith + */ +class AsseticNode extends BaseAsseticNode +{ + protected function compileAssetUrl(\Twig_Compiler $compiler, AssetInterface $asset, $name) + { + $compiler + ->raw('isset($context[\'assetic\'][\'use_controller\']) && $context[\'assetic\'][\'use_controller\'] ? ') + ->subcompile($this->getPathFunction($name)) + ->raw(' : ') + ->subcompile($this->getAssetFunction($asset->getTargetUrl())) + ; + } + + private function getPathFunction($name) + { + return new \Twig_Node_Expression_Function( + new \Twig_Node_Expression_Name('path', $this->getLine()), + new \Twig_Node(array(new \Twig_Node_Expression_Constant('_assetic_'.$name, $this->getLine()))), + $this->getLine() + ); + } + + private function getAssetFunction($path) + { + $arguments = array(new \Twig_Node_Expression_Constant($path, $this->getLine())); + + if ($this->hasAttribute('package')) { + $arguments[] = new \Twig_Node_Expression_Constant($this->getAttribute('package'), $this->getLine()); + } + + return new \Twig_Node_Expression_Function( + new \Twig_Node_Expression_Name('asset', $this->getLine()), + new \Twig_Node($arguments), + $this->getLine() + ); + } +} diff --git a/src/Symfony/Bundle/AsseticBundle/Twig/AsseticTokenParser.php b/src/Symfony/Bundle/AsseticBundle/Twig/AsseticTokenParser.php new file mode 100644 index 0000000000..fc0673ea24 --- /dev/null +++ b/src/Symfony/Bundle/AsseticBundle/Twig/AsseticTokenParser.php @@ -0,0 +1,28 @@ + + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace Symfony\Bundle\AsseticBundle\Twig; + +use Assetic\Asset\AssetInterface; +use Assetic\Extension\Twig\AsseticTokenParser as BaseAsseticTokenParser; + +/** + * Assetic token parser. + * + * @author Kris Wallsmith + */ +class AsseticTokenParser extends BaseAsseticTokenParser +{ + protected function createNode(AssetInterface $asset, \Twig_NodeInterface $body, array $inputs, array $filters, $name, array $attributes = array(), $lineno = 0, $tag = null) + { + return new AsseticNode($asset, $body, $inputs, $filters, $name, $attributes, $lineno, $tag); + } +} diff --git a/src/Symfony/Bundle/AsseticBundle/Twig/DynamicExtension.php b/src/Symfony/Bundle/AsseticBundle/Twig/DynamicExtension.php deleted file mode 100644 index fc95aec740..0000000000 --- a/src/Symfony/Bundle/AsseticBundle/Twig/DynamicExtension.php +++ /dev/null @@ -1,32 +0,0 @@ - - * - * This source file is subject to the MIT license that is bundled - * with this source code in the file LICENSE. - */ - -namespace Symfony\Bundle\AsseticBundle\Twig; - -use Assetic\Extension\Twig\AsseticExtension; -use Assetic\Factory\AssetFactory; - -/** - * The dynamic extension is used when use_controllers is enabled. - * - * @author Kris Wallsmith - */ -class DynamicExtension extends AsseticExtension -{ - public function getTokenParsers() - { - return array( - new DynamicTokenParser($this->factory, 'javascripts', 'js/*.js', $this->debug, false, array('package')), - new DynamicTokenParser($this->factory, 'stylesheets', 'css/*.css', $this->debug, false, array('package')), - new DynamicTokenParser($this->factory, 'image', 'images/*', $this->debug, true, array('package')), - ); - } -} diff --git a/src/Symfony/Bundle/AsseticBundle/Twig/DynamicNode.php b/src/Symfony/Bundle/AsseticBundle/Twig/DynamicNode.php deleted file mode 100644 index b17c0d0541..0000000000 --- a/src/Symfony/Bundle/AsseticBundle/Twig/DynamicNode.php +++ /dev/null @@ -1,36 +0,0 @@ - - * - * This source file is subject to the MIT license that is bundled - * with this source code in the file LICENSE. - */ - -namespace Symfony\Bundle\AsseticBundle\Twig; - -use Assetic\Extension\Twig\AsseticNode; - -/** - * The "dynamic" node uses a controller to render assets. - * - * @author Kris Wallsmith - */ -class DynamicNode extends AsseticNode -{ - /** - * Renders the asset URL using Symfony's path() function. - */ - protected function getAssetUrlNode(\Twig_NodeInterface $body) - { - return new \Twig_Node_Expression_Function( - new \Twig_Node_Expression_Name('path', $body->getLine()), - new \Twig_Node(array( - new \Twig_Node_Expression_Constant('assetic_'.$this->getAttribute('name'), $body->getLine()), - )), - $body->getLine() - ); - } -} diff --git a/src/Symfony/Bundle/AsseticBundle/Twig/DynamicTokenParser.php b/src/Symfony/Bundle/AsseticBundle/Twig/DynamicTokenParser.php deleted file mode 100644 index 418b48d50e..0000000000 --- a/src/Symfony/Bundle/AsseticBundle/Twig/DynamicTokenParser.php +++ /dev/null @@ -1,27 +0,0 @@ - - * - * This source file is subject to the MIT license that is bundled - * with this source code in the file LICENSE. - */ - -namespace Symfony\Bundle\AsseticBundle\Twig; - -use Assetic\Extension\Twig\AsseticTokenParser; - -/** - * Parses an Assetic tag. - * - * @author Kris Wallsmith - */ -class DynamicTokenParser extends AsseticTokenParser -{ - static protected function createNode(\Twig_NodeInterface $body, array $inputs, array $filters, array $attributes, $lineno = 0, $tag = null) - { - return new DynamicNode($body, $inputs, $filters, $attributes, $lineno, $tag); - } -} diff --git a/src/Symfony/Bundle/AsseticBundle/Twig/StaticExtension.php b/src/Symfony/Bundle/AsseticBundle/Twig/StaticExtension.php deleted file mode 100644 index 884e6c7f24..0000000000 --- a/src/Symfony/Bundle/AsseticBundle/Twig/StaticExtension.php +++ /dev/null @@ -1,32 +0,0 @@ - - * - * This source file is subject to the MIT license that is bundled - * with this source code in the file LICENSE. - */ - -namespace Symfony\Bundle\AsseticBundle\Twig; - -use Assetic\Extension\Twig\AsseticExtension; -use Assetic\Factory\AssetFactory; - -/** - * The static extension is used when use_controllers is disabled. - * - * @author Kris Wallsmith - */ -class StaticExtension extends AsseticExtension -{ - public function getTokenParsers() - { - return array( - new StaticTokenParser($this->factory, 'javascripts', 'js/*.js', $this->debug, false, array('package')), - new StaticTokenParser($this->factory, 'stylesheets', 'css/*.css', $this->debug, false, array('package')), - new StaticTokenParser($this->factory, 'image', 'images/*', $this->debug, true, array('package')), - ); - } -} diff --git a/src/Symfony/Bundle/AsseticBundle/Twig/StaticNode.php b/src/Symfony/Bundle/AsseticBundle/Twig/StaticNode.php deleted file mode 100644 index 73f0fe383f..0000000000 --- a/src/Symfony/Bundle/AsseticBundle/Twig/StaticNode.php +++ /dev/null @@ -1,37 +0,0 @@ - - * - * This source file is subject to the MIT license that is bundled - * with this source code in the file LICENSE. - */ - -namespace Symfony\Bundle\AsseticBundle\Twig; - -use Assetic\Extension\Twig\AsseticNode; - -/** - * The "static" node references a file in the web directory. - * - * @author Kris Wallsmith - */ -class StaticNode extends AsseticNode -{ - /** - * Renders the asset URL using Symfony's asset() function. - */ - protected function getAssetUrlNode(\Twig_NodeInterface $body) - { - return new \Twig_Node_Expression_Function( - new \Twig_Node_Expression_Name('asset', $body->getLine()), - new \Twig_Node(array( - new \Twig_Node_Expression_Constant($this->getAttribute('output'), $body->getLine()), - new \Twig_Node_Expression_Constant($this->hasAttribute('package') ? $this->getAttribute('package') : null, $body->getLine()), - )), - $body->getLine() - ); - } -} diff --git a/src/Symfony/Bundle/AsseticBundle/Twig/StaticTokenParser.php b/src/Symfony/Bundle/AsseticBundle/Twig/StaticTokenParser.php deleted file mode 100644 index 5ee21b8ec7..0000000000 --- a/src/Symfony/Bundle/AsseticBundle/Twig/StaticTokenParser.php +++ /dev/null @@ -1,27 +0,0 @@ - - * - * This source file is subject to the MIT license that is bundled - * with this source code in the file LICENSE. - */ - -namespace Symfony\Bundle\AsseticBundle\Twig; - -use Assetic\Extension\Twig\AsseticTokenParser; - -/** - * Parses an Assetic tag. - * - * @author Kris Wallsmith - */ -class StaticTokenParser extends AsseticTokenParser -{ - static protected function createNode(\Twig_NodeInterface $body, array $inputs, array $filters, array $attributes, $lineno = 0, $tag = null) - { - return new StaticNode($body, $inputs, $filters, $attributes, $lineno, $tag); - } -} From 6a227f858a2a3687459dcda899409150eec24512 Mon Sep 17 00:00:00 2001 From: Kris Wallsmith Date: Thu, 21 Apr 2011 07:08:29 -0700 Subject: [PATCH 78/91] [AsseticBundle] removed fake front controller from URL before creating route --- ...trollerWorker.php => UseControllerWorker.php} | 16 ++++++---------- .../Resources/config/controller.xml | 4 ++-- .../AsseticBundle/Routing/AsseticLoader.php | 14 +++++++++++++- 3 files changed, 21 insertions(+), 13 deletions(-) rename src/Symfony/Bundle/AsseticBundle/Factory/Worker/{PrependControllerWorker.php => UseControllerWorker.php} (59%) diff --git a/src/Symfony/Bundle/AsseticBundle/Factory/Worker/PrependControllerWorker.php b/src/Symfony/Bundle/AsseticBundle/Factory/Worker/UseControllerWorker.php similarity index 59% rename from src/Symfony/Bundle/AsseticBundle/Factory/Worker/PrependControllerWorker.php rename to src/Symfony/Bundle/AsseticBundle/Factory/Worker/UseControllerWorker.php index 81862ba17e..527c81d706 100644 --- a/src/Symfony/Bundle/AsseticBundle/Factory/Worker/PrependControllerWorker.php +++ b/src/Symfony/Bundle/AsseticBundle/Factory/Worker/UseControllerWorker.php @@ -15,23 +15,19 @@ use Assetic\Asset\AssetInterface; use Assetic\Factory\Worker\WorkerInterface; /** - * Prepends a fake front controller to every asset's target URL. - * - * This worker should only be added when the use_controller configuration - * option is true. It changes the target URL to include the front controller. + * Prepends a fake front controller so the asset knows where it is-ish. * * @author Kris Wallsmith */ -class PrependControllerWorker implements WorkerInterface +class UseControllerWorker implements WorkerInterface { - const CONTROLLER = 'front_controller/'; - public function process(AssetInterface $asset) { $targetUrl = $asset->getTargetUrl(); - - if ($targetUrl && '/' != $targetUrl[0] && 0 !== strpos($targetUrl, self::CONTROLLER)) { - $asset->setTargetUrl(self::CONTROLLER.$targetUrl); + if ($targetUrl && '/' != $targetUrl[0] && 0 !== strpos($targetUrl, '_controller/')) { + $asset->setTargetUrl('_controller/'.$targetUrl); } + + return $asset; } } diff --git a/src/Symfony/Bundle/AsseticBundle/Resources/config/controller.xml b/src/Symfony/Bundle/AsseticBundle/Resources/config/controller.xml index 4b56f8fcb6..1da0a603e5 100644 --- a/src/Symfony/Bundle/AsseticBundle/Resources/config/controller.xml +++ b/src/Symfony/Bundle/AsseticBundle/Resources/config/controller.xml @@ -8,7 +8,7 @@ Symfony\Bundle\AsseticBundle\Controller\AsseticController Symfony\Bundle\AsseticBundle\Routing\AsseticLoader Assetic\Cache\FilesystemCache - Symfony\Bundle\AsseticBundle\Factory\Worker\PrependControllerWorker + Symfony\Bundle\AsseticBundle\Factory\Worker\UseControllerWorker @@ -24,7 +24,7 @@ %assetic.cache_dir%/assets - + diff --git a/src/Symfony/Bundle/AsseticBundle/Routing/AsseticLoader.php b/src/Symfony/Bundle/AsseticBundle/Routing/AsseticLoader.php index 214c9bc8fe..97435441ee 100644 --- a/src/Symfony/Bundle/AsseticBundle/Routing/AsseticLoader.php +++ b/src/Symfony/Bundle/AsseticBundle/Routing/AsseticLoader.php @@ -80,6 +80,17 @@ class AsseticLoader extends Loader return $routes; } + /** + * Loads a route to serve an supplied asset. + * + * The fake front controller that {@link UseControllerWorker} adds to the + * target URL will be removed before set as a route pattern. + * + * @param RouteCollection $routes The route collection + * @param AssetInterface $asset The asset + * @param string $name The name to use + * @param integer $pos The leaf index + */ private function loadRouteForAsset(RouteCollection $routes, AssetInterface $asset, $name, $pos = null) { $defaults = array( @@ -88,7 +99,8 @@ class AsseticLoader extends Loader 'pos' => $pos, ); - $pattern = $asset->getTargetUrl(); + // remove the fake front controller + $pattern = str_replace('_controller/', '', $asset->getTargetUrl()); if ($format = pathinfo($pattern, PATHINFO_EXTENSION)) { $defaults['_format'] = $format; From 57dd6aef865f82c0b627d2826aeb97b913256381 Mon Sep 17 00:00:00 2001 From: Kris Wallsmith Date: Thu, 21 Apr 2011 07:28:23 -0700 Subject: [PATCH 79/91] [AsseticBundle] fixed router and controller --- .../Controller/AsseticController.php | 26 ++++++++++++------- .../AsseticBundle/Routing/AsseticLoader.php | 10 ++++--- 2 files changed, 23 insertions(+), 13 deletions(-) diff --git a/src/Symfony/Bundle/AsseticBundle/Controller/AsseticController.php b/src/Symfony/Bundle/AsseticBundle/Controller/AsseticController.php index 136ef133d6..6ffd6fb95e 100644 --- a/src/Symfony/Bundle/AsseticBundle/Controller/AsseticController.php +++ b/src/Symfony/Bundle/AsseticBundle/Controller/AsseticController.php @@ -12,6 +12,7 @@ namespace Symfony\Bundle\AsseticBundle\Controller; use Assetic\Asset\AssetCache; +use Assetic\Asset\AssetInterface; use Assetic\Factory\LazyAssetManager; use Assetic\Cache\CacheInterface; use Symfony\Component\HttpFoundation\Request; @@ -42,13 +43,9 @@ class AsseticController throw new NotFoundHttpException(sprintf('The "%s" asset could not be found.', $name)); } - $asset = $this->getAsset($name); - if (null !== $pos) { - $leaves = array_values(iterator_to_array($asset)); - if (!isset($leaves[$pos])) { - throw new NotFoundHttpException(sprintf('The "%s" asset does not include a leaf at position %d.', $name, $pos)); - } - $asset = $leaves[$pos]; + $asset = $this->am->get($name); + if (null !== $pos && !$asset = $this->findAssetLeaf($asset, $pos)) { + throw new NotFoundHttpException(sprintf('The "%s" asset does not include a leaf at position %d.', $name, $pos)); } $response = $this->createResponse(); @@ -71,7 +68,7 @@ class AsseticController return $response; } - $response->setContent($asset->dump()); + $response->setContent($this->cachifyAsset($asset)->dump()); return $response; } @@ -81,8 +78,17 @@ class AsseticController return new Response(); } - protected function getAsset($name) + protected function cachifyAsset(AssetInterface $asset) { - return new AssetCache($this->am->get($name), $this->cache); + return new AssetCache($asset, $this->cache); + } + + private function findAssetLeaf(AssetInterface $asset, $pos) + { + $leaves = array_values(iterator_to_array($asset)); + + if (isset($leaves[$pos])) { + return $leaves[$pos]; + } } } diff --git a/src/Symfony/Bundle/AsseticBundle/Routing/AsseticLoader.php b/src/Symfony/Bundle/AsseticBundle/Routing/AsseticLoader.php index 97435441ee..9525fc8ff2 100644 --- a/src/Symfony/Bundle/AsseticBundle/Routing/AsseticLoader.php +++ b/src/Symfony/Bundle/AsseticBundle/Routing/AsseticLoader.php @@ -71,8 +71,7 @@ class AsseticLoader extends Loader if (isset($formula[2]['debug']) ? $formula[2]['debug'] : $this->am->isDebug()) { $i = 0; foreach ($asset as $leaf) { - $pos = $i++; - $this->loadRouteForAsset($routes, $leaf, $name.'_'.$pos, $pos); + $this->loadRouteForAsset($routes, $leaf, $name, $i++); } } } @@ -106,7 +105,12 @@ class AsseticLoader extends Loader $defaults['_format'] = $format; } - $routes->add('_assetic_'.$name, new Route($pattern, $defaults)); + $route = '_assetic_'.$name; + if (null !== $pos) { + $route .= '_'.$pos; + } + + $routes->add($route, new Route($pattern, $defaults)); } public function supports($resource, $type = null) From 314684df24c81ed2c098d0e48ac214c121311d1b Mon Sep 17 00:00:00 2001 From: Fabien Potencier Date: Thu, 21 Apr 2011 18:53:59 +0200 Subject: [PATCH 80/91] [FrameworkBundle] made ESI URL relative as allowed by the spec (no need to generate absolute URLs) see http://www.w3.org/TR/esi-lang (Section 3.1 "Relative URIs will be resolved relative to the template.") --- src/Symfony/Bundle/FrameworkBundle/HttpKernel.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Symfony/Bundle/FrameworkBundle/HttpKernel.php b/src/Symfony/Bundle/FrameworkBundle/HttpKernel.php index c06fcd7ded..dcde0d34df 100644 --- a/src/Symfony/Bundle/FrameworkBundle/HttpKernel.php +++ b/src/Symfony/Bundle/FrameworkBundle/HttpKernel.php @@ -169,7 +169,7 @@ class HttpKernel extends BaseHttpKernel 'controller' => $controller, 'path' => $attributes ? http_build_query($attributes) : 'none', '_format' => $this->container->get('request')->getRequestFormat(), - ), true); + )); if ($query) { $uri = $uri.'?'.http_build_query($query); From 98e46a23fad17801cb4fef3a548ab1942028cd91 Mon Sep 17 00:00:00 2001 From: Josiah Date: Thu, 21 Apr 2011 10:36:25 -0700 Subject: [PATCH 81/91] Added 201 to the possible status codes that indicate a response is a redirect. --- src/Symfony/Component/HttpFoundation/Response.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Symfony/Component/HttpFoundation/Response.php b/src/Symfony/Component/HttpFoundation/Response.php index 44ee891c9a..9e11e27822 100644 --- a/src/Symfony/Component/HttpFoundation/Response.php +++ b/src/Symfony/Component/HttpFoundation/Response.php @@ -751,7 +751,7 @@ class Response public function isRedirect() { - return in_array($this->statusCode, array(301, 302, 303, 307)); + return in_array($this->statusCode, array(201, 301, 302, 303, 307)); } public function isEmpty() From 40e6030aff5ddf06e175b6bf6569475db9e5574b Mon Sep 17 00:00:00 2001 From: Fabien Potencier Date: Thu, 21 Apr 2011 20:00:06 +0200 Subject: [PATCH 82/91] updated vendors --- vendors.sh | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/vendors.sh b/vendors.sh index 957d28eb8c..7646a10017 100755 --- a/vendors.sh +++ b/vendors.sh @@ -38,16 +38,16 @@ install_git() install_git assetic git://github.com/kriswallsmith/assetic.git # Doctrine ORM -install_git doctrine git://github.com/doctrine/doctrine2.git +install_git doctrine git://github.com/doctrine/doctrine2.git 2.0.3 # Doctrine Data Fixtures Extension install_git doctrine-data-fixtures git://github.com/doctrine/data-fixtures.git # Doctrine DBAL -install_git doctrine-dbal git://github.com/doctrine/dbal.git +install_git doctrine-dbal git://github.com/doctrine/dbal.git 2.0.2 # Doctrine Common -install_git doctrine-common git://github.com/doctrine/common.git +install_git doctrine-common git://github.com/doctrine/common.git 2.0.2 # Doctrine migrations install_git doctrine-migrations git://github.com/doctrine/migrations.git From c5497c7c670eb79e2c72668618e2426a56d7790e Mon Sep 17 00:00:00 2001 From: Fabien Potencier Date: Thu, 21 Apr 2011 20:00:27 +0200 Subject: [PATCH 83/91] [HttpFoundation] fixed a potential security problem in Request --- src/Symfony/Component/HttpFoundation/Request.php | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/Symfony/Component/HttpFoundation/Request.php b/src/Symfony/Component/HttpFoundation/Request.php index a2b964bd80..466236da67 100644 --- a/src/Symfony/Component/HttpFoundation/Request.php +++ b/src/Symfony/Component/HttpFoundation/Request.php @@ -311,7 +311,8 @@ class Request public function hasSession() { - return $this->cookies->has(session_name()); + // the check for $this->session avoids malicious users trying to fake a session cookie with proper name + return $this->cookies->has(session_name()) && null !== $this->session; } public function setSession(Session $session) From 813627bd4c22210b8982f9b2a6c71858bcd449e5 Mon Sep 17 00:00:00 2001 From: Fabien Potencier Date: Thu, 21 Apr 2011 21:20:27 +0200 Subject: [PATCH 84/91] [Routing] added getContext() accessor --- .../Component/Routing/Generator/UrlGenerator.php | 10 ++++++++++ src/Symfony/Component/Routing/Matcher/UrlMatcher.php | 10 ++++++++++ src/Symfony/Component/Routing/Router.php | 12 ++++++++++++ 3 files changed, 32 insertions(+) diff --git a/src/Symfony/Component/Routing/Generator/UrlGenerator.php b/src/Symfony/Component/Routing/Generator/UrlGenerator.php index b9e294362d..5c02f2f69d 100644 --- a/src/Symfony/Component/Routing/Generator/UrlGenerator.php +++ b/src/Symfony/Component/Routing/Generator/UrlGenerator.php @@ -50,6 +50,16 @@ class UrlGenerator implements UrlGeneratorInterface $this->context = $context; } + /** + * Gets the request context. + * + * @return RequestContext The context + */ + public function getContext() + { + return $this->context; + } + /** * Generates a URL from the given parameters. * diff --git a/src/Symfony/Component/Routing/Matcher/UrlMatcher.php b/src/Symfony/Component/Routing/Matcher/UrlMatcher.php index 41660584dd..aa1ddf4db6 100644 --- a/src/Symfony/Component/Routing/Matcher/UrlMatcher.php +++ b/src/Symfony/Component/Routing/Matcher/UrlMatcher.php @@ -50,6 +50,16 @@ class UrlMatcher implements UrlMatcherInterface $this->context = $context; } + /** + * Gets the request context. + * + * @return RequestContext The context + */ + public function getContext() + { + return $this->context; + } + /** * Tries to match a URL with a set of routes. * diff --git a/src/Symfony/Component/Routing/Router.php b/src/Symfony/Component/Routing/Router.php index 74a6889b70..6459fc658e 100644 --- a/src/Symfony/Component/Routing/Router.php +++ b/src/Symfony/Component/Routing/Router.php @@ -106,10 +106,22 @@ class Router implements RouterInterface */ public function setContext(RequestContext $context) { + $this->context = $context; + $this->getMatcher()->setContext($context); $this->getGenerator()->setContext($context); } + /** + * Gets the request context. + * + * @return RequestContext The context + */ + public function getContext() + { + return $this->context; + } + /** * Generates a URL from the given parameters. * From 4dc5b8ec78b7407210a6c9008a59d16975192519 Mon Sep 17 00:00:00 2001 From: Fabien Potencier Date: Thu, 21 Apr 2011 21:49:05 +0200 Subject: [PATCH 85/91] [FrameworkBundle] removed the need to boot a Kernel in a unit test file --- .../Tests/Templating/TemplateNameParserTest.php | 14 +++++++++++--- 1 file changed, 11 insertions(+), 3 deletions(-) diff --git a/src/Symfony/Bundle/FrameworkBundle/Tests/Templating/TemplateNameParserTest.php b/src/Symfony/Bundle/FrameworkBundle/Tests/Templating/TemplateNameParserTest.php index e43fc8194c..b5240021b5 100644 --- a/src/Symfony/Bundle/FrameworkBundle/Tests/Templating/TemplateNameParserTest.php +++ b/src/Symfony/Bundle/FrameworkBundle/Tests/Templating/TemplateNameParserTest.php @@ -12,7 +12,6 @@ namespace Symfony\Bundle\FrameworkBundle\Tests\Templating; use Symfony\Bundle\FrameworkBundle\Tests\TestCase; -use Symfony\Bundle\FrameworkBundle\Tests\Kernel; use Symfony\Bundle\FrameworkBundle\Templating\TemplateNameParser; use Symfony\Bundle\FrameworkBundle\Templating\TemplateReference; @@ -22,9 +21,18 @@ class TemplateNameParserTest extends TestCase protected function setUp() { - $kernel = new Kernel(); - $kernel->boot(); + $kernel = $this->getMock('Symfony\Component\HttpKernel\KernelInterface'); + $kernel + ->expects($this->any()) + ->method('getBundle') + ->will($this->returnCallback(function ($bundle) { + if (in_array($bundle, array('SensioFooBundle', 'SensioCmsFooBundle', 'FooBundle'))) { + return true; + } + throw new \InvalidArgumentException(); + })) + ; $this->parser = new TemplateNameParser($kernel); } From d86aa74e3d68b8e5cf808bedcbf241fe0413649a Mon Sep 17 00:00:00 2001 From: Fabien Potencier Date: Thu, 21 Apr 2011 22:34:53 +0200 Subject: [PATCH 86/91] [FrameworkBundle] removed the need to boot a Kernel in a unit test file --- .../Controller/ControllerNameParserTest.php | 52 +++++++++++++++---- 1 file changed, 43 insertions(+), 9 deletions(-) diff --git a/src/Symfony/Bundle/FrameworkBundle/Tests/Controller/ControllerNameParserTest.php b/src/Symfony/Bundle/FrameworkBundle/Tests/Controller/ControllerNameParserTest.php index 159e999d3f..158848d2df 100644 --- a/src/Symfony/Bundle/FrameworkBundle/Tests/Controller/ControllerNameParserTest.php +++ b/src/Symfony/Bundle/FrameworkBundle/Tests/Controller/ControllerNameParserTest.php @@ -13,14 +13,27 @@ namespace Symfony\Bundle\FrameworkBundle\Tests\Controller; use Symfony\Bundle\FrameworkBundle\Tests\TestCase; use Symfony\Bundle\FrameworkBundle\Controller\ControllerNameParser; -use Symfony\Bundle\FrameworkBundle\Tests\Logger; -use Symfony\Bundle\FrameworkBundle\Tests\Kernel; - -require_once __DIR__.'/../Kernel.php'; -require_once __DIR__.'/../Logger.php'; +use Symfony\Component\ClassLoader\UniversalClassLoader; class ControllerNameParserTest extends TestCase { + protected $loader; + + public function setUp() + { + $this->loader = new UniversalClassLoader(); + $this->loader->registerNamespaces(array( + 'TestBundle' => __DIR__.'/../Fixtures', + 'TestApplication' => __DIR__.'/../Fixtures', + )); + $this->loader->register(); + } + + public function tearDown() + { + spl_autoload_unregister(array($this->loader, 'loadClass')); + } + public function testParse() { $parser = $this->createParser(); @@ -63,10 +76,31 @@ class ControllerNameParserTest extends TestCase private function createParser() { - $kernel = new Kernel(); - $kernel->boot(); - $logger = new Logger(); + $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')), + ); - return new ControllerNameParser($kernel, $logger); + $kernel = $this->getMock('Symfony\Component\HttpKernel\KernelInterface'); + $kernel + ->expects($this->any()) + ->method('getBundle') + ->will($this->returnCallback(function ($bundle) use ($bundles) { + return $bundles[$bundle]; + })) + ; + + 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; } } From 6452878d28e6f78694c815429c567dda4ec5809d Mon Sep 17 00:00:00 2001 From: Fabien Potencier Date: Thu, 21 Apr 2011 22:40:59 +0200 Subject: [PATCH 87/91] updated vendors --- vendors.sh | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/vendors.sh b/vendors.sh index 7646a10017..fa9bf6453f 100755 --- a/vendors.sh +++ b/vendors.sh @@ -38,16 +38,16 @@ install_git() install_git assetic git://github.com/kriswallsmith/assetic.git # Doctrine ORM -install_git doctrine git://github.com/doctrine/doctrine2.git 2.0.3 +install_git doctrine git://github.com/doctrine/doctrine2.git 2.0.4 # Doctrine Data Fixtures Extension install_git doctrine-data-fixtures git://github.com/doctrine/data-fixtures.git # Doctrine DBAL -install_git doctrine-dbal git://github.com/doctrine/dbal.git 2.0.2 +install_git doctrine-dbal git://github.com/doctrine/dbal.git 2.0.4 # Doctrine Common -install_git doctrine-common git://github.com/doctrine/common.git 2.0.2 +install_git doctrine-common git://github.com/doctrine/common.git # Doctrine migrations install_git doctrine-migrations git://github.com/doctrine/migrations.git From 30e907663b4bbbe4dbece8ebca530181f39d541e Mon Sep 17 00:00:00 2001 From: Fabien Potencier Date: Thu, 21 Apr 2011 22:43:38 +0200 Subject: [PATCH 88/91] [FrameworkBundle] removed unneeded files in tests --- .../Controller/RedirectControllerTest.php | 2 - .../Bundle/FrameworkBundle/Tests/Kernel.php | 65 -------------- .../Bundle/FrameworkBundle/Tests/Logger.php | 88 ------------------- .../Tests/Templating/TemplateTest.php | 1 - 4 files changed, 156 deletions(-) delete mode 100644 src/Symfony/Bundle/FrameworkBundle/Tests/Kernel.php delete mode 100644 src/Symfony/Bundle/FrameworkBundle/Tests/Logger.php diff --git a/src/Symfony/Bundle/FrameworkBundle/Tests/Controller/RedirectControllerTest.php b/src/Symfony/Bundle/FrameworkBundle/Tests/Controller/RedirectControllerTest.php index 85e2c1ff37..04c39b0f62 100644 --- a/src/Symfony/Bundle/FrameworkBundle/Tests/Controller/RedirectControllerTest.php +++ b/src/Symfony/Bundle/FrameworkBundle/Tests/Controller/RedirectControllerTest.php @@ -17,8 +17,6 @@ use Symfony\Component\HttpFoundation\Request; use Symfony\Bundle\FrameworkBundle\Controller\RedirectController; use Symfony\Bundle\FrameworkBundle\Tests\TestCase; use Symfony\Bundle\FrameworkBundle\Controller\ControllerNameParser; -use Symfony\Bundle\FrameworkBundle\Tests\Logger; -use Symfony\Bundle\FrameworkBundle\Tests\Kernel; /** * @author Marcin Sikon diff --git a/src/Symfony/Bundle/FrameworkBundle/Tests/Kernel.php b/src/Symfony/Bundle/FrameworkBundle/Tests/Kernel.php deleted file mode 100644 index cbbf78226d..0000000000 --- a/src/Symfony/Bundle/FrameworkBundle/Tests/Kernel.php +++ /dev/null @@ -1,65 +0,0 @@ - - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -namespace Symfony\Bundle\FrameworkBundle\Tests; - -use Symfony\Component\HttpKernel\Kernel as BaseKernel; -use Symfony\Component\HttpKernel\Util\Filesystem; -use Symfony\Component\ClassLoader\UniversalClassLoader; -use Symfony\Component\Config\Loader\LoaderInterface; - -class Kernel extends BaseKernel -{ - public function __construct() - { - $this->rootDir = sys_get_temp_dir().'/sf2_'.rand(1, 9999); - if (!is_dir($this->rootDir)) { - if (false === @mkdir($this->rootDir)) { - exit(sprintf('Unable to create a temporary directory (%s)', $this->rootDir)); - } - } elseif (!is_writable($this->rootDir)) { - exit(sprintf('Unable to write in a temporary directory (%s)', $this->rootDir)); - } - - parent::__construct('env', true); - - $loader = new UniversalClassLoader(); - $loader->registerNamespaces(array( - 'TestBundle' => __DIR__.'/Fixtures/', - 'TestApplication' => __DIR__.'/Fixtures/', - )); - $loader->register(); - } - - public function __destruct() - { - $fs = new Filesystem(); - $fs->remove($this->rootDir); - } - - public function registerBundles() - { - return array( - new \Symfony\Bundle\FrameworkBundle\FrameworkBundle(), - new \TestBundle\Sensio\FooBundle\SensioFooBundle(), - new \TestBundle\Sensio\Cms\FooBundle\SensioCmsFooBundle(), - new \TestBundle\FooBundle\FooBundle(), - new \TestBundle\Fabpot\FooBundle\FabpotFooBundle(), - ); - } - - public function registerContainerConfiguration(LoaderInterface $loader) - { - $loader->load(function ($container) { - $container->setParameter('kernel.compiled_classes', array()); - }); - } -} diff --git a/src/Symfony/Bundle/FrameworkBundle/Tests/Logger.php b/src/Symfony/Bundle/FrameworkBundle/Tests/Logger.php deleted file mode 100644 index e975d61978..0000000000 --- a/src/Symfony/Bundle/FrameworkBundle/Tests/Logger.php +++ /dev/null @@ -1,88 +0,0 @@ - - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -namespace Symfony\Bundle\FrameworkBundle\Tests; - -use Symfony\Component\HttpKernel\Log\LoggerInterface; - -class Logger implements LoggerInterface -{ - protected $logs; - - public function __construct() - { - $this->clear(); - } - - public function getLogs($priority = false) - { - return false === $priority ? $this->logs : $this->logs[$priority]; - } - - public function clear() - { - $this->logs = array( - 'emerg' => array(), - 'alert' => array(), - 'crit' => array(), - 'err' => array(), - 'warn' => array(), - 'notice' => array(), - 'info' => array(), - 'debug' => array(), - ); - } - - public function log($message, $priority) - { - $this->logs[$priority][] = $message; - } - - public function emerg($message) - { - $this->log($message, 'emerg'); - } - - public function alert($message) - { - $this->log($message, 'alert'); - } - - public function crit($message) - { - $this->log($message, 'crit'); - } - - public function err($message) - { - $this->log($message, 'err'); - } - - public function warn($message) - { - $this->log($message, 'warn'); - } - - public function notice($message) - { - $this->log($message, 'notice'); - } - - public function info($message) - { - $this->log($message, 'info'); - } - - public function debug($message) - { - $this->log($message, 'debug'); - } -} diff --git a/src/Symfony/Bundle/FrameworkBundle/Tests/Templating/TemplateTest.php b/src/Symfony/Bundle/FrameworkBundle/Tests/Templating/TemplateTest.php index df38b286da..c49010bfdc 100644 --- a/src/Symfony/Bundle/FrameworkBundle/Tests/Templating/TemplateTest.php +++ b/src/Symfony/Bundle/FrameworkBundle/Tests/Templating/TemplateTest.php @@ -12,7 +12,6 @@ namespace Symfony\Bundle\FrameworkBundle\Tests\Templating; use Symfony\Bundle\FrameworkBundle\Tests\TestCase; -use Symfony\Bundle\FrameworkBundle\Tests\Kernel; use Symfony\Bundle\FrameworkBundle\Templating\TemplateReference; class TemplateTest extends TestCase From fc23f3933592ebe172c4cf348dd9f8e0a1eed370 Mon Sep 17 00:00:00 2001 From: Fabien Potencier Date: Thu, 21 Apr 2011 22:50:25 +0200 Subject: [PATCH 89/91] [AsseticBundle] fixed unit tests --- .../Tests/DependencyInjection/AsseticExtensionTest.php | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/src/Symfony/Bundle/AsseticBundle/Tests/DependencyInjection/AsseticExtensionTest.php b/src/Symfony/Bundle/AsseticBundle/Tests/DependencyInjection/AsseticExtensionTest.php index 05f1b0ef29..e73793b863 100644 --- a/src/Symfony/Bundle/AsseticBundle/Tests/DependencyInjection/AsseticExtensionTest.php +++ b/src/Symfony/Bundle/AsseticBundle/Tests/DependencyInjection/AsseticExtensionTest.php @@ -46,9 +46,7 @@ class AsseticExtensionTest extends \PHPUnit_Framework_TestCase $this->markTestSkipped('Assetic is not available.'); } - $this->kernel = $this->getMockBuilder('Symfony\\Component\\HttpKernel\\Kernel') - ->disableOriginalConstructor() - ->getMock(); + $this->kernel = $this->getMock('Symfony\\Component\\HttpKernel\\KernelInterface'); $this->container = new ContainerBuilder(); $this->container->addScope(new Scope('request')); @@ -61,6 +59,7 @@ class AsseticExtensionTest extends \PHPUnit_Framework_TestCase $this->container->setParameter('kernel.cache_dir', __DIR__); $this->container->setParameter('kernel.debug', false); $this->container->setParameter('kernel.root_dir', __DIR__); + $this->container->set('kernel', $this->kernel); } /** From e6d86eb9f7b116ab9e926feb3d080402cafef00f Mon Sep 17 00:00:00 2001 From: Fabien Potencier Date: Thu, 21 Apr 2011 23:14:15 +0200 Subject: [PATCH 90/91] moved DoctrineMongoDBBundle to its own repository The repo is now here: https://github.com/symfony/DoctrineMongoDBBundle It has been done as the bundle depends on Doctrine Common 2.1, but everything else in Symfony relies on Doctrine Common 2.0. --- .../CacheWarmer/HydratorCacheWarmer.php | 76 ---- .../CacheWarmer/ProxyCacheWarmer.php | 76 ---- .../ClearMetadataCacheDoctrineODMCommand.php | 54 --- .../CreateSchemaDoctrineODMCommand.php | 53 --- .../Command/DoctrineODMCommand.php | 121 ------ .../Command/DropSchemaDoctrineODMCommand.php | 53 --- .../GenerateDocumentsDoctrineODMCommand.php | 80 ---- .../GenerateHydratorsDoctrineODMCommand.php | 54 --- .../GenerateProxiesDoctrineODMCommand.php | 54 --- ...GenerateRepositoriesDoctrineODMCommand.php | 77 ---- .../Command/InfoDoctrineODMCommand.php | 84 ---- .../LoadDataFixturesDoctrineODMCommand.php | 108 ------ .../Command/QueryDoctrineODMCommand.php | 44 --- .../DoctrineMongoDBDataCollector.php | 59 --- .../AddValidatorNamespaceAliasPass.php | 22 -- .../Compiler/CreateHydratorDirectoryPass.php | 30 -- .../Compiler/CreateProxyDirectoryPass.php | 30 -- ...gisterEventListenersAndSubscribersPass.php | 59 --- .../DependencyInjection/Configuration.php | 193 ---------- .../DoctrineMongoDBExtension.php | 344 ----------------- .../DoctrineMongoDBBundle.php | 40 -- .../Logger/DoctrineMongoDBLogger.php | 301 --------------- .../Resources/config/mongodb.xml | 119 ------ .../Resources/config/schema/mongodb-1.0.xsd | 36 -- .../views/Collector/mongodb.html.twig | 45 --- .../Security/DocumentUserProvider.php | 78 ---- .../CacheWarmer/HydratorCacheWarmerTest.php | 97 ----- .../CacheWarmer/ProxyCacheWarmerTest.php | 97 ----- .../Tests/ContainerTest.php | 60 --- .../AbstractMongoDBExtensionTest.php | 364 ------------------ .../DependencyInjection/ConfigurationTest.php | 283 -------------- .../DoctrineMongoDBExtensionTest.php | 41 -- .../AnnotationsBundle/AnnotationsBundle.php | 9 - .../AnnotationsBundle/Document/Test.php | 7 - .../Bundles/XmlBundle/Document/Test.php | 7 - ...xtures.Bundles.XmlBundle.Document.Test.xml | 0 .../Fixtures/Bundles/XmlBundle/XmlBundle.php | 9 - .../Bundles/YamlBundle/Document/Test.php | 7 - ...tures.Bundles.YamlBundle.Document.Test.yml | 0 .../Bundles/YamlBundle/YamlBundle.php | 9 - .../mongodb_service_multiple_connections.xml | 29 -- ...ngodb_service_simple_single_connection.xml | 24 -- .../xml/mongodb_service_single_connection.xml | 27 -- .../Fixtures/config/xml/odm_imports.xml | 17 - .../config/xml/odm_imports_import.xml | 13 - .../Fixtures/config/yml/full.yml | 47 --- .../mongodb_service_multiple_connections.yml | 19 - ...ngodb_service_simple_single_connection.yml | 14 - .../yml/mongodb_service_single_connection.yml | 15 - .../Fixtures/config/yml/odm_imports.yml | 5 - .../config/yml/odm_imports_import.yml | 2 - .../XmlMongoDBExtensionTest.php | 25 -- .../YamlMongoDBExtensionTest.php | 25 -- .../Tests/Fixtures/Validator/Document.php | 9 - .../Logger/DoctrineMongoDBLoggerTest.php | 50 --- .../DoctrineMongoDBBundle/Tests/TestCase.php | 42 -- .../Constraints/UniqueValidatorTest.php | 156 -------- .../Validator/Constraints/Unique.php | 56 --- .../Validator/Constraints/UniqueValidator.php | 138 ------- vendors.sh | 8 +- 60 files changed, 1 insertion(+), 4000 deletions(-) delete mode 100644 src/Symfony/Bundle/DoctrineMongoDBBundle/CacheWarmer/HydratorCacheWarmer.php delete mode 100644 src/Symfony/Bundle/DoctrineMongoDBBundle/CacheWarmer/ProxyCacheWarmer.php delete mode 100644 src/Symfony/Bundle/DoctrineMongoDBBundle/Command/ClearMetadataCacheDoctrineODMCommand.php delete mode 100644 src/Symfony/Bundle/DoctrineMongoDBBundle/Command/CreateSchemaDoctrineODMCommand.php delete mode 100644 src/Symfony/Bundle/DoctrineMongoDBBundle/Command/DoctrineODMCommand.php delete mode 100644 src/Symfony/Bundle/DoctrineMongoDBBundle/Command/DropSchemaDoctrineODMCommand.php delete mode 100644 src/Symfony/Bundle/DoctrineMongoDBBundle/Command/GenerateDocumentsDoctrineODMCommand.php delete mode 100644 src/Symfony/Bundle/DoctrineMongoDBBundle/Command/GenerateHydratorsDoctrineODMCommand.php delete mode 100644 src/Symfony/Bundle/DoctrineMongoDBBundle/Command/GenerateProxiesDoctrineODMCommand.php delete mode 100644 src/Symfony/Bundle/DoctrineMongoDBBundle/Command/GenerateRepositoriesDoctrineODMCommand.php delete mode 100644 src/Symfony/Bundle/DoctrineMongoDBBundle/Command/InfoDoctrineODMCommand.php delete mode 100644 src/Symfony/Bundle/DoctrineMongoDBBundle/Command/LoadDataFixturesDoctrineODMCommand.php delete mode 100644 src/Symfony/Bundle/DoctrineMongoDBBundle/Command/QueryDoctrineODMCommand.php delete mode 100644 src/Symfony/Bundle/DoctrineMongoDBBundle/DataCollector/DoctrineMongoDBDataCollector.php delete mode 100644 src/Symfony/Bundle/DoctrineMongoDBBundle/DependencyInjection/Compiler/AddValidatorNamespaceAliasPass.php delete mode 100644 src/Symfony/Bundle/DoctrineMongoDBBundle/DependencyInjection/Compiler/CreateHydratorDirectoryPass.php delete mode 100644 src/Symfony/Bundle/DoctrineMongoDBBundle/DependencyInjection/Compiler/CreateProxyDirectoryPass.php delete mode 100644 src/Symfony/Bundle/DoctrineMongoDBBundle/DependencyInjection/Compiler/RegisterEventListenersAndSubscribersPass.php delete mode 100644 src/Symfony/Bundle/DoctrineMongoDBBundle/DependencyInjection/Configuration.php delete mode 100644 src/Symfony/Bundle/DoctrineMongoDBBundle/DependencyInjection/DoctrineMongoDBExtension.php delete mode 100755 src/Symfony/Bundle/DoctrineMongoDBBundle/DoctrineMongoDBBundle.php delete mode 100644 src/Symfony/Bundle/DoctrineMongoDBBundle/Logger/DoctrineMongoDBLogger.php delete mode 100755 src/Symfony/Bundle/DoctrineMongoDBBundle/Resources/config/mongodb.xml delete mode 100644 src/Symfony/Bundle/DoctrineMongoDBBundle/Resources/config/schema/mongodb-1.0.xsd delete mode 100644 src/Symfony/Bundle/DoctrineMongoDBBundle/Resources/views/Collector/mongodb.html.twig delete mode 100644 src/Symfony/Bundle/DoctrineMongoDBBundle/Security/DocumentUserProvider.php delete mode 100644 src/Symfony/Bundle/DoctrineMongoDBBundle/Tests/CacheWarmer/HydratorCacheWarmerTest.php delete mode 100644 src/Symfony/Bundle/DoctrineMongoDBBundle/Tests/CacheWarmer/ProxyCacheWarmerTest.php delete mode 100644 src/Symfony/Bundle/DoctrineMongoDBBundle/Tests/ContainerTest.php delete mode 100644 src/Symfony/Bundle/DoctrineMongoDBBundle/Tests/DependencyInjection/AbstractMongoDBExtensionTest.php delete mode 100644 src/Symfony/Bundle/DoctrineMongoDBBundle/Tests/DependencyInjection/ConfigurationTest.php delete mode 100644 src/Symfony/Bundle/DoctrineMongoDBBundle/Tests/DependencyInjection/DoctrineMongoDBExtensionTest.php delete mode 100644 src/Symfony/Bundle/DoctrineMongoDBBundle/Tests/DependencyInjection/Fixtures/Bundles/AnnotationsBundle/AnnotationsBundle.php delete mode 100644 src/Symfony/Bundle/DoctrineMongoDBBundle/Tests/DependencyInjection/Fixtures/Bundles/AnnotationsBundle/Document/Test.php delete mode 100644 src/Symfony/Bundle/DoctrineMongoDBBundle/Tests/DependencyInjection/Fixtures/Bundles/XmlBundle/Document/Test.php delete mode 100644 src/Symfony/Bundle/DoctrineMongoDBBundle/Tests/DependencyInjection/Fixtures/Bundles/XmlBundle/Resources/config/doctrine/metadata/mongodb/Fixtures.Bundles.XmlBundle.Document.Test.xml delete mode 100644 src/Symfony/Bundle/DoctrineMongoDBBundle/Tests/DependencyInjection/Fixtures/Bundles/XmlBundle/XmlBundle.php delete mode 100644 src/Symfony/Bundle/DoctrineMongoDBBundle/Tests/DependencyInjection/Fixtures/Bundles/YamlBundle/Document/Test.php delete mode 100644 src/Symfony/Bundle/DoctrineMongoDBBundle/Tests/DependencyInjection/Fixtures/Bundles/YamlBundle/Resources/config/doctrine/metadata/mongodb/Fixtures.Bundles.YamlBundle.Document.Test.yml delete mode 100644 src/Symfony/Bundle/DoctrineMongoDBBundle/Tests/DependencyInjection/Fixtures/Bundles/YamlBundle/YamlBundle.php delete mode 100644 src/Symfony/Bundle/DoctrineMongoDBBundle/Tests/DependencyInjection/Fixtures/config/xml/mongodb_service_multiple_connections.xml delete mode 100644 src/Symfony/Bundle/DoctrineMongoDBBundle/Tests/DependencyInjection/Fixtures/config/xml/mongodb_service_simple_single_connection.xml delete mode 100644 src/Symfony/Bundle/DoctrineMongoDBBundle/Tests/DependencyInjection/Fixtures/config/xml/mongodb_service_single_connection.xml delete mode 100644 src/Symfony/Bundle/DoctrineMongoDBBundle/Tests/DependencyInjection/Fixtures/config/xml/odm_imports.xml delete mode 100644 src/Symfony/Bundle/DoctrineMongoDBBundle/Tests/DependencyInjection/Fixtures/config/xml/odm_imports_import.xml delete mode 100644 src/Symfony/Bundle/DoctrineMongoDBBundle/Tests/DependencyInjection/Fixtures/config/yml/full.yml delete mode 100644 src/Symfony/Bundle/DoctrineMongoDBBundle/Tests/DependencyInjection/Fixtures/config/yml/mongodb_service_multiple_connections.yml delete mode 100644 src/Symfony/Bundle/DoctrineMongoDBBundle/Tests/DependencyInjection/Fixtures/config/yml/mongodb_service_simple_single_connection.yml delete mode 100644 src/Symfony/Bundle/DoctrineMongoDBBundle/Tests/DependencyInjection/Fixtures/config/yml/mongodb_service_single_connection.yml delete mode 100644 src/Symfony/Bundle/DoctrineMongoDBBundle/Tests/DependencyInjection/Fixtures/config/yml/odm_imports.yml delete mode 100644 src/Symfony/Bundle/DoctrineMongoDBBundle/Tests/DependencyInjection/Fixtures/config/yml/odm_imports_import.yml delete mode 100644 src/Symfony/Bundle/DoctrineMongoDBBundle/Tests/DependencyInjection/XmlMongoDBExtensionTest.php delete mode 100644 src/Symfony/Bundle/DoctrineMongoDBBundle/Tests/DependencyInjection/YamlMongoDBExtensionTest.php delete mode 100755 src/Symfony/Bundle/DoctrineMongoDBBundle/Tests/Fixtures/Validator/Document.php delete mode 100644 src/Symfony/Bundle/DoctrineMongoDBBundle/Tests/Logger/DoctrineMongoDBLoggerTest.php delete mode 100644 src/Symfony/Bundle/DoctrineMongoDBBundle/Tests/TestCase.php delete mode 100755 src/Symfony/Bundle/DoctrineMongoDBBundle/Tests/Validator/Constraints/UniqueValidatorTest.php delete mode 100755 src/Symfony/Bundle/DoctrineMongoDBBundle/Validator/Constraints/Unique.php delete mode 100755 src/Symfony/Bundle/DoctrineMongoDBBundle/Validator/Constraints/UniqueValidator.php diff --git a/src/Symfony/Bundle/DoctrineMongoDBBundle/CacheWarmer/HydratorCacheWarmer.php b/src/Symfony/Bundle/DoctrineMongoDBBundle/CacheWarmer/HydratorCacheWarmer.php deleted file mode 100644 index ca875c01a0..0000000000 --- a/src/Symfony/Bundle/DoctrineMongoDBBundle/CacheWarmer/HydratorCacheWarmer.php +++ /dev/null @@ -1,76 +0,0 @@ - - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -namespace Symfony\Bundle\DoctrineMongoDBBundle\CacheWarmer; - -use Symfony\Component\DependencyInjection\Container; -use Symfony\Component\HttpKernel\CacheWarmer\CacheWarmerInterface; - -/** - * The hydrator generator cache warmer generates all document hydrators. - * - * In the process of generating hydrators the cache for all the metadata is primed also, - * since this information is necessary to build the hydrators in the first place. - * - * @author Benjamin Eberlei - * @author Jonathan H. Wage - */ -class HydratorCacheWarmer implements CacheWarmerInterface -{ - /** - * @var Container - */ - private $container; - - /** - * @param Container $container - */ - public function __construct(Container $container) - { - $this->container = $container; - } - - /** - * This cache warmer is not optional, without hydrators fatal error occurs! - * - * @return false - */ - public function isOptional() - { - return false; - } - - public function warmUp($cacheDir) - { - // we need the directory no matter the hydrator cache generation strategy. - $hydratorCacheDir = $this->container->getParameter('doctrine.odm.mongodb.hydrator_dir'); - if (!file_exists($hydratorCacheDir)) { - if (false === @mkdir($hydratorCacheDir, 0777, true)) { - throw new \RuntimeException(sprintf('Unable to create the Doctrine Hydrator directory (%s)', dirname($hydratorCacheDir))); - } - } else if (!is_writable($hydratorCacheDir)) { - throw new \RuntimeException(sprintf('Doctrine Hydrator directory (%s) is not writeable for the current system user.', $hydratorCacheDir)); - } - - // if hydrators are autogenerated we don't need to generate them in the cache warmer. - if ($this->container->getParameter('doctrine.odm.mongodb.auto_generate_hydrator_classes') === true) { - return; - } - - $documentManagers = $this->container->getParameter('doctrine.odm.mongodb.document_managers'); - foreach ($documentManagers as $documentManagerName) { - $dm = $this->container->get(sprintf('doctrine.odm.mongodb.%s_document_manager', $documentManagerName)); - /* @var $dm Doctrine\ODM\MongoDB\DocumentManager */ - $classes = $dm->getMetadataFactory()->getAllMetadata(); - $dm->getHydratorFactory()->generateHydratorClasses($classes); - } - } -} \ No newline at end of file diff --git a/src/Symfony/Bundle/DoctrineMongoDBBundle/CacheWarmer/ProxyCacheWarmer.php b/src/Symfony/Bundle/DoctrineMongoDBBundle/CacheWarmer/ProxyCacheWarmer.php deleted file mode 100644 index 0fb7870521..0000000000 --- a/src/Symfony/Bundle/DoctrineMongoDBBundle/CacheWarmer/ProxyCacheWarmer.php +++ /dev/null @@ -1,76 +0,0 @@ - - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -namespace Symfony\Bundle\DoctrineMongoDBBundle\CacheWarmer; - -use Symfony\Component\DependencyInjection\Container; -use Symfony\Component\HttpKernel\CacheWarmer\CacheWarmerInterface; - -/** - * The proxy generator cache warmer generates all document proxies. - * - * In the process of generating proxies the cache for all the metadata is primed also, - * since this information is necessary to build the proxies in the first place. - * - * @author Benjamin Eberlei - * @author Jonathan H. Wage - */ -class ProxyCacheWarmer implements CacheWarmerInterface -{ - /** - * @var Container - */ - private $container; - - /** - * @param Container $container - */ - public function __construct(Container $container) - { - $this->container = $container; - } - - /** - * This cache warmer is not optional, without proxies fatal error occurs! - * - * @return false - */ - public function isOptional() - { - return false; - } - - public function warmUp($cacheDir) - { - // we need the directory no matter the proxy cache generation strategy. - $proxyCacheDir = $this->container->getParameter('doctrine.odm.mongodb.proxy_dir'); - if (!file_exists($proxyCacheDir)) { - if (false === @mkdir($proxyCacheDir, 0777, true)) { - throw new \RuntimeException(sprintf('Unable to create the Doctrine Proxy directory (%s)', dirname($proxyCacheDir))); - } - } else if (!is_writable($proxyCacheDir)) { - throw new \RuntimeException(sprintf('Doctrine Proxy directory (%s) is not writeable for the current system user.', $proxyCacheDir)); - } - - // if proxies are autogenerated we don't need to generate them in the cache warmer. - if ($this->container->getParameter('doctrine.odm.mongodb.auto_generate_proxy_classes') === true) { - return; - } - - $documentManagers = $this->container->getParameter('doctrine.odm.mongodb.document_managers'); - foreach ($documentManagers as $documentManagerName) { - $dm = $this->container->get(sprintf('doctrine.odm.mongodb.%s_document_manager', $documentManagerName)); - /* @var $dm Doctrine\ODM\MongoDB\DocumentManager */ - $classes = $dm->getMetadataFactory()->getAllMetadata(); - $dm->getProxyFactory()->generateProxyClasses($classes); - } - } -} \ No newline at end of file diff --git a/src/Symfony/Bundle/DoctrineMongoDBBundle/Command/ClearMetadataCacheDoctrineODMCommand.php b/src/Symfony/Bundle/DoctrineMongoDBBundle/Command/ClearMetadataCacheDoctrineODMCommand.php deleted file mode 100644 index be10a906d2..0000000000 --- a/src/Symfony/Bundle/DoctrineMongoDBBundle/Command/ClearMetadataCacheDoctrineODMCommand.php +++ /dev/null @@ -1,54 +0,0 @@ - - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -namespace Symfony\Bundle\DoctrineMongoDBBundle\Command; - -use Symfony\Component\Console\Input\InputOption; -use Symfony\Component\Console\Input\InputInterface; -use Symfony\Component\Console\Output\OutputInterface; -use Doctrine\ODM\MongoDB\Tools\Console\Command\ClearCache\MetadataCommand; - -/** - * Command to clear the metadata cache of the various cache drivers. - * - * @author Fabien Potencier - * @author Jonathan H. Wage - * @author Henrik Westphal - */ -class ClearMetadataCacheDoctrineODMCommand extends MetadataCommand -{ - protected function configure() - { - parent::configure(); - - $this - ->setName('doctrine:mongodb:cache:clear-metadata') - ->setDescription('Clear all metadata cache for a document manager.') - ->addOption('dm', null, InputOption::VALUE_OPTIONAL, 'The document manager to use for this command.') - ->setHelp(<<doctrine:mongodb:cache:clear-metadata command clears all metadata cache for the default document manager: - - ./app/console doctrine:mongodb:cache:clear-metadata - -You can also optionally specify the --dm option to specify which document manager to clear the cache for: - - ./app/console doctrine:mongodb:cache:clear-metadata --dm=default -EOT - ); - } - - protected function execute(InputInterface $input, OutputInterface $output) - { - DoctrineODMCommand::setApplicationDocumentManager($this->getApplication(), $input->getOption('dm')); - - return parent::execute($input, $output); - } -} \ No newline at end of file diff --git a/src/Symfony/Bundle/DoctrineMongoDBBundle/Command/CreateSchemaDoctrineODMCommand.php b/src/Symfony/Bundle/DoctrineMongoDBBundle/Command/CreateSchemaDoctrineODMCommand.php deleted file mode 100644 index 78cc32e702..0000000000 --- a/src/Symfony/Bundle/DoctrineMongoDBBundle/Command/CreateSchemaDoctrineODMCommand.php +++ /dev/null @@ -1,53 +0,0 @@ - - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -namespace Symfony\Bundle\DoctrineMongoDBBundle\Command; - -use Symfony\Component\Console\Input\InputArgument; -use Symfony\Component\Console\Input\InputOption; -use Symfony\Component\Console\Input\InputInterface; -use Symfony\Component\Console\Output\OutputInterface; -use Symfony\Component\Console\Output\Output; -use Doctrine\ODM\MongoDB\Tools\Console\Command\Schema\CreateCommand; - -/** - * Command to create the database schema for a set of classes based on their mappings. - * - * @author Justin Hileman - */ -class CreateSchemaDoctrineODMCommand extends CreateCommand -{ - protected function configure() - { - parent::configure(); - - $this - ->setName('doctrine:mongodb:schema:create') - ->addOption('dm', null, InputOption::VALUE_REQUIRED, 'The document manager to use for this command.') - ->setHelp(<<doctrine:mongodb:schema:create command creates the default document manager's schema: - - ./app/console doctrine:mongodb:schema:create - -You can also optionally specify the name of a document manager to create the schema for: - - ./app/console doctrine:mongodb:schema:create --dm=default -EOT - ); - } - - protected function execute(InputInterface $input, OutputInterface $output) - { - DoctrineODMCommand::setApplicationDocumentManager($this->getApplication(), $input->getOption('dm')); - - parent::execute($input, $output); - } -} \ No newline at end of file diff --git a/src/Symfony/Bundle/DoctrineMongoDBBundle/Command/DoctrineODMCommand.php b/src/Symfony/Bundle/DoctrineMongoDBBundle/Command/DoctrineODMCommand.php deleted file mode 100644 index d0f8241785..0000000000 --- a/src/Symfony/Bundle/DoctrineMongoDBBundle/Command/DoctrineODMCommand.php +++ /dev/null @@ -1,121 +0,0 @@ - - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -namespace Symfony\Bundle\DoctrineMongoDBBundle\Command; - -use Symfony\Bundle\FrameworkBundle\Command\Command; -use Symfony\Bundle\FrameworkBundle\Console\Application; -use Doctrine\ODM\MongoDB\Tools\Console\Helper\DocumentManagerHelper; -use Symfony\Component\HttpKernel\Bundle\Bundle; -use Doctrine\ODM\MongoDB\Tools\DisconnectedClassMetadataFactory; -use Doctrine\ODM\MongoDB\Tools\DocumentGenerator; - -/** - * Base class for Doctrine ODM console commands to extend. - * - * @author Justin Hileman - */ -abstract class DoctrineODMCommand extends Command -{ - public static function setApplicationDocumentManager(Application $application, $dmName) - { - $container = $application->getKernel()->getContainer(); - $dmName = $dmName ? $dmName : 'default'; - $dmServiceName = sprintf('doctrine.odm.mongodb.%s_document_manager', $dmName); - if (!$container->has($dmServiceName)) { - throw new \InvalidArgumentException(sprintf('Could not find Doctrine ODM DocumentManager named "%s"', $dmName)); - } - - $dm = $container->get($dmServiceName); - $helperSet = $application->getHelperSet(); - $helperSet->set(new DocumentManagerHelper($dm), 'dm'); - } - - protected function getDocumentGenerator() - { - $documentGenerator = new DocumentGenerator(); - $documentGenerator->setAnnotationPrefix('mongodb:'); - $documentGenerator->setGenerateAnnotations(false); - $documentGenerator->setGenerateStubMethods(true); - $documentGenerator->setRegenerateDocumentIfExists(false); - $documentGenerator->setUpdateDocumentIfExists(true); - $documentGenerator->setNumSpaces(4); - return $documentGenerator; - } - - protected function getDoctrineDocumentManagers() - { - $documentManagerNames = $this->container->getParameter('doctrine.odm.mongodb.document_managers'); - $documentManagers = array(); - foreach ($documentManagerNames as $documentManagerName) { - $dm = $this->container->get(sprintf('doctrine.odm.mongodb.%s_document_manager', $documentManagerName)); - $documentManagers[] = $dm; - } - return $documentManagers; - } - - protected function getBundleMetadatas(Bundle $bundle) - { - $namespace = $bundle->getNamespace(); - $bundleMetadatas = array(); - $documentManagers = $this->getDoctrineDocumentManagers(); - foreach ($documentManagers as $key => $dm) { - $cmf = new DisconnectedClassMetadataFactory(); - $cmf->setDocumentManager($dm); - $cmf->setConfiguration($dm->getConfiguration()); - $metadatas = $cmf->getAllMetadata(); - foreach ($metadatas as $metadata) { - if (strpos($metadata->name, $namespace) === 0) { - $bundleMetadatas[$metadata->name] = $metadata; - } - } - } - - return $bundleMetadatas; - } - - protected function findBundle($bundleName) - { - $foundBundle = false; - foreach ($this->getApplication()->getKernel()->getBundles() as $bundle) { - /* @var $bundle Bundle */ - if (strtolower($bundleName) == strtolower($bundle->getName())) { - $foundBundle = $bundle; - break; - } - } - - if (!$foundBundle) { - throw new \InvalidArgumentException("No bundle " . $bundleName . " was found."); - } - - return $foundBundle; - } - - /** - * Transform classname to a path $foundBundle substract it to get the destination - * - * @param Bundle $bundle - * @return string - */ - protected function findBasePathForBundle($bundle) - { - $path = str_replace('\\', '/', $bundle->getNamespace()); - $search = str_replace('\\', '/', $bundle->getPath()); - $destination = str_replace('/'.$path, '', $search, $c); - - if ($c != 1) { - throw new \RuntimeException(sprintf('Can\'t find base path for bundle (path: "%s", destination: "%s").', $path, $destination)); - } - - return $destination; - } -} \ No newline at end of file diff --git a/src/Symfony/Bundle/DoctrineMongoDBBundle/Command/DropSchemaDoctrineODMCommand.php b/src/Symfony/Bundle/DoctrineMongoDBBundle/Command/DropSchemaDoctrineODMCommand.php deleted file mode 100644 index cb1ab9e888..0000000000 --- a/src/Symfony/Bundle/DoctrineMongoDBBundle/Command/DropSchemaDoctrineODMCommand.php +++ /dev/null @@ -1,53 +0,0 @@ - - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -namespace Symfony\Bundle\DoctrineMongoDBBundle\Command; - -use Symfony\Component\Console\Input\InputArgument; -use Symfony\Component\Console\Input\InputOption; -use Symfony\Component\Console\Input\InputInterface; -use Symfony\Component\Console\Output\OutputInterface; -use Symfony\Component\Console\Output\Output; -use Doctrine\ODM\MongoDB\Tools\Console\Command\Schema\DropCommand; - -/** - * Command to create the database schema for a set of classes based on their mappings. - * - * @author Justin Hileman - */ -class DropSchemaDoctrineODMCommand extends DropCommand -{ - protected function configure() - { - parent::configure(); - - $this - ->setName('doctrine:mongodb:schema:drop') - ->addOption('dm', null, InputOption::VALUE_REQUIRED, 'The document manager to use for this command.') - ->setHelp(<<doctrine:mongodb:schema:drop command drops the default document manager's schema: - - ./app/console doctrine:mongodb:schema:drop - -You can also optionally specify the name of a document manager to drop the schema for: - - ./app/console doctrine:mongodb:schema:drop --dm=default -EOT - ); - } - - protected function execute(InputInterface $input, OutputInterface $output) - { - DoctrineODMCommand::setApplicationDocumentManager($this->getApplication(), $input->getOption('dm')); - - parent::execute($input, $output); - } -} \ No newline at end of file diff --git a/src/Symfony/Bundle/DoctrineMongoDBBundle/Command/GenerateDocumentsDoctrineODMCommand.php b/src/Symfony/Bundle/DoctrineMongoDBBundle/Command/GenerateDocumentsDoctrineODMCommand.php deleted file mode 100644 index fabb536b59..0000000000 --- a/src/Symfony/Bundle/DoctrineMongoDBBundle/Command/GenerateDocumentsDoctrineODMCommand.php +++ /dev/null @@ -1,80 +0,0 @@ - - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -namespace Symfony\Bundle\DoctrineMongoDBBundle\Command; - -use Symfony\Component\Console\Input\InputArgument; -use Symfony\Component\Console\Input\InputOption; -use Symfony\Component\Console\Input\InputInterface; -use Symfony\Component\Console\Output\OutputInterface; -use Symfony\Component\Console\Output\Output; - -/** - * Generate document classes from mapping information - * - * @author Fabien Potencier - * @author Jonathan H. Wage - */ -class GenerateDocumentsDoctrineODMCommand extends DoctrineODMCommand -{ - protected function configure() - { - $this - ->setName('doctrine:mongodb:generate:documents') - ->setDescription('Generate document classes and method stubs from your mapping information.') - ->addArgument('bundle', InputArgument::REQUIRED, 'The bundle to initialize the document or documents in.') - ->addOption('document', null, InputOption::VALUE_OPTIONAL, 'The document class to initialize (shortname without namespace).') - ->setHelp(<<doctrine:mongodb:generate:documents command generates document classes and method stubs from your mapping information: - -You have to limit generation of documents to an individual bundle: - - ./app/console doctrine:mongodb:generate:documents MyCustomBundle - -Alternatively, you can limit generation to a single document within a bundle: - - ./app/console doctrine:mongodb:generate:documents "MyCustomBundle" --document="User" - -You have to specify the shortname (without namespace) of the document you want to filter for. -EOT - ); - } - - protected function execute(InputInterface $input, OutputInterface $output) - { - $bundleName = $input->getArgument('bundle'); - $filterDocument = $input->getOption('document'); - - $foundBundle = $this->findBundle($bundleName); - - if ($metadatas = $this->getBundleMetadatas($foundBundle)) { - $output->writeln(sprintf('Generating documents for "%s"', $foundBundle->getName())); - $documentGenerator = $this->getDocumentGenerator(); - - foreach ($metadatas as $metadata) { - if ($filterDocument && $metadata->reflClass->getShortName() == $filterDocument) { - continue; - } - - if (strpos($metadata->name, $foundBundle->getNamespace()) === false) { - throw new \RuntimeException( - "Document " . $metadata->name . " and bundle don't have a common namespace, ". - "generation failed because the target directory cannot be detected."); - } - - $output->writeln(sprintf(' > generating %s', $metadata->name)); - $documentGenerator->generate(array($metadata), $this->findBasePathForBundle($foundBundle)); - } - } else { - throw new \RuntimeException("Bundle " . $bundleName . " does not contain any mapped documents."); - } - } -} diff --git a/src/Symfony/Bundle/DoctrineMongoDBBundle/Command/GenerateHydratorsDoctrineODMCommand.php b/src/Symfony/Bundle/DoctrineMongoDBBundle/Command/GenerateHydratorsDoctrineODMCommand.php deleted file mode 100644 index c025fae963..0000000000 --- a/src/Symfony/Bundle/DoctrineMongoDBBundle/Command/GenerateHydratorsDoctrineODMCommand.php +++ /dev/null @@ -1,54 +0,0 @@ - - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -namespace Symfony\Bundle\DoctrineMongoDBBundle\Command; - -use Symfony\Component\Console\Input\InputArgument; -use Symfony\Component\Console\Input\InputOption; -use Symfony\Component\Console\Input\InputInterface; -use Symfony\Component\Console\Output\OutputInterface; -use Symfony\Component\Console\Output\Output; -use Doctrine\ODM\MongoDB\Tools\Console\Command\GenerateHydratorsCommand; - -/** - * Generate the Doctrine ORM document hydrators to your cache directory. - * - * @author Fabien Potencier - * @author Jonathan H. Wage - */ -class GenerateHydratorsDoctrineODMCommand extends GenerateHydratorsCommand -{ - protected function configure() - { - parent::configure(); - - $this - ->setName('doctrine:mongodb:generate:hydrators') - ->addOption('dm', null, InputOption::VALUE_OPTIONAL, 'The document manager to use for this command.') - ->setHelp(<<doctrine:mongodb:generate:hydrators command generates hydrator classes for your documents: - - ./app/console doctrine:mongodb:generate:hydrators - -You can specify the document manager you want to generate the hydrators for: - - ./app/console doctrine:mongodb:generate:hydrators --dm=name -EOT - ); - } - - protected function execute(InputInterface $input, OutputInterface $output) - { - DoctrineODMCommand::setApplicationDocumentManager($this->getApplication(), $input->getOption('dm')); - - return parent::execute($input, $output); - } -} diff --git a/src/Symfony/Bundle/DoctrineMongoDBBundle/Command/GenerateProxiesDoctrineODMCommand.php b/src/Symfony/Bundle/DoctrineMongoDBBundle/Command/GenerateProxiesDoctrineODMCommand.php deleted file mode 100644 index ecf8b650b2..0000000000 --- a/src/Symfony/Bundle/DoctrineMongoDBBundle/Command/GenerateProxiesDoctrineODMCommand.php +++ /dev/null @@ -1,54 +0,0 @@ - - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -namespace Symfony\Bundle\DoctrineMongoDBBundle\Command; - -use Symfony\Component\Console\Input\InputArgument; -use Symfony\Component\Console\Input\InputOption; -use Symfony\Component\Console\Input\InputInterface; -use Symfony\Component\Console\Output\OutputInterface; -use Symfony\Component\Console\Output\Output; -use Doctrine\ODM\MongoDB\Tools\Console\Command\GenerateProxiesCommand; - -/** - * Generate the Doctrine ORM document proxies to your cache directory. - * - * @author Fabien Potencier - * @author Jonathan H. Wage - */ -class GenerateProxiesDoctrineODMCommand extends GenerateProxiesCommand -{ - protected function configure() - { - parent::configure(); - - $this - ->setName('doctrine:mongodb:generate:proxies') - ->addOption('dm', null, InputOption::VALUE_OPTIONAL, 'The document manager to use for this command.') - ->setHelp(<<doctrine:mongodb:generate:proxies command generates proxy classes for your default document manager: - - ./app/console doctrine:mongodb:generate:proxies - -You can specify the document manager you want to generate the proxies for: - - ./app/console doctrine:mongodb:generate:proxies --dm=name -EOT - ); - } - - protected function execute(InputInterface $input, OutputInterface $output) - { - DoctrineODMCommand::setApplicationDocumentManager($this->getApplication(), $input->getOption('dm')); - - return parent::execute($input, $output); - } -} diff --git a/src/Symfony/Bundle/DoctrineMongoDBBundle/Command/GenerateRepositoriesDoctrineODMCommand.php b/src/Symfony/Bundle/DoctrineMongoDBBundle/Command/GenerateRepositoriesDoctrineODMCommand.php deleted file mode 100644 index c20774315c..0000000000 --- a/src/Symfony/Bundle/DoctrineMongoDBBundle/Command/GenerateRepositoriesDoctrineODMCommand.php +++ /dev/null @@ -1,77 +0,0 @@ - - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -namespace Symfony\Bundle\DoctrineMongoDBBundle\Command; - -use Symfony\Component\Console\Input\InputArgument; -use Symfony\Component\Console\Input\InputOption; -use Symfony\Component\Console\Input\InputInterface; -use Symfony\Component\Console\Output\OutputInterface; -use Symfony\Component\Console\Output\Output; -use Doctrine\ODM\MongoDB\Tools\DocumentRepositoryGenerator; - -/** - * Command to generate repository classes for mapping information. - * - * @author Fabien Potencier - * @author Jonathan H. Wage - */ -class GenerateRepositoriesDoctrineODMCommand extends DoctrineODMCommand -{ - protected function configure() - { - $this - ->setName('doctrine:mongodb:generate:repositories') - ->setDescription('Generate repository classes from your mapping information.') - ->addArgument('bundle', InputArgument::REQUIRED, 'The bundle to initialize the repositories in.') - ->addOption('document', null, InputOption::VALUE_OPTIONAL, 'The document class to generate the repository for (shortname without namespace).') - ->setHelp(<<doctrine:mongodb:generate:repositories command generates the configured document repository classes from your mapping information: - - ./app/console doctrine:mongodb:generate:repositories -EOT - ); - } - - protected function execute(InputInterface $input, OutputInterface $output) - { - $bundleName = $input->getArgument('bundle'); - $filterDocument = $input->getOption('document'); - - $foundBundle = $this->findBundle($bundleName); - - if ($metadatas = $this->getBundleMetadatas($foundBundle)) { - $output->writeln(sprintf('Generating document repositories for "%s"', $foundBundle->getName())); - $generator = new DocumentRepositoryGenerator(); - - foreach ($metadatas as $metadata) { - if ($filterDocument && $filterDocument !== $metadata->reflClass->getShortname()) { - continue; - } - - if ($metadata->customRepositoryClassName) { - if (strpos($metadata->customRepositoryClassName, $foundBundle->getNamespace()) === false) { - throw new \RuntimeException( - "Repository " . $metadata->customRepositoryClassName . " and bundle don't have a common namespace, ". - "generation failed because the target directory cannot be detected."); - } - - $output->writeln(sprintf(' > OK generating %s', $metadata->customRepositoryClassName)); - $generator->writeDocumentRepositoryClass($metadata->customRepositoryClassName, $this->findBasePathForBundle($foundBundle)); - } else { - $output->writeln(sprintf(' > SKIP no custom repository for %s', $metadata->name)); - } - } - } else { - throw new \RuntimeException("Bundle " . $bundleName . " does not contain any mapped documents."); - } - } -} diff --git a/src/Symfony/Bundle/DoctrineMongoDBBundle/Command/InfoDoctrineODMCommand.php b/src/Symfony/Bundle/DoctrineMongoDBBundle/Command/InfoDoctrineODMCommand.php deleted file mode 100644 index 51779b22d6..0000000000 --- a/src/Symfony/Bundle/DoctrineMongoDBBundle/Command/InfoDoctrineODMCommand.php +++ /dev/null @@ -1,84 +0,0 @@ - - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -namespace Symfony\Bundle\DoctrineMongoDBBundle\Command; - -use Symfony\Component\Console\Input\InputArgument; -use Symfony\Component\Console\Input\InputOption; -use Symfony\Component\Console\Input\InputInterface; -use Symfony\Component\Console\Output\OutputInterface; - -/** - * Show information about mapped documents - * - * @author Benjamin Eberlei - * @author Jonathan H. Wage - */ -class InfoDoctrineODMCommand extends DoctrineODMCommand -{ - protected function configure() - { - $this - ->setName('doctrine:mongodb:mapping:info') - ->addOption('dm', null, InputOption::VALUE_OPTIONAL, 'The document manager to use for this command.') - ->setDescription('Show basic information about all mapped documents.') - ->setHelp(<<doctrine:mongodb:mapping:info shows basic information about which -documents exist and possibly if their mapping information contains errors or not. - - ./app/console doctrine:mongodb:mapping:info - -If you are using multiple document managers you can pick your choice with the --dm option: - - ./app/console doctrine:mongodb:mapping:info --dm=default -EOT - ); - } - - protected function execute(InputInterface $input, OutputInterface $output) - { - $documentManagerName = $input->getOption('dm') ? - $input->getOption('dm') : - $this->container->getParameter('doctrine.odm.mongodb.default_document_manager'); - - $documentManagerService = sprintf('doctrine.odm.mongodb.%s_document_manager', $documentManagerName); - - /* @var $documentManager Doctrine\ODM\MongoDB\DocumentManager */ - $documentManager = $this->container->get($documentManagerService); - - $documentClassNames = $documentManager->getConfiguration() - ->getMetadataDriverImpl() - ->getAllClassNames(); - - if (!$documentClassNames) { - throw new \Exception( - 'You do not have any mapped Doctrine MongoDB ODM documents for any of your bundles. '. - 'Create a class inside the Document namespace of any of your bundles and provide '. - 'mapping information for it with Annotations directly in the classes doc blocks '. - 'or with XML/YAML in your bundles Resources/config/doctrine/metadata/mongodb directory.' - ); - } - - $output->write(sprintf("Found %d documents mapped in document manager %s:\n", - count($documentClassNames), $documentManagerName), true); - - foreach ($documentClassNames AS $documentClassName) { - try { - $cm = $documentManager->getClassMetadata($documentClassName); - $output->write("[OK] " . $documentClassName, true); - } catch(\Exception $e) { - $output->write("[FAIL] " . $documentClassName, true); - $output->write("" . $e->getMessage()."", true); - $output->write("", true); - } - } - } -} diff --git a/src/Symfony/Bundle/DoctrineMongoDBBundle/Command/LoadDataFixturesDoctrineODMCommand.php b/src/Symfony/Bundle/DoctrineMongoDBBundle/Command/LoadDataFixturesDoctrineODMCommand.php deleted file mode 100644 index 6d88b9c781..0000000000 --- a/src/Symfony/Bundle/DoctrineMongoDBBundle/Command/LoadDataFixturesDoctrineODMCommand.php +++ /dev/null @@ -1,108 +0,0 @@ - - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -namespace Symfony\Bundle\DoctrineMongoDBBundle\Command; - -use Symfony\Component\Console\Input\InputArgument; -use Symfony\Component\Console\Input\InputOption; -use Symfony\Component\Console\Input\InputInterface; -use Symfony\Component\Console\Output\OutputInterface; -use Symfony\Component\Console\Output\Output; -use Symfony\Component\Finder\Finder; -use Symfony\Component\HttpKernel\Util\Filesystem; -use Symfony\Bundle\DoctrineAbstractBundle\Common\DataFixtures\Loader as DataFixturesLoader; -use Doctrine\Common\DataFixtures\Executor\MongoDBExecutor; -use Doctrine\Common\DataFixtures\Purger\MongoDBPurger; -use Doctrine\ODM\MongoDB\DocumentManager; -use Doctrine\ODM\MongoDB\Internal\CommitOrderCalculator; -use Doctrine\ODM\MongoDB\Mapping\ClassMetadata; -use InvalidArgumentException; - -/** - * Load data fixtures from bundles. - * - * @author Fabien Potencier - * @author Jonathan H. Wage - */ -class LoadDataFixturesDoctrineODMCommand extends DoctrineODMCommand -{ - protected function configure() - { - $this - ->setName('doctrine:mongodb:data:load') - ->setDescription('Load data fixtures to your database.') - ->addOption('fixtures', null, InputOption::VALUE_OPTIONAL | InputOption::VALUE_IS_ARRAY, 'The directory or file to load data fixtures from.') - ->addOption('append', null, InputOption::VALUE_NONE, 'Append the data fixtures instead of flushing the database first.') - ->addOption('dm', null, InputOption::VALUE_REQUIRED, 'The document manager to use for this command.') - ->setHelp(<<doctrine:mongodb:data:load command loads data fixtures from your bundles: - - ./app/console doctrine:mongodb:data:load - -You can also optionally specify the path to fixtures with the --fixtures option: - - ./app/console doctrine:mongodb:data:load --fixtures=/path/to/fixtures1 --fixtures=/path/to/fixtures2 - -If you want to append the fixtures instead of flushing the database first you can use the --append option: - - ./app/console doctrine:mongodb:data:load --append -EOT - ); - } - - protected function execute(InputInterface $input, OutputInterface $output) - { - $dmName = $input->getOption('dm'); - $dmName = $dmName ? $dmName : 'default'; - $dmServiceName = sprintf('doctrine.odm.mongodb.%s_document_manager', $dmName); - - if (!$this->container->has($dmServiceName)) { - throw new InvalidArgumentException( - sprintf( - 'Could not find a document manager configured with the name "%s". Check your '. - 'application configuration to configure your Doctrine document managers.', $dmName - ) - ); - } - - $dm = $this->container->get($dmServiceName); - $dirOrFile = $input->getOption('fixtures'); - if ($dirOrFile) { - $paths = is_array($dirOrFile) ? $dirOrFile : array($dirOrFile); - } else { - $paths = array(); - foreach ($this->container->get('kernel')->getBundles() as $bundle) { - $paths[] = $bundle->getPath().'/DataFixtures/MongoDB'; - } - } - - $loader = new DataFixturesLoader($this->container); - foreach ($paths as $path) { - if (is_dir($path)) { - $loader->loadFromDirectory($path); - } - } - - $fixtures = $loader->getFixtures(); - if (!$fixtures) { - throw new InvalidArgumentException( - sprintf('Could not find any fixtures to load in: %s', "\n\n- ".implode("\n- ", $paths)) - ); - } - - $purger = new MongoDBPurger($dm); - $executor = new MongoDBExecutor($dm, $purger); - $executor->setLogger(function($message) use ($output) { - $output->writeln(sprintf(' > %s', $message)); - }); - $executor->execute($fixtures, $input->getOption('append')); - } -} \ No newline at end of file diff --git a/src/Symfony/Bundle/DoctrineMongoDBBundle/Command/QueryDoctrineODMCommand.php b/src/Symfony/Bundle/DoctrineMongoDBBundle/Command/QueryDoctrineODMCommand.php deleted file mode 100644 index fdacd39768..0000000000 --- a/src/Symfony/Bundle/DoctrineMongoDBBundle/Command/QueryDoctrineODMCommand.php +++ /dev/null @@ -1,44 +0,0 @@ - - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -namespace Symfony\Bundle\DoctrineMongoDBBundle\Command; - -use Symfony\Component\Console\Input\InputArgument; -use Symfony\Component\Console\Input\InputOption; -use Symfony\Component\Console\Input\InputInterface; -use Symfony\Component\Console\Output\OutputInterface; -use Symfony\Component\Console\Output\Output; -use Doctrine\ODM\MongoDB\Tools\Console\Command\QueryCommand; - -/** - * Execute a Doctrine MongoDB ODM query and output the results. - * - * @author Fabien Potencier - * @author Jonathan H. Wage - */ -class QueryDoctrineODMCommand extends QueryCommand -{ - protected function configure() - { - parent::configure(); - - $this - ->setName('doctrine:mongodb:query') - ->addOption('dm', null, InputOption::VALUE_OPTIONAL, 'The document manager to use for this command.'); - } - - protected function execute(InputInterface $input, OutputInterface $output) - { - DoctrineODMCommand::setApplicationDocumentManager($this->getApplication(), $input->getOption('dm')); - - return parent::execute($input, $output); - } -} \ No newline at end of file diff --git a/src/Symfony/Bundle/DoctrineMongoDBBundle/DataCollector/DoctrineMongoDBDataCollector.php b/src/Symfony/Bundle/DoctrineMongoDBBundle/DataCollector/DoctrineMongoDBDataCollector.php deleted file mode 100644 index dc2e675726..0000000000 --- a/src/Symfony/Bundle/DoctrineMongoDBBundle/DataCollector/DoctrineMongoDBDataCollector.php +++ /dev/null @@ -1,59 +0,0 @@ - - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -namespace Symfony\Bundle\DoctrineMongoDBBundle\DataCollector; - -use Symfony\Component\HttpKernel\DataCollector\DataCollector; -use Symfony\Bundle\DoctrineMongoDBBundle\Logger\DoctrineMongoDBLogger; -use Symfony\Component\HttpFoundation\Request; -use Symfony\Component\HttpFoundation\Response; - -/** - * Data collector for the Doctrine MongoDB ODM. - * - * @author Kris Wallsmith - */ -class DoctrineMongoDBDataCollector extends DataCollector -{ - protected $logger; - - public function __construct(DoctrineMongoDBLogger $logger) - { - $this->logger = $logger; - } - - /** - * {@inheritdoc} - */ - public function collect(Request $request, Response $response, \Exception $exception = null) - { - $this->data['nb_queries'] = $this->logger->getNbQueries(); - $this->data['queries'] = $this->logger->getQueries(); - } - - public function getQueryCount() - { - return $this->data['nb_queries']; - } - - public function getQueries() - { - return $this->data['queries']; - } - - /** - * {@inheritdoc} - */ - public function getName() - { - return 'mongodb'; - } -} diff --git a/src/Symfony/Bundle/DoctrineMongoDBBundle/DependencyInjection/Compiler/AddValidatorNamespaceAliasPass.php b/src/Symfony/Bundle/DoctrineMongoDBBundle/DependencyInjection/Compiler/AddValidatorNamespaceAliasPass.php deleted file mode 100644 index 3cfd2e93ac..0000000000 --- a/src/Symfony/Bundle/DoctrineMongoDBBundle/DependencyInjection/Compiler/AddValidatorNamespaceAliasPass.php +++ /dev/null @@ -1,22 +0,0 @@ -hasDefinition('validator.mapping.loader.annotation_loader')) { - return; - } - - $loader = $container->getDefinition('validator.mapping.loader.annotation_loader'); - $args = $loader->getArguments(); - - $args[0]['assertMongoDB'] = 'Symfony\\Bundle\\DoctrineMongoDBBundle\\Validator\\Constraints\\'; - $loader->replaceArgument(0, $args[0]); - } -} diff --git a/src/Symfony/Bundle/DoctrineMongoDBBundle/DependencyInjection/Compiler/CreateHydratorDirectoryPass.php b/src/Symfony/Bundle/DoctrineMongoDBBundle/DependencyInjection/Compiler/CreateHydratorDirectoryPass.php deleted file mode 100644 index 1855c4e827..0000000000 --- a/src/Symfony/Bundle/DoctrineMongoDBBundle/DependencyInjection/Compiler/CreateHydratorDirectoryPass.php +++ /dev/null @@ -1,30 +0,0 @@ -hasParameter('doctrine.odm.mongodb.hydrator_dir')) { - return; - } - // Don't do anything if auto_generate_hydrator_classes is false - if (!$container->getParameter('doctrine.odm.mongodb.auto_generate_hydrator_classes')) { - return; - } - // Create document proxy directory - $hydratorCacheDir = $container->getParameter('doctrine.odm.mongodb.hydrator_dir'); - if (!is_dir($hydratorCacheDir)) { - if (false === @mkdir($hydratorCacheDir, 0777, true)) { - exit(sprintf('Unable to create the Doctrine Hydrator directory (%s)', dirname($hydratorCacheDir))); - } - } elseif (!is_writable($hydratorCacheDir)) { - exit(sprintf('Unable to write in the Doctrine Hydrator directory (%s)', $hydratorCacheDir)); - } - } - -} diff --git a/src/Symfony/Bundle/DoctrineMongoDBBundle/DependencyInjection/Compiler/CreateProxyDirectoryPass.php b/src/Symfony/Bundle/DoctrineMongoDBBundle/DependencyInjection/Compiler/CreateProxyDirectoryPass.php deleted file mode 100644 index e14cc9e503..0000000000 --- a/src/Symfony/Bundle/DoctrineMongoDBBundle/DependencyInjection/Compiler/CreateProxyDirectoryPass.php +++ /dev/null @@ -1,30 +0,0 @@ -hasParameter('doctrine.odm.mongodb.proxy_dir')) { - return; - } - // Don't do anything if auto_generate_proxy_classes is false - if (!$container->getParameter('doctrine.odm.mongodb.auto_generate_proxy_classes')) { - return; - } - // Create document proxy directory - $proxyCacheDir = $container->getParameter('doctrine.odm.mongodb.proxy_dir'); - if (!is_dir($proxyCacheDir)) { - if (false === @mkdir($proxyCacheDir, 0777, true)) { - exit(sprintf('Unable to create the Doctrine Proxy directory (%s)', dirname($proxyCacheDir))); - } - } elseif (!is_writable($proxyCacheDir)) { - exit(sprintf('Unable to write in the Doctrine Proxy directory (%s)', $proxyCacheDir)); - } - } - -} diff --git a/src/Symfony/Bundle/DoctrineMongoDBBundle/DependencyInjection/Compiler/RegisterEventListenersAndSubscribersPass.php b/src/Symfony/Bundle/DoctrineMongoDBBundle/DependencyInjection/Compiler/RegisterEventListenersAndSubscribersPass.php deleted file mode 100644 index b104c57845..0000000000 --- a/src/Symfony/Bundle/DoctrineMongoDBBundle/DependencyInjection/Compiler/RegisterEventListenersAndSubscribersPass.php +++ /dev/null @@ -1,59 +0,0 @@ -container = $container; - foreach ($container->findTaggedServiceIds('doctrine.odm.mongodb.event_manager') as $id => $tag) { - $definition = $container->getDefinition($id); - $prefix = substr($id, 0, -1 * strlen('_event_manager')); - $this->registerListeners($prefix, $definition); - $this->registerSubscribers($prefix, $definition); - } - } - - protected function registerSubscribers($prefix, $definition) - { - $subscribers = array_merge( - $this->container->findTaggedServiceIds('doctrine.common.event_subscriber'), - $this->container->findTaggedServiceIds($prefix.'_event_subscriber') - ); - - foreach ($subscribers as $id => $instances) { - $definition->addMethodCall('addEventSubscriber', array(new Reference($id))); - } - } - - protected function registerListeners($prefix, $definition) - { - $listeners = array_merge( - $this->container->findTaggedServiceIds('doctrine.common.event_listener'), - $this->container->findTaggedServiceIds($prefix.'_event_listener') - ); - - foreach ($listeners as $listenerId => $instances) { - $events = array(); - foreach ($instances as $attributes) { - if (isset($attributes['event'])) { - $events[] = $attributes['event']; - } - } - - if (0 < count($events)) { - $definition->addMethodCall('addEventListener', array( - $events, - new Reference($listenerId), - )); - } - } - } -} diff --git a/src/Symfony/Bundle/DoctrineMongoDBBundle/DependencyInjection/Configuration.php b/src/Symfony/Bundle/DoctrineMongoDBBundle/DependencyInjection/Configuration.php deleted file mode 100644 index 44bd4da798..0000000000 --- a/src/Symfony/Bundle/DoctrineMongoDBBundle/DependencyInjection/Configuration.php +++ /dev/null @@ -1,193 +0,0 @@ - - */ -class Configuration implements ConfigurationInterface -{ - private $debug; - - /** - * Constructor. - * - * @param Boolean $debug The kernel.debug value - */ - public function __construct($debug) - { - $this->debug = (Boolean) $debug; - } - - /** - * Generates the configuration tree builder. - * - * @return \Symfony\Component\Config\Definition\Builder\TreeBuilder The tree builder - */ - public function getConfigTreeBuilder() - { - $treeBuilder = new TreeBuilder(); - $rootNode = $treeBuilder->root('doctrine_mongo_db'); - - $this->addDocumentManagersSection($rootNode); - $this->addConnectionsSection($rootNode); - - $rootNode - ->children() - ->scalarNode('proxy_namespace')->defaultValue('Proxies')->end() - ->scalarNode('proxy_dir')->defaultValue('%kernel.cache_dir%/doctrine/odm/mongodb/Proxies')->end() - ->scalarNode('auto_generate_proxy_classes')->defaultValue(false)->end() - ->scalarNode('hydrator_namespace')->defaultValue('Hydrators')->end() - ->scalarNode('hydrator_dir')->defaultValue('%kernel.cache_dir%/doctrine/odm/mongodb/Hydrators')->end() - ->scalarNode('auto_generate_hydrator_classes')->defaultValue(false)->end() - ->scalarNode('default_document_manager')->end() - ->scalarNode('default_connection')->end() - ->scalarNode('default_database')->defaultValue('default')->end() - ->end() - ; - - return $treeBuilder; - } - - /** - * Configures the "document_managers" section - */ - private function addDocumentManagersSection(ArrayNodeDefinition $rootNode) - { - $rootNode - ->fixXmlConfig('document_manager') - ->children() - ->arrayNode('document_managers') - ->useAttributeAsKey('id') - ->prototype('array') - //->performNoDeepMerging() - ->treatNullLike(array()) - ->append($this->getMetadataCacheDriverNode()) - ->children() - ->scalarNode('connection')->end() - ->scalarNode('database')->end() - ->booleanNode('logging')->defaultValue($this->debug)->end() - ->end() - ->fixXmlConfig('mapping') - ->append($this->getMappingsNode()) - ->end() - ->end() - ->end() - ; - } - - /** - * Adds the configuration for the "connections" key - */ - private function addConnectionsSection(ArrayNodeDefinition $rootNode) - { - $rootNode - ->fixXmlConfig('connection') - ->children() - ->arrayNode('connections') - ->useAttributeAsKey('id') - ->prototype('array') - ->performNoDeepMerging() - ->children() - ->scalarNode('server')->defaultNull()->end() - ->end() - ->append($this->addConnectionOptionsNode()) - ->end() - ->end() - ->end() - ; - } - - /** - * Returns the array node used for "mappings". - * - * This is used in two different parts of the tree. - * - * @param NodeBuilder $rootNode The parent node - * @return NodeBuilder - */ - protected function getMappingsNode() - { - $builder = new TreeBuilder(); - $node = $builder->root('mappings'); - - $node - ->useAttributeAsKey('name') - ->prototype('array') - ->beforeNormalization() - // if it's not an array, then the scalar is the type key - ->ifString() - ->then(function($v) { return array ('type' => $v); }) - ->end() - // I believe that "null" should *not* set the type - // it's guessed in AbstractDoctrineExtension::detectMetadataDriver - ->treatNullLike(array()) - ->children() - ->scalarNode('type')->end() - ->scalarNode('dir')->end() - ->scalarNode('prefix')->end() - ->scalarNode('alias')->end() - ->booleanNode('is_bundle')->end() - ->end() - ->performNoDeepMerging() - ->end() - ; - - return $node; - } - - /** - * Adds the NodeBuilder for the "options" key of a connection. - */ - private function addConnectionOptionsNode() - { - $builder = new TreeBuilder(); - $node = $builder->root('options'); - - $node - ->performNoDeepMerging() - ->addDefaultsIfNotSet() // adds an empty array of omitted - // options go into the Mongo constructor - // http://www.php.net/manual/en/mongo.construct.php - ->children() - ->booleanNode('connect')->end() - ->scalarNode('persist')->end() - ->scalarNode('timeout')->end() - ->booleanNode('replicaSet')->end() - ->scalarNode('username')->end() - ->scalarNode('password')->end() - ->end() - ->end(); - - return $node; - } - - private function getMetadataCacheDriverNode() - { - $builder = new TreeBuilder(); - $node = $builder->root('metadata_cache_driver'); - - $node - ->beforeNormalization() - // if scalar - ->ifTrue(function($v) { return !is_array($v); }) - ->then(function($v) { return array('type' => $v); }) - ->end() - ->children() - ->scalarNode('type')->end() - ->scalarNode('class')->end() - ->scalarNode('host')->end() - ->scalarNode('port')->end() - ->scalarNode('instance_class')->end() - ->end() - ->end(); - - return $node; - } -} diff --git a/src/Symfony/Bundle/DoctrineMongoDBBundle/DependencyInjection/DoctrineMongoDBExtension.php b/src/Symfony/Bundle/DoctrineMongoDBBundle/DependencyInjection/DoctrineMongoDBExtension.php deleted file mode 100644 index 7d0f002dc7..0000000000 --- a/src/Symfony/Bundle/DoctrineMongoDBBundle/DependencyInjection/DoctrineMongoDBExtension.php +++ /dev/null @@ -1,344 +0,0 @@ - - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -namespace Symfony\Bundle\DoctrineMongoDBBundle\DependencyInjection; - -use Symfony\Component\DependencyInjection\Loader\XmlFileLoader; -use Symfony\Component\DependencyInjection\ContainerBuilder; -use Symfony\Component\DependencyInjection\Alias; -use Symfony\Component\DependencyInjection\Reference; -use Symfony\Component\DependencyInjection\Definition; -use Symfony\Component\Config\FileLocator; -use Symfony\Component\Config\Definition\Processor; -use Symfony\Bundle\DoctrineAbstractBundle\DependencyInjection\AbstractDoctrineExtension; - -/** - * Doctrine MongoDB ODM extension. - * - * @author Bulat Shakirzyanov - * @author Kris Wallsmith - * @author Jonathan H. Wage - */ -class DoctrineMongoDBExtension extends AbstractDoctrineExtension -{ - /** - * Responds to the doctrine_mongo_db configuration parameter. - */ - public function load(array $configs, ContainerBuilder $container) - { - // Load DoctrineMongoDBBundle/Resources/config/mongodb.xml - $loader = new XmlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config')); - $loader->load('mongodb.xml'); - - $processor = new Processor(); - $configuration = new Configuration($container->getParameter('kernel.debug')); - $config = $processor->processConfiguration($configuration, $configs); - - // can't currently default this correctly in Configuration - if (!isset($config['metadata_cache_driver'])) { - $config['metadata_cache_driver'] = array('type' => 'array'); - } - - if (empty ($config['default_connection'])) { - $keys = array_keys($config['connections']); - $config['default_connection'] = reset($keys); - } - - if (empty ($config['default_document_manager'])) { - $keys = array_keys($config['document_managers']); - $config['default_document_manager'] = reset($keys); - } - - // set some options as parameters and unset them - $config = $this->overrideParameters($config, $container); - - // load the connections - $this->loadConnections($config['connections'], $container); - - // load the document managers - $this->loadDocumentManagers( - $config['document_managers'], - $config['default_document_manager'], - $config['default_database'], - $config['metadata_cache_driver'], - $container - ); - } - - /** - * Uses some of the extension options to override DI extension parameters. - * - * @param array $options The available configuration options - * @param ContainerBuilder $container A ContainerBuilder instance - */ - protected function overrideParameters($options, ContainerBuilder $container) - { - $overrides = array( - 'proxy_namespace', - 'proxy_dir', - 'auto_generate_proxy_classes', - 'hydrator_namespace', - 'hydrator_dir', - 'auto_generate_hydrator_classes', - ); - - foreach ($overrides as $key) { - if (isset($options[$key])) { - $container->setParameter('doctrine.odm.mongodb.'.$key, $options[$key]); - - // the option should not be used, the parameter should be referenced - unset($options[$key]); - } - } - - return $options; - } - - /** - * Loads the document managers configuration. - * - * @param array $dmConfigs An array of document manager configs - * @param string $defaultDM The default document manager name - * @param string $defaultDB The default db name - * @param string $defaultMetadataCache The default metadata cache configuration - * @param ContainerBuilder $container A ContainerBuilder instance - */ - protected function loadDocumentManagers(array $dmConfigs, $defaultDM, $defaultDB, $defaultMetadataCache, ContainerBuilder $container) - { - foreach ($dmConfigs as $name => $documentManager) { - $documentManager['name'] = $name; - $this->loadDocumentManager( - $documentManager, - $defaultDM, - $defaultDB, - $defaultMetadataCache, - $container - ); - } - $container->setParameter('doctrine.odm.mongodb.document_managers', array_keys($dmConfigs)); - } - - /** - * Loads a document manager configuration. - * - * @param array $documentManager A document manager configuration array - * @param string $defaultDM The default document manager name - * @param string $defaultDB The default db name - * @param string $defaultMetadataCache The default metadata cache configuration - * @param ContainerBuilder $container A ContainerBuilder instance - */ - protected function loadDocumentManager(array $documentManager, $defaultDM, $defaultDB, $defaultMetadataCache, ContainerBuilder $container) - { - $defaultDatabase = isset($documentManager['default_database']) ? $documentManager['default_database'] : $defaultDB; - $configServiceName = sprintf('doctrine.odm.mongodb.%s_configuration', $documentManager['name']); - - if ($container->hasDefinition($configServiceName)) { - $odmConfigDef = $container->getDefinition($configServiceName); - } else { - $odmConfigDef = new Definition('%doctrine.odm.mongodb.configuration_class%'); - $container->setDefinition($configServiceName, $odmConfigDef); - } - - $this->loadDocumentManagerBundlesMappingInformation($documentManager, $odmConfigDef, $container); - $this->loadDocumentManagerMetadataCacheDriver($documentManager, $container, $defaultMetadataCache); - - $methods = array( - 'setMetadataCacheImpl' => new Reference(sprintf('doctrine.odm.mongodb.%s_metadata_cache', $documentManager['name'])), - 'setMetadataDriverImpl' => new Reference(sprintf('doctrine.odm.mongodb.%s_metadata_driver', $documentManager['name'])), - 'setProxyDir' => '%doctrine.odm.mongodb.proxy_dir%', - 'setProxyNamespace' => '%doctrine.odm.mongodb.proxy_namespace%', - 'setAutoGenerateProxyClasses' => '%doctrine.odm.mongodb.auto_generate_proxy_classes%', - 'setHydratorDir' => '%doctrine.odm.mongodb.hydrator_dir%', - 'setHydratorNamespace' => '%doctrine.odm.mongodb.hydrator_namespace%', - 'setAutoGenerateHydratorClasses' => '%doctrine.odm.mongodb.auto_generate_hydrator_classes%', - 'setDefaultDB' => $defaultDatabase, - ); - - if ($documentManager['logging']) { - $methods['setLoggerCallable'] = array(new Reference('doctrine.odm.mongodb.logger'), 'logQuery'); - } - - foreach ($methods as $method => $arg) { - if ($odmConfigDef->hasMethodCall($method)) { - $odmConfigDef->removeMethodCall($method); - } - $odmConfigDef->addMethodCall($method, array($arg)); - } - - // event manager - $eventManagerName = isset($documentManager['event_manager']) ? $documentManager['event_manager'] : $documentManager['name']; - $eventManagerId = sprintf('doctrine.odm.mongodb.%s_event_manager', $eventManagerName); - if (!$container->hasDefinition($eventManagerId)) { - $eventManagerDef = new Definition('%doctrine.odm.mongodb.event_manager_class%'); - $eventManagerDef->addTag('doctrine.odm.mongodb.event_manager'); - $eventManagerDef->setPublic(false); - $container->setDefinition($eventManagerId, $eventManagerDef); - } - - $odmDmArgs = array( - new Reference(sprintf('doctrine.odm.mongodb.%s_connection', isset($documentManager['connection']) ? $documentManager['connection'] : $documentManager['name'])), - new Reference(sprintf('doctrine.odm.mongodb.%s_configuration', $documentManager['name'])), - new Reference($eventManagerId), - ); - $odmDmDef = new Definition('%doctrine.odm.mongodb.document_manager_class%', $odmDmArgs); - $odmDmDef->setFactoryClass('%doctrine.odm.mongodb.document_manager_class%'); - $odmDmDef->setFactoryMethod('create'); - $odmDmDef->addTag('doctrine.odm.mongodb.document_manager'); - $container->setDefinition(sprintf('doctrine.odm.mongodb.%s_document_manager', $documentManager['name']), $odmDmDef); - - if ($documentManager['name'] == $defaultDM) { - $container->setAlias( - 'doctrine.odm.mongodb.document_manager', - new Alias(sprintf('doctrine.odm.mongodb.%s_document_manager', $documentManager['name'])) - ); - $container->setAlias( - 'doctrine.odm.mongodb.event_manager', - new Alias(sprintf('doctrine.odm.mongodb.%s_event_manager', $documentManager['name'])) - ); - } - } - - /** - * Loads the configured document manager metadata cache driver. - * - * @param array $config A configured document manager array - * @param ContainerBuilder $container A ContainerBuilder instance - * @param array $defaultMetadataCache The default metadata cache configuration array - */ - protected function loadDocumentManagerMetadataCacheDriver(array $documentManager, ContainerBuilder $container, $defaultMetadataCache) - { - $dmMetadataCacheDriver = isset($documentManager['metadata_cache_driver']) ? $documentManager['metadata_cache_driver'] : $defaultMetadataCache; - $type = $dmMetadataCacheDriver['type']; - - if ('memcache' === $type) { - $memcacheClass = isset($dmMetadataCacheDriver['class']) ? $dmMetadataCacheDriver['class'] : sprintf('%%doctrine.odm.mongodb.cache.%s_class%%', $type); - $cacheDef = new Definition($memcacheClass); - $memcacheHost = isset($dmMetadataCacheDriver['host']) ? $dmMetadataCacheDriver['host'] : '%doctrine.odm.mongodb.cache.memcache_host%'; - $memcachePort = isset($dmMetadataCacheDriver['port']) ? $dmMetadataCacheDriver['port'] : '%doctrine.odm.mongodb.cache.memcache_port%'; - $memcacheInstanceClass = isset($dmMetadataCacheDriver['instance-class']) ? $dmMetadataCacheDriver['instance-class'] : (isset($dmMetadataCacheDriver['instance_class']) ? $dmMetadataCacheDriver['instance_class'] : '%doctrine.odm.mongodb.cache.memcache_instance_class%'); - $memcacheInstance = new Definition($memcacheInstanceClass); - $memcacheInstance->addMethodCall('connect', array($memcacheHost, $memcachePort)); - $container->setDefinition(sprintf('doctrine.odm.mongodb.%s_memcache_instance', $documentManager['name']), $memcacheInstance); - $cacheDef->addMethodCall('setMemcache', array(new Reference(sprintf('doctrine.odm.mongodb.%s_memcache_instance', $documentManager['name'])))); - } else { - $cacheDef = new Definition(sprintf('%%doctrine.odm.mongodb.cache.%s_class%%', $type)); - } - - $container->setDefinition(sprintf('doctrine.odm.mongodb.%s_metadata_cache', $documentManager['name']), $cacheDef); - } - - /** - * Loads the configured connections. - * - * @param array $config An array of connections configurations - * @param ContainerBuilder $container A ContainerBuilder instance - */ - protected function loadConnections(array $connections, ContainerBuilder $container) - { - foreach ($connections as $name => $connection) { - $odmConnArgs = array( - isset($connection['server']) ? $connection['server'] : null, - isset($connection['options']) ? $connection['options'] : array(), - new Reference(sprintf('doctrine.odm.mongodb.%s_configuration', $name)) - ); - $odmConnDef = new Definition('%doctrine.odm.mongodb.connection_class%', $odmConnArgs); - $container->setDefinition(sprintf('doctrine.odm.mongodb.%s_connection', $name), $odmConnDef); - } - } - - /** - * Loads an ODM document managers bundle mapping information. - * - * There are two distinct configuration possibilities for mapping information: - * - * 1. Specify a bundle and optionally details where the entity and mapping information reside. - * 2. Specify an arbitrary mapping location. - * - * @example - * - * doctrine.orm: - * mappings: - * MyBundle1: ~ - * MyBundle2: yml - * MyBundle3: { type: annotation, dir: Documents/ } - * MyBundle4: { type: xml, dir: Resources/config/doctrine/mapping } - * MyBundle5: - * type: yml - * dir: [bundle-mappings1/, bundle-mappings2/] - * alias: BundleAlias - * arbitrary_key: - * type: xml - * dir: %kernel.dir%/../src/vendor/DoctrineExtensions/lib/DoctrineExtensions/Documents - * prefix: DoctrineExtensions\Documents\ - * alias: DExt - * - * In the case of bundles everything is really optional (which leads to autodetection for this bundle) but - * in the mappings key everything except alias is a required argument. - * - * @param array $documentManager A configured ODM entity manager. - * @param Definition A Definition instance - * @param ContainerBuilder $container A ContainerBuilder instance - */ - protected function loadDocumentManagerBundlesMappingInformation(array $documentManager, Definition $odmConfigDef, ContainerBuilder $container) - { - // reset state of drivers and alias map. They are only used by this methods and children. - $this->drivers = array(); - $this->aliasMap = array(); - - $this->loadMappingInformation($documentManager, $container); - $this->registerMappingDrivers($documentManager, $container); - - if ($odmConfigDef->hasMethodCall('setDocumentNamespaces')) { - // TODO: Can we make a method out of it on Definition? replaceMethodArguments() or something. - $calls = $odmConfigDef->getMethodCalls(); - foreach ($calls as $call) { - if ($call[0] == 'setDocumentNamespaces') { - $this->aliasMap = array_merge($call[1][0], $this->aliasMap); - } - } - $method = $odmConfigDef->removeMethodCall('setDocumentNamespaces'); - } - $odmConfigDef->addMethodCall('setDocumentNamespaces', array($this->aliasMap)); - } - - protected function getObjectManagerElementName($name) - { - return 'doctrine.odm.mongodb.' . $name; - } - - protected function getMappingObjectDefaultName() - { - return 'Document'; - } - - protected function getMappingResourceConfigDirectory() - { - return 'Resources/config/doctrine/metadata/mongodb'; - } - - /** - * Returns the namespace to be used for this extension (XML namespace). - * - * @return string The XML namespace - */ - public function getNamespace() - { - return 'http://symfony.com/schema/dic/doctrine/odm/mongodb'; - } - - /** - * @return string - */ - public function getXsdValidationBasePath() - { - return __DIR__.'/../Resources/config/schema'; - } -} diff --git a/src/Symfony/Bundle/DoctrineMongoDBBundle/DoctrineMongoDBBundle.php b/src/Symfony/Bundle/DoctrineMongoDBBundle/DoctrineMongoDBBundle.php deleted file mode 100755 index 4e85a8aaa1..0000000000 --- a/src/Symfony/Bundle/DoctrineMongoDBBundle/DoctrineMongoDBBundle.php +++ /dev/null @@ -1,40 +0,0 @@ - - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -namespace Symfony\Bundle\DoctrineMongoDBBundle; - -use Symfony\Component\DependencyInjection\Compiler\PassConfig; -use Symfony\Component\DependencyInjection\ContainerBuilder; -use Symfony\Component\HttpKernel\Bundle\Bundle; -use Symfony\Bundle\DoctrineMongoDBBundle\DependencyInjection\Compiler\AddValidatorNamespaceAliasPass; -use Symfony\Bundle\DoctrineMongoDBBundle\DependencyInjection\Compiler\CreateHydratorDirectoryPass; -use Symfony\Bundle\DoctrineMongoDBBundle\DependencyInjection\Compiler\CreateProxyDirectoryPass; -use Symfony\Bundle\DoctrineMongoDBBundle\DependencyInjection\Compiler\RegisterEventListenersAndSubscribersPass; - -/** - * Doctrine MongoDB ODM bundle. - * - * @author Bulat Shakirzyanov - * @author Kris Wallsmith - * @author Jonathan H. Wage - */ -class DoctrineMongoDBBundle extends Bundle -{ - public function build(ContainerBuilder $container) - { - parent::build($container); - - $container->addCompilerPass(new AddValidatorNamespaceAliasPass(), PassConfig::TYPE_BEFORE_OPTIMIZATION); - $container->addCompilerPass(new RegisterEventListenersAndSubscribersPass(), PassConfig::TYPE_BEFORE_OPTIMIZATION); - $container->addCompilerPass(new CreateProxyDirectoryPass(), PassConfig::TYPE_BEFORE_REMOVING); - $container->addCompilerPass(new CreateHydratorDirectoryPass(), PassConfig::TYPE_BEFORE_REMOVING); - } -} diff --git a/src/Symfony/Bundle/DoctrineMongoDBBundle/Logger/DoctrineMongoDBLogger.php b/src/Symfony/Bundle/DoctrineMongoDBBundle/Logger/DoctrineMongoDBLogger.php deleted file mode 100644 index 8f0d84abf0..0000000000 --- a/src/Symfony/Bundle/DoctrineMongoDBBundle/Logger/DoctrineMongoDBLogger.php +++ /dev/null @@ -1,301 +0,0 @@ - - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -namespace Symfony\Bundle\DoctrineMongoDBBundle\Logger; - -use Doctrine\MongoDB\GridFSFile; -use Symfony\Component\HttpKernel\Log\LoggerInterface; - -/** - * Logger for the Doctrine MongoDB ODM. - * - * The {@link logQuery()} method is configured as the logger callable in the - * service container. - * - * @author Kris Wallsmith - */ -class DoctrineMongoDBLogger -{ - protected $logger; - - protected $prefix; - protected $queries; - - protected $processed; - protected $formattedQueries; - protected $nbRealQueries; - - /** - * Constructor. - * - * @param LoggerInterface $logger The Symfony logger - * @param string $prefix A prefix for messages sent to the Symfony logger - */ - public function __construct(LoggerInterface $logger = null, $prefix = 'MongoDB query: ') - { - $this->logger = $logger; - $this->prefix = $prefix; - $this->queries = array(); - $this->processed = false; - } - - /** - * Logs a query. - * - * This method is configured as the logger callable in the service - * container. - * - * @param array $query A query log array from Doctrine - */ - public function logQuery(array $query) - { - $this->queries[] = $query; - $this->processed = false; - - if (null !== $this->logger) { - $this->logger->info($this->prefix.static::bsonEncode($query)); - } - } - - /** - * Returns the number of queries that have been logged. - * - * @return integer The number of queries logged - */ - public function getNbQueries() - { - if (!$this->processed) { - $this->processQueries(); - } - - return $this->nbRealQueries; - } - - /** - * Returns a human-readable array of queries logged. - * - * @return array An array of queries - */ - public function getQueries() - { - if (!$this->processed) { - $this->processQueries(); - } - - return $this->formattedQueries; - } - - /** - * Groups and formats query arrays. - * - * @param array $queries An array of query arrays - * - * @return array An array of human-readable queries - */ - protected function processQueries() - { - $this->formattedQueries = array(); - $this->nbRealQueries = 0; - - $grouped = array(); - $ordered = array(); - foreach ($this->queries as $query) { - if (!isset($query['query']) || !isset($query['fields'])) { - // no grouping necessary - $ordered[] = array($query); - continue; - } - - $cursor = serialize($query['query']).serialize($query['fields']); - - // append if issued from cursor (currently just "sort") - if (isset($query['sort'])) { - unset($query['query'], $query['fields']); - $grouped[$cursor][count($grouped[$cursor]) - 1][] = $query; - } else { - $grouped[$cursor][] = array($query); - $ordered[] =& $grouped[$cursor][count($grouped[$cursor]) - 1]; - } - } - - $i = 0; - $db = ''; - $query = ''; - foreach ($ordered as $logs) { - foreach ($logs as $log) { - if (isset($log['db']) && $db != $log['db']) { - // for readability - $this->formattedQueries[$i++] = 'use '.$log['db'].';'; - $db = $log['db']; - } - - if (isset($log['collection'])) { - // flush the previous and start a new query - if (!empty($query)) { - if ('.' == $query[0]) { - $query = 'db'.$query; - } - - $this->formattedQueries[$i++] = $query.';'; - ++$this->nbRealQueries; - } - - $query = 'db.'.$log['collection']; - } - - // format the method call - if (isset($log['authenticate'])) { - $query .= '.authenticate()'; - } elseif (isset($log['batchInsert'])) { - $query .= '.batchInsert(**'.$log['num'].' item(s)**)'; - } elseif (isset($log['command'])) { - $query .= '.command()'; - } elseif (isset($log['count'])) { - $query .= '.count('; - if ($log['query'] || $log['limit'] || $log['skip']) { - $query .= static::bsonEncode($log['query']); - if ($log['limit'] || $log['skip']) { - $query .= ', '.static::bsonEncode($log['limit']); - if ($log['skip']) { - $query .= ', '.static::bsonEncode($log['skip']); - } - } - } - $query .= ')'; - } elseif (isset($log['createCollection'])) { - $query .= '.createCollection()'; - } elseif (isset($log['createDBRef'])) { - $query .= '.createDBRef()'; - } elseif (isset($log['deleteIndex'])) { - $query .= '.dropIndex('.static::bsonEncode($log['keys']).')'; - } elseif (isset($log['deleteIndexes'])) { - $query .= '.dropIndexes()'; - } elseif (isset($log['drop'])) { - $query .= '.drop()'; - } elseif (isset($log['dropDatabase'])) { - $query .= '.dropDatabase()'; - } elseif (isset($log['ensureIndex'])) { - $query .= '.ensureIndex('.static::bsonEncode($log['keys']).', '.static::bsonEncode($log['options']).')'; - } elseif (isset($log['execute'])) { - $query .= '.execute()'; - } elseif (isset($log['find'])) { - $query .= '.find('; - if ($log['query'] || $log['fields']) { - $query .= static::bsonEncode($log['query']); - if ($log['fields']) { - $query .= ', '.static::bsonEncode($log['fields']); - } - } - $query .= ')'; - } elseif (isset($log['findOne'])) { - $query .= '.findOne('; - if ($log['query'] || $log['fields']) { - $query .= static::bsonEncode($log['query']); - if ($log['fields']) { - $query .= ', '.static::bsonEncode($log['fields']); - } - } - $query .= ')'; - } elseif (isset($log['getDBRef'])) { - $query .= '.getDBRef()'; - } elseif (isset($log['group'])) { - $query .= '.group('.static::bsonEncode(array( - 'keys' => $log['keys'], - 'initial' => $log['initial'], - 'reduce' => $log['reduce'], - )).')'; - } elseif (isset($log['insert'])) { - $query .= '.insert('.static::bsonEncode($log['document']).')'; - } elseif (isset($log['remove'])) { - $query .= '.remove('.static::bsonEncode($log['query']).')'; - } elseif (isset($log['save'])) { - $query .= '.save('.static::bsonEncode($log['document']).')'; - } elseif (isset($log['sort'])) { - $query .= '.sort('.static::bsonEncode($log['sortFields']).')'; - } elseif (isset($log['update'])) { - // todo: include $log['options'] - $query .= '.update('.static::bsonEncode($log['query']).', '.static::bsonEncode($log['newObj']).')'; - } elseif (isset($log['validate'])) { - $query .= '.validate()'; - } - } - } - - if (!empty($query)) { - if ('.' == $query[0]) { - $query = 'db'.$query; - } - - $this->formattedQueries[$i++] = $query.';'; - ++$this->nbRealQueries; - } - } - - static protected function bsonEncode($query, $array = true) - { - $parts = array(); - - foreach ($query as $key => $value) { - if (!is_numeric($key)) { - $array = false; - } - - if (null === $value) { - $formatted = 'null'; - } elseif (is_bool($value)) { - $formatted = $value ? 'true' : 'false'; - } elseif (is_numeric($value)) { - $formatted = $value; - } elseif (is_scalar($value)) { - $formatted = '"'.$value.'"'; - } elseif (is_array($value)) { - $formatted = static::bsonEncode($value); - } elseif ($value instanceof \MongoId) { - $formatted = 'ObjectId("'.$value.'")'; - } elseif ($value instanceof \MongoDate) { - $formatted = 'new Date("'.date('r', $value->sec).'")'; - } elseif ($value instanceof \DateTime) { - $formatted = 'new Date("'.date('r', $value->getTimestamp()).'")'; - } elseif ($value instanceof \MongoRegex) { - $formatted = 'new RegExp("'.$value->regex.'", "'.$value->flags.'")'; - } elseif ($value instanceof \MongoMinKey) { - $formatted = 'new MinKey()'; - } elseif ($value instanceof \MongoMaxKey) { - $formatted = 'new MaxKey()'; - } elseif ($value instanceof \MongoBinData) { - $formatted = 'new BinData("'.$value->bin.'", "'.$value->type.'")'; - } elseif ($value instanceof \MongoGridFSFile || $value instanceof GridFSFile) { - $formatted = 'new MongoGridFSFile("'.$value->getFilename().'")'; - } elseif ($value instanceof \stdClass) { - $formatted = static::bsonEncode((array) $value); - } else { - $formatted = (string) $value; - } - - $parts['"'.$key.'"'] = $formatted; - } - - if (0 == count($parts)) { - return $array ? '[ ]' : '{ }'; - } - - if ($array) { - return '[ '.implode(', ', $parts).' ]'; - } else { - $mapper = function($key, $value) - { - return $key.': '.$value; - }; - - return '{ '.implode(', ', array_map($mapper, array_keys($parts), array_values($parts))).' }'; - } - } -} diff --git a/src/Symfony/Bundle/DoctrineMongoDBBundle/Resources/config/mongodb.xml b/src/Symfony/Bundle/DoctrineMongoDBBundle/Resources/config/mongodb.xml deleted file mode 100755 index 9d8d49e6dd..0000000000 --- a/src/Symfony/Bundle/DoctrineMongoDBBundle/Resources/config/mongodb.xml +++ /dev/null @@ -1,119 +0,0 @@ - - - - - - Doctrine\MongoDB\Connection - Doctrine\ODM\MongoDB\Configuration - Doctrine\ODM\MongoDB\DocumentManager - Symfony\Bundle\DoctrineMongoDBBundle\Logger\DoctrineMongoDBLogger - Symfony\Bundle\DoctrineMongoDBBundle\DataCollector\DoctrineMongoDBDataCollector - Doctrine\Common\EventManager - - - Proxies - %kernel.cache_dir%/doctrine/odm/mongodb/Proxies - false - - - Hydrators - %kernel.cache_dir%/doctrine/odm/mongodb/Hydrators - false - - - Doctrine\Common\Cache\ArrayCache - Doctrine\Common\Cache\ApcCache - Doctrine\Common\Cache\MemcacheCache - localhost - 11211 - Memcache - Doctrine\Common\Cache\XcacheCache - - - Doctrine\ODM\MongoDB\Mapping\Driver\DriverChain - Doctrine\ODM\MongoDB\Mapping\Driver\AnnotationDriver - Doctrine\Common\Annotations\AnnotationReader - Doctrine\ODM\MongoDB\Mapping\Driver\XmlDriver - Doctrine\ODM\MongoDB\Mapping\Driver\YamlDriver - - - - %doctrine.odm.mongodb.mapping_dirs% - %doctrine.odm.mongodb.mapping_dirs% - - - - Symfony\Bundle\DoctrineMongoDBBundle\Security\DocumentUserProvider - - - Symfony\Bundle\DoctrineMongoDBBundle\CacheWarmer\ProxyCacheWarmer - - - Symfony\Bundle\DoctrineMongoDBBundle\CacheWarmer\HydratorCacheWarmer - - - Symfony\Bundle\DoctrineMongoDBBundle\Validator\Constraints\UniqueValidator - - - - - - - - - - - %doctrine.odm.mongodb.document_dirs% - - - - - Doctrine\ODM\MongoDB\Mapping\ - mongodb - - - - %doctrine.odm.mongodb.xml_mapping_dirs% - - - %doctrine.odm.mongodb.yml_mapping_dirs% - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/src/Symfony/Bundle/DoctrineMongoDBBundle/Resources/config/schema/mongodb-1.0.xsd b/src/Symfony/Bundle/DoctrineMongoDBBundle/Resources/config/schema/mongodb-1.0.xsd deleted file mode 100644 index f214496b5b..0000000000 --- a/src/Symfony/Bundle/DoctrineMongoDBBundle/Resources/config/schema/mongodb-1.0.xsd +++ /dev/null @@ -1,36 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/src/Symfony/Bundle/DoctrineMongoDBBundle/Resources/views/Collector/mongodb.html.twig b/src/Symfony/Bundle/DoctrineMongoDBBundle/Resources/views/Collector/mongodb.html.twig deleted file mode 100644 index 253d9d622e..0000000000 --- a/src/Symfony/Bundle/DoctrineMongoDBBundle/Resources/views/Collector/mongodb.html.twig +++ /dev/null @@ -1,45 +0,0 @@ -{% extends 'WebProfilerBundle:Profiler:layout.html.twig' %} - -{% block toolbar %} - {% set icon %} - Mongo - {% endset %} - {% set text %} - {{ collector.querycount }} - {% endset %} - {% include 'WebProfilerBundle:Profiler:toolbar_item.html.twig' with { 'link': profiler_url } %} -{% endblock %} - -{% block menu %} - - - Doctrine MongoDB - - {{ collector.querycount }} - - -{% endblock %} - -{% block panel %} -

Queries

- - {% if not collector.queries %} -

- Query logging is disabled. -

- {% elseif not collector.querycount %} -

- No queries. -

- {% else %} -
    - {% for query in collector.queries %} -
  • -
    - {{ query }} -
    -
  • - {% endfor %} -
- {% endif %} -{% endblock %} diff --git a/src/Symfony/Bundle/DoctrineMongoDBBundle/Security/DocumentUserProvider.php b/src/Symfony/Bundle/DoctrineMongoDBBundle/Security/DocumentUserProvider.php deleted file mode 100644 index 651c21c554..0000000000 --- a/src/Symfony/Bundle/DoctrineMongoDBBundle/Security/DocumentUserProvider.php +++ /dev/null @@ -1,78 +0,0 @@ - - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -namespace Symfony\Bundle\DoctrineMongoDBBundle\Security; - -use Symfony\Component\Security\Core\User\UserInterface; -use Symfony\Component\Security\Core\User\UserProviderInterface; -use Symfony\Component\Security\Core\Exception\UnsupportedUserException; -use Symfony\Component\Security\Core\Exception\UsernameNotFoundException; - -class DocumentUserProvider implements UserProviderInterface -{ - protected $class; - protected $repository; - protected $property; - - public function __construct($em, $class, $property = null) - { - $this->class = $class; - - if (false !== strpos($this->class, ':')) { - $this->class = $em->getClassMetadata($class)->getName(); - } - - $this->repository = $em->getRepository($class); - $this->property = $property; - } - - /** - * {@inheritdoc} - */ - public function loadUserByUsername($username) - { - if (null !== $this->property) { - $user = $this->repository->findOneBy(array($this->property => $username)); - } else { - if (!$this->repository instanceof UserProviderInterface) { - throw new \InvalidArgumentException(sprintf('The Doctrine repository "%s" must implement UserProviderInterface.', get_class($this->repository))); - } - - $user = $this->repository->loadUserByUsername($username); - } - - if (null === $user) { - throw new UsernameNotFoundException(sprintf('User "%s" not found.', $username)); - } - - return $user; - } - - /** - * {@inheritDoc} - */ - public function loadUser(UserInterface $user) - { - if (!$user instanceof $this->class) { - throw new UnsupportedUserException(sprintf('Instances of "%s" are not supported.', get_class($user))); - } - - return $this->loadUserByUsername($user->getUsername()); - } - - /** - * {@inheritDoc} - */ - public function supportsClass($class) - { - return $class === $this->class; - } -} diff --git a/src/Symfony/Bundle/DoctrineMongoDBBundle/Tests/CacheWarmer/HydratorCacheWarmerTest.php b/src/Symfony/Bundle/DoctrineMongoDBBundle/Tests/CacheWarmer/HydratorCacheWarmerTest.php deleted file mode 100644 index 6444c6b7b9..0000000000 --- a/src/Symfony/Bundle/DoctrineMongoDBBundle/Tests/CacheWarmer/HydratorCacheWarmerTest.php +++ /dev/null @@ -1,97 +0,0 @@ - - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -namespace Symfony\Bundle\DoctrineMongoDBBundle\Tests\CacheWarmer; - -use Symfony\Bundle\DoctrineMongoDBBundle\CacheWarmer\HydratorCacheWarmer; - -class HydratorCacheWarmerTest extends \Symfony\Bundle\DoctrineMongoDBBundle\Tests\TestCase -{ - /** - * This is not necessarily a good test, it doesn't generate any hydrators - * because there are none in the AnnotationsBundle. However that is - * rather a task of doctrine to test. We touch the lines here and - * verify that the container is called correctly for the relevant information. - * - * @group DoctrineODMMongoDBHydrator - */ - public function testWarmCache() - { - $testManager = $this->createTestDocumentManager(array( - __DIR__ . "/../DependencyInjection/Fixtures/Bundles/AnnotationsBundle/Document") - ); - - $container = $this->getMock('Symfony\Component\DependencyInjection\Container'); - $container->expects($this->at(0)) - ->method('getParameter') - ->with($this->equalTo('doctrine.odm.mongodb.hydrator_dir')) - ->will($this->returnValue(sys_get_temp_dir())); - $container->expects($this->at(1)) - ->method('getParameter') - ->with($this->equalTo('doctrine.odm.mongodb.auto_generate_hydrator_classes')) - ->will($this->returnValue(false)); - $container->expects($this->at(2)) - ->method('getParameter') - ->with($this->equalTo('doctrine.odm.mongodb.document_managers')) - ->will($this->returnValue(array('default', 'foo'))); - $container->expects($this->at(3)) - ->method('get') - ->with($this->equalTo('doctrine.odm.mongodb.default_document_manager')) - ->will($this->returnValue($testManager)); - $container->expects($this->at(4)) - ->method('get') - ->with($this->equalTo('doctrine.odm.mongodb.foo_document_manager')) - ->will($this->returnValue($testManager)); - - $cacheWarmer = new HydratorCacheWarmer($container); - $cacheWarmer->warmUp(sys_get_temp_dir()); - } - - /** - * @group DoctrineODMMongoDBHydrator - */ - public function testSkipWhenHydratorsAreAutoGenerated() - { - $testManager = $this->createTestDocumentManager(array( - __DIR__ . "/../DependencyInjection/Fixtures/Bundles/AnnotationsBundle/Document") - ); - - $container = $this->getMock('Symfony\Component\DependencyInjection\Container'); - $container->expects($this->at(0)) - ->method('getParameter') - ->with($this->equalTo('doctrine.odm.mongodb.hydrator_dir')) - ->will($this->returnValue(sys_get_temp_dir())); - $container->expects($this->at(1)) - ->method('getParameter') - ->with($this->equalTo('doctrine.odm.mongodb.auto_generate_hydrator_classes')) - ->will($this->returnValue(true)); - $container->expects($this->at(2)) - ->method('getParameter') - ->with($this->equalTo('assertion')) - ->will($this->returnValue(true)); - - $cacheWarmer = new HydratorCacheWarmer($container); - $cacheWarmer->warmUp(sys_get_temp_dir()); - - $container->getParameter('assertion'); // check that the assertion is really the third call. - } - - /** - * @group DoctrineODMMongoDBHydrator - */ - public function testHydratorCacheWarmingIsNotOptional() - { - $container = $this->getMock('Symfony\Component\DependencyInjection\Container'); - $cacheWarmer = new HydratorCacheWarmer($container); - - $this->assertFalse($cacheWarmer->isOptional()); - } -} \ No newline at end of file diff --git a/src/Symfony/Bundle/DoctrineMongoDBBundle/Tests/CacheWarmer/ProxyCacheWarmerTest.php b/src/Symfony/Bundle/DoctrineMongoDBBundle/Tests/CacheWarmer/ProxyCacheWarmerTest.php deleted file mode 100644 index 9184b2f35b..0000000000 --- a/src/Symfony/Bundle/DoctrineMongoDBBundle/Tests/CacheWarmer/ProxyCacheWarmerTest.php +++ /dev/null @@ -1,97 +0,0 @@ - - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -namespace Symfony\Bundle\DoctrineMongoDBBundle\Tests\CacheWarmer; - -use Symfony\Bundle\DoctrineMongoDBBundle\CacheWarmer\ProxyCacheWarmer; - -class ProxyCacheWarmerTest extends \Symfony\Bundle\DoctrineMongoDBBundle\Tests\TestCase -{ - /** - * This is not necessarily a good test, it doesn't generate any proxies - * because there are none in the AnnotationsBundle. However that is - * rather a task of doctrine to test. We touch the lines here and - * verify that the container is called correctly for the relevant information. - * - * @group DoctrineODMMongoDBProxy - */ - public function testWarmCache() - { - $testManager = $this->createTestDocumentManager(array( - __DIR__ . "/../DependencyInjection/Fixtures/Bundles/AnnotationsBundle/Document") - ); - - $container = $this->getMock('Symfony\Component\DependencyInjection\Container'); - $container->expects($this->at(0)) - ->method('getParameter') - ->with($this->equalTo('doctrine.odm.mongodb.proxy_dir')) - ->will($this->returnValue(sys_get_temp_dir())); - $container->expects($this->at(1)) - ->method('getParameter') - ->with($this->equalTo('doctrine.odm.mongodb.auto_generate_proxy_classes')) - ->will($this->returnValue(false)); - $container->expects($this->at(2)) - ->method('getParameter') - ->with($this->equalTo('doctrine.odm.mongodb.document_managers')) - ->will($this->returnValue(array('default', 'foo'))); - $container->expects($this->at(3)) - ->method('get') - ->with($this->equalTo('doctrine.odm.mongodb.default_document_manager')) - ->will($this->returnValue($testManager)); - $container->expects($this->at(4)) - ->method('get') - ->with($this->equalTo('doctrine.odm.mongodb.foo_document_manager')) - ->will($this->returnValue($testManager)); - - $cacheWarmer = new ProxyCacheWarmer($container); - $cacheWarmer->warmUp(sys_get_temp_dir()); - } - - /** - * @group DoctrineODMMongoDBProxy - */ - public function testSkipWhenProxiesAreAutoGenerated() - { - $testManager = $this->createTestDocumentManager(array( - __DIR__ . "/../DependencyInjection/Fixtures/Bundles/AnnotationsBundle/Document") - ); - - $container = $this->getMock('Symfony\Component\DependencyInjection\Container'); - $container->expects($this->at(0)) - ->method('getParameter') - ->with($this->equalTo('doctrine.odm.mongodb.proxy_dir')) - ->will($this->returnValue(sys_get_temp_dir())); - $container->expects($this->at(1)) - ->method('getParameter') - ->with($this->equalTo('doctrine.odm.mongodb.auto_generate_proxy_classes')) - ->will($this->returnValue(true)); - $container->expects($this->at(2)) - ->method('getParameter') - ->with($this->equalTo('assertion')) - ->will($this->returnValue(true)); - - $cacheWarmer = new ProxyCacheWarmer($container); - $cacheWarmer->warmUp(sys_get_temp_dir()); - - $container->getParameter('assertion'); // check that the assertion is really the third call. - } - - /** - * @group DoctrineODMMongoDBProxy - */ - public function testProxyCacheWarmingIsNotOptional() - { - $container = $this->getMock('Symfony\Component\DependencyInjection\Container'); - $cacheWarmer = new ProxyCacheWarmer($container); - - $this->assertFalse($cacheWarmer->isOptional()); - } -} \ No newline at end of file diff --git a/src/Symfony/Bundle/DoctrineMongoDBBundle/Tests/ContainerTest.php b/src/Symfony/Bundle/DoctrineMongoDBBundle/Tests/ContainerTest.php deleted file mode 100644 index 8c79cae1fb..0000000000 --- a/src/Symfony/Bundle/DoctrineMongoDBBundle/Tests/ContainerTest.php +++ /dev/null @@ -1,60 +0,0 @@ - - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -namespace Symfony\Bundle\DoctrineMongoDBBundle\Tests; - -use Symfony\Component\DependencyInjection\ContainerBuilder; -use Symfony\Component\DependencyInjection\ParameterBag\ParameterBag; -use Symfony\Bundle\DoctrineMongoDBBundle\DependencyInjection\DoctrineMongoDBExtension; -use Symfony\Component\DependencyInjection\Loader\YamlFileLoader; - -class ContainerTest extends TestCase -{ - public function getContainer() - { - require_once __DIR__.'/DependencyInjection/Fixtures/Bundles/YamlBundle/YamlBundle.php'; - - $container = new ContainerBuilder(new ParameterBag(array( - 'kernel.bundles' => array('YamlBundle' => 'DoctrineMongoDBBundle\Tests\DependencyInjection\Fixtures\Bundles\YamlBundle\YamlBundle'), - 'kernel.cache_dir' => sys_get_temp_dir(), - 'kernel.debug' => false, - ))); - $loader = new DoctrineMongoDBExtension(); - $container->registerExtension($loader); - - $configs = array(); - $configs[] = array('connections' => array('default' => array()), 'document_managers' => array('default' => array('mappings' => array('YamlBundle' => array())))); - $loader->load($configs, $container); - - return $container; - } - - public function testContainer() - { - $container = $this->getContainer(); - $this->assertInstanceOf('Doctrine\ODM\MongoDB\Mapping\Driver\DriverChain', $container->get('doctrine.odm.mongodb.metadata.chain')); - $this->assertInstanceOf('Doctrine\ODM\MongoDB\Mapping\Driver\AnnotationDriver', $container->get('doctrine.odm.mongodb.metadata.annotation')); - $this->assertInstanceOf('Doctrine\Common\Annotations\AnnotationReader', $container->get('doctrine.odm.mongodb.metadata.annotation_reader')); - $this->assertInstanceOf('Doctrine\ODM\MongoDB\Mapping\Driver\XmlDriver', $container->get('doctrine.odm.mongodb.metadata.xml')); - $this->assertInstanceOf('Doctrine\ODM\MongoDB\Mapping\Driver\YamlDriver', $container->get('doctrine.odm.mongodb.metadata.yml')); - $this->assertInstanceOf('Doctrine\Common\Cache\ArrayCache', $container->get('doctrine.odm.mongodb.cache.array')); - $this->assertInstanceOf('Symfony\Bundle\DoctrineMongoDBBundle\Logger\DoctrineMongoDBLogger', $container->get('doctrine.odm.mongodb.logger')); - $this->assertInstanceOf('Symfony\Bundle\DoctrineMongoDBBundle\DataCollector\DoctrineMongoDBDataCollector', $container->get('doctrine.odm.mongodb.data_collector')); - $this->assertInstanceOf('Doctrine\MongoDB\Connection', $container->get('doctrine.odm.mongodb.default_connection')); - $this->assertInstanceOf('Doctrine\ODM\MongoDB\Configuration', $container->get('doctrine.odm.mongodb.default_configuration')); - $this->assertInstanceOf('Doctrine\ODM\MongoDB\Mapping\Driver\DriverChain', $container->get('doctrine.odm.mongodb.default_metadata_driver')); - $this->assertInstanceOf('Doctrine\Common\Cache\ArrayCache', $container->get('doctrine.odm.mongodb.default_metadata_cache')); - $this->assertInstanceOf('Doctrine\ODM\MongoDB\DocumentManager', $container->get('doctrine.odm.mongodb.default_document_manager')); - $this->assertInstanceOf('Doctrine\Common\Cache\ArrayCache', $container->get('doctrine.odm.mongodb.cache')); - $this->assertInstanceOf('Doctrine\ODM\MongoDB\DocumentManager', $container->get('doctrine.odm.mongodb.document_manager')); - $this->assertInstanceof('Doctrine\Common\EventManager', $container->get('doctrine.odm.mongodb.event_manager')); - } -} diff --git a/src/Symfony/Bundle/DoctrineMongoDBBundle/Tests/DependencyInjection/AbstractMongoDBExtensionTest.php b/src/Symfony/Bundle/DoctrineMongoDBBundle/Tests/DependencyInjection/AbstractMongoDBExtensionTest.php deleted file mode 100644 index 82bca769c7..0000000000 --- a/src/Symfony/Bundle/DoctrineMongoDBBundle/Tests/DependencyInjection/AbstractMongoDBExtensionTest.php +++ /dev/null @@ -1,364 +0,0 @@ - - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -namespace Symfony\Bundle\DoctrineMongoDBBundle\Tests\DependencyInjection; - -use Symfony\Bundle\DoctrineMongoDBBundle\Tests\TestCase; -use Symfony\Bundle\DoctrineMongoDBBundle\DependencyInjection\Compiler\AddValidatorNamespaceAliasPass; -use Symfony\Bundle\DoctrineMongoDBBundle\DependencyInjection\DoctrineMongoDBExtension; -use Symfony\Component\DependencyInjection\ContainerBuilder; -use Symfony\Component\DependencyInjection\ParameterBag\ParameterBag; -use Symfony\Component\DependencyInjection\Reference; - -abstract class AbstractMongoDBExtensionTest extends TestCase -{ - abstract protected function loadFromFile(ContainerBuilder $container, $file); - - public function testDependencyInjectionConfigurationDefaults() - { - $container = $this->getContainer(); - $loader = new DoctrineMongoDBExtension(); - - $loader->load(array(array()), $container); - - $this->assertEquals('Doctrine\MongoDB\Connection', $container->getParameter('doctrine.odm.mongodb.connection_class')); - $this->assertEquals('Doctrine\ODM\MongoDB\Configuration', $container->getParameter('doctrine.odm.mongodb.configuration_class')); - $this->assertEquals('Doctrine\ODM\MongoDB\DocumentManager', $container->getParameter('doctrine.odm.mongodb.document_manager_class')); - $this->assertEquals('Proxies', $container->getParameter('doctrine.odm.mongodb.proxy_namespace')); - $this->assertEquals(false, $container->getParameter('doctrine.odm.mongodb.auto_generate_proxy_classes')); - $this->assertEquals('Doctrine\Common\Cache\ArrayCache', $container->getParameter('doctrine.odm.mongodb.cache.array_class')); - $this->assertEquals('Doctrine\Common\Cache\ApcCache', $container->getParameter('doctrine.odm.mongodb.cache.apc_class')); - $this->assertEquals('Doctrine\Common\Cache\MemcacheCache', $container->getParameter('doctrine.odm.mongodb.cache.memcache_class')); - $this->assertEquals('localhost', $container->getParameter('doctrine.odm.mongodb.cache.memcache_host')); - $this->assertEquals('11211', $container->getParameter('doctrine.odm.mongodb.cache.memcache_port')); - $this->assertEquals('Memcache', $container->getParameter('doctrine.odm.mongodb.cache.memcache_instance_class')); - $this->assertEquals('Doctrine\Common\Cache\XcacheCache', $container->getParameter('doctrine.odm.mongodb.cache.xcache_class')); - $this->assertEquals('Doctrine\ODM\MongoDB\Mapping\Driver\DriverChain', $container->getParameter('doctrine.odm.mongodb.metadata.driver_chain_class')); - $this->assertEquals('Doctrine\ODM\MongoDB\Mapping\Driver\AnnotationDriver', $container->getParameter('doctrine.odm.mongodb.metadata.annotation_class')); - $this->assertEquals('Doctrine\Common\Annotations\AnnotationReader', $container->getParameter('doctrine.odm.mongodb.metadata.annotation_reader_class')); - $this->assertEquals('Doctrine\ODM\MongoDB\Mapping\Driver\XmlDriver', $container->getParameter('doctrine.odm.mongodb.metadata.xml_class')); - $this->assertEquals('Doctrine\ODM\MongoDB\Mapping\Driver\YamlDriver', $container->getParameter('doctrine.odm.mongodb.metadata.yml_class')); - - $this->assertEquals('Symfony\Bundle\DoctrineMongoDBBundle\Validator\Constraints\UniqueValidator', $container->getParameter('doctrine_odm.mongodb.validator.unique.class')); - - $config = array( - 'proxy_namespace' => 'MyProxies', - 'auto_generate_proxy_classes' => true, - 'connections' => array('default' => array()), - 'document_managers' => array('default' => array()) - ); - $loader->load(array($config), $container); - - $this->assertEquals('MyProxies', $container->getParameter('doctrine.odm.mongodb.proxy_namespace')); - $this->assertEquals(true, $container->getParameter('doctrine.odm.mongodb.auto_generate_proxy_classes')); - - $definition = $container->getDefinition('doctrine.odm.mongodb.default_connection'); - $this->assertEquals('%doctrine.odm.mongodb.connection_class%', $definition->getClass()); - $this->assertEquals(array(null, array(), new Reference('doctrine.odm.mongodb.default_configuration')), $definition->getArguments()); - - $definition = $container->getDefinition('doctrine.odm.mongodb.default_document_manager'); - $this->assertEquals('%doctrine.odm.mongodb.document_manager_class%', $definition->getClass()); - $this->assertEquals('%doctrine.odm.mongodb.document_manager_class%', $definition->getFactoryClass()); - $this->assertEquals('create', $definition->getFactoryMethod()); - $this->assertArrayHasKey('doctrine.odm.mongodb.document_manager', $definition->getTags()); - - $arguments = $definition->getArguments(); - $this->assertInstanceOf('Symfony\Component\DependencyInjection\Reference', $arguments[0]); - $this->assertEquals('doctrine.odm.mongodb.default_connection', (string) $arguments[0]); - $this->assertInstanceOf('Symfony\Component\DependencyInjection\Reference', $arguments[1]); - $this->assertEquals('doctrine.odm.mongodb.default_configuration', (string) $arguments[1]); - } - - public function testSingleDocumentManagerConfiguration() - { - $container = $this->getContainer(); - $loader = new DoctrineMongoDBExtension(); - - $config = array( - 'connections' => array( - 'default' => array( - 'server' => 'mongodb://localhost:27017', - 'options' => array('connect' => true) - ) - ), - 'document_managers' => array('default' => array()) - ); - $loader->load(array($config), $container); - - $definition = $container->getDefinition('doctrine.odm.mongodb.default_connection'); - $this->assertEquals('%doctrine.odm.mongodb.connection_class%', $definition->getClass()); - $this->assertEquals(array('mongodb://localhost:27017', array('connect' => true), new Reference('doctrine.odm.mongodb.default_configuration')), $definition->getArguments()); - - $definition = $container->getDefinition('doctrine.odm.mongodb.default_document_manager'); - $this->assertEquals('%doctrine.odm.mongodb.document_manager_class%', $definition->getClass()); - $this->assertEquals('%doctrine.odm.mongodb.document_manager_class%', $definition->getFactoryClass()); - $this->assertEquals('create', $definition->getFactoryMethod()); - $this->assertArrayHasKey('doctrine.odm.mongodb.document_manager', $definition->getTags()); - - $arguments = $definition->getArguments(); - $this->assertInstanceOf('Symfony\Component\DependencyInjection\Reference', $arguments[0]); - $this->assertEquals('doctrine.odm.mongodb.default_connection', (string) $arguments[0]); - $this->assertInstanceOf('Symfony\Component\DependencyInjection\Reference', $arguments[1]); - $this->assertEquals('doctrine.odm.mongodb.default_configuration', (string) $arguments[1]); - } - - public function testLoadSimpleSingleConnection() - { - $container = $this->getContainer(); - $loader = new DoctrineMongoDBExtension(); - $container->registerExtension($loader); - - $this->loadFromFile($container, 'mongodb_service_simple_single_connection'); - - $container->getCompilerPassConfig()->setOptimizationPasses(array()); - $container->getCompilerPassConfig()->setRemovingPasses(array()); - $container->compile(); - - $definition = $container->getDefinition('doctrine.odm.mongodb.default_connection'); - $this->assertEquals('%doctrine.odm.mongodb.connection_class%', $definition->getClass()); - $this->assertEquals(array('mongodb://localhost:27017', array('connect' => true), new Reference('doctrine.odm.mongodb.default_configuration')), $definition->getArguments()); - - $definition = $container->getDefinition('doctrine.odm.mongodb.default_configuration'); - $methodCalls = $definition->getMethodCalls(); - $methodNames = array_map(function($call) { return $call[0]; }, $methodCalls); - $this->assertInternalType('integer', $pos = array_search('setDefaultDB', $methodNames)); - $this->assertEquals('mydb', $methodCalls[$pos][1][0]); - - $definition = $container->getDefinition('doctrine.odm.mongodb.default_document_manager'); - $this->assertEquals('%doctrine.odm.mongodb.document_manager_class%', $definition->getClass()); - $this->assertEquals('%doctrine.odm.mongodb.document_manager_class%', $definition->getFactoryClass()); - $this->assertEquals('create', $definition->getFactoryMethod()); - $this->assertArrayHasKey('doctrine.odm.mongodb.document_manager', $definition->getTags()); - - $arguments = $definition->getArguments(); - $this->assertInstanceOf('Symfony\Component\DependencyInjection\Reference', $arguments[0]); - $this->assertEquals('doctrine.odm.mongodb.default_connection', (string) $arguments[0]); - $this->assertInstanceOf('Symfony\Component\DependencyInjection\Reference', $arguments[1]); - $this->assertEquals('doctrine.odm.mongodb.default_configuration', (string) $arguments[1]); - } - - public function testLoadSingleConnection() - { - $container = $this->getContainer(); - $loader = new DoctrineMongoDBExtension(); - $container->registerExtension($loader); - - $this->loadFromFile($container, 'mongodb_service_single_connection'); - - $container->getCompilerPassConfig()->setOptimizationPasses(array()); - $container->getCompilerPassConfig()->setRemovingPasses(array()); - $container->compile(); - - $definition = $container->getDefinition('doctrine.odm.mongodb.default_connection'); - $this->assertEquals('%doctrine.odm.mongodb.connection_class%', $definition->getClass()); - $this->assertEquals(array('mongodb://localhost:27017', array('connect' => true), new Reference('doctrine.odm.mongodb.default_configuration')), $definition->getArguments()); - - $definition = $container->getDefinition('doctrine.odm.mongodb.default_document_manager'); - $this->assertEquals('%doctrine.odm.mongodb.document_manager_class%', $definition->getClass()); - $this->assertEquals('%doctrine.odm.mongodb.document_manager_class%', $definition->getFactoryClass()); - $this->assertEquals('create', $definition->getFactoryMethod()); - $this->assertArrayHasKey('doctrine.odm.mongodb.document_manager', $definition->getTags()); - - $arguments = $definition->getArguments(); - $this->assertInstanceOf('Symfony\Component\DependencyInjection\Reference', $arguments[0]); - $this->assertEquals('doctrine.odm.mongodb.default_connection', (string) $arguments[0]); - $this->assertInstanceOf('Symfony\Component\DependencyInjection\Reference', $arguments[1]); - $this->assertEquals('doctrine.odm.mongodb.default_configuration', (string) $arguments[1]); - } - - public function testLoadMultipleConnections() - { - $container = $this->getContainer(); - $loader = new DoctrineMongoDBExtension(); - $container->registerExtension($loader); - - $this->loadFromFile($container, 'mongodb_service_multiple_connections'); - - $container->getCompilerPassConfig()->setOptimizationPasses(array()); - $container->getCompilerPassConfig()->setRemovingPasses(array()); - $container->compile(); - - $definition = $container->getDefinition('doctrine.odm.mongodb.conn1_connection'); - $this->assertEquals('%doctrine.odm.mongodb.connection_class%', $definition->getClass()); - $this->assertEquals(array('mongodb://localhost:27017', array('connect' => true), new Reference('doctrine.odm.mongodb.conn1_configuration')), $definition->getArguments()); - - $this->assertEquals('doctrine.odm.mongodb.dm2_document_manager', (string) $container->getAlias('doctrine.odm.mongodb.document_manager')); - - $definition = $container->getDefinition('doctrine.odm.mongodb.dm1_document_manager'); - $this->assertEquals('%doctrine.odm.mongodb.document_manager_class%', $definition->getClass()); - $this->assertEquals('%doctrine.odm.mongodb.document_manager_class%', $definition->getFactoryClass()); - $this->assertEquals('create', $definition->getFactoryMethod()); - $this->assertArrayHasKey('doctrine.odm.mongodb.document_manager', $definition->getTags()); - - $arguments = $definition->getArguments(); - $this->assertInstanceOf('Symfony\Component\DependencyInjection\Reference', $arguments[0]); - $this->assertEquals('doctrine.odm.mongodb.conn1_connection', (string) $arguments[0]); - $this->assertInstanceOf('Symfony\Component\DependencyInjection\Reference', $arguments[1]); - $this->assertEquals('doctrine.odm.mongodb.dm1_configuration', (string) $arguments[1]); - - $definition = $container->getDefinition('doctrine.odm.mongodb.conn2_connection'); - $this->assertEquals('%doctrine.odm.mongodb.connection_class%', $definition->getClass()); - $this->assertEquals(array('mongodb://localhost:27017', array('connect' => true), new Reference('doctrine.odm.mongodb.conn2_configuration')), $definition->getArguments()); - - $definition = $container->getDefinition('doctrine.odm.mongodb.dm2_document_manager'); - $this->assertEquals('%doctrine.odm.mongodb.document_manager_class%', $definition->getClass()); - $this->assertEquals('%doctrine.odm.mongodb.document_manager_class%', $definition->getFactoryClass()); - $this->assertEquals('create', $definition->getFactoryMethod()); - $this->assertArrayHasKey('doctrine.odm.mongodb.document_manager', $definition->getTags()); - - $arguments = $definition->getArguments(); - $this->assertInstanceOf('Symfony\Component\DependencyInjection\Reference', $arguments[0]); - $this->assertEquals('doctrine.odm.mongodb.conn2_connection', (string) $arguments[0]); - $this->assertInstanceOf('Symfony\Component\DependencyInjection\Reference', $arguments[1]); - $this->assertEquals('doctrine.odm.mongodb.dm2_configuration', (string) $arguments[1]); - } - - public function testBundleDocumentAliases() - { - $container = $this->getContainer(); - $loader = new DoctrineMongoDBExtension(); - - $loader->load(array(array('document_managers' => array('default' => array('mappings' => array('YamlBundle' => array()))))), $container); - - $definition = $container->getDefinition('doctrine.odm.mongodb.default_configuration'); - $calls = $definition->getMethodCalls(); - $this->assertTrue(isset($calls[0][1][0]['YamlBundle'])); - $this->assertEquals('DoctrineMongoDBBundle\Tests\DependencyInjection\Fixtures\Bundles\YamlBundle\Document', $calls[0][1][0]['YamlBundle']); - } - - public function testYamlBundleMappingDetection() - { - $container = $this->getContainer(); - $loader = new DoctrineMongoDBExtension('YamlBundle'); - - $loader->load(array(array('document_managers' => array('default' => array('mappings' => array('YamlBundle' => array()))))), $container); - - $calls = $container->getDefinition('doctrine.odm.mongodb.default_metadata_driver')->getMethodCalls(); - $this->assertEquals('doctrine.odm.mongodb.default_yml_metadata_driver', (string) $calls[0][1][0]); - $this->assertEquals('DoctrineMongoDBBundle\Tests\DependencyInjection\Fixtures\Bundles\YamlBundle\Document', $calls[0][1][1]); - } - - public function testXmlBundleMappingDetection() - { - $container = $this->getContainer('XmlBundle'); - $loader = new DoctrineMongoDBExtension(); - - $loader->load(array(array('document_managers' => array('default' => array('mappings' => array('XmlBundle' => array()))))), $container); - - $calls = $container->getDefinition('doctrine.odm.mongodb.default_metadata_driver')->getMethodCalls(); - $this->assertEquals('doctrine.odm.mongodb.default_xml_metadata_driver', (string) $calls[0][1][0]); - $this->assertEquals('DoctrineMongoDBBundle\Tests\DependencyInjection\Fixtures\Bundles\XmlBundle\Document', $calls[0][1][1]); - } - - public function testAnnotationsBundleMappingDetection() - { - $container = $this->getContainer('AnnotationsBundle'); - $loader = new DoctrineMongoDBExtension(); - - $loader->load(array(array('document_managers' => array('default' => array('mappings' => array('AnnotationsBundle' => array()))))), $container); - - $calls = $container->getDefinition('doctrine.odm.mongodb.default_metadata_driver')->getMethodCalls(); - $this->assertEquals('doctrine.odm.mongodb.default_annotation_metadata_driver', (string) $calls[0][1][0]); - $this->assertEquals('DoctrineMongoDBBundle\Tests\DependencyInjection\Fixtures\Bundles\AnnotationsBundle\Document', $calls[0][1][1]); - } - - public function testDocumentManagerMetadataCacheDriverConfiguration() - { - $container = $this->getContainer(); - $loader = new DoctrineMongoDBExtension(); - $container->registerExtension($loader); - - $this->loadFromFile($container, 'mongodb_service_multiple_connections'); - - $container->getCompilerPassConfig()->setOptimizationPasses(array()); - $container->getCompilerPassConfig()->setRemovingPasses(array()); - $container->compile(); - - $definition = $container->getDefinition('doctrine.odm.mongodb.dm1_metadata_cache'); - $this->assertEquals('%doctrine.odm.mongodb.cache.xcache_class%', $definition->getClass()); - - $definition = $container->getDefinition('doctrine.odm.mongodb.dm2_metadata_cache'); - $this->assertEquals('%doctrine.odm.mongodb.cache.apc_class%', $definition->getClass()); - } - - public function testDocumentManagerMemcacheMetadataCacheDriverConfiguration() - { - $container = $this->getContainer(); - $loader = new DoctrineMongoDBExtension(); - $container->registerExtension($loader); - - $this->loadFromFile($container, 'mongodb_service_simple_single_connection'); - - $container->getCompilerPassConfig()->setOptimizationPasses(array()); - $container->getCompilerPassConfig()->setRemovingPasses(array()); - $container->compile(); - - $definition = $container->getDefinition('doctrine.odm.mongodb.default_metadata_cache'); - $this->assertEquals('Doctrine\Common\Cache\MemcacheCache', $definition->getClass()); - - $calls = $definition->getMethodCalls(); - $this->assertEquals('setMemcache', $calls[0][0]); - $this->assertEquals('doctrine.odm.mongodb.default_memcache_instance', (string) $calls[0][1][0]); - - $definition = $container->getDefinition('doctrine.odm.mongodb.default_memcache_instance'); - $this->assertEquals('Memcache', $definition->getClass()); - - $calls = $definition->getMethodCalls(); - $this->assertEquals('connect', $calls[0][0]); - $this->assertEquals('localhost', $calls[0][1][0]); - $this->assertEquals(11211, $calls[0][1][1]); - } - - public function testDependencyInjectionImportsOverrideDefaults() - { - $container = $this->getContainer(); - $loader = new DoctrineMongoDBExtension(); - $container->registerExtension($loader); - - $this->loadFromFile($container, 'odm_imports'); - - $container->getCompilerPassConfig()->setOptimizationPasses(array()); - $container->getCompilerPassConfig()->setRemovingPasses(array()); - $container->compile(); - - $this->assertTrue($container->getParameter('doctrine.odm.mongodb.auto_generate_proxy_classes')); - } - - public function testRegistersValidatorNamespace() - { - $container = $this->getContainer(); - $container->register('validator.mapping.loader.annotation_loader') - ->setClass('stdClass') - ->addArgument(array('foo' => 'Foo\\')); - $container->getCompilerPassConfig()->setOptimizationPasses(array()); - $container->getCompilerPassConfig()->setRemovingPasses(array()); - $container->addCompilerPass(new AddValidatorNamespaceAliasPass()); - $container->compile(); - - $definition = $container->getDefinition('validator.mapping.loader.annotation_loader'); - $arguments = $definition->getArguments(); - $this->assertEquals(array( - 'assertMongoDB' => 'Symfony\\Bundle\\DoctrineMongoDBBundle\\Validator\\Constraints\\', - 'foo' => 'Foo\\', - ), $arguments[0], 'compiler adds constraint alias to validator'); - } - - protected function getContainer($bundle = 'YamlBundle') - { - require_once __DIR__.'/Fixtures/Bundles/'.$bundle.'/'.$bundle.'.php'; - - return new ContainerBuilder(new ParameterBag(array( - 'kernel.bundles' => array($bundle => 'DoctrineMongoDBBundle\\Tests\\DependencyInjection\\Fixtures\\Bundles\\'.$bundle.'\\'.$bundle), - 'kernel.cache_dir' => sys_get_temp_dir(), - 'kernel.debug' => false, - ))); - } -} diff --git a/src/Symfony/Bundle/DoctrineMongoDBBundle/Tests/DependencyInjection/ConfigurationTest.php b/src/Symfony/Bundle/DoctrineMongoDBBundle/Tests/DependencyInjection/ConfigurationTest.php deleted file mode 100644 index b566650464..0000000000 --- a/src/Symfony/Bundle/DoctrineMongoDBBundle/Tests/DependencyInjection/ConfigurationTest.php +++ /dev/null @@ -1,283 +0,0 @@ - - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -namespace Symfony\Bundle\DoctrineMongoDBBundle\Tests\DependencyInjection; - -use Symfony\Component\DependencyInjection\ContainerBuilder; -use Symfony\Bundle\DoctrineMongoDBBundle\DependencyInjection\Configuration; -use Symfony\Component\Yaml\Yaml; -use Symfony\Component\Config\Definition\Processor; - -class ConfigurationTest extends \PHPUnit_Framework_TestCase -{ - public function testDefaults() - { - $processor = new Processor(); - $configuration = new Configuration(false); - $options = $processor->processConfiguration($configuration, array()); - - $defaults = array( - 'auto_generate_hydrator_classes' => false, - 'auto_generate_proxy_classes' => false, - 'default_database' => 'default', - 'document_managers' => array(), - 'connections' => array(), - 'proxy_dir' => '%kernel.cache_dir%/doctrine/odm/mongodb/Proxies', - 'proxy_namespace' => 'Proxies', - 'hydrator_dir' => '%kernel.cache_dir%/doctrine/odm/mongodb/Hydrators', - 'hydrator_namespace' => 'Hydrators', - ); - - foreach ($defaults as $key => $default) { - $this->assertTrue(array_key_exists($key, $options), sprintf('The default "%s" exists', $key)); - $this->assertEquals($default, $options[$key]); - - unset($options[$key]); - } - - if (count($options)) { - $this->fail('Extra defaults were returned: '. print_r($options, true)); - } - } - - /** - * Tests a full configuration. - * - * @dataProvider fullConfigurationProvider - */ - public function testFullConfiguration($config) - { - $processor = new Processor(); - $configuration = new Configuration(false); - $options = $processor->processConfiguration($configuration, array($config)); - - $expected = array( - 'proxy_dir' => '%kernel.cache_dir%/doctrine/odm/mongodb/Proxies', - 'proxy_namespace' => 'Test_Proxies', - 'auto_generate_proxy_classes' => true, - 'hydrator_dir' => '%kernel.cache_dir%/doctrine/odm/mongodb/Hydrators', - 'hydrator_namespace' => 'Test_Hydrators', - 'auto_generate_hydrator_classes' => true, - 'default_document_manager' => 'default_dm_name', - 'default_database' => 'default_db_name', - 'default_connection' => 'conn1', - 'connections' => array( - 'conn1' => array( - 'server' => 'http://server', - 'options' => array( - 'connect' => true, - 'persist' => 'persist_val', - 'timeout' => 500, - 'replicaSet' => true, - 'username' => 'username_val', - 'password' => 'password_val', - ), - ), - 'conn2' => array( - 'server' => 'http://server2', - 'options' => array(), - ), - ), - 'document_managers' => array( - 'dm1' => array( - 'mappings' => array( - 'FooBundle' => array( - 'type' => 'annotations', - ), - ), - 'metadata_cache_driver' => array( - 'type' => 'memcache', - 'class' => 'fooClass', - 'host' => 'host_val', - 'port' => 1234, - 'instance_class' => 'instance_val', - ), - 'logging' => false, - ), - 'dm2' => array( - 'connection' => 'dm2_connection', - 'database' => 'db1', - 'mappings' => array( - 'BarBundle' => array( - 'type' => 'yml', - 'dir' => '%kernel.cache_dir%', - 'prefix' => 'prefix_val', - 'alias' => 'alias_val', - 'is_bundle' => false, - ) - ), - 'metadata_cache_driver' => array( - 'type' => 'apc', - ), - 'logging' => true, - ) - ) - ); - - $this->assertEquals($expected, $options); - } - - public function fullConfigurationProvider() - { - $yaml = Yaml::load(__DIR__.'/Fixtures/config/yml/full.yml'); - $yaml = $yaml['doctrine_mongo_db']; - - return array( - array($yaml), - ); - } - - /** - * @dataProvider optionProvider - * @param array $configs The source array of configuration arrays - * @param array $correctValues A key-value pair of end values to check - */ - public function testMergeOptions(array $configs, array $correctValues) - { - $processor = new Processor(); - $configuration = new Configuration(false); - $options = $processor->processConfiguration($configuration, $configs); - - foreach ($correctValues as $key => $correctVal) - { - $this->assertEquals($correctVal, $options[$key]); - } - } - - public function optionProvider() - { - $cases = array(); - - // single config, testing normal option setting - $cases[] = array( - array( - array('default_document_manager' => 'foo'), - ), - array('default_document_manager' => 'foo') - ); - - // single config, testing normal option setting with dashes - $cases[] = array( - array( - array('default-document-manager' => 'bar'), - ), - array('default_document_manager' => 'bar') - ); - - // testing the normal override merging - the later config array wins - $cases[] = array( - array( - array('default_document_manager' => 'foo'), - array('default_document_manager' => 'baz'), - ), - array('default_document_manager' => 'baz') - ); - - // the "options" array is totally replaced - $cases[] = array( - array( - array('connections' => array('default' => array('options' => array('timeout' => 2000)))), - array('connections' => array('default' => array('options' => array('username' => 'foo')))), - ), - array('connections' => array('default' => array('options' => array('username' => 'foo'), 'server' => null))), - ); - - // mappings are merged non-recursively. - $cases[] = array( - array( - array('document_managers' => array('default' => array('mappings' => array('foomap' => array('type' => 'val1'), 'barmap' => array('dir' => 'val2'))))), - array('document_managers' => array('default' => array('mappings' => array('barmap' => array('prefix' => 'val3'))))), - ), - array('document_managers' => array('default' => array('logging' => false, 'mappings' => array('foomap' => array('type' => 'val1'), 'barmap' => array('prefix' => 'val3'))))), - ); - - // connections are merged non-recursively. - $cases[] = array( - array( - array('connections' => array('foocon' => array('server' => 'val1'), 'barcon' => array('options' => array('username' => 'val2')))), - array('connections' => array('barcon' => array('server' => 'val3'))), - ), - array('connections' => array( - 'foocon' => array('server' => 'val1', 'options' => array()), - 'barcon' => array('server' => 'val3', 'options' => array()) - )), - ); - - // managers are merged non-recursively. - $cases[] = array( - array( - array('document_managers' => array('foodm' => array('database' => 'val1'), 'bardm' => array('database' => 'val2'))), - array('document_managers' => array('bardm' => array('database' => 'val3'))), - ), - array('document_managers' => array( - 'foodm' => array('database' => 'val1', 'logging' => false, 'mappings' => array()), - 'bardm' => array('database' => 'val3', 'logging' => false, 'mappings' => array()), - )), - ); - - return $cases; - } - - /** - * @dataProvider getNormalizationTests - */ - public function testNormalizeOptions(array $config, $targetKey, array $normalized) - { - $processor = new Processor(); - $configuration = new Configuration(false); - $options = $processor->processConfiguration($configuration, array($config)); - $this->assertSame($normalized, $options[$targetKey]); - } - - public function getNormalizationTests() - { - return array( - // connection versus connections (id is the identifier) - array( - array('connection' => array( - array('server' => 'mongodb://abc', 'id' => 'foo'), - array('server' => 'mongodb://def', 'id' => 'bar'), - )), - 'connections', - array( - 'foo' => array('server' => 'mongodb://abc', 'options' => array()), - 'bar' => array('server' => 'mongodb://def', 'options' => array()), - ), - ), - // document_manager versus document_managers (id is the identifier) - array( - array('document_manager' => array( - array('connection' => 'conn1', 'id' => 'foo'), - array('connection' => 'conn2', 'id' => 'bar'), - )), - 'document_managers', - array( - 'foo' => array('connection' => 'conn1', 'logging' => false, 'mappings' => array()), - 'bar' => array('connection' => 'conn2', 'logging' => false, 'mappings' => array()), - ), - ), - // mapping configuration that's beneath a specific document manager - array( - array('document_manager' => array( - array('id' => 'foo', 'connection' => 'conn1', 'mapping' => array( - 'type' => 'xml', 'name' => 'foo-mapping' - )), - )), - 'document_managers', - array( - 'foo' => array('connection' => 'conn1', 'mappings' => array( - 'foo-mapping' => array('type' => 'xml'), - ), 'logging' => false), - ), - ), - ); - } -} diff --git a/src/Symfony/Bundle/DoctrineMongoDBBundle/Tests/DependencyInjection/DoctrineMongoDBExtensionTest.php b/src/Symfony/Bundle/DoctrineMongoDBBundle/Tests/DependencyInjection/DoctrineMongoDBExtensionTest.php deleted file mode 100644 index 39e9f4f0a6..0000000000 --- a/src/Symfony/Bundle/DoctrineMongoDBBundle/Tests/DependencyInjection/DoctrineMongoDBExtensionTest.php +++ /dev/null @@ -1,41 +0,0 @@ - - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -namespace Symfony\Bundle\DoctrineMongoDBBundle\Tests\DependencyInjection; - -use Symfony\Component\DependencyInjection\ContainerBuilder; -use Symfony\Bundle\DoctrineMongoDBBundle\DependencyInjection\DoctrineMongoDBExtension; - -use Symfony\Component\Config\Definition\Processor; - -class DoctrineMongoDBExtensionTest extends \PHPUnit_Framework_TestCase -{ - /** - * @dataProvider parameterProvider - */ - public function testParameterOverride($option, $parameter, $value) - { - $container = new ContainerBuilder(); - $container->setParameter('kernel.debug', false); - $loader = new DoctrineMongoDBExtension(); - $loader->load(array(array($option => $value)), $container); - - $this->assertEquals($value, $container->getParameter('doctrine.odm.mongodb.'.$parameter)); - } - - public function parameterProvider() - { - return array( - array('proxy_namespace', 'proxy_namespace', 'foo'), - array('proxy-namespace', 'proxy_namespace', 'bar'), - ); - } -} \ No newline at end of file diff --git a/src/Symfony/Bundle/DoctrineMongoDBBundle/Tests/DependencyInjection/Fixtures/Bundles/AnnotationsBundle/AnnotationsBundle.php b/src/Symfony/Bundle/DoctrineMongoDBBundle/Tests/DependencyInjection/Fixtures/Bundles/AnnotationsBundle/AnnotationsBundle.php deleted file mode 100644 index 23b96a825d..0000000000 --- a/src/Symfony/Bundle/DoctrineMongoDBBundle/Tests/DependencyInjection/Fixtures/Bundles/AnnotationsBundle/AnnotationsBundle.php +++ /dev/null @@ -1,9 +0,0 @@ - - - - - - - - true - - - - - true - - - - - - - \ No newline at end of file diff --git a/src/Symfony/Bundle/DoctrineMongoDBBundle/Tests/DependencyInjection/Fixtures/config/xml/mongodb_service_simple_single_connection.xml b/src/Symfony/Bundle/DoctrineMongoDBBundle/Tests/DependencyInjection/Fixtures/config/xml/mongodb_service_simple_single_connection.xml deleted file mode 100644 index 0663a9c314..0000000000 --- a/src/Symfony/Bundle/DoctrineMongoDBBundle/Tests/DependencyInjection/Fixtures/config/xml/mongodb_service_simple_single_connection.xml +++ /dev/null @@ -1,24 +0,0 @@ - - - - - - - - true - - - - - Doctrine\Common\Cache\MemcacheCache - localhost - 11211 - Memcache - - - - \ No newline at end of file diff --git a/src/Symfony/Bundle/DoctrineMongoDBBundle/Tests/DependencyInjection/Fixtures/config/xml/mongodb_service_single_connection.xml b/src/Symfony/Bundle/DoctrineMongoDBBundle/Tests/DependencyInjection/Fixtures/config/xml/mongodb_service_single_connection.xml deleted file mode 100644 index 0ee2ddb300..0000000000 --- a/src/Symfony/Bundle/DoctrineMongoDBBundle/Tests/DependencyInjection/Fixtures/config/xml/mongodb_service_single_connection.xml +++ /dev/null @@ -1,27 +0,0 @@ - - - - - - - - - true - - - - - - Doctrine\Common\Cache\MemcacheCache - localhost - 11211 - Memcache - - - - - \ No newline at end of file diff --git a/src/Symfony/Bundle/DoctrineMongoDBBundle/Tests/DependencyInjection/Fixtures/config/xml/odm_imports.xml b/src/Symfony/Bundle/DoctrineMongoDBBundle/Tests/DependencyInjection/Fixtures/config/xml/odm_imports.xml deleted file mode 100644 index 1e215a1635..0000000000 --- a/src/Symfony/Bundle/DoctrineMongoDBBundle/Tests/DependencyInjection/Fixtures/config/xml/odm_imports.xml +++ /dev/null @@ -1,17 +0,0 @@ - - - - - - - - - - - diff --git a/src/Symfony/Bundle/DoctrineMongoDBBundle/Tests/DependencyInjection/Fixtures/config/xml/odm_imports_import.xml b/src/Symfony/Bundle/DoctrineMongoDBBundle/Tests/DependencyInjection/Fixtures/config/xml/odm_imports_import.xml deleted file mode 100644 index b06efb4628..0000000000 --- a/src/Symfony/Bundle/DoctrineMongoDBBundle/Tests/DependencyInjection/Fixtures/config/xml/odm_imports_import.xml +++ /dev/null @@ -1,13 +0,0 @@ - - - - - - - diff --git a/src/Symfony/Bundle/DoctrineMongoDBBundle/Tests/DependencyInjection/Fixtures/config/yml/full.yml b/src/Symfony/Bundle/DoctrineMongoDBBundle/Tests/DependencyInjection/Fixtures/config/yml/full.yml deleted file mode 100644 index 6ebed849a1..0000000000 --- a/src/Symfony/Bundle/DoctrineMongoDBBundle/Tests/DependencyInjection/Fixtures/config/yml/full.yml +++ /dev/null @@ -1,47 +0,0 @@ -doctrine_mongo_db: - proxy_namespace: Test_Proxies - auto_generate_proxy_classes: true - - hydrator_namespace: Test_Hydrators - auto_generate_hydrator_classes: true - - default_document_manager: default_dm_name - default_database: default_db_name - - default_connection: conn1 - - connections: - conn1: - server: http://server - options: - connect: true - persist: persist_val - timeout: 500 - replicaSet: true - username: username_val - password: password_val - conn2: - server: http://server2 - - document_managers: - dm1: - mappings: - FooBundle: annotations - metadata_cache_driver: - type: memcache - class: fooClass - host: host_val - port: 1234 - instance_class: instance_val - dm2: - connection: dm2_connection - database: db1 - mappings: - BarBundle: - type: yml - dir: %kernel.cache_dir% - prefix: prefix_val - alias: alias_val - is_bundle: false - metadata_cache_driver: apc - logging: true diff --git a/src/Symfony/Bundle/DoctrineMongoDBBundle/Tests/DependencyInjection/Fixtures/config/yml/mongodb_service_multiple_connections.yml b/src/Symfony/Bundle/DoctrineMongoDBBundle/Tests/DependencyInjection/Fixtures/config/yml/mongodb_service_multiple_connections.yml deleted file mode 100644 index d56d9383ee..0000000000 --- a/src/Symfony/Bundle/DoctrineMongoDBBundle/Tests/DependencyInjection/Fixtures/config/yml/mongodb_service_multiple_connections.yml +++ /dev/null @@ -1,19 +0,0 @@ -doctrine_mongo_db: - default_document_manager: dm2 - default_connection: conn2 - connections: - conn1: - server: mongodb://localhost:27017 - options: - connect: true - conn2: - server: mongodb://localhost:27017 - options: - connect: true - document_managers: - dm1: - connection: conn1 - metadata_cache_driver: xcache - dm2: - connection: conn2 - metadata_cache_driver: apc diff --git a/src/Symfony/Bundle/DoctrineMongoDBBundle/Tests/DependencyInjection/Fixtures/config/yml/mongodb_service_simple_single_connection.yml b/src/Symfony/Bundle/DoctrineMongoDBBundle/Tests/DependencyInjection/Fixtures/config/yml/mongodb_service_simple_single_connection.yml deleted file mode 100644 index 4e55aa119e..0000000000 --- a/src/Symfony/Bundle/DoctrineMongoDBBundle/Tests/DependencyInjection/Fixtures/config/yml/mongodb_service_simple_single_connection.yml +++ /dev/null @@ -1,14 +0,0 @@ -doctrine_mongo_db: - connections: - default: - server: mongodb://localhost:27017 - options: { connect: true } - default_database: mydb - document_managers: - default: - metadata_cache_driver: - type: memcache - class: Doctrine\Common\Cache\MemcacheCache - host: localhost - port: 11211 - instance_class: Memcache \ No newline at end of file diff --git a/src/Symfony/Bundle/DoctrineMongoDBBundle/Tests/DependencyInjection/Fixtures/config/yml/mongodb_service_single_connection.yml b/src/Symfony/Bundle/DoctrineMongoDBBundle/Tests/DependencyInjection/Fixtures/config/yml/mongodb_service_single_connection.yml deleted file mode 100644 index 95466f9126..0000000000 --- a/src/Symfony/Bundle/DoctrineMongoDBBundle/Tests/DependencyInjection/Fixtures/config/yml/mongodb_service_single_connection.yml +++ /dev/null @@ -1,15 +0,0 @@ -doctrine_mongo_db: - connections: - default: - server: mongodb://localhost:27017 - options: - connect: true - document_managers: - default: - connection: default - metadata_cache_driver: - type: memcache - class: Doctrine\Common\Cache\MemcacheCache - host: localhost - port: 11211 - instance_class: Memcache \ No newline at end of file diff --git a/src/Symfony/Bundle/DoctrineMongoDBBundle/Tests/DependencyInjection/Fixtures/config/yml/odm_imports.yml b/src/Symfony/Bundle/DoctrineMongoDBBundle/Tests/DependencyInjection/Fixtures/config/yml/odm_imports.yml deleted file mode 100644 index e4292b8662..0000000000 --- a/src/Symfony/Bundle/DoctrineMongoDBBundle/Tests/DependencyInjection/Fixtures/config/yml/odm_imports.yml +++ /dev/null @@ -1,5 +0,0 @@ -imports: - - { resource: odm_imports_import.yml } - -doctrine_mongo_db: - auto_generate_proxy_classes: true diff --git a/src/Symfony/Bundle/DoctrineMongoDBBundle/Tests/DependencyInjection/Fixtures/config/yml/odm_imports_import.yml b/src/Symfony/Bundle/DoctrineMongoDBBundle/Tests/DependencyInjection/Fixtures/config/yml/odm_imports_import.yml deleted file mode 100644 index 888177d921..0000000000 --- a/src/Symfony/Bundle/DoctrineMongoDBBundle/Tests/DependencyInjection/Fixtures/config/yml/odm_imports_import.yml +++ /dev/null @@ -1,2 +0,0 @@ -doctrine_mongo_db: - auto_generate_proxy_classes: false diff --git a/src/Symfony/Bundle/DoctrineMongoDBBundle/Tests/DependencyInjection/XmlMongoDBExtensionTest.php b/src/Symfony/Bundle/DoctrineMongoDBBundle/Tests/DependencyInjection/XmlMongoDBExtensionTest.php deleted file mode 100644 index 00976d6bb9..0000000000 --- a/src/Symfony/Bundle/DoctrineMongoDBBundle/Tests/DependencyInjection/XmlMongoDBExtensionTest.php +++ /dev/null @@ -1,25 +0,0 @@ - - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -namespace Symfony\Bundle\DoctrineMongoDBBundle\Tests\DependencyInjection; - -use Symfony\Component\DependencyInjection\ContainerBuilder; -use Symfony\Component\DependencyInjection\Loader\XmlFileLoader; -use Symfony\Component\Config\FileLocator; - -class XmlMongoDBExtensionTest extends AbstractMongoDBExtensionTest -{ - protected function loadFromFile(ContainerBuilder $container, $file) - { - $loadXml = new XmlFileLoader($container, new FileLocator(__DIR__.'/Fixtures/config/xml')); - $loadXml->load($file.'.xml'); - } -} \ No newline at end of file diff --git a/src/Symfony/Bundle/DoctrineMongoDBBundle/Tests/DependencyInjection/YamlMongoDBExtensionTest.php b/src/Symfony/Bundle/DoctrineMongoDBBundle/Tests/DependencyInjection/YamlMongoDBExtensionTest.php deleted file mode 100644 index 2c56e63d6a..0000000000 --- a/src/Symfony/Bundle/DoctrineMongoDBBundle/Tests/DependencyInjection/YamlMongoDBExtensionTest.php +++ /dev/null @@ -1,25 +0,0 @@ - - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -namespace Symfony\Bundle\DoctrineMongoDBBundle\Tests\DependencyInjection; - -use Symfony\Component\DependencyInjection\ContainerBuilder; -use Symfony\Component\DependencyInjection\Loader\YamlFileLoader; -use Symfony\Component\Config\FileLocator; - -class YamlMongoDBExtensionTest extends AbstractMongoDBExtensionTest -{ - protected function loadFromFile(ContainerBuilder $container, $file) - { - $loadYaml = new YamlFileLoader($container, new FileLocator(__DIR__.'/Fixtures/config/yml')); - $loadYaml->load($file.'.yml'); - } -} \ No newline at end of file diff --git a/src/Symfony/Bundle/DoctrineMongoDBBundle/Tests/Fixtures/Validator/Document.php b/src/Symfony/Bundle/DoctrineMongoDBBundle/Tests/Fixtures/Validator/Document.php deleted file mode 100755 index 6c8b77d6ca..0000000000 --- a/src/Symfony/Bundle/DoctrineMongoDBBundle/Tests/Fixtures/Validator/Document.php +++ /dev/null @@ -1,9 +0,0 @@ - - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -namespace Symfony\Bundle\DoctrineMongoDBBundle\Tests\Logger; - -use Symfony\Bundle\DoctrineMongoDBBundle\Logger\DoctrineMongoDBLogger; - -class DoctrineMongoDBLoggerTest extends \PHPUnit_Framework_TestCase -{ - protected $logger; - - protected function setUp() - { - $this->logger = new DoctrineMongoDBLogger(); - } - - /** - * @dataProvider getQueries - */ - public function testLogger($query, $formatted) - { - $this->logger->logQuery($query); - - $this->assertEquals($formatted, $this->logger->getQueries()); - } - - public function getQueries() - { - return array( - // batchInsert - array( - array('db' => 'foo', 'collection' => 'bar', 'batchInsert' => true, 'num' => 1, 'data' => array('foo'), 'options' => array()), - array('use foo;', 'db.bar.batchInsert(**1 item(s)**);'), - ), - // find - array( - array('db' => 'foo', 'collection' => 'bar', 'find' => true, 'query' => array('foo' => null), 'fields' => array()), - array('use foo;', 'db.bar.find({ "foo": null });'), - ), - ); - } -} diff --git a/src/Symfony/Bundle/DoctrineMongoDBBundle/Tests/TestCase.php b/src/Symfony/Bundle/DoctrineMongoDBBundle/Tests/TestCase.php deleted file mode 100644 index 3e14e1bb78..0000000000 --- a/src/Symfony/Bundle/DoctrineMongoDBBundle/Tests/TestCase.php +++ /dev/null @@ -1,42 +0,0 @@ - - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -namespace Symfony\Bundle\DoctrineMongoDBBundle\Tests; - -use Doctrine\ODM\MongoDB\DocumentManager; -use Doctrine\MongoDB\Connection; - -class TestCase extends \PHPUnit_Framework_TestCase -{ - protected function setUp() - { - if (!class_exists('Doctrine\\ODM\\MongoDB\\Version')) { - $this->markTestSkipped('Doctrine MongoDB ODM is not available.'); - } - } - - /** - * @return DocumentManager - */ - protected function createTestDocumentManager($paths = array()) - { - $config = new \Doctrine\ODM\MongoDB\Configuration(); - $config->setAutoGenerateProxyClasses(true); - $config->setProxyDir(\sys_get_temp_dir()); - $config->setHydratorDir(\sys_get_temp_dir()); - $config->setProxyNamespace('SymfonyTests\Doctrine'); - $config->setHydratorNamespace('SymfonyTests\Doctrine'); - $config->setMetadataDriverImpl($config->newDefaultAnnotationDriver($paths)); - $config->setMetadataCacheImpl(new \Doctrine\Common\Cache\ArrayCache()); - - return DocumentManager::create(new Connection(), $config); - } -} diff --git a/src/Symfony/Bundle/DoctrineMongoDBBundle/Tests/Validator/Constraints/UniqueValidatorTest.php b/src/Symfony/Bundle/DoctrineMongoDBBundle/Tests/Validator/Constraints/UniqueValidatorTest.php deleted file mode 100755 index f3e0d6fae7..0000000000 --- a/src/Symfony/Bundle/DoctrineMongoDBBundle/Tests/Validator/Constraints/UniqueValidatorTest.php +++ /dev/null @@ -1,156 +0,0 @@ -classMetadata = $this->getClassMetadata(); - $this->repository = $this->getDocumentRepository(); - $this->dm = $this->getDocumentManager($this->classMetadata, $this->repository); - $container = $this->getContainer(); - $this->validator = new UniqueValidator($container); - } - - public function tearDown() - { - unset($this->validator, $this->dm, $this->repository, $this->classMetadata); - } - - /** - * @dataProvider getFieldsPathsValuesDocumentsAndReturns - */ - public function testShouldValidateValidStringMappingValues($field, $path, $value, $document, $return) - { - $this->setFieldMapping($field, 'string'); - - $this->repository->expects($this->once()) - ->method('findOneBy') - ->with(array($path => $value)) - ->will($this->returnValue($return)); - - $this->assertTrue($this->validator->isValid($document, new Unique($path))); - } - - public function getFieldsPathsValuesDocumentsAndReturns() - { - $field = 'unique'; - $path = $field; - $value = 'someUniqueValueToBeValidated'; - $document = $this->getFixtureDocument($field, $value); - - return array( - array('unique', 'unique', 'someUniqueValueToBeValidated', $document, null), - array('unique', 'unique', 'someUniqueValueToBeValidated', $document, $document), - array('unique', 'unique', 'someUniqueValueToBeValidated', $document, $this->getFixtureDocument($field, $value)), - ); - } - - /** - * @dataProvider getFieldTypesFieldsPathsValuesAndQueries - */ - public function testGetsCorrectQueryArrayForCollection($type, $field, $path, $value, $query) - { - $this->setFieldMapping($field, $type); - $document = $this->getFixtureDocument($field, $value); - - $this->repository->expects($this->once()) - ->method('findOneBy') - ->with($query); - - $this->validator->isValid($document, new Unique($path)); - } - - public function getFieldTypesFieldsPathsValuesAndQueries() - { - $field = 'unique'; - $key = 'uniqueValue'; - $path = $field.'.'.$key; - $value = 'someUniqueValueToBeValidated'; - - return array( - array('collection', $field, $path, array($value), array($field => array('$in' => array($value)))), - array('hash', $field, $path, array($key => $value), array($path => $value)), - ); - } - - private function getContainer() - { - $container = $this->getMock('Symfony\Component\DependencyInjection\ContainerInterface'); - - $container->expects($this->once()) - ->method('get') - ->will($this->returnValue($this->dm)); - - return $container; - } - - private function getDocumentManager(ClassMetadata $classMetadata, DocumentRepository $repository) - { - $dm = $this->getMockBuilder('Doctrine\ODM\MongoDB\DocumentManager') - ->disableOriginalConstructor() - ->setMethods(array('getClassMetadata', 'getRepository')) - ->getMock(); - $dm->expects($this->any()) - ->method('getClassMetadata') - ->will($this->returnValue($classMetadata)); - $dm->expects($this->any()) - ->method('getRepository') - ->will($this->returnValue($repository)); - - return $dm; - } - - protected function getDocumentRepository() - { - $dm = $this->getMock('Doctrine\ODM\MongoDB\DocumentRepository', array('findOneBy'), array(), '', false, false); - - return $dm; - } - - protected function getClassMetadata() - { - $classMetadata = $this->getMock('Doctrine\ODM\MongoDB\Mapping\ClassMetadata', array(), array(), '', false, false); - $classMetadata->expects($this->any()) - ->method('getFieldValue') - ->will($this->returnCallback(function($document, $fieldName) { - return $document->{$fieldName}; - })); - - $classMetadata->fieldmappings = array(); - - return $classMetadata; - } - - protected function setFieldMapping($fieldName, $type, array $attributes = array()) - { - $this->classMetadata->fieldMappings[$fieldName] = array_merge(array( - 'fieldName' => $fieldName, - 'type' => $type, - ), $attributes); - } - - protected function getFixtureDocument($field, $value, $id = 1) - { - $document = new Document(); - $document->{$field} = $value; - $document->id = 1; - - return $document; - } -} diff --git a/src/Symfony/Bundle/DoctrineMongoDBBundle/Validator/Constraints/Unique.php b/src/Symfony/Bundle/DoctrineMongoDBBundle/Validator/Constraints/Unique.php deleted file mode 100755 index 3a29894d0d..0000000000 --- a/src/Symfony/Bundle/DoctrineMongoDBBundle/Validator/Constraints/Unique.php +++ /dev/null @@ -1,56 +0,0 @@ - - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -namespace Symfony\Bundle\DoctrineMongoDBBundle\Validator\Constraints; - -use Symfony\Component\Validator\Constraint; - -/** - * Doctrine MongoDB ODM unique value constraint. - * - * @author Bulat Shakirzyanov - */ -class Unique extends Constraint -{ - public $message = 'The value for {{ property }} already exists.'; - public $path; - public $documentManager; - - public function getDefaultOption() - { - return 'path'; - } - - public function getRequiredOptions() - { - return array('path'); - } - - public function validatedBy() - { - return 'doctrine_odm.mongodb.unique'; - } - - public function getTargets() - { - return Constraint::CLASS_CONSTRAINT; - } - - public function getDocumentManagerId() - { - $id = 'doctrine.odm.mongodb.document_manager'; - if (null !== $this->documentManager) { - $id = sprintf('doctrine.odm.mongodb.%s_document_manager', $this->documentManager); - } - - return $id; - } -} diff --git a/src/Symfony/Bundle/DoctrineMongoDBBundle/Validator/Constraints/UniqueValidator.php b/src/Symfony/Bundle/DoctrineMongoDBBundle/Validator/Constraints/UniqueValidator.php deleted file mode 100755 index 3708760971..0000000000 --- a/src/Symfony/Bundle/DoctrineMongoDBBundle/Validator/Constraints/UniqueValidator.php +++ /dev/null @@ -1,138 +0,0 @@ - - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -namespace Symfony\Bundle\DoctrineMongoDBBundle\Validator\Constraints; - -use Doctrine\ODM\MongoDB\DocumentManager; -use Doctrine\ODM\MongoDB\Proxy\Proxy; -use Doctrine\ODM\MongoDB\Mapping\ClassMetadata; -use Symfony\Component\DependencyInjection\ContainerInterface; -use Symfony\Component\Validator\Constraint; -use Symfony\Component\Validator\ConstraintValidator; - -/** - * Doctrine MongoDB ODM unique value validator. - * - * @author Bulat Shakirzyanov - */ -class UniqueValidator extends ConstraintValidator -{ - - private $container; - - public function __construct(ContainerInterface $container) - { - $this->container = $container; - } - - /** - * @param Doctrine\ODM\MongoDB\Document $value - * @param Constraint $constraint - * @return Boolean - */ - public function isValid($document, Constraint $constraint) - { - $class = get_class($document); - $dm = $this->getDocumentManager($constraint); - $metadata = $dm->getClassMetadata($class); - - if ($metadata->isEmbeddedDocument) { - throw new \InvalidArgumentException(sprintf("Document '%s' is an embedded document, and cannot be validated", $class)); - } - - $query = $this->getQueryArray($metadata, $document, $constraint->path); - - // check if document exists in mongodb - if (null === ($doc = $dm->getRepository($class)->findOneBy($query))) { - return true; - } - - // check if document in mongodb is the same document as the checked one - if ($doc === $document) { - return true; - } - - // check if returned document is proxy and initialize the minimum identifier if needed - if ($doc instanceof Proxy) { - $metadata->setIdentifierValue($doc, $doc->__identifier); - } - - // check if document has the same identifier as the current one - if ($metadata->getIdentifierValue($doc) === $metadata->getIdentifierValue($document)) { - return true; - } - - $this->context->setPropertyPath($this->context->getPropertyPath() . '.' . $constraint->path); - $this->setMessage($constraint->message, array( - '{{ property }}' => $constraint->path, - )); - return false; - } - - protected function getQueryArray(ClassMetadata $metadata, $document, $path) - { - $class = $metadata->name; - $field = $this->getFieldNameFromPropertyPath($path); - if (!isset($metadata->fieldMappings[$field])) { - throw new \LogicException('Mapping for \'' . $path . '\' doesn\'t exist for ' . $class); - } - $mapping = $metadata->fieldMappings[$field]; - if (isset($mapping['reference']) && $mapping['reference']) { - throw new \LogicException('Cannot determine uniqueness of referenced document values'); - } - switch ($mapping['type']) { - case 'one': - // TODO: implement support for embed one documents - case 'many': - // TODO: implement support for embed many documents - throw new \RuntimeException('Not Implemented.'); - case 'hash': - $value = $metadata->getFieldValue($document, $mapping['fieldName']); - return array($path => $this->getFieldValueRecursively($path, $value)); - case 'collection': - return array($mapping['fieldName'] => array('$in' => $metadata->getFieldValue($document, $mapping['fieldName']))); - default: - return array($mapping['fieldName'] => $metadata->getFieldValue($document, $mapping['fieldName'])); - } - } - - /** - * Returns the actual document field value - * - * E.g. document.someVal -> document - * user.emails -> user - * username -> username - * - * @param string $field - * @return string - */ - private function getFieldNameFromPropertyPath($field) - { - $pieces = explode('.', $field); - return $pieces[0]; - } - - private function getFieldValueRecursively($fieldName, $value) - { - $pieces = explode('.', $fieldName); - unset($pieces[0]); - foreach ($pieces as $piece) { - $value = $value[$piece]; - } - return $value; - } - - private function getDocumentManager(Unique $constraint) - { - return $this->container->get($constraint->getDocumentManagerId()); - } - -} diff --git a/vendors.sh b/vendors.sh index fa9bf6453f..3f2723ce44 100755 --- a/vendors.sh +++ b/vendors.sh @@ -47,17 +47,11 @@ install_git doctrine-data-fixtures git://github.com/doctrine/data-fixtures.git install_git doctrine-dbal git://github.com/doctrine/dbal.git 2.0.4 # Doctrine Common -install_git doctrine-common git://github.com/doctrine/common.git +install_git doctrine-common git://github.com/doctrine/common.git 2.0.2 # Doctrine migrations install_git doctrine-migrations git://github.com/doctrine/migrations.git -# Doctrine MongoDB -install_git doctrine-mongodb git://github.com/doctrine/mongodb.git - -# Doctrine MongoDB -install_git doctrine-mongodb-odm git://github.com/doctrine/mongodb-odm.git - # Monolog install_git monolog git://github.com/Seldaek/monolog.git From 7bbb8beb1783fbfd7907f79068b08527a2640e91 Mon Sep 17 00:00:00 2001 From: Eriksen Costa Date: Thu, 21 Apr 2011 23:20:52 -0300 Subject: [PATCH 91/91] [FrameworkBundle] updated method call --- .../DependencyInjection/Compiler/AddFormGuessersPass.php | 2 +- .../DependencyInjection/Compiler/AddFormTypesPass.php | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/Symfony/Bundle/FrameworkBundle/DependencyInjection/Compiler/AddFormGuessersPass.php b/src/Symfony/Bundle/FrameworkBundle/DependencyInjection/Compiler/AddFormGuessersPass.php index 5431798e10..3795eb13d1 100644 --- a/src/Symfony/Bundle/FrameworkBundle/DependencyInjection/Compiler/AddFormGuessersPass.php +++ b/src/Symfony/Bundle/FrameworkBundle/DependencyInjection/Compiler/AddFormGuessersPass.php @@ -35,6 +35,6 @@ class AddFormGuessersPass implements CompilerPassInterface $guessers[] = new Reference($serviceId); } - $container->getDefinition('form.factory')->setArgument(1, $guessers); + $container->getDefinition('form.factory')->replaceArgument(1, $guessers); } } diff --git a/src/Symfony/Bundle/FrameworkBundle/DependencyInjection/Compiler/AddFormTypesPass.php b/src/Symfony/Bundle/FrameworkBundle/DependencyInjection/Compiler/AddFormTypesPass.php index edd23e2f9b..43e0a5d8b4 100644 --- a/src/Symfony/Bundle/FrameworkBundle/DependencyInjection/Compiler/AddFormTypesPass.php +++ b/src/Symfony/Bundle/FrameworkBundle/DependencyInjection/Compiler/AddFormTypesPass.php @@ -41,6 +41,6 @@ class AddFormTypesPass implements CompilerPassInterface $types[$alias] = $serviceId; } - $container->getDefinition('form.type.loader')->setArgument(1, $types); + $container->getDefinition('form.type.loader')->replaceArgument(1, $types); } } \ No newline at end of file