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