8000 [DependencyInjection] Add ability to define an index for service in an injected service locator argument by XuruDragon · Pull Request #30348 · symfony/symfony · GitHub
[go: up one dir, main page]

Skip to content

[DependencyInjection] Add ability to define an index for service in an injected service locator argument #30348

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
Mar 15, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
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
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@

namespace Symfony\Component\DependencyInjection\Argument;

use Symfony\Component\DependencyInjection\Reference;

/**
* Represents a closure acting as a service locator.
*
Expand All @@ -19,4 +21,24 @@
class ServiceLocatorArgument implements ArgumentInterface
{
use ReferenceSetArgumentTrait;

private $taggedIteratorArgument;

/**
* @param Reference[]|TaggedIteratorArgument $values
*/
public function __construct($values = [])
{
if ($values instanceof TaggedIteratorArgument) {
$this->taggedIteratorArgument = $values;
$this->values = [];
} else {
$this->setValues($values);
}
}

public function getTaggedIteratorArgument(): ?TaggedIteratorArgument
{
return $this->taggedIteratorArgument;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -21,24 +21,22 @@ class TaggedIteratorArgument extends IteratorArgument
private $tag;
private $indexAttribute;
private $defaultIndexMethod;
private $useFqcnAsFallback = false;

/**
* TaggedIteratorArgument constructor.
*
* @param string $tag The name of the tag identifying the target services
* @param string|null $indexAttribute The name of the attribute that defines the key referencing each service in the tagged collection
* @param string|null $defaultIndexMethod The static method that should be called to get each service's key when their tag doesn't define the previous attribute
* @param bool $useFqcnAsFallback Whether the FQCN of the service should be used as index when neither the attribute nor the method are defined
*/
public function __construct(string $tag, string $indexAttribute = null, string $defaultIndexMethod = null)
public function __construct(string $tag, string $indexAttribute = null, string $defaultIndexMethod = null, bool $useFqcnAsFallback = false)
{
parent::__construct([]);

$this->tag = $tag;

if ($indexAttribute) {
$this->indexAttribute = $indexAttribute;
$this->defaultIndexMethod = $defaultIndexMethod ?: ('getDefault'.str_replace(' ', '', ucwords(preg_replace('/[^a-zA-Z0-9\x7f-\xff]++/', ' ', $indexAttribute))).'Name');
}
$this->indexAttribute = $indexAttribute;
$this->defaultIndexMethod = $defaultIndexMethod ?: ('getDefault'.str_replace(' ', '', ucwords(preg_replace('/[^a-zA-Z0-9\x7f-\xff]++/', ' ', $indexAttribute ?? ''))).'Name');
$this->useFqcnAsFallback = $useFqcnAsFallback;
}

public function getTag()
Expand All @@ -55,4 +53,9 @@ public function getDefaultIndexMethod(): ?string
{
return $this->defaultIndexMethod;
}

public function useFqcnAsFallback(): bool
{
return $this->useFqcnAsFallback;
}
}
1 change: 1 addition & 0 deletions src/Symfony/Component/DependencyInjection/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ CHANGELOG
* added support for deprecating aliases
* made `ContainerParametersResource` final and not implement `Serializable` anymore
* added ability to define an index for a tagged collection
* added ability to define an index for services in an injected service locator argument

4.2.0
-----
Expand Down
< 67E6 td id="diff-e95ab96f0f1aa21244f00f2494014aae9e8d951e09c02e67c94e3a42bdbaba95R49" data-line-number="49" class="blob-num blob-num-addition js-linkable-line-number js-blob-rnum">
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Exception\InvalidArgumentException;
use Symfony\Component\DependencyInjection\Reference;
use Symfony\Component\DependencyInjection\TypedReference;

