merged branch GromNaN/2.3-di-dump-exception (PR #8524)

This PR was merged into the 2.3 branch.

Discussion
----------

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

Same as #8494 for branch 2.3 since the DI component has been refactored (bb797ee755, f1c2ab78af)

| Q             | A
| ------------- | ---
| Bug fix?      | no
| New feature?  | no
| BC breaks?    | no
| Deprecations? | no
| Tests pass?   | yes
| Fixed tickets | #8485 #8030
| License       | MIT
| Doc PR        | n/a

Throws an exception when the DIC is dumped to PHP, before generating invalid PHP.
The regex comes from the PHP doc: http://www.php.net/manual/en/language.oop5.basic.php

Commits
-------

9ac3556 [DependencyInjection] Add exception for service name not dumpable in PHP
This commit is contained in:
Fabien Potencier 2013-07-20 09:33:53 +02:00
commit 017c44d2c3
2 changed files with 35 additions and 6 deletions

View File

@ -490,7 +490,6 @@ class PhpDumper extends Dumper
*/
private function addService($id, $definition)
{
$name = Container::camelize($id);
$this->definitionVariables = new \SplObjectStorage();
$this->referenceVariables = array();
$this->variableCount = 0;
@ -555,7 +554,7 @@ EOF;
*$lazyInitializationDoc
* $return
*/
{$visibility} function get{$name}Service($lazyInitialization)
{$visibility} function get{$this->camelize($id)}Service($lazyInitialization)
{
EOF;
@ -656,14 +655,12 @@ EOF;
return;
}
$name = Container::camelize($id);
return <<<EOF
/**
* Updates the '$id' service.
*/
protected function synchronize{$name}Service()
protected function synchronize{$this->camelize($id)}Service()
{
$code }
@ -835,7 +832,7 @@ EOF;
$code = " \$this->methodMap = array(\n";
ksort($definitions);
foreach ($definitions as $id => $definition) {
$code .= ' '.var_export($id, true).' => '.var_export('get'.Container::camelize($id).'Service', true).",\n";
$code .= ' '.var_export($id, true).' => '.var_export('get'.$this->camelize($id).'Service', true).",\n";
}
return $code . " );\n";
@ -1260,6 +1257,26 @@ EOF;
}
}
/**
* Convert a service id to a valid PHP method name.
*
* @param string $id
*
* @return string
*
* @throws InvalidArgumentException
*/
private function camelize($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 $name;
}
/**
* Returns the next name to use
*

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 testAliases()
{
$container = include self::$fixturesPath.'/containers/container9.php';