1 | <?php |
||
17 | class ServiceInjectingSlumberAnnotation extends SlumberAnnotation |
||
18 | { |
||
19 | /** |
||
20 | * The ID of the request service |
||
21 | * |
||
22 | * @var string |
||
23 | * |
||
24 | * @Annotation\Required() |
||
25 | */ |
||
26 | public $service; |
||
27 | |||
28 | /** |
||
29 | * The class that the service must be an instance of |
||
30 | * |
||
31 | * @var string |
||
32 | * |
||
33 | * @Annotation\Required() |
||
34 | */ |
||
35 | public $ofClass; |
||
36 | |||
37 | /** |
||
38 | * @return string |
||
39 | */ |
||
40 | public function getServiceDefinition() |
||
44 | |||
45 | /** |
||
46 | * @return null |
||
47 | */ |
||
48 | public function getServiceDefinitionDefault() |
||
52 | |||
53 | /** |
||
54 | * @return string |
||
55 | */ |
||
56 | public function getServiceClassDefinition() |
||
60 | |||
61 | /** |
||
62 | * @return string |
||
63 | */ |
||
64 | public function getServiceClassDefinitionDefault() |
||
68 | |||
69 | /** |
||
70 | * |
||
71 | * @param ValidationContext $context |
||
72 | * |
||
73 | * @throws SlumberException |
||
74 | */ |
||
75 | public function validate($context) |
||
76 | { |
||
77 | $service = $this->getServiceDefinition(); |
||
78 | $ofClass = $this->getServiceClassDefinition(); |
||
79 | |||
80 | if (empty($service) || empty($ofClass)) { |
||
81 | throw $this->createValidationException( |
||
82 | $context, |
||
83 | "you must set the 'service' and the 'ofClass'" |
||
84 | ); |
||
85 | } |
||
86 | |||
87 | if (! $context->getProvider()->has($service)) { |
||
88 | throw $this->createValidationException( |
||
89 | $context, |
||
90 | "you requested the non-existing service '$service'" |
||
91 | ); |
||
92 | } |
||
93 | |||
94 | if (! class_exists($ofClass) && ! interface_exists($ofClass)) { |
||
95 | throw $this->createValidationException( |
||
96 | $context, |
||
97 | "you requested a service instance of the non-existing class or interface '$ofClass'" |
||
98 | ); |
||
99 | } |
||
100 | |||
101 | $instance = $this->getService($context->getProvider()); |
||
102 | $check = new IsInstanceOf($ofClass); |
||
103 | |||
104 | if (! $check->__invoke($instance)) { |
||
105 | throw $this->createValidationException( |
||
106 | $context, |
||
107 | "the service '$service' is not of instance '$ofClass' but is '" . |
||
108 | (\is_object($instance) ? \get_class($instance) : \gettype($instance)) . "'" |
||
109 | ); |
||
110 | } |
||
111 | } |
||
112 | |||
113 | /** |
||
114 | * @param ContainerInterface $provider |
||
115 | * |
||
116 | * @return mixed |
||
117 | */ |
||
118 | protected function getService(ContainerInterface $provider) |
||
124 | } |
||
125 |