Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feature #52820 [DependencyInjection] Add
#[AutowireInline]
attribut…
…e to allow service definition at the class level (DaDeather, nicolas-grekas) This PR was merged into the 7.1 branch. Discussion ---------- [DependencyInjection] Add `#[AutowireInline]` attribute to allow service definition at the class level | Q | A | ------------- | --- | Branch | 7.1 | Bug fix | no | New feature | yes | Deprecations | no | Issues | Fix #52819 | License | MIT For the idea behind this feature see the issue that contains examples #52819 ### Example usage: ```php class SomeSourceAwareLogger { public function __construct( private readonly LoggerInterface $logger, private readonly string $someSource, ) { } } class SomeSourceAwareLoggerFactory { public function __construct( private readonly LoggerInterface $logger, ) { } public function create(string $someSource): SomeSourceAwareLogger { return new SomeSourceAwareLogger($this->logger, $someSource); } public static function staticCreate(LoggerInterface $logger, string $someSource): SomeSourceAwareLogger { return new SomeSourceAwareLogger($logger, $someSource); } } // ----------- class SomeClass1 { public function __construct( #[AutowireInline(class: SomeSourceAwareLogger::class, args: [new Reference(LoggerInterface::class), 'bar'])] public SomeSourceAwareLogger $someSourceAwareLogger, ) { } } // AND/OR class SomeClass2 { public function __construct( #[AutowireInline( class: SomeSourceAwareLogger::class, factory: [SomeSourceAwareLoggerFactory::class, 'staticCreate'], args: [new Reference(LoggerInterface::class), 'someParam'], )] public SomeSourceAwareLogger $someSourceAwareLogger, ) { } } // AND/OR class SomeClass3 { public function __construct( #[AutowireInline( class: SomeSourceAwareLogger::class, factory: [new Reference(SomeSourceAwareLoggerFactory::class), 'create'], args: ['someParam'], )] public SomeSourceAwareLogger $someSourceAwareLogger, ) { } } ``` Commits ------- b9a838e Finish implementing AutowireInline attribute a596142 [DependencyInjection] Add `#[AutowireInline]` attribute to allow service definition at the class level
- Loading branch information
Showing
23 changed files
with
860 additions
and
40 deletions.
There are no files selected for viewing
This file contains 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 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, | ||
'calls' => $calls, | ||
'properties' => $properties, | ||
'parent' => $parent, | ||
], 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 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 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 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 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 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 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 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.