[DependencyInjection] Add exception for service name not dumpable in PHP

This commit is contained in:
Jérôme Tamarelle 2013-07-15 22:34:29 +02:00 committed by Jerome TAMARELLE
parent 76f918a125
commit 242b3184b9
2 changed files with 34 additions and 4 deletions

View File

@ -436,7 +436,6 @@ class PhpDumper extends Dumper
*/ */
private function addService($id, $definition) private function addService($id, $definition)
{ {
$name = Container::camelize($id);
$this->definitionVariables = new \SplObjectStorage(); $this->definitionVariables = new \SplObjectStorage();
$this->referenceVariables = array(); $this->referenceVariables = array();
$this->variableCount = 0; $this->variableCount = 0;
@ -479,7 +478,7 @@ EOF;
* *
* $return * $return
*/ */
protected function get{$name}Service() protected function {$this->getMethodName($id)}()
{ {
EOF; EOF;
@ -527,7 +526,6 @@ EOF;
*/ */
private function addServiceAlias($alias, $id) private function addServiceAlias($alias, $id)
{ {
$name = Container::camelize($alias);
$type = 'Object'; $type = 'Object';
if ($this->container->hasDefinition($id)) { if ($this->container->hasDefinition($id)) {
@ -542,7 +540,7 @@ EOF;
* *
* @return $type An instance of the $id service * @return $type An instance of the $id service
*/ */
protected function get{$name}Service() protected function {$this->getMethodName($alias)}()
{ {
return {$this->getServiceCall($id)}; return {$this->getServiceCall($id)};
} }
@ -550,6 +548,26 @@ EOF;
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 * Adds multiple services
* *

View File

@ -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() public function testOverrideServiceWhenUsingADumpedContainer()
{ {
require_once self::$fixturesPath.'/php/services9.php'; require_once self::$fixturesPath.'/php/services9.php';