2015-08-24 02:36:41 +01:00
< ? 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 ;
2016-03-12 20:10:13 +00:00
use Symfony\Component\DependencyInjection\Config\AutowireServiceResource ;
2015-08-24 02:36:41 +01:00
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 >
*/
2017-01-31 12:10:56 +00:00
class AutowirePass extends AbstractRecursivePass
2015-08-24 02:36:41 +01:00
{
private $definedTypes = array ();
private $types ;
2016-02-22 00:27:26 +00:00
private $ambiguousServiceTypes = array ();
2015-08-24 02:36:41 +01:00
/**
* { @ inheritdoc }
*/
public function process ( ContainerBuilder $container )
{
2016-04-20 13:06:08 +01:00
try {
2017-01-17 20:04:53 +00:00
parent :: process ( $container );
2016-08-15 10:28:45 +01:00
} finally {
// Free memory and remove circular reference to container
$this -> definedTypes = array ();
$this -> types = null ;
$this -> ambiguousServiceTypes = array ();
2016-04-20 13:06:08 +01:00
}
2015-08-24 02:36:41 +01:00
}
2016-03-12 20:10:13 +00:00
/**
* Creates a resource to help know if this service has changed .
*
* @ param \ReflectionClass $reflectionClass
*
* @ return AutowireServiceResource
2017-01-26 15:09:57 +00:00
*
* @ deprecated since version 3.3 , to be removed in 4.0 . Use ContainerBuilder :: getReflectionClass () instead .
2016-03-12 20:10:13 +00:00
*/
public static function createResourceForClass ( \ReflectionClass $reflectionClass )
{
2017-01-26 15:09:57 +00:00
@ trigger_error ( 'The ' . __METHOD__ . '() method is deprecated since version 3.3 and will be removed in 4.0. Use ContainerBuilder::getReflectionClass() instead.' , E_USER_DEPRECATED );
2016-03-12 20:10:13 +00:00
$metadata = array ();
2016-10-05 21:46:29 +01:00
foreach ( $reflectionClass -> getMethods ( \ReflectionMethod :: IS_PUBLIC ) as $reflectionMethod ) {
if ( ! $reflectionMethod -> isStatic ()) {
$metadata [ $reflectionMethod -> name ] = self :: getResourceMetadataForMethod ( $reflectionMethod );
}
2016-03-12 20:10:13 +00:00
}
return new AutowireServiceResource ( $reflectionClass -> name , $reflectionClass -> getFileName (), $metadata );
}
2015-08-24 02:36:41 +01:00
/**
2017-01-17 20:04:53 +00:00
* { @ inheritdoc }
2015-08-24 02:36:41 +01:00
*/
2017-01-17 20:04:53 +00:00
protected function processValue ( $value , $isRoot = false )
2015-08-24 02:36:41 +01:00
{
2017-01-17 20:04:53 +00:00
if ( ! $value instanceof Definition || ! $autowiredMethods = $value -> getAutowiredMethods ()) {
return parent :: processValue ( $value , $isRoot );
}
2017-01-26 15:09:57 +00:00
if ( ! $reflectionClass = $this -> container -> getReflectionClass ( $value -> getClass ())) {
2017-01-17 20:04:53 +00:00
return parent :: processValue ( $value , $isRoot );
2015-08-24 02:36:41 +01:00
}
2017-01-25 12:02:51 +00:00
$autowiredMethods = $this -> getMethodsToAutowire ( $reflectionClass , $autowiredMethods );
$methodCalls = $value -> getMethodCalls ();
if ( $constructor = $reflectionClass -> getConstructor ()) {
array_unshift ( $methodCalls , array ( $constructor -> name , $value -> getArguments ()));
} elseif ( $value -> getArguments ()) {
throw new RuntimeException ( sprintf ( 'Cannot autowire service "%s": class %s has no constructor but arguments are defined.' , $this -> currentId , $reflectionClass -> name , $method ));
2016-01-30 09:38:42 +00:00
}
2017-01-25 12:02:51 +00:00
$methodCalls = $this -> autowireMethodCalls ( $reflectionClass , $methodCalls , $autowiredMethods );
if ( $constructor ) {
list (, $arguments ) = array_shift ( $methodCalls );
if ( $arguments !== $value -> getArguments ()) {
$value -> setArguments ( $arguments );
2016-10-05 21:46:29 +01:00
}
}
2017-01-17 20:04:53 +00:00
2017-01-25 12:02:51 +00:00
if ( $methodCalls !== $value -> getMethodCalls ()) {
$value -> setMethodCalls ( $methodCalls );
}
2017-01-17 20:04:53 +00:00
return parent :: processValue ( $value , $isRoot );
2016-10-05 21:46:29 +01:00
}
/**
* Gets the list of methods to autowire .
*
* @ param \ReflectionClass $reflectionClass
2017-01-25 12:02:51 +00:00
* @ param string [] $autowiredMethods
2016-10-05 21:46:29 +01:00
*
* @ return \ReflectionMethod []
*/
2017-01-25 12:02:51 +00:00
private function getMethodsToAutowire ( \ReflectionClass $reflectionClass , array $autowiredMethods )
2016-10-05 21:46:29 +01:00
{
$found = array ();
$regexList = array ();
2017-01-25 12:02:51 +00:00
$methodsToAutowire = array ();
2017-01-16 15:14:49 +00:00
2016-10-05 21:46:29 +01:00
foreach ( $autowiredMethods as $pattern ) {
$regexList [] = '/^' . str_replace ( '\*' , '.*' , preg_quote ( $pattern , '/' )) . '$/i' ;
}
foreach ( $reflectionClass -> getMethods ( \ReflectionMethod :: IS_PUBLIC ) as $reflectionMethod ) {
if ( $reflectionMethod -> isStatic ()) {
continue ;
}
foreach ( $regexList as $k => $regex ) {
if ( preg_match ( $regex , $reflectionMethod -> name )) {
$found [] = $autowiredMethods [ $k ];
2017-01-25 12:02:51 +00:00
$methodsToAutowire [ strtolower ( $reflectionMethod -> name )] = $reflectionMethod ;
2016-10-05 21:46:29 +01:00
continue 2 ;
}
}
2017-01-25 12:02:51 +00:00
if ( $reflectionMethod -> isConstructor ()) {
$methodsToAutowire [ strtolower ( $reflectionMethod -> name )] = $reflectionMethod ;
}
2016-10-05 21:46:29 +01:00
}
2017-01-25 12:02:51 +00:00
if ( $notFound = array_diff ( $autowiredMethods , $found )) {
2017-01-24 18:16:15 +00:00
$this -> container -> log ( $this , sprintf ( 'Autowiring\'s patterns "%s" for service "%s" don\'t match any method.' , implode ( '", "' , $notFound ), $this -> currentId ));
2016-10-05 21:46:29 +01:00
}
2017-01-25 12:02:51 +00:00
return $methodsToAutowire ;
}
/**
* @ param \ReflectionClass $reflectionClass
* @ param array $methodCalls
* @ param \ReflectionMethod [] $autowiredMethods
*
* @ return array
*/
private function autowireMethodCalls ( \ReflectionClass $reflectionClass , array $methodCalls , array $autowiredMethods )
{
$parameterBag = $this -> container -> getParameterBag ();
foreach ( $methodCalls as $i => $call ) {
list ( $method , $arguments ) = $call ;
$method = $parameterBag -> resolveValue ( $method );
if ( isset ( $autowiredMethods [ $lcMethod = strtolower ( $method )])) {
$reflectionMethod = $autowiredMethods [ $lcMethod ];
unset ( $autowiredMethods [ $lcMethod ]);
} else {
if ( ! $reflectionClass -> hasMethod ( $method )) {
throw new RuntimeException ( sprintf ( 'Cannot autowire service "%s": method %s::%s() does not exist.' , $this -> currentId , $reflectionClass -> name , $method ));
}
$reflectionMethod = $reflectionClass -> getMethod ( $method );
if ( ! $reflectionMethod -> isPublic ()) {
throw new RuntimeException ( sprintf ( 'Cannot autowire service "%s": method %s::%s() must be public.' , $this -> currentId , $reflectionClass -> name , $method ));
}
}
$arguments = $this -> autowireMethod ( $reflectionMethod , $arguments , true );
if ( $arguments !== $call [ 1 ]) {
$methodCalls [ $i ][ 1 ] = $arguments ;
}
}
foreach ( $autowiredMethods as $reflectionMethod ) {
if ( $arguments = $this -> autowireMethod ( $reflectionMethod , array (), false )) {
$methodCalls [] = array ( $reflectionMethod -> name , $arguments );
}
}
return $methodCalls ;
2016-10-05 21:46:29 +01:00
}
/**
* Autowires the constructor or a setter .
*
* @ param \ReflectionMethod $reflectionMethod
2017-01-25 12:02:51 +00:00
* @ param array $arguments
* @ param bool $mustAutowire
*
* @ return array The autowired arguments
2016-10-05 21:46:29 +01:00
*
* @ throws RuntimeException
*/
2017-01-25 12:02:51 +00:00
private function autowireMethod ( \ReflectionMethod $reflectionMethod , array $arguments , $mustAutowire )
2016-10-05 21:46:29 +01:00
{
2017-01-25 12:02:51 +00:00
$didAutowire = false ; // Whether any arguments have been autowired or not
2016-10-05 21:46:29 +01:00
foreach ( $reflectionMethod -> getParameters () as $index => $parameter ) {
2016-02-29 00:33:45 +00:00
if ( array_key_exists ( $index , $arguments ) && '' !== $arguments [ $index ]) {
2015-08-24 02:36:41 +01:00
continue ;
}
2017-02-01 12:10:11 +00:00
if ( method_exists ( $parameter , 'getType' )) {
if ( $typeName = $parameter -> getType ()) {
$typeName = $typeName -> isBuiltin () ? null : ( $typeName instanceof \ReflectionNamedType ? $typeName -> getName () : $typeName -> __toString ());
}
} elseif ( preg_match ( '/^(?:[^ ]++ ){4}([a-zA-Z_\x7F-\xFF][^ ]++)/' , $parameter , $typeName )) {
$typeName = 'callable' === $typeName [ 1 ] || 'array' === $typeName [ 1 ] ? null : $typeName [ 1 ];
}
2016-02-22 01:17:09 +00:00
2017-02-01 12:10:11 +00:00
if ( ! $typeName ) {
// no default value? Then fail
if ( ! $parameter -> isOptional ()) {
if ( $mustAutowire ) {
throw new RuntimeException ( sprintf ( 'Cannot autowire service "%s": argument $%s of method %s::%s() must have a type-hint or be given a value explicitly.' , $this -> currentId , $parameter -> name , $reflectionMethod -> class , $reflectionMethod -> name ));
2017-01-25 12:10:29 +00:00
}
2016-02-22 01:17:09 +00:00
2017-02-01 12:10:11 +00:00
return array ();
2015-08-24 02:36:41 +01:00
}
2017-02-01 12:10:11 +00:00
if ( ! array_key_exists ( $index , $arguments )) {
// specifically pass the default value
$arguments [ $index ] = $parameter -> getDefaultValue ();
2015-08-24 02:36:41 +01:00
}
2017-02-01 12:10:11 +00:00
continue ;
}
2017-02-01 11:51:46 +00:00
if ( $this -> container -> has ( $typeName ) && ! $this -> container -> findDefinition ( $typeName ) -> isAbstract ()) {
$arguments [ $index ] = new Reference ( $typeName );
$didAutowire = true ;
continue ;
}
2017-02-01 12:10:11 +00:00
if ( null === $this -> types ) {
$this -> populateAvailableTypes ();
}
if ( isset ( $this -> types [ $typeName ])) {
2017-01-26 15:09:57 +00:00
$value = new Reference ( $this -> types [ $typeName ]);
2017-02-01 12:10:11 +00:00
$didAutowire = true ;
2017-01-26 15:09:57 +00:00
} elseif ( $typeHint = $this -> container -> getReflectionClass ( $typeName , true )) {
2017-02-01 12:10:11 +00:00
try {
$value = $this -> createAutowiredDefinition ( $typeHint );
2017-01-25 12:02:51 +00:00
$didAutowire = true ;
2017-02-01 12:10:11 +00:00
} catch ( RuntimeException $e ) {
if ( $parameter -> allowsNull ()) {
$value = null ;
} elseif ( $parameter -> isDefaultValueAvailable ()) {
$value = $parameter -> getDefaultValue ();
} else {
// The exception code is set to 1 if the exception must be thrown even if it's an optional setter
if ( 1 === $e -> getCode () || $mustAutowire ) {
throw $e ;
2015-08-24 02:36:41 +01:00
}
2017-02-01 12:10:11 +00:00
return array ();
2015-08-24 02:36:41 +01:00
}
}
2017-02-01 12:10:11 +00:00
} else {
2017-01-26 15:09:57 +00:00
// Typehint against a non-existing class
2015-08-24 02:36:41 +01:00
if ( ! $parameter -> isDefaultValueAvailable ()) {
2017-01-25 12:02:51 +00:00
if ( $mustAutowire ) {
2017-01-26 15:09:57 +00:00
throw new RuntimeException ( sprintf ( 'Cannot autowire argument $%s of method %s::%s() for service "%s": Class %s does not exist.' , $parameter -> name , $reflectionMethod -> class , $reflectionMethod -> name , $this -> currentId , $typeName ));
2016-10-05 21:46:29 +01:00
}
2017-01-25 12:02:51 +00:00
return array ();
2015-08-24 02:36:41 +01:00
}
$value = $parameter -> getDefaultValue ();
}
2016-02-21 23:51:49 +00:00
$arguments [ $index ] = $value ;
2015-08-24 02:36:41 +01:00
}
2016-02-21 23:51:49 +00:00
2017-01-25 12:02:51 +00:00
if ( ! $mustAutowire && ! $didAutowire ) {
return array ();
}
2016-02-21 23:51:49 +00:00
// it's possible index 1 was set, then index 0, then 2, etc
// make sure that we re-order so they're injected as expected
ksort ( $arguments );
2016-10-05 21:46:29 +01:00
2017-01-25 12:02:51 +00:00
return $arguments ;
2015-08-24 02:36:41 +01:00
}
/**
* 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 )
{
2015-11-04 00:40:26 +00:00
// Never use abstract services
if ( $definition -> isAbstract ()) {
return ;
}
2017-02-01 11:51:46 +00:00
foreach ( $definition -> getAutowiringTypes ( false ) as $type ) {
2015-08-24 02:36:41 +01:00
$this -> definedTypes [ $type ] = true ;
$this -> types [ $type ] = $id ;
}
2017-01-26 15:09:57 +00:00
if ( ! $reflectionClass = $this -> container -> getReflectionClass ( $definition -> getClass (), true )) {
2015-11-03 19:42:49 +00:00
return ;
}
2016-02-23 09:13:51 +00:00
foreach ( $reflectionClass -> getInterfaces () as $reflectionInterface ) {
$this -> set ( $reflectionInterface -> name , $id );
2015-08-24 02:36:41 +01:00
}
2016-02-23 09:13:51 +00:00
do {
$this -> set ( $reflectionClass -> name , $id );
} while ( $reflectionClass = $reflectionClass -> getParentClass ());
2015-08-24 02:36:41 +01:00
}
/**
* Associates a type and a service id if applicable .
*
* @ param string $type
* @ param string $id
*/
private function set ( $type , $id )
{
2016-02-22 00:27:26 +00:00
if ( isset ( $this -> definedTypes [ $type ])) {
2015-08-24 02:36:41 +01:00
return ;
}
2016-03-06 22:03:14 +00:00
// is this already a type/class that is known to match multiple services?
if ( isset ( $this -> ambiguousServiceTypes [ $type ])) {
$this -> addServiceToAmbiguousType ( $id , $type );
return ;
}
2016-02-22 00:27:26 +00:00
// check to make sure the type doesn't match multiple services
2015-08-24 02:36:41 +01:00
if ( isset ( $this -> types [ $type ])) {
if ( $this -> types [ $type ] === $id ) {
return ;
}
2016-02-22 00:27:26 +00:00
// keep an array of all services matching this type
2016-03-06 22:03:14 +00:00
$this -> addServiceToAmbiguousType ( $id , $type );
2016-02-22 00:27:26 +00:00
2015-08-24 02:36:41 +01:00
unset ( $this -> types [ $type ]);
return ;
}
$this -> types [ $type ] = $id ;
}
/**
* Registers a definition for the type if possible or throws an exception .
*
* @ param \ReflectionClass $typeHint
*
* @ return Reference A reference to the registered definition
*
* @ throws RuntimeException
*/
2017-01-17 20:04:53 +00:00
private function createAutowiredDefinition ( \ReflectionClass $typeHint )
2015-08-24 02:36:41 +01:00
{
2016-02-22 00:27:26 +00:00
if ( isset ( $this -> ambiguousServiceTypes [ $typeHint -> name ])) {
$classOrInterface = $typeHint -> isInterface () ? 'interface' : 'class' ;
$matchingServices = implode ( ', ' , $this -> ambiguousServiceTypes [ $typeHint -> name ]);
2017-01-17 20:04:53 +00:00
throw new RuntimeException ( sprintf ( 'Unable to autowire argument of type "%s" for the service "%s". Multiple services exist for this %s (%s).' , $typeHint -> name , $this -> currentId , $classOrInterface , $matchingServices ), 1 );
2016-02-22 00:27:26 +00:00
}
if ( ! $typeHint -> isInstantiable ()) {
$classOrInterface = $typeHint -> isInterface () ? 'interface' : 'class' ;
2017-01-17 20:04:53 +00:00
throw new RuntimeException ( sprintf ( 'Unable to autowire argument of type "%s" for the service "%s". No services were found matching this %s and it cannot be auto-registered.' , $typeHint -> name , $this -> currentId , $classOrInterface ));
2015-08-24 02:36:41 +01:00
}
2017-01-17 20:04:53 +00:00
$currentId = $this -> currentId ;
$this -> currentId = $argumentId = sprintf ( 'autowired.%s' , $typeHint -> name );
2015-08-24 02:36:41 +01:00
$argumentDefinition = $this -> container -> register ( $argumentId , $typeHint -> name );
$argumentDefinition -> setPublic ( false );
2017-01-17 20:04:53 +00:00
$argumentDefinition -> setAutowired ( true );
2015-08-24 02:36:41 +01:00
$this -> populateAvailableType ( $argumentId , $argumentDefinition );
2016-05-02 16:12:26 +01:00
try {
2017-01-17 20:04:53 +00:00
$this -> processValue ( $argumentDefinition , true );
$this -> currentId = $currentId ;
2016-05-02 16:12:26 +01:00
} catch ( RuntimeException $e ) {
2016-05-02 16:12:26 +01:00
$classOrInterface = $typeHint -> isInterface () ? 'interface' : 'class' ;
2017-01-17 20:04:53 +00:00
$message = sprintf ( 'Unable to autowire argument of type "%s" for the service "%s". No services were found matching this %s and it cannot be auto-registered.' , $typeHint -> name , $this -> currentId , $classOrInterface );
2016-05-02 16:12:26 +01:00
throw new RuntimeException ( $message , 0 , $e );
}
2015-08-24 02:36:41 +01:00
return new Reference ( $argumentId );
}
2016-03-06 22:03:14 +00:00
private function addServiceToAmbiguousType ( $id , $type )
{
// keep an array of all services matching this type
if ( ! isset ( $this -> ambiguousServiceTypes [ $type ])) {
$this -> ambiguousServiceTypes [ $type ] = array (
$this -> types [ $type ],
);
}
$this -> ambiguousServiceTypes [ $type ][] = $id ;
}
2016-03-12 20:10:13 +00:00
2017-01-26 15:09:57 +00:00
/**
* @ deprecated since version 3.3 , to be removed in 4.0 .
*/
2016-04-03 08:41:26 +01:00
private static function getResourceMetadataForMethod ( \ReflectionMethod $method )
2016-03-12 20:10:13 +00:00
{
$methodArgumentsMetadata = array ();
foreach ( $method -> getParameters () as $parameter ) {
try {
$class = $parameter -> getClass ();
} catch ( \ReflectionException $e ) {
// type-hint is against a non-existent class
$class = false ;
}
2017-01-22 14:49:28 +00:00
$isVariadic = method_exists ( $parameter , 'isVariadic' ) && $parameter -> isVariadic ();
2016-03-12 20:10:13 +00:00
$methodArgumentsMetadata [] = array (
'class' => $class ,
'isOptional' => $parameter -> isOptional (),
2017-01-22 14:49:28 +00:00
'defaultValue' => ( $parameter -> isOptional () && ! $isVariadic ) ? $parameter -> getDefaultValue () : null ,
2016-03-12 20:10:13 +00:00
);
}
return $methodArgumentsMetadata ;
}
2015-08-24 02:36:41 +01:00
}