carusogabriel · GitHub

Implements all changes that have been proposed by @beberlei and myself in RFC: Attribute Amendments. Support for attribute grouping is left out because Shorter Attribute Syntax will likely make it obsolete. All new features are demonstrated in this little example:

<<Attribute(Attribute::TARGET_FUNCTION | Attribute::IS_REPEATABLE)>>
class A1 { }
$ref = new ReflectionFunction(<<A1>> <<A1>> function () {});
foreach ($ref->getAttributes(A1::class) as $a) {
    var_dump($a->getName(), $a->getTarget(), $a->isRepeated(), $a->newInstance());
}

These are the extensions to existing APIs:

final class Attribute
{
    public const TARGET_CLASS = 1;
    public const TARGET_FUNCTION = (1 << 1);
    public const TARGET_METHOD = (1 << 2);
    public const TARGET_PROPERTY = (1 << 3);
    public const TARGET_CLASS_CONST = (1 << 4);
    public const TARGET_PARAMETER = (1 << 5);
    public const TARGET_ALL = ((1 << 6) - 1);
    public const IS_REPEATABLE = (1 << 6);
    public int $flags;
    public function __construct(int $flags = self::TARGET_ALL) { }
}
final class ReflectionAttribute
{
    ...
    public function getTarget(): int { }
    public function isRepeated(): bool {}
}

Read the original on github.com ↗