HookAttributeService.php 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. <?php
  2. declare(strict_types=1);
  3. namespace SixShop\Core\Service;
  4. use ReflectionClass;
  5. use ReflectionMethod;
  6. use SixShop\Core\Attribute\Hook;
  7. use think\Event;
  8. use think\exception\ClassNotFoundException;
  9. use function SixShop\Core\extension_name_list;
  10. readonly class HookAttributeService
  11. {
  12. public function __construct(private AutoloadService $autoloadService, private Event $event)
  13. {
  14. }
  15. public function init(): void
  16. {
  17. foreach (extension_name_list() as $extensionName) {
  18. try {
  19. $extension = $this->autoloadService->getExtension($extensionName);
  20. } catch (ClassNotFoundException) {
  21. continue;
  22. }
  23. if (!$extension->available()) {
  24. continue;
  25. }
  26. $hookClassList = $extension->getHooks();
  27. foreach ($hookClassList as $hookClass) {
  28. $ref = new ReflectionClass($hookClass);
  29. foreach ($ref->getMethods(ReflectionMethod::IS_PUBLIC) as $method) {
  30. $attributes = $method->getAttributes(Hook::class);
  31. foreach ($attributes as $attr) {
  32. $hookNameList = (array)$attr->newInstance()->hook;
  33. foreach ($hookNameList as $hookName) {
  34. $this->event->listen($hookName, [$hookClass, $method->getName()]);
  35. }
  36. }
  37. }
  38. }
  39. }
  40. }
  41. }