Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings

[DI] Optional class for named services #21133

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Jan 7, 2017
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Next Next commit
[DI] Optional class for named services
  • Loading branch information
nicolas-grekas committed Jan 7, 2017
commit 71b17c779077fffb595325f439c84d6a53dee784
Original file line number Diff line number Diff line change
Expand Up @@ -17,9 +17,21 @@

/**
* @author Guilhem N. <egetick@gmail.com>
*
* @deprecated since version 3.3, to be removed in 4.0.
*/
class FactoryReturnTypePass implements CompilerPassInterface
{
private $resolveClassPass;

public function __construct(ResolveClassPass $resolveClassPass = null)
{
if (null === $resolveClassPass) {
@trigger_error('The '.__CLASS__.' class is deprecated since version 3.3 and will be removed in 4.0.', E_USER_DEPRECATED);
}
$this->resolveClassPass = $resolveClassPass;
}

/**
* {@inheritdoc}
*/
Expand All @@ -29,21 +41,22 @@ public function process(ContainerBuilder $container)
if (!method_exists(\ReflectionMethod::class, 'getReturnType')) {
return;
}
$resolveClassPassChanges = null !== $this->resolveClassPass ? $this->resolveClassPass->getChanges() : array();

foreach ($container->getDefinitions() as $id => $definition) {
$this->updateDefinition($container, $id, $definition);
$this->updateDefinition($container, $id, $definition, $resolveClassPassChanges);
}
}