/**
* Trait that allows a generic method to find and sort service by priority option in the tag.
Expand All @@ -40,34 +41,48 @@ trait PriorityTaggedServiceTrait
*/
private function findAndSortTaggedServices($tagName, ContainerBuilder $container)
{
$indexAttribute = $defaultIndexMethod = null;
$indexAttribute = $defaultIndexMethod = $useFqcnAsFallback = null;

if ($tagName instanceof TaggedIteratorArgument) {
$indexAttribute = $tagName->getIndexAttribute();
$defaultIndexMethod = $tagName->getDefaultIndexMethod();
$useFqcnAsFallback = $tagName->useFqcnAsFallback();
$tagName = $tagName->getTag();
}

$services = [];

foreach ($container->findTaggedServiceIds($tagName, true) as $serviceId => $attributes) {
$priority = isset($attributes[0]['priority']) ? $attributes[0]['priority'] : 0;

if (null === $indexAttribute) {
if (null === $indexAttribute && !$useFqcnAsFallback) {
$services[$priority][] = new Reference($serviceId);

continue;
}

if (isset($attributes[0][$indexAttribute])) {
$services[$priority][$attributes[0][$indexAttribute]] = new Reference($serviceId);
$class = $container->getDefinition($serviceId)->getClass();
$class = $container->getParameterBag()->resolveValue($class) ?: null;

if (null !== $indexAttribute && isset($attributes[0][$indexAttribute])) {
$services[$priority][$attributes[0][$indexAttribute]] = new TypedReference($serviceId, $class, ContainerBuilder::EXCEPTION_ON_INVALID_REFERENCE, $attributes[0][$indexAttribute]);

continue;
}

if (!$r = $container->getReflectionClass($class = $container->getDefinition($serviceId)->getClass())) {
if (!$r = $container->getReflectionClass($class)) {
throw new InvalidArgumentException(sprintf('Class "%s" used for service "%s" cannot be found.', $class, $serviceId));
}

$class = $r->name;

if (!$r->hasMethod($defaultIndexMethod)) {
if ($useFqcnAsFallback) {
$services[$priority][$class] = new TypedReference($serviceId, $class);

continue;
}

throw new InvalidArgumentException(sprintf('Method "%s::%s()" not found: tag "%s" on service "%s" is missing "%s" attribute.', $class, $defaultIndexMethod, $tagName, $serviceId, $indexAttribute));
}

Expand All @@ -85,7 +100,7 @@ private function findAndSortTaggedServices($tagName, ContainerBuilder $container
throw new InvalidArgumentException(sprintf('Method "%s::%s()" should return a string, got %s: tag "%s" on service "%s" is missing "%s" attribute.', $class, $defaultIndexMethod, \gettype($key), $tagName, $serviceId, $indexAttribute));
}

$services[$priority][$key] = new Reference($serviceId);
$services[$priority][$key] = new TypedReference($serviceId, $class, ContainerBuilder::EXCEPTION_ON_INVALID_REFERENCE, $key);
}

if ($services) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,11 +27,18 @@
*/
final class ServiceLocatorTagPass extends AbstractRecursivePass
{
use PriorityTaggedServiceTrait;

protected function processValue($value, $isRoot = false)
{
if ($value instanceof ServiceLocatorArgument) {
if ($value->getTaggedIteratorArgument()) {
$value->setValues($this->findAndSortTaggedServices($value->getTaggedIteratorArgument(), $this->container));
}

return self::register($this->container, $value->getValues());
}

if (!$value instanceof Definition || !$value->hasTag('container.service_locator')) {
return parent::processValue($value, $isRoot);
}
Expand Down
18 changes: 9 additions & 9 deletions src/Symfony/Component/DependencyInjection/Dumper/XmlDumper.php
Original file line number Diff line number Diff line change
Expand Up @@ -280,19 +280,19 @@ private function convertParameters(array $parameters, $type, \DOMElement $parent
if ($value instanceof ServiceClosureArgument) {
$value = $value->getValues()[0];
}
if (\is_array($value)) {
if (\is_array($tag = $value)) {
$element->setAttribute('type', 'collection');
$this->convertParameters($value, $type, $element, 'key');
} elseif ($value instanceof TaggedIteratorArgument) {
$element->setAttribute('type', 'tagged');
$element->setAttribute('tag', $value->getTag());
} elseif ($value instanceof TaggedIteratorArgument || ($value instanceof ServiceLocatorArgument && $tag = $value->getTaggedIteratorArgument())) {
$element->setAttribute('type', $value instanceof TaggedIteratorArgument ? 'tagged' : 'tagged_locator');
$element->setAttribute('tag', $tag->getTag());

if (null !== $value->getIndexAttribute()) {
$element->setAttribute('index-by', $value->getIndexAttribute());
}
if (null !== $tag->getIndexAttribute()) {
$element->setAttribute('index-by', $tag->getIndexAttribute());

if (null !== $value->getDefaultIndexMethod()) {
$element->setAttribute('default-index-method', $value->getDefaultIndexMethod());
if (null !== $tag->getDefaultIndexMethod()) {
$element->setAttribute('default-index-method', $tag->getDefaultIndexMethod());
}
}
} elseif ($value instanceof IteratorArgument) {
$element->setAttribute('type', 'iterator');
Expand Down
23 changes: 13 additions & 10 deletions src/Symfony/Component/DependencyInjection/Dumper/YamlDumper.php
Original file line number Diff line number Diff line change
Expand Up @@ -232,22 +232,25 @@ private function dumpValue($value)
$value = $value->getValues()[0];
}
if ($value instanceof ArgumentInterface) {
if ($value instanceof TaggedIteratorArgument) {
if (null !== $value->getIndexAttribute()) {
$taggedValueContent = [
'tag' => $value->getTag(),
'index_by' => $value->getIndexAttribute(),
$tag = $value;

if ($value instanceof TaggedIteratorArgument || ($value instanceof ServiceLocatorArgument && $tag = $value->getTaggedIteratorArgument())) {
if (null === $tag->getIndexAttribute()) {
$content = $tag->getTag();
} else {
$content = [
'tag' => $tag->getTag(),
'index_by' => $tag->getIndexAttribute(),
];

if (null !== $value->getDefaultIndexMethod()) {
$taggedValueContent['default_index_method'] = $value->getDefaultIndexMethod();
if (null !== $tag->getDefaultIndexMethod()) {
$content['default_index_method'] = $tag->getDefaultIndexMethod();
}

return new TaggedValue('tagged', $taggedValueContent);
}

return new TaggedValue('tagged', $value->getTag());
return new TaggedValue($value instanceof TaggedIteratorArgument ? 'tagged' : 'tagged_locator', $content);
}

if ($value instanceof IteratorArgument) {
$tag = 'iterator';
} elseif ($value instanceof ServiceLocatorArgument) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -121,6 +121,14 @@ function tagged(string $tag, string $indexAttribute = null, string $defaultIndex
return new TaggedIteratorArgument($tag, $indexAttribute, $defaultIndexMethod);
}

/**
* Creates a service locator by tag name.
*/
function tagged_locator(string $tag, string $indexAttribute, string $defaultIndexMethod = null): ServiceLocatorArgument
{
return new ServiceLocatorArgument(new TaggedIteratorArgument($tag, $indexAttribute, $defaultIndexMethod, true));
}

/**
* Creates an expression.
*/
Expand Down
12 changes: 10 additions & 2 deletions src/Symfony/Component/DependencyInjection/Loader/XmlFileLoader.php
Original file line number Diff line number Diff line change
Expand Up @@ -534,11 +534,19 @@ private function getArgumentsAsPhp(\DOMElement $node, $name, $file, $lowercase =
}
break;
case 'tagged':
case 'tagged_locator':
$type = $arg->getAttribute('type');
$forLocator = 'tagged_locator' === $type;

if (!$arg->getAttribute('tag')) {
throw new InvalidArgumentException(sprintf('Tag "<%s>" with type="tagged" has no or empty "tag" attribute in "%s".', $name, $file));
throw new InvalidArgumentException(sprintf('Tag "<%s>" with type="%s" has no or empty "tag" attribute in "%s".', $name, $type, $file));
}

$arguments[$key] = new TaggedIteratorArgument($arg->getAttribute('tag'), $arg->getAttribute('index-by') ?: null, $arg->getAttribute('default-index-method') ?: null);
$arguments[$key] = new TaggedIteratorArgument($arg->getAttribute('tag'), $arg->getAttribute('index-by') ?: null, $arg->getAttribute('default-index-method') ?: null, $forLocator);

if ($forLocator) {
$arguments[$key] = new ServiceLocatorArgument($arguments[$key]);
}
break;
case 'binary':
F42D if (false === $value = base64_decode($arg->nodeValue)) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -702,27 +702,37 @@ private function resolveServices($value, $file, $isParameter = false)
if (!\is_array($argument)) {
throw new InvalidArgumentException(sprintf('"!service_locator" tag only accepts maps in "%s".', $file));
}

$argument = $this->resolveServices($argument, $file, $isParameter);

try {
return new ServiceLocatorArgument($argument);
} catch (InvalidArgumentException $e) {
throw new InvalidArgumentException(sprintf('"!service_locator" tag only accepts maps of "@service" references in "%s".', $file));
}
}
if ('tagged' === $value->getTag()) {
if (\in_array($value->getTag(), ['tagged', 'tagged_locator'], true)) {
$forLocator = 'tagged_locator' === $value->getTag();

if (\is_string($argument) && $argument) {
return new TaggedIteratorArgument($argument);
return new TaggedIteratorArgument($argument, null, null, $forLocator);
}

if (\is_array($argument) && isset($argument['tag']) && $argument['tag']) {
if ($diff = array_diff(array_keys($argument), ['tag', 'index_by', 'default_index_method'])) {
throw new InvalidArgumentException(sprintf('"!tagged" tag contains unsupported key "%s"; supported ones are "tag", "index_by" and "default_index_method".', implode('"", "', $diff)));
throw new InvalidArgumentException(sprintf('"!%s" tag contains unsupported key "%s"; supported ones are "tag", "index_by" and "default_index_method".', $value->getTag(), implode('"", "', $diff)));
}

$argument = new TaggedIteratorArgument($argument['tag'], $argument['index_by'], $argument['default_index_method'] ?? null, $forLocator);

if ($forLocator) {
$argument = new ServiceLocatorArgument($argument);
}

return new TaggedIteratorArgument($argument['tag'], $argument['index_by'] ?? null, $argument['default_index_method'] ?? null);
return $argument;
}

throw new InvalidArgumentException(sprintf('"!tagged" tags only accept a non empty string or an array with a key "tag" in "%s".', $file));
throw new InvalidArgumentException(sprintf('"!%s" tags only accept a non empty string or an array with a key "tag" in "%s".', $value->getTag(), $file));
}
if ('service' === $value->getTag()) {
if ($isParameter) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -264,6 +264,7 @@
<xsd:enumeration value="iterator" />
<xsd:enumeration value="service_locator" />
<xsd:enumeration value="tagged" />
<xsd:enumeration value="tagged_locator" />
</xsd:restriction>
</xsd:simpleType>

Expand Down
Loading
0