| 1 |
<?php |
| 2 |
|
| 3 |
declare(strict_types=1); |
| 4 |
|
| 5 |
namespace WPDeveloper\BetterDocs\Dependencies\DI\Definition\Resolver; |
| 6 |
|
| 7 |
use WPDeveloper\BetterDocs\Dependencies\DI\Definition\DecoratorDefinition; |
| 8 |
use WPDeveloper\BetterDocs\Dependencies\DI\Definition\Definition; |
| 9 |
use WPDeveloper\BetterDocs\Dependencies\DI\Definition\Exception\InvalidDefinition; |
| 10 |
use WPDeveloper\BetterDocs\Dependencies\Psr\Container\ContainerInterface; |
| 11 |
|
| 12 |
/** |
| 13 |
* Resolves a decorator definition to a value. |
| 14 |
* |
| 15 |
* @since 5.0 |
| 16 |
* @author Matthieu Napoli <matthieu@mnapoli.fr> |
| 17 |
*/ |
| 18 |
class DecoratorResolver implements DefinitionResolver |
| 19 |
{ |
| 20 |
/** |
| 21 |
* @var ContainerInterface |
| 22 |
*/ |
| 23 |
private $container; |
| 24 |
|
| 25 |
/** |
| 26 |
* @var DefinitionResolver |
| 27 |
*/ |
| 28 |
private $definitionResolver; |
| 29 |
|
| 30 |
/** |
| 31 |
* The resolver needs a container. This container will be passed to the factory as a parameter |
| 32 |
* so that the factory can access other entries of the container. |
| 33 |
* |
| 34 |
* @param DefinitionResolver $definitionResolver Used to resolve nested definitions. |
| 35 |
*/ |
| 36 |
public function __construct(ContainerInterface $container, DefinitionResolver $definitionResolver) |
| 37 |
{ |
| 38 |
$this->container = $container; |
| 39 |
$this->definitionResolver = $definitionResolver; |
| 40 |
} |
| 41 |
|
| 42 |
/** |
| 43 |
* Resolve a decorator definition to a value. |
| 44 |
* |
| 45 |
* This will call the callable of the definition and pass it the decorated entry. |
| 46 |
* |
| 47 |
* @param DecoratorDefinition $definition |
| 48 |
* |
| 49 |
* {@inheritdoc} |
| 50 |
*/ |
| 51 |
public function resolve(Definition $definition, array $parameters = []) |
| 52 |
{ |
| 53 |
$callable = $definition->getCallable(); |
| 54 |
|
| 55 |
if (! is_callable($callable)) { |
| 56 |
throw new InvalidDefinition(sprintf( |
| 57 |
'The decorator "%s" is not callable', |
| 58 |
$definition->getName() |
| 59 |
)); |
| 60 |
} |
| 61 |
|
| 62 |
$decoratedDefinition = $definition->getDecoratedDefinition(); |
| 63 |
|
| 64 |
if (! $decoratedDefinition instanceof Definition) { |
| 65 |
if (! $definition->getName()) { |
| 66 |
throw new InvalidDefinition('Decorators cannot be nested in another definition'); |
| 67 |
} |
| 68 |
|
| 69 |
throw new InvalidDefinition(sprintf( |
| 70 |
'Entry "%s" decorates nothing: no previous definition with the same name was found', |
| 71 |
$definition->getName() |
| 72 |
)); |
| 73 |
} |
| 74 |
|
| 75 |
$decorated = $this->definitionResolver->resolve($decoratedDefinition, $parameters); |
| 76 |
|
| 77 |
return call_user_func($callable, $decorated, $this->container); |
| 78 |
} |
| 79 |
|
| 80 |
public function isResolvable(Definition $definition, array $parameters = []) : bool |
| 81 |
{ |
| 82 |
return true; |
| 83 |
} |
| 84 |
} |
| 85 |
|