Created
May 17, 2026 13:54
-
-
Save vudaltsov/6dbab6a69967a55037fc7d6b13bd593b to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?php | |
| #[Attribute(Attribute::TARGET_FUNCTION | Attribute::TARGET_METHOD)] | |
| final readonly class Handler | |
| { | |
| /** | |
| * @param ?class-string $messageClass | |
| */ | |
| public function __construct( | |
| public ?string $messageClass = null | |
| ) {} | |
| } | |
| final readonly class HandlerMetadata | |
| { | |
| public static function fromAttribute(ReflectionFunctionAbstract $function): ?self | |
| { | |
| $attribute = $function->getAttributes(Handler::class)[0] ?? null; | |
| if ($attribute === null) { | |
| return null; | |
| } | |
| $messageClass = $attribute->newInstance()->messageClass; | |
| if ($messageClass === null) { | |
| return null; | |
| } | |
| return new self($messageClass); | |
| } | |
| public static function fromSignature(ReflectionFunctionAbstract $function): ?self | |
| { | |
| $messageParameter = $function->getParameters()[0] ?? null; | |
| if ($messageParameter === null) { | |
| return null; | |
| } | |
| $messageClass = (string) $messageParameter->getType(); | |
| if (!class_exists($messageClass)) { | |
| return null; | |
| } | |
| return new self($messageClass); | |
| } | |
| /** | |
| * @param class-string $messageClass | |
| */ | |
| public function __construct( | |
| public string $messageClass, | |
| ) {} | |
| } | |
| $function = new ReflectionFunction(myHandler(...)); | |
| $metadata = HandlerMetadata::fromAttribute($function) | |
| ?? HandlerMetadata::fromSignature($function) | |
| ?? throw new \LogicException('Failed to infer metadata for myHandler()'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment