From 242b3184b9314294268433c448081a3c309003f1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=A9r=C3=B4me=20Tamarelle?= Date: Mon, 15 Jul 2013 22:34:29 +0200 Subject: [PATCH] [DependencyInjection] Add exception for service name not dumpable in PHP --- .../DependencyInjection/Dumper/PhpDumper.php | 26 ++++++++++++++++--- .../Tests/Dumper/PhpDumperTest.php | 12 +++++++++ 2 files changed, 34 insertions(+), 4 deletions(-) diff --git a/src/Symfony/Component/DependencyInjection/Dumper/PhpDumper.php b/src/Symfony/Component/DependencyInjection/Dumper/PhpDumper.php index 8ae9b616c5..31be3f416b 100644 --- a/src/Symfony/Component/DependencyInjection/Dumper/PhpDumper.php +++ b/src/Symfony/Component/DependencyInjection/Dumper/PhpDumper.php @@ -436,7 +436,6 @@ class PhpDumper extends Dumper */ private function addService($id, $definition) { - $name = Container::camelize($id); $this->definitionVariables = new \SplObjectStorage(); $this->referenceVariables = array(); $this->variableCount = 0; @@ -479,7 +478,7 @@ EOF; * * $return */ - protected function get{$name}Service() + protected function {$this->getMethodName($id)}() { EOF; @@ -527,7 +526,6 @@ EOF; */ private function addServiceAlias($alias, $id) { - $name = Container::camelize($alias); $type = 'Object'; if ($this->container->hasDefinition($id)) { @@ -542,7 +540,7 @@ EOF; * * @return $type An instance of the $id service */ - protected function get{$name}Service() + protected function {$this->getMethodName($alias)}() { return {$this->getServiceCall($id)}; } @@ -550,6 +548,26 @@ EOF; EOF; } + /** + * Convert a service id to a valid PHP method name. + * + * @param string $id + * + * @return string + * + * @throws InvalidArgumentException + */ + private function getMethodName($id) + { + $name = Container::camelize($id); + + if (!preg_match('/^[a-zA-Z0-9_\x7f-\xff]+$/', $name)) { + throw new InvalidArgumentException(sprintf('Service id "%s" cannot be converted to a valid PHP method name.', $id)); + } + + return 'get'.$name.'Service'; + } + /** * Adds multiple services * diff --git a/src/Symfony/Component/DependencyInjection/Tests/Dumper/PhpDumperTest.php b/src/Symfony/Component/DependencyInjection/Tests/Dumper/PhpDumperTest.php index 72d587ff07..369ac81bbe 100644 --- a/src/Symfony/Component/DependencyInjection/Tests/Dumper/PhpDumperTest.php +++ b/src/Symfony/Component/DependencyInjection/Tests/Dumper/PhpDumperTest.php @@ -120,6 +120,18 @@ class PhpDumperTest extends \PHPUnit_Framework_TestCase } } + /** + * @expectedException InvalidArgumentException + * @expectedExceptionMessage Service id "bar$" cannot be converted to a valid PHP method name. + */ + public function testAddServiceInvalidServiceId() + { + $container = new ContainerBuilder(); + $container->register('bar$', 'FooClass'); + $dumper = new PhpDumper($container); + $dumper->dump(); + } + public function testOverrideServiceWhenUsingADumpedContainer() { require_once self::$fixturesPath.'/php/services9.php';