Skip to content

[DependencyInjection] Add autowiring capabilities #15613

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

Closed
wants to merge 19 commits into from
Closed
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
263 changes: 263 additions & 0 deletions src/Symfony/Component/DependencyInjection/Compiler/AutowirePass.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,263 @@
<?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\Definition;
use Symfony\Component\DependencyInjection\Exception\RuntimeException;
use Symfony\Component\DependencyInjection\Reference;

/**
* Guesses constructor arguments of services definitions and try to instantiate services if necessary.
*
* @author Kévin Dunglas <dunglas@gmail.com>
*/
class AutowirePass implements CompilerPassInterface
{
private $container;
private $reflectionClasses = array();
private $definedTypes = array();
private $types;
private $notGuessableTypes = array();

/**
* {@inheritdoc}
*/
public function process(ContainerBuilder $container)
{
$this->container = $container;
foreach ($container->getDefinitions() as $id => $definition) {
if ($definition->isAutowired()) {
$this->completeDefinition($id, $definition);
}
}

// Free memory and remove circular reference to container
$this->container = null;
$this->reflectionClasses = array();
$this->definedTypes = array();
$this->types = null;
$this->notGuessableTypes = array();
}

/**
* Wires the given definition.
*
* @param string $id
* @param Definition $definition
*
* @throws RuntimeException
*/
private function completeDefinition($id, Definition $definition)
Copy link
Contributor

Choose a reason for hiding this comment

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

I guess this method can be simplified if we use PropertyInfo component ?

Copy link
Member Author

Choose a reason for hiding this comment

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

I don't think so. What do you have in mind?

Copy link
Contributor

Choose a reason for hiding this comment

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

I thought it might be useful for guessing types

Copy link
Member Author

Choose a reason for hiding this comment

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

I don't think it's useful here because the PHP reflection is enough. We only need typehint information.

{
if (!$reflectionClass = $this->getReflectionClass($id, $definition)) {
return;
}

$this->container->addClassResource($reflectionClass);

if (!$constructor = $reflectionClass->getConstructor()) {
return;
}

$arguments = $definition->getArguments();
foreach ($constructor->getParameters() as $index => $parameter) {
$argumentExists = array_key_exists($index, $arguments);
if ($argumentExists && '' !== $arguments[$index]) {
continue;
}

try {
if (!$typeHint = $parameter->getClass()) {
continue;
}

if (null === $this->types) {
$this->populateAvailableTypes();
}

if (isset($this->types[$typeHint->name])) {
$value = new Reference($this->types[$typeHint->name]);
} else {
try {
$value = $this->createAutowiredDefinition($typeHint, $id);
} catch (RuntimeException $e) {
if (!$parameter->isDefaultValueAvailable()) {
throw $e;
}

$value = $parameter->getDefaultValue();
}
}
} catch (\ReflectionException $reflectionException) {
// Typehint against a non-existing class

if (!$parameter->isDefaultValueAvailable()) {
continue;
}

$value = $parameter->getDefaultValue();
}

if ($argumentExists) {
$definition->replaceArgument($index, $value);
} else {
$definition->addArgument($value);
}
}
}

/**
* Populates the list of available types.
*/
private function populateAvailableTypes()
{
$this->types = array();

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

/**
* Populates the list of available types for a given definition.
*
* @param string $id
* @param Definition $definition
*/
private function populateAvailableType($id, Definition $definition)
{
if (!$definition->getClass()) {
return;
}

foreach ($definition->getAutowiringTypes() as $type) {
$this->definedTypes[$type] = true;
$this->types[$type] = $id;
}

if ($reflectionClass = $this->getReflectionClass($id, $definition)) {
$this->extractInterfaces($id, $reflectionClass);
$this->extractAncestors($id, $reflectionClass);
}
}

/**
* Extracts the list of all interfaces implemented by a class.
*
* @param string $id
* @param \ReflectionClass $reflectionClass
*/
private function extractInterfaces($id, \ReflectionClass $reflectionClass)
{
foreach ($reflectionClass->getInterfaces() as $interfaceName => $reflectionInterface) {
$this->set($interfaceName, $id);

$this->extractInterfaces($id, $reflectionInterface);
}
}

/**
* Extracts all inherited types of a class.
*
* @param string $id
* @param \ReflectionClass $reflectionClass
*/
private function extractAncestors($id, \ReflectionClass $reflectionClass)
{
$this->set($reflectionClass->name, $id);

if ($reflectionParentClass = $reflectionClass->getParentClass()) {
$this->extractAncestors($id, $reflectionParentClass);
}
}

/**
* Associates a type and a service id if applicable.
*
* @param string $type
* @param string $id
*/
private function set($type, $id)
{
if (isset($this->definedTypes[$type]) || isset($this->notGuessableTypes[$type])) {
return;
}

if (isset($this->types[$type])) {
if ($this->types[$type] === $id) {
return;
}

unset($this->types[$type]);
$this->notGuessableTypes[$type] = true;

return;
}

$this->types[$type] = $id;
}

/**
* Registers a definition for the type if possible or throws an exception.
*
* @param \ReflectionClass $typeHint
* @param string $id
*
* @return Reference A reference to the registered definition
*
* @throws RuntimeException
*/
private function createAutowiredDefinition(\ReflectionClass $typeHint, $id)
{
if (!$typeHint->isInstantiable()) {
throw new RuntimeException(sprintf('Unable to autowire argument of type "%s" for the service "%s".', $typeHint->name, $id));
}

$argumentId = sprintf('autowired.%s', $typeHint->name);
Copy link
Contributor

Choose a reason for hiding this comment

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

This will register a service with an id like 'autowired.AppBundle\Foo' which is not consistent with Service Naming Conventions

Copy link
Member Author

Choose a reason for hiding this comment

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

You're right but it is only intended for internal services name (they should not be used directly) so it should not be a big deal.

From a debug point of view, autowired.AppBundle\Foo is more explicit than autowired.app_bundle_foo or autowired.app_bundle.foo.

IMO it's better to keep it as is but I can change it if everyone think it's better to follow conventions here.


$argumentDefinition = $this->container->register($argumentId, $typeHint->name);
$argumentDefinition->setPublic(false);

$this->populateAvailableType($argumentId, $argumentDefinition);
$this->completeDefinition($argumentId, $argumentDefinition);

return new Reference($argumentId);
}

/**
* Retrieves the reflection class associated with the given service.
*
* @param string $id
* @param Definition $definition
*
* @return \ReflectionClass|null
*/
private function getReflectionClass($id, Definition $definition)
{
if (isset($this->reflectionClasses[$id])) {
return $this->reflectionClasses[$id];
}

if (!$class = $definition->getClass()) {
return;
}

$class = $this->container->getParameterBag()->resolveValue($class);

try {
return $this->reflectionClasses[$id] = new \ReflectionClass($class);
} catch (\ReflectionException $reflectionException) {
// return null
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,7 @@ public function __construct()
new CheckDefinitionValidityPass(),
new ResolveReferencesToAliasesPass(),
new ResolveInvalidReferencesPass(),
new AutowirePass(),
new AnalyzeServiceReferencesPass(true),
new CheckCircularReferencesPass(),
new CheckReferenceValidityPass(),
Expand Down
94 changes: 94 additions & 0 deletions src/Symfony/Component/DependencyInjection/Definition.php
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,8 @@ class Definition
private $synchronized = false;
private $lazy = false;
private $decoratedService;
private $autowired = false;
private $autowiringTypes = array();
Copy link
Contributor

Choose a reason for hiding this comment

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

you might want change this prop. name with autowireTypesaccording to @weaverryan suggestion

Copy link
Member Author

Choose a reason for hiding this comment

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

$definition->isAutowire() looks weirder than $definition->isAutowired(). It's why I've kept autowired here but not in the loaders.


protected $arguments;

Expand Down Expand Up @@ -818,4 +820,96 @@ public function getConfigurator()
{
return $this->configurator;
}

/**
* Sets types that will default to this definition.
*
* @param string[] $types
*
* @return Definition The current instance
*/
public function setAutowiringTypes(array $types)
{
$this->autowiringTypes = array();

foreach ($types as $type) {
$this->autowiringTypes[$type] = true;
}

return $this;
}

/**
* Is the definition autowired?
*
* @return bool
*/
public function isAutowired()
{
return $this->autowired;
}

/**
* Sets autowired.
*
* @param $autowired
*
* @return Definition The current instance
*/
public function setAutowired($autowired)
{
$this->autowired = $autowired;

return $this;
}

/**
* Gets autowiring types that will default to this definition.
*
* @return string[]
*/
public function getAutowiringTypes()
{
return array_keys($this->autowiringTypes);
}

/**
* Adds a type that will default to this definition.
*
* @param string $type
*
* @return Definition The current instance
*/
public function addAutowiringType($type)
{
$this->autowiringTypes[$type] = true;

return $this;
}

/**
* Removes a type.
*
* @param string $type
*
* @return Definition The current instance
*/
public function removeAutowiringType($type)
{
unset($this->autowiringTypes[$type]);

return $this;
}

/**
* Will this definition default for the given type?
*
* @param string $type
*
* @return bool
*/
public function hasAutowiringType($type)
{
return isset($this->autowiringTypes[$type]);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -157,6 +157,10 @@ private function parseDefinition(\DOMElement $service, $file)
}
}

if ($value = $service->getAttribute('autowire')) {
$definition->setAutowired(XmlUtils::phpize($value));
}

if ($value = $service->getAttribute('scope')) {
$triggerDeprecation = 'request' !== (string) $service->getAttribute('id');

Expand Down Expand Up @@ -247,6 +251,10 @@ private function parseDefinition(\DOMElement $service, $file)
$definition->addTag($tag->getAttribute('name'), $parameters);
}

foreach ($this->getChildren($service, 'autowiring-type') as $type) {
$definition->addAutowiringType($type->textContent);
}

if ($value = $service->getAttribute('decorates')) {
$renameId = $service->hasAttribute('decoration-inner-name') ? $service->getAttribute('decoration-inner-name') : null;
$priority = $service->hasAttribute('decoration-priority') ? $service->getAttribute('decoration-priority') : 0;
Expand Down
Loading