-
-
Notifications
You must be signed in to change notification settings - Fork 9.6k
[DependencyInjection] Add #[AutowireInline]
attribute to allow service definition at the class level
#52820
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
fabpot
merged 2 commits into
symfony:7.1
from
DaDeather:52819-dependency-injection-new-inline-attributes
May 2, 2024
Merged
[DependencyInjection] Add #[AutowireInline]
attribute to allow service definition at the class level
#52820
Changes from all commits
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
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
64 changes: 64 additions & 0 deletions
64
src/Symfony/Component/DependencyInjection/Attribute/AutowireInline.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,64 @@ | ||
<?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\Attribute; | ||
|
||
use Symfony\Component\DependencyInjection\Definition; | ||
use Symfony\Component\DependencyInjection\Exception\LogicException; | ||
use Symfony\Component\DependencyInjection\Loader\YamlFileLoader; | ||
|
||
/** | ||
* Allows inline service definition for an argument. | ||
* | ||
* Using this attribute on a class autowires a new instance | ||
* which is not shared between different services. | ||
* | ||
* $class a FQCN, or an array to define a factory. | ||
* Use the "@" prefix to reference a service. | ||
* | ||
* @author Ismail Özgün Turan <oezguen.turan@dadadev.com> | ||
*/ | ||
#[\Attribute(\Attribute::TARGET_PARAMETER)] | ||
class AutowireInline extends Autowire | ||
{ | ||
public function __construct(string|array|null $class = null, array $arguments = [], array $calls = [], array $properties = [], ?string $parent = null, bool|string $lazy = false) | ||
{ | ||
if (null === $class && null === $parent) { | ||
throw new LogicException('#[AutowireInline] attribute should declare either $class or $parent.'); | ||
} | ||
|
||
parent::__construct([ | ||
\is_array($class) ? 'factory' : 'class' => $class, | ||
'arguments' => $arguments, | ||
nicolas-grekas marked this conversation as resolved.
Show resolved
Hide resolved
|
||
'calls' => $calls, | ||
'properties' => $properties, | ||
'parent' => $parent, | ||
nicolas-grekas marked this conversation as resolved.
Show resolved
Hide resolved
|
||
], lazy: $lazy); | ||
} | ||
|
||
public function buildDefinition(mixed $value, ?string $type, \ReflectionParameter $parameter): Definition | ||
{ | ||
static $parseDefinition; | ||
static $yamlLoader; | ||
|
||
$parseDefinition ??= new \ReflectionMethod(YamlFileLoader::class, 'parseDefinition'); | ||
$yamlLoader ??= $parseDefinition->getDeclaringClass()->newInstanceWithoutConstructor(); | ||
|
||
if (isset($value['factory'])) { | ||
$value['class'] = $type; | ||
$value['factory'][0] ??= $type; | ||
$value['factory'][1] ??= '__invoke'; | ||
} | ||
$class = $parameter->getDeclaringClass(); | ||
|
||
return $parseDefinition->invoke($yamlLoader, $class->name, $value, $class->getFileName(), ['autowire' => true], true); | ||
} | ||
} |
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
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
141 changes: 141 additions & 0 deletions
141
src/Symfony/Component/DependencyInjection/Compiler/ResolveAutowireInlineAttributesPass.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,141 @@ | ||
<?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\Attribute\AutowireInline; | ||
use Symfony\Component\DependencyInjection\ChildDefinition; | ||
use Symfony\Component\DependencyInjection\ContainerBuilder; | ||
use Symfony\Component\DependencyInjection\Definition; | ||
use Symfony\Component\DependencyInjection\Exception\RuntimeException; | ||
use Symfony\Component\DependencyInjection\Reference; | ||
use Symfony\Component\VarExporter\ProxyHelper; | ||
|
||
/** | ||
* Inspects existing autowired services for {@see AutowireInline} attributes and registers the definitions for reuse. | ||
* | ||
* @author Ismail Özgün Turan <oezguen.turan@dadadev.com> | ||
*/ | ||
class ResolveAutowireInlineAttributesPass extends AbstractRecursivePass | ||
{ | ||
protected bool $skipScalars = true; | ||
|
||
protected function processValue(mixed $value, bool $isRoot = false): mixed | ||
{ | ||
$value = parent::processValue($value, $isRoot); | ||
|
||
if (!$value instanceof Definition || !$value->isAutowired() || !$value->getClass() || $value->hasTag('container.ignore_attributes')) { | ||
return $value; | ||
} | ||
|
||
$isChildDefinition = $value instanceof ChildDefinition; | ||
|
||
try { | ||
$constructor = $this->getConstructor($value, false); | ||
} catch (RuntimeException) { | ||
return $value; | ||
} | ||
|
||
if ($constructor) { | ||
$arguments = $this->registerAutowireInlineAttributes($constructor, $value->getArguments(), $isChildDefinition); | ||
|
||
if ($arguments !== $value->getArguments()) { | ||
$value->setArguments($arguments); | ||
} | ||
} | ||
|
||
$dummy = $value; | ||
while (null === $dummy->getClass() && $dummy instanceof ChildDefinition) { | ||
$dummy = $this->container->findDefinition($dummy->getParent()); | ||
} | ||
|
||
$methodCalls = $value->getMethodCalls(); | ||
|
||
foreach ($methodCalls as $i => $call) { | ||
[$method, $arguments] = $call; | ||
|
||
try { | ||
$method = $this->getReflectionMethod($dummy, $method); | ||
} catch (RuntimeException) { | ||
continue; | ||
} | ||
|
||
$arguments = $this->registerAutowireInlineAttributes($method, $arguments, $isChildDefinition); | ||
|
||
if ($arguments !== $call[1]) { | ||
$methodCalls[$i][1] = $arguments; | ||
} | ||
} | ||
|
||
if ($methodCalls !== $value->getMethodCalls()) { | ||
$value->setMethodCalls($methodCalls); | ||
} | ||
|
||
return $value; | ||
} | ||
|
||
private function registerAutowireInlineAttributes(\ReflectionFunctionAbstract $method, array $arguments, bool $isChildDefinition): array | ||
{ | ||
$parameters = $method->getParameters(); | ||
|
||
if ($method->isVariadic()) { | ||
array_pop($parameters); | ||
} | ||
$dummyContainer = new ContainerBuilder($this->container->getParameterBag()); | ||
|
||
foreach ($parameters as $index => $parameter) { | ||
if ($isChildDefinition) { | ||
$index = 'index_'.$index; | ||
} | ||
|
||
$name = '$'.$parameter->name; | ||
if (\array_key_exists($name, $arguments)) { | ||
$arguments[$index] = $arguments[$name]; | ||
unset($arguments[$name]); | ||
} | ||
if (\array_key_exists($index, $arguments) && '' !== $arguments[$index]) { | ||
continue; | ||
} | ||
if (!$attribute = $parameter->getAttributes(AutowireInline::class, \ReflectionAttribute::IS_INSTANCEOF)[0] ?? null) { | ||
continue; | ||
} | ||
|
||
$type = ProxyHelper::exportType($parameter, true); | ||
|
||
if (!$type && isset($arguments[$index])) { | ||
continue; | ||
} | ||
|
||
$attribute = $attribute->newInstance(); | ||
$definition = $attribute->buildDefinition($attribute->value, $type, $parameter); | ||
|
||
$dummyContainer->setDefinition('.autowire_inline', $definition); | ||
(new ResolveParameterPlaceHoldersPass(false, false))->process($dummyContainer); | ||
|
||
$id = '.autowire_inline.'.ContainerBuilder::hash([$this->currentId, $method->class ?? null, $method->name, (string) $parameter]); | ||
|
||
$this->container->setDefinition($id, $definition); | ||
$arguments[$index] = new Reference($id); | ||
|
||
if ($definition->isAutowired()) { | ||
$currentId = $this->currentId; | ||
try { | ||
$this->currentId = $id; | ||
$this->processValue($definition, true); | ||
} finally { | ||
$this->currentId = $currentId; | ||
} | ||
} | ||
} | ||
|
||
return $arguments; | ||
} | ||
} |
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 |
---|---|---|
|
@@ -494,7 +494,9 @@ public function removeDefinition(string $id): void | |
{ | ||
if (isset($this->definitions[$id])) { | ||
unset($this->definitions[$id]); | ||
$this->removedIds[$id] = true; | ||
if ('.' !== ($id[0] ?? '-')) { | ||
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. I added this rule so that we don't use internal service ids in error messages. This matters to this PR because the added code creates new removed-ids, which means fixtures have to be updated with (what I consider as) noise. |
||
$this->removedIds[$id] = true; | ||
} | ||
} | ||
} | ||
|
||
|
@@ -768,6 +770,9 @@ public function compile(bool $resolveEnvPlaceholders = false): void | |
parent::compile(); | ||
|
||
foreach ($this->definitions + $this->aliasDefinitions as $id => $definition) { | ||
if ('.' === ($id[0] ?? '-')) { | ||
continue; | ||
} | ||
if (!$definition->isPublic() || $definition->isPrivate()) { | ||
$this->removedIds[$id] = true; | ||
} | ||
|
@@ -841,7 +846,9 @@ public function removeAlias(string $alias): void | |
{ | ||
if (isset($this->aliasDefinitions[$alias])) { | ||
unset($this->aliasDefinitions[$alias]); | ||
$this->removedIds[$alias] = true; | ||
if ('.' !== ($alias[0] ?? '-')) { | ||
$this->removedIds[$alias] = true; | ||
} | ||
} | ||
} | ||
|
||
|
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.
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.
Uh oh!
There was an error while loading. Please reload this page.
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.
AutowireInline
looks pretty cryptic, any newcomer wouldn't be able to get what the attribute is for by just looking at its name nor its description as it currently is. I think we either need to find a super self-explanatory name (I've no clue) or extend the description so that it tells what's the purpose of the attribute and when it should be used (inline service definition only means something to advanced Symfony's DIC hackers)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.
Naming things... :)
"inline" refers to "inline_service()" in the PHP-DSL
AutowireInlineService? but verbose
AutowireNew? AutowireObject? AutowireInstance? or keep AutowireInline?
of course, a top notch description is also desirable
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.
I added a better description here feel free to request further suggestments to it 👍.