Merge branch '3.4' into 4.2

* 3.4:
  [DI] Check service IDs are valid
This commit is contained in:
Nicolas Grekas 2019-04-16 13:19:53 +02:00
commit 3fd01abf11
12 changed files with 239 additions and 39 deletions

View File

@ -53,7 +53,7 @@ class ProxyDumper implements DumperInterface
$instantiation = 'return';
if ($definition->isShared()) {
$instantiation .= sprintf(' $this->%s[\'%s\'] =', $definition->isPublic() && !$definition->isPrivate() ? 'services' : 'privates', $id);
$instantiation .= sprintf(' $this->%s[%s] =', $definition->isPublic() && !$definition->isPrivate() ? 'services' : 'privates', var_export($id, true));
}
if (null === $factoryCode) {

View File

@ -828,6 +828,10 @@ class ContainerBuilder extends Container implements TaggedContainerInterface
{
$alias = (string) $alias;
if ('' === $alias || '\\' === $alias[-1] || \strlen($alias) !== strcspn($alias, "\0\r\n'")) {
throw new InvalidArgumentException(sprintf('Invalid alias id: "%s"', $alias));
}
if (\is_string($id)) {
$id = new Alias($id);
} elseif (!$id instanceof Alias) {
@ -981,6 +985,10 @@ class ContainerBuilder extends Container implements TaggedContainerInterface
$id = (string) $id;
if ('' === $id || '\\' === $id[-1] || \strlen($id) !== strcspn($id, "\0\r\n'")) {
throw new InvalidArgumentException(sprintf('Invalid service id: "%s"', $id));
}
unset($this->aliasDefinitions[$id], $this->removedIds[$id]);
return $this->definitions[$id] = $definition;

View File

@ -506,7 +506,7 @@ EOF;
$instantiation = '';
if (!$isProxyCandidate && $definition->isShared() && !isset($this->singleUsePrivateIds[$id])) {
$instantiation = sprintf('$this->%s[\'%s\'] = %s', $this->container->getDefinition($id)->isPublic() ? 'services' : 'privates', $id, $isSimpleInstance ? '' : '$instance');
$instantiation = sprintf('$this->%s[%s] = %s', $this->container->getDefinition($id)->isPublic() ? 'services' : 'privates', $this->doExport($id), $isSimpleInstance ? '' : '$instance');
} elseif (!$isSimpleInstance) {
$instantiation = '$instance';
}
@ -674,6 +674,9 @@ EOF;
* Gets the $public '$id'$shared$autowired service.
*
* $return
EOF;
$code = str_replace('*/', ' ', $code).<<<EOF
*/
protected function {$methodName}($lazyInitialization)
{
@ -687,8 +690,8 @@ EOF;
$code .= $this->addServiceInclude($id, $definition);
if ($this->getProxyDumper()->isProxyCandidate($definition)) {
$factoryCode = $asFile ? ($definition->isShared() ? "\$this->load('%s.php', false)" : "\$this->factories['%2$s'](false)") : '$this->%s(false)';
$code .= $this->getProxyDumper()->getProxyFactoryCode($definition, $id, sprintf($factoryCode, $methodName, $this->export($id)));
$factoryCode = $asFile ? ($definition->isShared() ? "\$this->load('%s.php', false)" : "\$this->factories[%2\$s](false)") : '$this->%s(false)';
$code .= $this->getProxyDumper()->getProxyFactoryCode($definition, $id, sprintf($factoryCode, $methodName, $this->doExport($id)));
}
if ($definition->isDeprecated()) {
@ -762,14 +765,14 @@ EOF;
$code .= sprintf(<<<'EOTXT'
if (isset($this->%s['%s'])) {
return $this->%1$s['%2$s'];
if (isset($this->%s[%s])) {
return $this->%1$s[%2$s];
}
EOTXT
,
$this->container->getDefinition($id)->isPublic() ? 'services' : 'privates',
$id
$this->doExport($id)
);
return $code;
@ -861,7 +864,7 @@ EOTXT
$code = ["\n", $code];
}
$code[1] = implode("\n", array_map(function ($line) { return $line ? ' '.$line : $line; }, explode("\n", $code[1])));
$factory = sprintf('$this->factories%s[\'%s\']', $definition->isPublic() ? '' : "['service_container']", $id);
$factory = sprintf('$this->factories%s[%s]', $definition->isPublic() ? '' : "['service_container']", $this->doExport($id));
$lazyloadInitialization = $definition->isLazy() ? '$lazyLoad = true' : '';
$code[1] = sprintf("%s = function (%s) {\n%s};\n\nreturn %1\$s();\n", $factory, $lazyloadInitialization, $code[1]);
@ -1383,14 +1386,14 @@ EOF;
if (!$this->container->hasDefinition($service)) {
return 'false';
}
$conditions[] = sprintf("isset(\$this->%s['%s'])", $this->container->getDefinition($service)->isPublic() ? 'services' : 'privates', $service);
$conditions[] = sprintf("isset(\$this->%s[%s])", $this->container->getDefinition($service)->isPublic() ? 'services' : 'privates', $this->doExport($service));
}
foreach (ContainerBuilder::getServiceConditionals($value) as $service) {
if ($this->container->hasDefinition($service) && !$this->container->getDefinition($service)->isPublic()) {
continue;
}
$conditions[] = sprintf("\$this->has('%s')", $service);
$conditions[] = sprintf("\$this->has(%s)", $this->doExport($service));
}
if (!$conditions) {
@ -1508,7 +1511,7 @@ EOF;
$serviceMap .= sprintf("\n %s => [%s, %s, %s, %s],",
$this->export($k),
$this->export($definition->isShared() ? ($definition->isPublic() ? 'services' : 'privates') : false),
$this->export($id),
$this->doExport($id),
$this->export(ContainerInterface::IGNORE_ON_UNINITIALIZED_REFERENCE !== $v->getInvalidBehavior() && !\is_string($load) ? $this->generateMethodName($id).($load ? '.php' : '') : null),
$this->export($load)
);
@ -1605,11 +1608,11 @@ EOF;
}
if (!preg_match("/\\\$this->(?:getEnv\('(?:\w++:)*+\w++'\)|targetDirs\[\d++\])/", $dumpedValue)) {
return sprintf("\$this->parameters['%s']", $name);
return sprintf('$this->parameters[%s]', $this->doExport($name));
}
}
return sprintf("\$this->getParameter('%s')", $name);
return sprintf('$this->getParameter(%s)', $this->doExport($name));
}
private function getServiceCall(string $id, Reference $reference = null): string
@ -1624,7 +1627,7 @@ EOF;
if ($this->container->hasDefinition($id) && $definition = $this->container->getDefinition($id)) {
if ($definition->isSynthetic()) {
$code = sprintf('$this->get(\'%s\'%s)', $id, null !== $reference ? ', '.$reference->getInvalidBehavior() : '');
$code = sprintf('$this->get(%s%s)', $this->doExport($id), null !== $reference ? ', '.$reference->getInvalidBehavior() : '');
} elseif (null !== $reference && ContainerInterface::IGNORE_ON_UNINITIALIZED_REFERENCE === $reference->getInvalidBehavior()) {
$code = 'null';
if (!$definition->isShared()) {
@ -1638,20 +1641,20 @@ EOF;
}
$code = $this->addNewInstance($definition, '', $id);
if ($definition->isShared() && !isset($this->singleUsePrivateIds[$id])) {
$code = sprintf('$this->%s[\'%s\'] = %s', $definition->isPublic() ? 'services' : 'privates', $id, $code);
$code = sprintf('$this->%s[%s] = %s', $definition->isPublic() ? 'services' : 'privates', $this->doExport($id), $code);
}
$code = "($code)";
} elseif ($this->asFiles && !$this->isHotPath($definition)) {
$code = sprintf("\$this->load('%s.php')", $this->generateMethodName($id));
if (!$definition->isShared()) {
$factory = sprintf('$this->factories%s[\'%s\']', $definition->isPublic() ? '' : "['service_container']", $id);
$factory = sprintf('$this->factories%s[%s]', $definition->isPublic() ? '' : "['service_container']", $this->doExport($id));
$code = sprintf('(isset(%s) ? %1$s() : %s)', $factory, $code);
}
} else {
$code = sprintf('$this->%s()', $this->generateMethodName($id));
}
if ($definition->isShared() && !isset($this->singleUsePrivateIds[$id])) {
$code = sprintf('($this->%s[\'%s\'] ?? %s)', $definition->isPublic() ? 'services' : 'privates', $id, $code);
$code = sprintf('($this->%s[%s] ?? %s)', $definition->isPublic() ? 'services' : 'privates', $this->doExport($id), $code);
}
return $code;
@ -1660,12 +1663,12 @@ EOF;
return 'null';
}
if (null !== $reference && ContainerInterface::EXCEPTION_ON_INVALID_REFERENCE < $reference->getInvalidBehavior()) {
$code = sprintf('$this->get(\'%s\', /* ContainerInterface::NULL_ON_INVALID_REFERENCE */ %d)', $id, ContainerInterface::NULL_ON_INVALID_REFERENCE);
$code = sprintf('$this->get(%s, /* ContainerInterface::NULL_ON_INVALID_REFERENCE */ %d)', $this->doExport($id), ContainerInterface::NULL_ON_INVALID_REFERENCE);
} else {
$code = sprintf('$this->get(\'%s\')', $id);
$code = sprintf('$this->get(%s)', $this->doExport($id));
}
return sprintf('($this->services[\'%s\'] ?? %s)', $id, $code);
return sprintf('($this->services[%s] ?? %s)', $this->doExport($id), $code);
}
/**

View File

@ -195,6 +195,38 @@ class ContainerBuilderTest extends TestCase
$this->assertNotSame($builder->get('bar'), $builder->get('bar'));
}
/**
* @expectedException \Symfony\Component\DependencyInjection\Exception\InvalidArgumentException
* @dataProvider provideBadId
*/
public function testBadAliasId($id)
{
$builder = new ContainerBuilder();
$builder->setAlias($id, 'foo');
}
/**
* @expectedException \Symfony\Component\DependencyInjection\Exception\InvalidArgumentException
* @dataProvider provideBadId
*/
public function testBadDefinitionId($id)
{
$builder = new ContainerBuilder();
$builder->setDefinition($id, new Definition('Foo'));
}
public function provideBadId()
{
return [
[''],
["\0"],
["\r"],
["\n"],
["'"],
['ab\\'],
];
}
/**
* @expectedException \Symfony\Component\DependencyInjection\Exception\RuntimeException
* @expectedExceptionMessage You have requested a synthetic service ("foo"). The DIC does not know how to construct this service.

View File

@ -261,12 +261,18 @@ class PhpDumperTest extends TestCase
{
$class = 'Symfony_DI_PhpDumper_Test_Unsupported_Characters';
$container = new ContainerBuilder();
$container->setParameter("'", 'oh-no');
$container->register("foo*/oh-no", 'FooClass')->setPublic(true);
$container->register('bar$', 'FooClass')->setPublic(true);
$container->register('bar$!', 'FooClass')->setPublic(true);
$container->compile();
$dumper = new PhpDumper($container);
eval('?>'.$dumper->dump(['class' => $class]));
$this->assertStringEqualsFile(self::$fixturesPath.'/php/services_unsupported_characters.php', $dumper->dump(['class' => $class]));
require_once self::$fixturesPath.'/php/services_unsupported_characters.php';
$this->assertTrue(method_exists($class, 'getFooOhNoService'));
$this->assertTrue(method_exists($class, 'getBarService'));
$this->assertTrue(method_exists($class, 'getBar2Service'));
}

