bakabot/attribute

Provides accessors to single-value PHP Attributes.

2.0.1 2025-07-10 20:06 UTC

This package is auto-updated.

Last update: 2025-07-10 20:09:44 UTC


README

Provides accessors to single-value PHP Attributes.

Installation

composer require bakabot/attribute

Flavors

For ease of use the library provides three identical way of accessing attribute values:

namespace Bakabot\Attribute;

// functions
attr(string|object $class, string $attribute, mixed $default = null): mixed;
getValue(string|object $class, string $attribute, mixed $default = null): mixed;

// public static method
AttributeValueGetter::getAttributeValue(string|object $class, string $attribute, mixed $default = null): mixed;

Usage

Works on both instances and class names:

use function Bakabot\Attribute\getValue;

#[Attribute]
class SomeAttribute
{
    public function __construct(private string $value) {}
}

#[SomeAttribute('foo')]
class MyClass {}

$value = getValue(MyClass::class, 'SomeAttribute'); // "foo"
$value = getValue(new MyClass(), 'SomeAttribute'); // "foo"

Throws a MissingAttributeException if the attribute is not set:

getValue(MyClass::class, 'UnknownAttribute');
// uncaught Bakabot\Attribute\Exception\MissingAttributeException

Unless you provide a default value as a third argument:

getValue(MyClass::class, 'UnknownAttribute', 'foo'); // "foo"
getValue(MyClass::class, 'UnknownAttribute', 'bar'); // "bar"
getValue(MyClass::class, 'UnknownAttribute', 'baz'); // "baz"

For heavy lifting or lazy evaluation, a default value can be any callable, in which case its resulting value will be cached.

getValue(MyClass::class, 'UnknownAttribute', fn () => 'bar'); // "bar"
getValue(MyClass::class, 'UnknownAttribute'); // still "bar"

If the attribute is repeatable, it'll return an array of that attribute's values:

use function Bakabot\Attribute\getValue;

#[Attribute(Attribute::IS_REPEATABLE)]
final class RepeatableAttribute
{
    public function __construct(private string $value) {}
}

#[RepeatableAttribute('foo')]
#[RepeatableAttribute('bar')]
class MyClass {}

$value = getValue(MyClass::class, 'RepeatableAttribute'); // ["foo", "bar"]