private function updateDefinition(ContainerBuilder $container, $id, Definition $definition, array $previous = array())
private function updateDefinition(ContainerBuilder $container, $id, Definition $definition, array $resolveClassPassChanges, array $previous = array())
{
// circular reference
if (isset($previous[$id])) {
return;
}

$factory = $definition->getFactory();
if (null === $factory || null !== $definition->getClass()) {
if (null === $factory || (!isset($resolveClassPassChanges[$id]) && null !== $definition->getClass())) {
return;
}

Expand All @@ -58,7 +71,7 @@ private function updateDefinition(ContainerBuilder $container, $id, Definition $
if ($factory[0] instanceof Reference) {
$previous[$id] = true;
$factoryDefinition = $container->findDefinition((string) $factory[0]);
$this->updateDefinition($container, strtolower($factory[0]), $factoryDefinition, $previous);
$this->updateDefinition($container, strtolower($factory[0]), $factoryDefinition, $resolveClassPassChanges, $previous);
$class = $factoryDefinition->getClass();
} else {
$class = $factory[0];
Expand All @@ -83,6 +96,9 @@ private function updateDefinition(ContainerBuilder $container, $id, Definition $
}
}

if (null !== $returnType && (!isset($resolveClassPassChanges[$id]) || $returnType !== $resolveClassPassChanges[$id])) {
@trigger_error(sprintf('Relying on its factory\'s return-type to define the class of service "%s" is deprecated since Symfony 3.3 and won\'t work in 4.0. Set the "class" attribute to "%s" on the service definition instead.', $id, $returnType), E_USER_DEPRECATED);
}
$definition->setClass($returnType);
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -41,10 +41,11 @@ public function __construct()

$this->optimizationPasses = array(array(
new ExtensionCompilerPass(),
$resolveClassPass = new ResolveClassPass(),
new ResolveDefinitionTemplatesPass(),
new DecoratorServicePass(),
new ResolveParameterPlaceHoldersPass(),
new FactoryReturnTypePass(),
new FactoryReturnTypePass($resolveClassPass),
new CheckDefinitionValidityPass(),
new ResolveReferencesToAliasesPass(),
new ResolveInvalidReferencesPass(),
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
<?php

/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace Symfony\Component\DependencyInjection\Compiler;

use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\ChildDefinition;

/**
* @author Nicolas Grekas <p@tchwork.com>
*/
class ResolveClassPass implements CompilerPassInterface
{
private $changes = array();

/**
* {@inheritdoc}
*/
public function process(ContainerBuilder $container)
{
foreach ($container->getDefinitions() as $id => $definition) {
if ($definition instanceof ChildDefinition || $definition->isSynthetic() || null !== $definition->getClass()) {
continue;
}
if (preg_match('/^[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*+(?:\\\\[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*+)*+$/', $id)) {
$this->changes[$id] = $container->getCaseSensitiveId($id);
$definition->setClass($this->changes[$id]);
}
}
}

/**
* @internal
*
* @deprecated since 3.3, to be removed in 4.0.
*/
public function getChanges()
{
$changes = $this->changes;
$this->changes = array();

return $changes;
}
}
37 changes: 34 additions & 3 deletions 37 src/Symfony/Component/DependencyInjection/ContainerBuilder.php
Original file line number Diff line number Diff line change
Expand Up @@ -103,6 +103,11 @@ class ContainerBuilder extends Container implements TaggedContainerInterface
*/
private $envCounters = array();

/**
* @var array a map of case less to case sensitive ids
*/
private $caseSensitiveIds = array();

/**
* Sets the track resources flag.
*
Expand Down Expand Up @@ -367,14 +372,18 @@ public function getCompiler()
*/
public function set($id, $service)
{
$id = strtolower($id);
$caseSensitiveId = $id;
$id = strtolower($caseSensitiveId);

if ($this->isFrozen() && (isset($this->definitions[$id]) && !$this->definitions[$id]->isSynthetic())) {
// setting a synthetic service on a frozen container is alright
throw new BadMethodCallException(sprintf('Setting service "%s" for an unknown or non-synthetic service definition on a frozen container is not allowed.', $id));
}

unset($this->definitions[$id], $this->aliasDefinitions[$id]);
if ($id !== $caseSensitiveId) {
$this->caseSensitiveIds[$id] = $caseSensitiveId;
}

parent::set($id, $service);
}
Expand Down Expand Up @@ -628,7 +637,8 @@ public function setAliases(array $aliases)
*/
public function setAlias($alias, $id)
{
$alias = strtolower($alias);
$caseSensitiveAlias = $alias;
$alias = strtolower($caseSensitiveAlias);

if (is_string($id)) {
$id = new Alias($id);
Expand All @@ -641,6 +651,9 @@ public function setAlias($alias, $id)
}

unset($this->definitions[$alias]);
if ($alias !== $caseSensitiveAlias) {
$this->caseSensitiveIds[$alias] = $caseSensitiveAlias;
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Do we actually need the entry for aliases or could we just remove existing entries here?

Copy link
Member Author

@nicolas-grekas nicolas-grekas Jan 3, 2017

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

For completeness yes: we track any id, wherever it comes from

}

$this->aliasDefinitions[$alias] = $id;
}
Expand Down Expand Up @@ -778,9 +791,13 @@ public function setDefinition($id, Definition $definition)
throw new BadMethodCallException('Adding definition to a frozen container is not allowed');
}

$id = strtolower($id);
$caseSensitiveId = $id;
$id = strtolower($caseSensitiveId);

unset($this->aliasDefinitions[$id]);
if ($id !== $caseSensitiveId) {
$this->caseSensitiveIds[$id] = $caseSensitiveId;
}

return $this->definitions[$id] = $definition;
}
Expand Down Expand Up @@ -839,6 +856,20 @@ public function findDefinition($id)
return $this->getDefinition($id);
}

/**
* Returns the case sensitive id used at registration time.
*
* @param string $id
*
* @return string
*/
public function getCaseSensitiveId($id)
{
$id = strtolower($id);

return isset($this->caseSensitiveIds[$id]) ? $this->caseSensitiveIds[$id] : $id;
}

/**
* Creates a service for a service definition.
*
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -303,7 +303,7 @@ private function processAnonymousServices(\DOMDocument $xml, $file)
if (false !== $nodes = $xpath->query('//container:argument[@type="service"][not(@id)]|//container:property[@type="service"][not(@id)]')) {
foreach ($nodes as $node) {
// give it a unique name
$id = sprintf('%s_%d', hash('sha256', $file), ++$count);
$id = sprintf('%d_%s', ++$count, hash('sha256', $file));
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

just made these changes so that anonymous classes won't have their class set to a random string (+ added corresponding regexp check in ResolveClassPass)

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why hashing it? Wouldn't it be more explicit with the plain file name?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

not related to this PR :)

$node->setAttribute('id', $id);

if ($services = $this->getChildren($node, 'service')) {
Expand All @@ -321,15 +321,15 @@ private function processAnonymousServices(\DOMDocument $xml, $file)
if (false !== $nodes = $xpath->query('//container:services/container:service[not(@id)]')) {
foreach ($nodes as $node) {
// give it a unique name
$id = sprintf('%s_%d', hash('sha256', $file), ++$count);
$id = sprintf('%d_%s', ++$count, hash('sha256', $file));
$node->setAttribute('id', $id);
$definitions[$id] = array($node, $file, true);
}
}

// resolve definitions
krsort($definitions);
foreach ($definitions as $id => list($domElement, $file, $wild)) {
uksort($definitions, 'strnatcmp');
foreach (array_reverse($definitions) as $id => list($domElement, $file, $wild)) {
if (null !== $definition = $this->parseDefinition($domElement, $file)) {
$this->container->setDefinition($id, $definition);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,8 @@

/**
* @author Guilhem N. <egetick@gmail.com>
*
* @group legacy
*/
class FactoryReturnTypePassTest extends \PHPUnit_Framework_TestCase
{
Expand Down Expand Up @@ -103,17 +105,16 @@ public function testCircularReference()
$this->assertNull($factory2->getClass());
}

/**
* @requires function ReflectionMethod::getReturnType
* @expectedDeprecation Relying on its factory's return-type to define the class of service "factory" is deprecated since Symfony 3.3 and won't work in 4.0. Set the "class" attribute to "Symfony\Component\DependencyInjection\Tests\Fixtures\FactoryDummy" on the service definition instead.
*/
public function testCompile()
{
$container = new ContainerBuilder();

$factory = $container->register('factory');
$factory->setFactory(array(FactoryDummy::class, 'createFactory'));

if (!method_exists(\ReflectionMethod::class, 'getReturnType')) {
$this->setExpectedException(\RuntimeException::class, 'Please add the class to service "factory" even if it is constructed by a factory since we might need to add method calls based on compile-time checks.');
}

$container->compile();

$this->assertEquals(FactoryDummy::class, $container->getDefinition('factory')->getClass());
Expand Down
Morty Proxy This is a proxified and sanitized view of the page, visit original site.