View File

@ -55,7 +55,7 @@ class ProjectServiceContainer extends Container
*/
protected function getFooService()
{
return $this->services['Bar\Foo'] = new \Bar\Foo();
return $this->services['Bar\\Foo'] = new \Bar\Foo();
}
/**
@ -65,6 +65,6 @@ class ProjectServiceContainer extends Container
*/
protected function getFoo2Service()
{
return $this->services['Foo\Foo'] = new \Foo\Foo();
return $this->services['Foo\\Foo'] = new \Foo\Foo();
}
}

View File

@ -60,11 +60,11 @@ class ProjectServiceContainer extends Container
*/
protected function getBusService()
{
$a = ($this->services['App\Db'] ?? $this->getDbService());
$a = ($this->services['App\\Db'] ?? $this->getDbService());
$this->services['App\Bus'] = $instance = new \App\Bus($a);
$this->services['App\\Bus'] = $instance = new \App\Bus($a);
$b = ($this->privates['App\Schema'] ?? $this->getSchemaService());
$b = ($this->privates['App\\Schema'] ?? $this->getSchemaService());
$c = new \App\Registry();
$c->processor = [0 => $a, 1 => $instance];
@ -83,9 +83,9 @@ class ProjectServiceContainer extends Container
*/
protected function getDbService()
{
$this->services['App\Db'] = $instance = new \App\Db();
$this->services['App\\Db'] = $instance = new \App\Db();
$instance->schema = ($this->privates['App\Schema'] ?? $this->getSchemaService());
$instance->schema = ($this->privates['App\\Schema'] ?? $this->getSchemaService());
return $instance;
}
@ -97,12 +97,12 @@ class ProjectServiceContainer extends Container
*/
protected function getSchemaService()
{
$a = ($this->services['App\Db'] ?? $this->getDbService());
$a = ($this->services['App\\Db'] ?? $this->getDbService());
if (isset($this->privates['App\Schema'])) {
return $this->privates['App\Schema'];
if (isset($this->privates['App\\Schema'])) {
return $this->privates['App\\Schema'];
}
return $this->privates['App\Schema'] = new \App\Schema($a);
return $this->privates['App\\Schema'] = new \App\Schema($a);
}
}

View File

@ -70,7 +70,7 @@ class ProjectServiceContainer extends Container
*/
protected function getParentNotExistsService()
{
return $this->services['Symfony\Component\DependencyInjection\Tests\Fixtures\ParentNotExists'] = new \Symfony\Component\DependencyInjection\Tests\Fixtures\ParentNotExists();
return $this->services['Symfony\\Component\\DependencyInjection\\Tests\\Fixtures\\ParentNotExists'] = new \Symfony\Component\DependencyInjection\Tests\Fixtures\ParentNotExists();
}
/**
@ -80,7 +80,7 @@ class ProjectServiceContainer extends Container
*/
protected function getC1Service()
{
return $this->services['Symfony\Component\DependencyInjection\Tests\Fixtures\includes\HotPath\C1'] = new \Symfony\Component\DependencyInjection\Tests\Fixtures\includes\HotPath\C1();
return $this->services['Symfony\\Component\\DependencyInjection\\Tests\\Fixtures\\includes\\HotPath\\C1'] = new \Symfony\Component\DependencyInjection\Tests\Fixtures\includes\HotPath\C1();
}
/**
@ -93,7 +93,7 @@ class ProjectServiceContainer extends Container
include_once $this->targetDirs[1].'/includes/HotPath/C2.php';
include_once $this->targetDirs[1].'/includes/HotPath/C3.php';
return $this->services['Symfony\Component\DependencyInjection\Tests\Fixtures\includes\HotPath\C2'] = new \Symfony\Component\DependencyInjection\Tests\Fixtures\includes\HotPath\C2(new \Symfony\Component\DependencyInjection\Tests\Fixtures\includes\HotPath\C3());
return $this->services['Symfony\\Component\\DependencyInjection\\Tests\\Fixtures\\includes\\HotPath\\C2'] = new \Symfony\Component\DependencyInjection\Tests\Fixtures\includes\HotPath\C2(new \Symfony\Component\DependencyInjection\Tests\Fixtures\includes\HotPath\C3());
}
public function getParameter($name)

View File

@ -59,7 +59,7 @@ class Symfony_DI_PhpDumper_Test_Inline_Self_Ref extends Container
$b = new \App\Baz($a);
$b->bar = $a;
$this->services['App\Foo'] = $instance = new \App\Foo($b);
$this->services['App\\Foo'] = $instance = new \App\Foo($b);
$a->foo = $instance;

View File

@ -60,7 +60,7 @@ class Symfony_DI_PhpDumper_Test_Rot13Parameters extends Container
*/
protected function getRot13EnvVarProcessorService()
{
return $this->services['Symfony\Component\DependencyInjection\Tests\Dumper\Rot13EnvVarProcessor'] = new \Symfony\Component\DependencyInjection\Tests\Dumper\Rot13EnvVarProcessor();
return $this->services['Symfony\\Component\\DependencyInjection\\Tests\\Dumper\\Rot13EnvVarProcessor'] = new \Symfony\Component\DependencyInjection\Tests\Dumper\Rot13EnvVarProcessor();
}
/**

View File

@ -60,7 +60,7 @@ class ProjectServiceContainer extends Container
*/
protected function getTestServiceSubscriberService()
{
return $this->services['Symfony\Component\DependencyInjection\Tests\Fixtures\TestServiceSubscriber'] = new \Symfony\Component\DependencyInjection\Tests\Fixtures\TestServiceSubscriber();
return $this->services['Symfony\\Component\\DependencyInjection\\Tests\\Fixtures\\TestServiceSubscriber'] = new \Symfony\Component\DependencyInjection\Tests\Fixtures\TestServiceSubscriber();
}
/**
@ -85,6 +85,6 @@ class ProjectServiceContainer extends Container
*/
protected function getCustomDefinitionService()
{
return $this->privates['Symfony\Component\DependencyInjection\Tests\Fixtures\CustomDefinition'] = new \Symfony\Component\DependencyInjection\Tests\Fixtures\CustomDefinition();
return $this->privates['Symfony\\Component\\DependencyInjection\\Tests\\Fixtures\\CustomDefinition'] = new \Symfony\Component\DependencyInjection\Tests\Fixtures\CustomDefinition();
}
}

