-
-
Notifications
You must be signed in to change notification settings - Fork 9.6k
[DI] Add and wire ServiceSubscriberInterface - aka explicit service locators #21708
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
Changes from 1 commit
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
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] Add and wire ServiceSubscriberInterface
- Loading branch information
commit 9b7df3986584b6ce635b4631cbf8fc3594342d48
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
112 changes: 112 additions & 0 deletions
112
src/Symfony/Component/DependencyInjection/Compiler/RegisterServiceSubscribersPass.php
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,112 @@ | ||
<?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\Argument\ServiceClosureArgument; | ||
use Symfony\Component\DependencyInjection\ContainerInterface; | ||
use Symfony\Component\DependencyInjection\Definition; | ||
use Symfony\Component\DependencyInjection\Exception\InvalidArgumentException; | ||
use Symfony\Component\DependencyInjection\Reference; | ||
use Symfony\Component\DependencyInjection\ServiceSubscriberInterface; | ||
use Symfony\Component\DependencyInjection\ServiceLocator; | ||
use Symfony\Component\DependencyInjection\TypedReference; | ||
|
||
/** | ||
* Compiler pass to register tagged services that require a service locator. | ||
* | ||
* @author Nicolas Grekas <p@tchwork.com> | ||
*/ | ||
class RegisterServiceSubscribersPass extends AbstractRecursivePass | ||
{ | ||
private $serviceLocator; | ||
|
||
protected function processValue($value, $isRoot = false) | ||
{ | ||
if ($value instanceof Reference && $this->serviceLocator && 'container' === (string) $value) { | ||
return new Reference($this->serviceLocator); | ||
} | ||
|
||
if (!$value instanceof Definition || $value->isAbstract() || $value->isSynthetic() || !$value->hasTag('container.service_subscriber')) { | ||
return parent::processValue($value, $isRoot); | ||
} | ||
|
||
$serviceMap = array(); | ||
|
||
foreach ($value->getTag('container.service_subscriber') as $attributes) { | ||
if (!$attributes) { | ||
continue; | ||
} | ||
ksort($attributes); | ||
if (array() !== array_diff(array_keys($attributes), array('id', 'key'))) { | ||
throw new InvalidArgumentException(sprintf('The "container.service_subscriber" tag accepts only the "key" and "id" attributes, "%s" given for service "%s".', implode('", "', array_keys($attributes)), $this->currentId)); | ||
} | ||
if (!array_key_exists('id', $attributes)) { | ||
throw new InvalidArgumentException(sprintf('Missing "id" attribute on "container.service_subscriber" tag with key="%s" for service "%s".', $attributes['key'], $this->currentId)); | ||
} | ||
if (!array_key_exists('key', $attributes)) { | ||
$attributes['key'] = $attributes['id']; | ||
} | ||
if (isset($serviceMap[$attributes['key']])) { | ||
continue; | ||
} | ||
$serviceMap[$attributes['key']] = new Reference($attributes['id']); | ||
} | ||
$class = $value->getClass(); | ||
|
||
if (!is_subclass_of($class, ServiceSubscriberInterface::class)) { | ||
if (!class_exists($class, false)) { | ||
throw new InvalidArgumentException(sprintf('Class "%s" used for service "%s" cannot be found.', $class, $this->currentId)); | ||
} | ||
|
||
throw new InvalidArgumentException(sprintf('Service "%s" must implement interface "%s".', $this->currentId, ServiceSubscriberInterface::class)); | ||
} | ||
$this->container->addObjectResource($class); | ||
$subscriberMap = array(); | ||
|
||
foreach ($class::getSubscribedServices() as $key => $type) { | ||
if (!is_string($type) || !preg_match('/^\??[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*+(?:\\\\[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*+)*+$/', $type)) { | ||
throw new InvalidArgumentException(sprintf('%s::getSubscribedServices() must return valid PHP types for service "%s" key "%s", "%s" returned.', $class, $this->currentId, $key, is_string($type) ? $type : gettype($type))); | ||
} | ||
if ($optionalBehavior = '?' === $type[0]) { | ||
$type = substr($type, 1); | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. shouldn't you validate that the type is still not empty here ? ``?```alone should be forbidden too. |
||
$optionalBehavior = ContainerInterface::IGNORE_ON_INVALID_REFERENCE; | ||
} | ||
if (is_int($key)) { | ||
$key = $type; | ||
} | ||
if (!isset($serviceMap[$key])) { | ||
$serviceMap[$key] = new Reference($type); | ||
} | ||
|
||
$subscriberMap[$key] = new ServiceClosureArgument(new TypedReference((string) $serviceMap[$key], $type, $optionalBehavior ?: ContainerInterface::EXCEPTION_ON_INVALID_REFERENCE)); | ||
unset($serviceMap[$key]); | ||
} | ||
|
||
if ($serviceMap = array_keys($serviceMap)) { | ||
$this->container->log($this, sprintf('Service keys "%s" do not exist in the map returned by %s::getSubscribedServices() for service "%s".', implode('", "', $serviceMap), $class, $this->currentId)); | ||
} | ||
|
||
$serviceLocator = $this->serviceLocator; | ||
$this->serviceLocator = 'container.'.$this->currentId.'.'.md5(serialize($value)); | ||
$this->container->register($this->serviceLocator, ServiceLocator::class) | ||
->addArgument($subscriberMap) | ||
->setPublic(false) | ||
->setAutowired($value->isAutowired()) | ||
->addTag('container.service_locator'); | ||
|
||
try { | ||
return parent::processValue($value) 1E0A ; | ||
} finally { | ||
$this->serviceLocator = $serviceLocator; | ||
} | ||
} | ||
} |
50 changes: 50 additions & 0 deletions
50
src/Symfony/Component/DependencyInjection/ServiceSubscriberInterface.php
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,50 @@ | ||
<?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; | ||
|
||
/** | ||
* A ServiceSubscriber exposes its dependencies via the static {@link getSubscribedServices} method. | ||
* | ||
* The getSubscribedServices method returns an array of service types required by such instances, | ||
* optionally keyed by the service names used internally. Service types that start with an interrogation | ||
* mark "?" are optional, while the other ones are mandatory service dependencies. | ||
* | ||
* The injected service locators SHOULD NOT allow access to any other services not specified by the method. | ||
* | ||
* It is expected that ServiceSubscriber instances consume PSR-11-based service locators internally. | ||
* This interface does not dictate any injection method for these service locators, although constructor | ||
* injection is recommended. | ||
* | ||
* @author Nicolas Grekas <p@tchwork.com> | ||
*/ | ||
interface ServiceSubscriberInterface | ||
{ | ||
/** | ||
* Returns an array of service types required by such instances, optionally keyed by the service names used internally. | ||
* | ||
* For mandatory dependencies: | ||
* | ||
* * array('logger' => 'Psr\Log\LoggerInterface') means the objects use the "logger" name | ||
* internally to fetch a service which must implement Psr\Log\LoggerInterface. | ||
* * array('Psr\Log\LoggerInterface') is a shortcut for | ||
* * array('Psr\Log\LoggerInterface' => 'Psr\Log\LoggerInterface') | ||
* | ||
* otherwise: | ||
* | ||
* * array('logger' => '?Psr\Log\LoggerInterface') denotes an optional dependency | ||
* * array('?Psr\Log\LoggerInterface') is a shortcut for | ||
* * array('Psr\Log\LoggerInterface' => '?Psr\Log\LoggerInterface') | ||
* | ||
* @return array The required service types, optionally keyed by service names | ||
*/ | ||
public static function getSubscribedServices(); | ||
} |
118 changes: 118 additions & 0 deletions
118
...mfony/Component/DependencyInjection/Tests/Compiler/RegisterServiceSubscribersPassTest.php
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,118 @@ | ||
<?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\Tests\Compiler; | ||
|
||
use PHPUnit\Framework\TestCase; | ||
use Symfony\Component\DependencyInjection\Argument\ServiceClosureArgument; | ||
use Symfony\Component\DependencyInjection\Compiler\RegisterServiceSubscribersPass; | ||
use Symfony\Component\DependencyInjection\ContainerBuilder; | ||
use Symfony\Component\DependencyInjection\ContainerInterface; | ||
use Symfony\Component\DependencyInjection\Reference; | ||
use Symfony\Component\DependencyInjection\ServiceLocator; | ||
use Symfony\Component\DependencyInjection\TypedReference; | ||
|
||
require_once __DIR__.'/../Fixtures/includes/classes.php'; | ||
|
||
class RegisterServiceSubscribersPassTest extends TestCase | ||
{ | ||
/** | ||
* @expectedException \Symfony\Component\DependencyInjection\Exception\InvalidArgumentException | ||
* @expectedExceptionMessage Service "foo" must implement interface "Symfony\Component\DependencyInjection\ServiceSubscriberInterface". | ||
*/ | ||
public function testInvalidClass() | ||
{ | ||
$container = new ContainerBuilder(); | ||
|
||
$container->register('foo', 'stdClass') | ||
->addTag('container.service_subscriber') | ||
; | ||
|
||
$pass = new RegisterServiceSubscribersPass(); | ||
$pass->process($container); | ||
} | ||
|
||
/** | ||
* @expectedException \Symfony\Component\DependencyInjection\Exception\InvalidArgumentException | ||
* @expectedExceptionMessage The "container.service_subscriber" tag accepts only the "key" and "id" attributes, "bar" given for service "foo". | ||
*/ | ||
public function testInvalidAttributes() | ||
{ | ||
$container = new ContainerBuilder(); | ||
|
||
$container->register('foo', 'TestServiceSubscriber') | ||
->addTag('container.service_subscriber', array('bar' => '123')) | ||
; | ||
|
||
$pass = new RegisterServiceSubscribersPass(); | ||
$pass->process($container); | ||
} | ||
|
||
public function testNoAttributes() | ||
{ | ||
$container = new ContainerBuilder(); | ||
|
||
$container->register('foo', 'TestServiceSubscriber') | ||
->addArgument(new Reference('container')) | ||
->addTag('container.service_subscriber') | ||
; | ||
|
||
$pass = new RegisterServiceSubscribersPass(); | ||
$pass->process($container); | ||
|
||
$foo = $container->getDefinition('foo'); | ||
$locator = $container->getDefinition((string) $foo->getArgument(0)); | ||
|
||
$this->assertFalse($locator->isAutowired()); | ||
$this->assertFalse($locator->isPublic()); | ||
$this->assertSame(ServiceLocator::class, $locator->getClass()); | ||
|
||
$expected = array( | ||
'TestServiceSubscriber' => new ServiceClosureArgument(new TypedReference('TestServiceSubscriber', 'TestServiceSubscriber')), | ||
'stdClass' => new ServiceClosureArgument(new TypedReference('stdClass', 'stdClass', ContainerInterface::IGNORE_ON_INVALID_REFERENCE)), | ||
'bar' => new ServiceClosureArgument(new TypedReference('stdClass', 'stdClass')), | ||
'baz' => new ServiceClosureArgument(new TypedReference('stdClass', 'stdClass', ContainerInterface::IGNORE_ON_INVALID_REFERENCE)), | ||
); | ||
|
||
$this->assertEquals($expected, $locator->getArgument(0)); | ||
} | ||
|
||
public function testWithAttributes() | ||
{ | ||
$container = new ContainerBuilder(); | ||
|
||
$container->register('foo', 'TestServiceSubscriber') | ||
->setAutowired(true) | ||
->addArgument(new Reference('container')) | ||
->addTag('container.service_subscriber', array('key' => 'bar', 'id' => 'bar')) | ||
->addTag('container.service_subscriber', array('key' => 'bar', 'id' => 'baz')) // should be ignored: the first wins | ||
; | ||
|
||
$pass = new RegisterServiceSubscribersPass(); | ||
$pass->process($container); | ||
|
||
$foo = $container->getDefinition('foo'); | ||
$locator = $container->getDefinition((string) $foo->getArgument(0)); | ||
|
||
$this->assertTrue($locator->isAutowired()); | ||
$this->assertFalse($locator->isPublic()); | ||
$this->assertSame(ServiceLocator::class, $locator->getClass()); | ||
|
||
$expected = array( | ||
'TestServiceSubscriber' => new ServiceClosureArgument(new TypedReference('TestServiceSubscriber', 'TestServiceSubscriber')), | ||
'stdClass' => new ServiceClosureArgument(new TypedReference('stdClass', 'stdClass', ContainerInterface::IGNORE_ON_INVALID_REFERENCE)), | ||
'bar' => new ServiceClosureArgument(new TypedReference('bar', 'stdClass')), | ||
'baz' => new ServiceClosureArgument(new TypedReference('stdClass', 'stdClass', ContainerInterface::IGNORE_ON_INVALID_REFERENCE)), | ||
); | ||
|
||
$this->assertEquals($expected, $locator->getArgument(0)); | ||
} | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Shoudn't we throw an exception instead?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
When there is not attributes at all, L75 creates "TypedReference" that target the service that has the same name as the type
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
👍