|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
/* |
|
4
|
|
|
* This file is part of Symplify |
|
5
|
|
|
* Copyright (c) 2016 Tomas Votruba (http://tomasvotruba.cz). |
|
6
|
|
|
*/ |
|
7
|
|
|
|
|
8
|
|
|
namespace Symplify\DefaultAutowire\DependencyInjection\Compiler; |
|
9
|
|
|
|
|
10
|
|
|
use ReflectionClass; |
|
11
|
|
|
use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface; |
|
12
|
|
|
use Symfony\Component\DependencyInjection\ContainerBuilder; |
|
13
|
|
|
use Symfony\Component\DependencyInjection\Definition; |
|
14
|
|
|
|
|
15
|
|
|
final class TurnOnAutowireCompilerPass implements CompilerPassInterface |
|
16
|
|
|
{ |
|
17
|
|
|
/** |
|
18
|
|
|
* {@inheritdoc} |
|
19
|
|
|
*/ |
|
20
|
2 |
|
public function process(ContainerBuilder $containerBuilder) |
|
21
|
|
|
{ |
|
22
|
2 |
|
foreach ($containerBuilder->getDefinitions() as $definition) { |
|
23
|
2 |
|
if ($this->shouldDefinitionBeAutowired($definition)) { |
|
24
|
2 |
|
$definition->setAutowired(true); |
|
25
|
|
|
} |
|
26
|
|
|
} |
|
27
|
2 |
|
} |
|
28
|
|
|
|
|
29
|
|
|
/** |
|
30
|
|
|
* @return bool |
|
31
|
|
|
*/ |
|
32
|
2 |
|
private function shouldDefinitionBeAutowired(Definition $definition) |
|
33
|
|
|
{ |
|
34
|
2 |
|
if (!$this->isDefinitionValid($definition)) { |
|
35
|
|
|
return false; |
|
36
|
|
|
} |
|
37
|
|
|
|
|
38
|
2 |
|
$classReflection = new ReflectionClass($definition->getClass()); |
|
39
|
2 |
|
if (!$classReflection->hasMethod('__construct')) { |
|
40
|
1 |
|
return false; |
|
41
|
|
|
} |
|
42
|
|
|
|
|
43
|
2 |
|
if ($this->areAllConstructorArgumentsRequired($definition, $classReflection)) { |
|
44
|
|
|
return false; |
|
45
|
2 |
|
} |
|
46
|
2 |
|
|
|
47
|
|
|
return true; |
|
48
|
2 |
|
} |
|
49
|
|
|
|
|
50
|
|
|
/** |
|
51
|
|
|
* @return bool |
|
52
|
2 |
|
*/ |
|
53
|
|
|
private function isDefinitionValid(Definition $definition) |
|
54
|
|
|
{ |
|
55
|
|
|
if (null === $definition->getClass()) { |
|
56
|
|
|
return false; |
|
57
|
|
|
} |
|
58
|
2 |
|
|
|
59
|
|
|
if ($definition->isAbstract()) { |
|
60
|
2 |
|
return false; |
|
61
|
|
|
} |
|
62
|
|
|
|
|
63
|
|
|
if (!class_exists($definition->getClass())) { |
|
64
|
2 |
|
return false; |
|
65
|
|
|
} |
|
66
|
|
|
|
|
67
|
|
|
return true; |
|
68
|
2 |
|
} |
|
69
|
|
|
|
|
70
|
|
|
/** |
|
71
|
|
|
* @return bool |
|
72
|
2 |
|
*/ |
|
73
|
|
|
private function areAllConstructorArgumentsRequired(Definition $definition, ReflectionClass $classReflection) |
|
74
|
|
|
{ |
|
75
|
|
|
$constructorMethodReflection = $classReflection->getConstructor(); |
|
76
|
|
|
|
|
77
|
|
|
$constructorArgumentsCount = count($definition->getArguments()); |
|
78
|
|
|
$constructorRequiredArgumentsCount = $constructorMethodReflection->getNumberOfRequiredParameters(); |
|
79
|
|
|
|
|
80
|
|
|
if ($constructorArgumentsCount === $constructorRequiredArgumentsCount) { |
|
81
|
|
|
return true; |
|
82
|
|
|
} |
|
83
|
|
|
|
|
84
|
|
|
return false; |
|
85
|
|
|
} |
|
86
|
|
|
} |
|
87
|
|
|
|