Total Complexity | 83 |
Total Lines | 585 |
Duplicated Lines | 0 % |
Changes | 13 | ||
Bugs | 2 | Features | 0 |
Complex classes like Container often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.
Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.
While breaking up the class, it is a good idea to analyze how other classes use Container, and based on these observations, apply Extract Interface, too.
1 | <?php |
||
34 | final class Container implements ContainerInterface |
||
35 | { |
||
36 | private const META_TAGS = 'tags'; |
||
37 | private const META_RESET = 'reset'; |
||
38 | private const ALLOWED_META = [self::META_TAGS, self::META_RESET]; |
||
39 | |||
40 | /** |
||
41 | * @var DefinitionStorage Storage of object definitions. |
||
42 | */ |
||
43 | private DefinitionStorage $definitions; |
||
44 | |||
45 | /** |
||
46 | * @var array Used to collect IDs of objects instantiated during build |
||
47 | * to detect circular references. |
||
48 | */ |
||
49 | private array $building = []; |
||
50 | |||
51 | /** |
||
52 | * @var bool $validate If definitions should be validated. |
||
53 | */ |
||
54 | private bool $validate; |
||
55 | |||
56 | private array $instances = []; |
||
57 | |||
58 | private CompositeContainer $delegates; |
||
59 | |||
60 | /** |
||
61 | * @var array Tagged service IDs. The structure is `['tagID' => ['service1', 'service2']]`. |
||
62 | * @psalm-var array<string, list<string>> |
||
63 | */ |
||
64 | private array $tags; |
||
65 | |||
66 | /** |
||
67 | * @var Closure[] |
||
68 | */ |
||
69 | private array $resetters = []; |
||
70 | private bool $useResettersFromMeta = true; |
||
71 | |||
72 | /** |
||
73 | * @param ContainerConfigInterface $config Container configuration. |
||
74 | * |
||
75 | * @throws InvalidConfigException If configuration is not valid. |
||
76 | */ |
||
77 | public function __construct(ContainerConfigInterface $config) |
||
91 | } |
||
92 | |||
93 | /** |
||
94 | * Returns a value indicating whether the container has the definition of the specified name. |
||
95 | * |
||
96 | * @param string $id Class name, interface name or alias name. |
||
97 | * |
||
98 | * @return bool Whether the container is able to provide instance of class specified. |
||
99 | * |
||
100 | * @see addDefinition() |
||
101 | */ |
||
102 | public function has(string $id): bool |
||
103 | { |
||
104 | if (TagHelper::isTagAlias($id)) { |
||
105 | $tag = TagHelper::extractTagFromAlias($id); |
||
106 | return isset($this->tags[$tag]); |
||
107 | } |
||
108 | |||
109 | try { |
||
110 | return $this->definitions->has($id); |
||
111 | } catch (CircularReferenceException) { |
||
112 | return true; |
||
113 | } |
||
114 | } |
||
115 | |||
116 | /** |
||
117 | * Returns an instance by either interface name or alias. |
||
118 | * |
||
119 | * Same instance of the class will be returned each time this method is called. |
||
120 | * |
||
121 | * @param string $id The interface or an alias name that was previously registered. |
||
122 | * |
||
123 | * @throws BuildingException |
||
124 | * @throws CircularReferenceException |
||
125 | * @throws InvalidConfigException |
||
126 | * @throws NotFoundExceptionInterface |
||
127 | * @throws NotInstantiableException |
||
128 | * |
||
129 | * @return mixed|object An instance of the requested interface. |
||
130 | * |
||
131 | * @psalm-template T |
||
132 | * @psalm-param string|class-string<T> $id |
||
133 | * @psalm-return ($id is class-string ? T : mixed) |
||
134 | */ |
||
135 | public function get(string $id) |
||
187 | } |
||
188 | |||
189 | /** |
||
190 | * Sets a definition to the container. Definition may be defined multiple ways. |
||
191 | * |
||
192 | * @param string $id ID to set definition for. |
||
193 | * @param mixed $definition Definition to set. |
||
194 | * |
||
195 | * @throws InvalidConfigException |
||
196 | * |
||
197 | * @see DefinitionNormalizer::normalize() |
||
198 | */ |
||
199 | private function addDefinition(string $id, mixed $definition): void |
||
200 | { |
||
201 | /** @var mixed $definition */ |
||
202 | [$definition, $meta] = DefinitionParser::parse($definition); |
||
203 | if ($this->validate) { |
||
204 | $this->validateDefinition($definition, $id); |
||
205 | $this->validateMeta($meta); |
||
206 | } |
||
207 | /** |
||
208 | * @psalm-var array{reset?:Closure,tags?:string[]} $meta |
||
209 | */ |
||
210 | |||
211 | if (isset($meta[self::META_TAGS])) { |
||
212 | $this->setDefinitionTags($id, $meta[self::META_TAGS]); |
||
213 | } |
||
214 | if (isset($meta[self::META_RESET])) { |
||
215 | $this->setDefinitionResetter($id, $meta[self::META_RESET]); |
||
216 | } |
||
217 | |||
218 | unset($this->instances[$id]); |
||
219 | $this->addDefinitionToStorage($id, $definition); |
||
220 | } |
||
221 | |||
222 | /** |
||
223 | * Sets multiple definitions at once. |
||
224 | * |
||
225 | * @param array $config Definitions indexed by their IDs. |
||
226 | * |
||
227 | * @throws InvalidConfigException |
||
228 | */ |
||
229 | private function addDefinitions(array $config): void |
||
230 | { |
||
231 | /** @var mixed $definition */ |
||
232 | foreach ($config as $id => $definition) { |
||
233 | if ($this->validate && !is_string($id)) { |
||
234 | throw new InvalidConfigException( |
||
235 | sprintf( |
||
236 | 'Key must be a string. %s given.', |
||
237 | get_debug_type($id) |
||
238 | ) |
||
239 | ); |
||
240 | } |
||
241 | /** @var string $id */ |
||
242 | |||
243 | $this->addDefinition($id, $definition); |
||
244 | } |
||
245 | } |
||
246 | |||
247 | /** |
||
248 | * Set container delegates. |
||
249 | * |
||
250 | * Each delegate must is a callable in format "function (ContainerInterface $container): ContainerInterface". |
||
251 | * The container instance returned is used in case a service can not be found in primary container. |
||
252 | * |
||
253 | * @param array $delegates |
||
254 | * |
||
255 | * @throws InvalidConfigException |
||
256 | */ |
||
257 | private function setDelegates(array $delegates): void |
||
258 | { |
||
259 | $this->delegates = new CompositeContainer(); |
||
260 | foreach ($delegates as $delegate) { |
||
261 | if (!$delegate instanceof Closure) { |
||
262 | throw new InvalidConfigException( |
||
263 | 'Delegate must be callable in format "function (ContainerInterface $container): ContainerInterface".' |
||
264 | ); |
||
265 | } |
||
266 | |||
267 | /** @var ContainerInterface */ |
||
268 | $delegate = $delegate($this); |
||
269 | |||
270 | if (!$delegate instanceof ContainerInterface) { |
||
271 | throw new InvalidConfigException( |
||
272 | 'Delegate callable must return an object that implements ContainerInterface.' |
||
273 | ); |
||
274 | } |
||
275 | |||
276 | $this->delegates->attach($delegate); |
||
277 | } |
||
278 | $this->definitions->setDelegateContainer($this->delegates); |
||
279 | } |
||
280 | |||
281 | /** |
||
282 | * @param mixed $definition Definition to validate. |
||
283 | * @param string|null $id ID of the definition to validate. |
||
284 | * |
||
285 | * @throws InvalidConfigException |
||
286 | */ |
||
287 | private function validateDefinition(mixed $definition, ?string $id = null): void |
||
288 | { |
||
289 | if (is_array($definition) && isset($definition[DefinitionParser::IS_PREPARED_ARRAY_DEFINITION_DATA])) { |
||
290 | /** @var mixed $class */ |
||
291 | $class = $definition['class']; |
||
292 | |||
293 | /** @var mixed $constructorArguments */ |
||
294 | $constructorArguments = $definition['__construct()']; |
||
295 | |||
296 | /** |
||
297 | * @var array $methodsAndProperties Is always array for prepared array definition data. |
||
298 | * |
||
299 | * @see DefinitionParser::parse() |
||
300 | */ |
||
301 | $methodsAndProperties = $definition['methodsAndProperties']; |
||
302 | |||
303 | $definition = array_merge( |
||
304 | $class === null ? [] : [ArrayDefinition::CLASS_NAME => $class], |
||
305 | [ArrayDefinition::CONSTRUCTOR => $constructorArguments], |
||
306 | $methodsAndProperties, |
||
307 | ); |
||
308 | } |
||
309 | |||
310 | if ($definition instanceof ExtensibleService) { |
||
311 | throw new InvalidConfigException( |
||
312 | 'Invalid definition. ExtensibleService is only allowed in provider extensions.' |
||
313 | ); |
||
314 | } |
||
315 | |||
316 | DefinitionValidator::validate($definition, $id); |
||
317 | } |
||
318 | |||
319 | /** |
||
320 | * @throws InvalidConfigException |
||
321 | */ |
||
322 | private function validateMeta(array $meta): void |
||
323 | { |
||
324 | /** @var mixed $value */ |
||
325 | foreach ($meta as $key => $value) { |
||
326 | if (!in_array($key, self::ALLOWED_META, true)) { |
||
327 | throw new InvalidConfigException( |
||
328 | sprintf( |
||
329 | 'Invalid definition: metadata "%s" is not allowed. Did you mean "%s()" or "$%s"?', |
||
330 | $key, |
||
331 | $key, |
||
332 | $key, |
||
333 | ) |
||
334 | ); |
||
335 | } |
||
336 | |||
337 | if ($key === self::META_TAGS) { |
||
338 | $this->validateDefinitionTags($value); |
||
339 | } |
||
340 | |||
341 | if ($key === self::META_RESET) { |
||
342 | $this->validateDefinitionReset($value); |
||
343 | } |
||
344 | } |
||
345 | } |
||
346 | |||
347 | /** |
||
348 | * @throws InvalidConfigException |
||
349 | */ |
||
350 | private function validateDefinitionTags(mixed $tags): void |
||
351 | { |
||
352 | if (!is_array($tags)) { |
||
353 | throw new InvalidConfigException( |
||
354 | sprintf( |
||
355 | 'Invalid definition: tags should be array of strings, %s given.', |
||
356 | get_debug_type($tags) |
||
357 | ) |
||
358 | ); |
||
359 | } |
||
360 | |||
361 | foreach ($tags as $tag) { |
||
362 | if (!is_string($tag)) { |
||
363 | throw new InvalidConfigException('Invalid tag. Expected a string, got ' . var_export($tag, true) . '.'); |
||
364 | } |
||
365 | } |
||
366 | } |
||
367 | |||
368 | /** |
||
369 | * @throws InvalidConfigException |
||
370 | */ |
||
371 | private function validateDefinitionReset(mixed $reset): void |
||
372 | { |
||
373 | if (!$reset instanceof Closure) { |
||
374 | throw new InvalidConfigException( |
||
375 | sprintf( |
||
376 | 'Invalid definition: "reset" should be closure, %s given.', |
||
377 | get_debug_type($reset) |
||
378 | ) |
||
379 | ); |
||
380 | } |
||
381 | } |
||
382 | |||
383 | /** |
||
384 | * @throws InvalidConfigException |
||
385 | */ |
||
386 | private function setTags(array $tags): void |
||
422 | } |
||
423 | |||
424 | /** |
||
425 | * @psalm-param string[] $tags |
||
426 | */ |
||
427 | private function setDefinitionTags(string $id, array $tags): void |
||
428 | { |
||
429 | foreach ($tags as $tag) { |
||
430 | if (!isset($this->tags[$tag]) || !in_array($id, $this->tags[$tag], true)) { |
||
431 | $this->tags[$tag][] = $id; |
||
432 | } |
||
433 | } |
||
434 | } |
||
435 | |||
436 | private function setDefinitionResetter(string $id, Closure $resetter): void |
||
437 | { |
||
438 | $this->resetters[$id] = $resetter; |
||
439 | } |
||
440 | |||
441 | /** |
||
442 | * Add definition to storage. |
||
443 | * |
||
444 | * @see $definitions |
||
445 | * |
||
446 | * @param string $id ID to set definition for. |
||
447 | * @param mixed|object $definition Definition to set. |
||
448 | */ |
||
449 | private function addDefinitionToStorage(string $id, $definition): void |
||
450 | { |
||
451 | $this->definitions->set($id, $definition); |
||
452 | |||
453 | if ($id === StateResetter::class) { |
||
454 | $this->useResettersFromMeta = false; |
||
455 | } |
||
456 | } |
||
457 | |||
458 | /** |
||
459 | * Creates new instance by either interface name or alias. |
||
460 | * |
||
461 | * @param string $id The interface or an alias name that was previously registered. |
||
462 | * |
||
463 | * @throws CircularReferenceException |
||
464 | * @throws InvalidConfigException |
||
465 | * @throws NotFoundExceptionInterface |
||
466 | * |
||
467 | * @return mixed|object New built instance of the specified class. |
||
468 | * |
||
469 | * @internal |
||
470 | */ |
||
471 | private function build(string $id) |
||
472 | { |
||
473 | if (TagHelper::isTagAlias($id)) { |
||
474 | return $this->getTaggedServices($id); |
||
475 | } |
||
476 | |||
477 | if (isset($this->building[$id])) { |
||
478 | if ($id === ContainerInterface::class) { |
||
479 | return $this; |
||
480 | } |
||
481 | throw new CircularReferenceException(sprintf( |
||
482 | 'Circular reference to "%s" detected while building: %s.', |
||
483 | $id, |
||
484 | implode(', ', array_keys($this->building)) |
||
485 | )); |
||
486 | } |
||
487 | |||
488 | $this->building[$id] = 1; |
||
489 | try { |
||
490 | /** @var mixed $object */ |
||
491 | $object = $this->buildInternal($id); |
||
492 | } finally { |
||
493 | unset($this->building[$id]); |
||
494 | } |
||
495 | |||
496 | return $object; |
||
497 | } |
||
498 | |||
499 | private function getTaggedServices(string $tagAlias): array |
||
500 | { |
||
501 | $tag = TagHelper::extractTagFromAlias($tagAlias); |
||
502 | $services = []; |
||
503 | if (isset($this->tags[$tag])) { |
||
504 | foreach ($this->tags[$tag] as $service) { |
||
505 | /** @var mixed */ |
||
506 | $services[] = $this->get($service); |
||
507 | } |
||
508 | } |
||
509 | |||
510 | return $services; |
||
511 | } |
||
512 | |||
513 | /** |
||
514 | * @throws InvalidConfigException |
||
515 | * @throws NotFoundExceptionInterface |
||
516 | * |
||
517 | * @return mixed|object |
||
518 | */ |
||
519 | private function buildInternal(string $id) |
||
520 | { |
||
521 | if ($this->definitions->has($id)) { |
||
522 | $definition = DefinitionNormalizer::normalize($this->definitions->get($id), $id); |
||
523 | |||
524 | return $definition->resolve($this->get(ContainerInterface::class)); |
||
525 | } |
||
526 | |||
527 | throw new NotFoundException($id, $this->definitions->getBuildStack()); |
||
528 | } |
||
529 | |||
530 | /** |
||
531 | * @throws CircularReferenceException |
||
532 | * @throws InvalidConfigException |
||
533 | */ |
||
534 | private function addProviders(array $providers): void |
||
578 | } |
||
579 | } |
||
580 | } |
||
581 | |||
582 | /** |
||
583 | * Builds service provider by definition. |
||
584 | * |
||
585 | * @param mixed $provider Class name or instance of provider. |
||
586 | * |
||
587 | * @throws InvalidConfigException If provider argument is not valid. |
||
588 | * |
||
589 | * @return ServiceProviderInterface Instance of service provider. |
||
590 | */ |
||
591 | private function buildProvider(mixed $provider): ServiceProviderInterface |
||
619 | } |
||
620 | } |
||
621 |