| 1 |
<?php |
| 2 |
|
| 3 |
declare(strict_types=1); |
| 4 |
|
| 5 |
namespace WPDeveloper\BetterDocs\Dependencies\DI\Definition\Source; |
| 6 |
|
| 7 |
use WPDeveloper\BetterDocs\Dependencies\DI\Definition\ObjectDefinition; |
| 8 |
use WPDeveloper\BetterDocs\Dependencies\DI\Definition\ObjectDefinition\MethodInjection; |
| 9 |
use WPDeveloper\BetterDocs\Dependencies\DI\Definition\Reference; |
| 10 |
|
| 11 |
/** |
| 12 |
* Reads WPDeveloper\BetterDocs\Dependencies\DI class definitions using reflection. |
| 13 |
* |
| 14 |
* @author Matthieu Napoli <matthieu@mnapoli.fr> |
| 15 |
*/ |
| 16 |
class ReflectionBasedAutowiring implements DefinitionSource, Autowiring |
| 17 |
{ |
| 18 |
public function autowire(string $name, ObjectDefinition $definition = null) |
| 19 |
{ |
| 20 |
$className = $definition ? $definition->getClassName() : $name; |
| 21 |
|
| 22 |
if (!class_exists($className) && !interface_exists($className)) { |
| 23 |
return $definition; |
| 24 |
} |
| 25 |
|
| 26 |
$definition = $definition ?: new ObjectDefinition($name); |
| 27 |
|
| 28 |
// Constructor |
| 29 |
$class = new \ReflectionClass($className); |
| 30 |
$constructor = $class->getConstructor(); |
| 31 |
if ($constructor && $constructor->isPublic()) { |
| 32 |
$constructorInjection = MethodInjection::constructor($this->getParametersDefinition($constructor)); |
| 33 |
$definition->completeConstructorInjection($constructorInjection); |
| 34 |
} |
| 35 |
|
| 36 |
return $definition; |
| 37 |
} |
| 38 |
|
| 39 |
public function getDefinition(string $name) |
| 40 |
{ |
| 41 |
return $this->autowire($name); |
| 42 |
} |
| 43 |
|
| 44 |
/** |
| 45 |
* Autowiring cannot guess all existing definitions. |
| 46 |
*/ |
| 47 |
public function getDefinitions() : array |
| 48 |
{ |
| 49 |
return []; |
| 50 |
} |
| 51 |
|
| 52 |
/** |
| 53 |
* Read the type-hinting from the parameters of the function. |
| 54 |
*/ |
| 55 |
private function getParametersDefinition(\ReflectionFunctionAbstract $constructor) : array |
| 56 |
{ |
| 57 |
$parameters = []; |
| 58 |
|
| 59 |
foreach ($constructor->getParameters() as $index => $parameter) { |
| 60 |
// Skip optional parameters |
| 61 |
if ($parameter->isOptional()) { |
| 62 |
continue; |
| 63 |
} |
| 64 |
|
| 65 |
$parameterClass = $parameter->getType() && !$parameter->getType()->isBuiltin() ? new \ReflectionClass($parameter->getType()->getName()) : null; |
| 66 |
|
| 67 |
if ($parameterClass) { |
| 68 |
$parameters[$index] = new Reference($parameterClass->getName()); |
| 69 |
} |
| 70 |
} |
| 71 |
|
| 72 |
return $parameters; |
| 73 |
} |
| 74 |
} |
| 75 |
|