Skip to content

Instantly share code, notes, and snippets.

@vudaltsov
Created May 17, 2026 13:54
Show Gist options
  • Select an option

  • Save vudaltsov/6dbab6a69967a55037fc7d6b13bd593b to your computer and use it in GitHub Desktop.

Select an option

Save vudaltsov/6dbab6a69967a55037fc7d6b13bd593b to your computer and use it in GitHub Desktop.
<?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