|
| 1 | +<?php |
| 2 | + |
| 3 | +declare(strict_types=1); |
| 4 | + |
| 5 | +/* |
| 6 | + * This file is part of the zenstruck/foundry package. |
| 7 | + * |
| 8 | + * (c) Kevin Bond <[email protected]> |
| 9 | + * |
| 10 | + * For the full copyright and license information, please view the LICENSE |
| 11 | + * file that was distributed with this source code. |
| 12 | + */ |
| 13 | + |
| 14 | +namespace Zenstruck\Foundry\Hooks; |
| 15 | + |
| 16 | +use Symfony\Component\DependencyInjection\ServiceLocator; |
| 17 | + |
| 18 | +/** |
| 19 | + * @author Nicolas PHILIPPE <[email protected]> |
| 20 | + * |
| 21 | + * @internal |
| 22 | + */ |
| 23 | +final class HooksRegistry |
| 24 | +{ |
| 25 | + public function __construct( |
| 26 | + /** @var ServiceLocator<list<callable(HookEvent<object>): void>> */ |
| 27 | + private ServiceLocator $serviceLocator, |
| 28 | + ) { |
| 29 | + } |
| 30 | + |
| 31 | + /** |
| 32 | + * @param HookEvent<object> $hookEvent |
| 33 | + */ |
| 34 | + public function callHooks(HookEvent $hookEvent): void |
| 35 | + { |
| 36 | + foreach ($this->resolveHooks($hookEvent) as $hook) { |
| 37 | + ($hook)($hookEvent); |
| 38 | + } |
| 39 | + } |
| 40 | + |
| 41 | + public static function hookClassSpecificIndex(string $hookEventClass, string $objectClass): string |
| 42 | + { |
| 43 | + return "{$hookEventClass}-{$objectClass}"; |
| 44 | + } |
| 45 | + |
| 46 | + /** |
| 47 | + * @param HookEvent<object> $hookEvent |
| 48 | + * @return list<callable(HookEvent<object>): void> |
| 49 | + */ |
| 50 | + private function resolveHooks(HookEvent $hookEvent): array |
| 51 | + { |
| 52 | + $objectSpecificIndex = self::hookClassSpecificIndex($hookEvent::class, $hookEvent->getObjectClass()); |
| 53 | + |
| 54 | + return [ |
| 55 | + ...$this->serviceLocator->has($hookEvent::class) ? $this->serviceLocator->get($hookEvent::class) : [], |
| 56 | + ...$this->serviceLocator->has($objectSpecificIndex) ? $this->serviceLocator->get($objectSpecificIndex) : [], |
| 57 | + ]; |
| 58 | + } |
| 59 | +} |
0 commit comments