View File

@ -0,0 +1,151 @@
<?php
use Symfony\Component\DependencyInjection\Argument\RewindableGenerator;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\DependencyInjection\Container;
use Symfony\Component\DependencyInjection\Exception\InvalidArgumentException;
use Symfony\Component\DependencyInjection\Exception\LogicException;
use Symfony\Component\DependencyInjection\Exception\RuntimeException;
use Symfony\Component\DependencyInjection\ParameterBag\FrozenParameterBag;
/**
* This class has been auto-generated
* by the Symfony Dependency Injection Component.
*
* @final since Symfony 3.3
*/
class Symfony_DI_PhpDumper_Test_Unsupported_Characters extends Container
{
private $parameters;
private $targetDirs = [];
public function __construct()
{
$this->parameters = $this->getDefaultParameters();
$this->services = $this->privates = [];
$this->methodMap = [
'bar$' => 'getBarService',
'bar$!' => 'getBar2Service',
'foo*/oh-no' => 'getFooohnoService',
];
$this->aliases = [];
}
public function compile()
{
throw new LogicException('You cannot compile a dumped container that was already compiled.');
}
public function isCompiled()
{
return true;
}
public function getRemovedIds()
{
return [
'Psr\\Container\\ContainerInterface' => true,
'Symfony\\Component\\DependencyInjection\\ContainerInterface' => true,
];
}
/**
* Gets the public 'bar$' shared service.
*
* @return \FooClass
*/
protected function getBarService()
{
return $this->services['bar$'] = new \FooClass();
}
/**
* Gets the public 'bar$!' shared service.
*
* @return \FooClass
*/
protected function getBar2Service()
{
return $this->services['bar$!'] = new \FooClass();
}
/**
* Gets the public 'foo oh-no' shared service.
*
* @return \FooClass
*/
protected function getFooohnoService()
{
return $this->services['foo*/oh-no'] = new \FooClass();
}
public function getParameter($name)
{
$name = (string) $name;
if (!(isset($this->parameters[$name]) || isset($this->loadedDynamicParameters[$name]) || array_key_exists($name, $this->parameters))) {
throw new InvalidArgumentException(sprintf('The parameter "%s" must be defined.', $name));
}
if (isset($this->loadedDynamicParameters[$name])) {
return $this->loadedDynamicParameters[$name] ? $this->dynamicParameters[$name] : $this->getDynamicParameter($name);
}
return $this->parameters[$name];
}
public function hasParameter($name)
{
$name = (string) $name;
return isset($this->parameters[$name]) || isset($this->loadedDynamicParameters[$name]) || array_key_exists($name, $this->parameters);
}
public function setParameter($name, $value)
{
throw new LogicException('Impossible to call set() on a frozen ParameterBag.');
}
public function getParameterBag()
{
if (null === $this->parameterBag) {
$parameters = $this->parameters;
foreach ($this->loadedDynamicParameters as $name => $loaded) {
$parameters[$name] = $loaded ? $this->dynamicParameters[$name] : $this->getDynamicParameter($name);
}
$this->parameterBag = new FrozenParameterBag($parameters);
}
return $this->parameterBag;
}
private $loadedDynamicParameters = [];
private $dynamicParameters = [];
/**
* Computes a dynamic parameter.
*
* @param string $name The name of the dynamic parameter to load
*
* @return mixed The value of the dynamic parameter
*
* @throws InvalidArgumentException When the dynamic parameter does not exist
*/
private function getDynamicParameter($name)
{
throw new InvalidArgumentException(sprintf('The dynamic parameter "%s" must be defined.', $name));
}
/**
* Gets the default parameters.
*
* @return array An array of the default parameters
*/
protected function getDefaultParameters()
{
return [
'\'' => 'oh-no',
];
}
}