mirror of
https://github.com/archtechx/enums.git
synced 2025-12-12 22:54:04 +00:00
Metadata
This commit is contained in:
parent
cc5bba1912
commit
7b0871db00
7 changed files with 389 additions and 46 deletions
120
README.md
120
README.md
|
|
@ -7,6 +7,7 @@ A collection of enum helpers for PHP.
|
||||||
- [`Values`](#values)
|
- [`Values`](#values)
|
||||||
- [`Options`](#options)
|
- [`Options`](#options)
|
||||||
- [`From`](#from)
|
- [`From`](#from)
|
||||||
|
- [`Metadata`](#metadata)
|
||||||
|
|
||||||
You can read more about the idea on [Twitter](https://twitter.com/archtechx/status/1495158228757270528). I originally wanted to include the `InvokableCases` helper in [`archtechx/helpers`](https://github.com/archtechx/helpers), but it makes more sense to make it a separate dependency and use it *inside* the other package.
|
You can read more about the idea on [Twitter](https://twitter.com/archtechx/status/1495158228757270528). I originally wanted to include the `InvokableCases` helper in [`archtechx/helpers`](https://github.com/archtechx/helpers), but it makes more sense to make it a separate dependency and use it *inside* the other package.
|
||||||
|
|
||||||
|
|
@ -246,6 +247,125 @@ Role::tryFromName('GUEST'); // Role::GUEST
|
||||||
Role::tryFromName('TESTER'); // null
|
Role::tryFromName('TESTER'); // null
|
||||||
```
|
```
|
||||||
|
|
||||||
|
### Metadata
|
||||||
|
|
||||||
|
This trait lets you add metadata to enum cases.
|
||||||
|
|
||||||
|
#### Apply the trait on your enum
|
||||||
|
```php
|
||||||
|
use ArchTech\Enums\Metadata;
|
||||||
|
use ArchTech\Enums\Meta\Meta;
|
||||||
|
use App\Enums\MetaProperties\{Description, Color};
|
||||||
|
|
||||||
|
#[Meta(Description::class, Color::class)]
|
||||||
|
enum TaskStatus: int
|
||||||
|
{
|
||||||
|
use Metadata;
|
||||||
|
|
||||||
|
#[Description('Incomplete Task')] #[Color('red')]
|
||||||
|
case INCOMPLETE = 0;
|
||||||
|
|
||||||
|
#[Description('Completed Task')] #[Color('green')]
|
||||||
|
case COMPLETED = 1;
|
||||||
|
|
||||||
|
#[Description('Canceled Task')] #[Color('gray')]
|
||||||
|
case CANCELED = 2;
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Explanation:
|
||||||
|
- `Description` and `Color` are userland class attributes — meta properties
|
||||||
|
- The `#[Meta]` call enables those two meta properties on the enum
|
||||||
|
- Each case must have a defined description & color (in this example)
|
||||||
|
|
||||||
|
#### Access the metadata
|
||||||
|
|
||||||
|
```php
|
||||||
|
TaskStatus::INCOMPLETE->description(); // 'Incomplete Task'
|
||||||
|
TaskStatus::COMPLETED->color(); // 'green'
|
||||||
|
```
|
||||||
|
|
||||||
|
#### Creating meta properties
|
||||||
|
|
||||||
|
Each meta property (= attribute used on a case) needs to exist as a class.
|
||||||
|
```php
|
||||||
|
#[Attribute]
|
||||||
|
class Color extends MetaProperty {}
|
||||||
|
|
||||||
|
#[Attribute]
|
||||||
|
class Description extends MetaProperty {}
|
||||||
|
```
|
||||||
|
|
||||||
|
Inside the class, you can customize a few things. For instance, you may want to use a different method name than the one derived from the class name (`Description` becomes `description()` by default). To do that, override the `method()` method on the meta property:
|
||||||
|
```php
|
||||||
|
#[Attribute]
|
||||||
|
class Description extends MetaProperty
|
||||||
|
{
|
||||||
|
public static function method(): string
|
||||||
|
{
|
||||||
|
return 'note';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
With the code above, the description of a case will be accessible as `TaskStatus::INCOMPLETE->note()`.
|
||||||
|
|
||||||
|
Another thing you can customize is the passed value. For instance, to wrap a color name like `text-{$color}-500`, you'd add the following `transform()` method:
|
||||||
|
```php
|
||||||
|
#[Attribute]
|
||||||
|
class Color extends MetaProperty
|
||||||
|
{
|
||||||
|
protected function transform(mixed $value): mixed
|
||||||
|
{
|
||||||
|
return "text-{$color}-500";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
And now the returned color will be correctly transformed:
|
||||||
|
```php
|
||||||
|
TaskStatus::COMPLETED->color(); // 'text-green-500'
|
||||||
|
```
|
||||||
|
|
||||||
|
#### Use the `fromMeta()` method
|
||||||
|
```php
|
||||||
|
TaskStatus::fromMeta(Color::make('green')); // TaskStatus::COMPLETED
|
||||||
|
TaskStatus::fromMeta(Color::make('blue')); // Error: ValueError
|
||||||
|
```
|
||||||
|
|
||||||
|
#### Use the `tryFromMeta()` method
|
||||||
|
```php
|
||||||
|
TaskStatus::tryFromMeta(Color::make('green')); // TaskStatus::COMPLETED
|
||||||
|
TaskStatus::tryFromMeta(Color::make('blue')); // null
|
||||||
|
```
|
||||||
|
|
||||||
|
#### Recommendation: use annotations and traits
|
||||||
|
|
||||||
|
If you'd like to add better IDE support for the metadata getter methods, you can use `@method` annotations:
|
||||||
|
|
||||||
|
```php
|
||||||
|
/**
|
||||||
|
* @method string description()
|
||||||
|
* @method string color()
|
||||||
|
*/
|
||||||
|
#[Meta(Description::class, Color::class)]
|
||||||
|
enum TaskStatus: int
|
||||||
|
{
|
||||||
|
use Metadata;
|
||||||
|
|
||||||
|
#[Description('Incomplete Task')] #[Color('red')]
|
||||||
|
case INCOMPLETE = 0;
|
||||||
|
|
||||||
|
#[Description('Completed Task')] #[Color('green')]
|
||||||
|
case COMPLETED = 1;
|
||||||
|
|
||||||
|
#[Description('Canceled Task')] #[Color('gray')]
|
||||||
|
case CANCELED = 2;
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
And if you're using the same meta property in multiple enums, you can create a dedicated trait that includes this `@method` annotation.
|
||||||
|
|
||||||
## Development
|
## Development
|
||||||
|
|
||||||
Run all checks locally:
|
Run all checks locally:
|
||||||
|
|
|
||||||
22
src/Meta/Meta.php
Normal file
22
src/Meta/Meta.php
Normal file
|
|
@ -0,0 +1,22 @@
|
||||||
|
<?php
|
||||||
|
|
||||||
|
namespace ArchTech\Enums\Meta;
|
||||||
|
|
||||||
|
use Attribute;
|
||||||
|
|
||||||
|
#[Attribute(Attribute::TARGET_CLASS)]
|
||||||
|
class Meta
|
||||||
|
{
|
||||||
|
/** @var MetaProperty[] */
|
||||||
|
public array $metaProperties;
|
||||||
|
|
||||||
|
public function __construct(array|string ...$metaProperties) {
|
||||||
|
// When an array is passed, it'll be wrapped in an outer array due to the ...variadic parameter
|
||||||
|
if (isset($metaProperties[0]) && is_array($metaProperties[0])) {
|
||||||
|
// Extract the inner array
|
||||||
|
$metaProperties = $metaProperties[0];
|
||||||
|
}
|
||||||
|
|
||||||
|
$this->metaProperties = $metaProperties;
|
||||||
|
}
|
||||||
|
}
|
||||||
36
src/Meta/MetaProperty.php
Normal file
36
src/Meta/MetaProperty.php
Normal file
|
|
@ -0,0 +1,36 @@
|
||||||
|
<?php
|
||||||
|
|
||||||
|
namespace ArchTech\Enums\Meta;
|
||||||
|
|
||||||
|
abstract class MetaProperty
|
||||||
|
{
|
||||||
|
public function __construct(
|
||||||
|
public mixed $value,
|
||||||
|
) {
|
||||||
|
$this->value = $this->transform($value);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static function make(mixed $value): static
|
||||||
|
{
|
||||||
|
return new static($value);
|
||||||
|
}
|
||||||
|
|
||||||
|
protected function transform(mixed $value): mixed
|
||||||
|
{
|
||||||
|
// Feel free to override this to transform the value during instantiation
|
||||||
|
|
||||||
|
return $value;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Get the name of the accessor method */
|
||||||
|
public static function method(): string
|
||||||
|
{
|
||||||
|
if (property_exists(static::class, 'method')) {
|
||||||
|
return static::${'method'};
|
||||||
|
}
|
||||||
|
|
||||||
|
$parts = explode('\\', static::class);
|
||||||
|
|
||||||
|
return lcfirst(end($parts));
|
||||||
|
}
|
||||||
|
}
|
||||||
63
src/Meta/Reflection.php
Normal file
63
src/Meta/Reflection.php
Normal file
|
|
@ -0,0 +1,63 @@
|
||||||
|
<?php
|
||||||
|
|
||||||
|
namespace ArchTech\Enums\Meta;
|
||||||
|
|
||||||
|
use ReflectionAttribute;
|
||||||
|
use ReflectionEnumUnitCase;
|
||||||
|
use ReflectionObject;
|
||||||
|
|
||||||
|
class Reflection
|
||||||
|
{
|
||||||
|
/**
|
||||||
|
* Get the meta properties enabled on an Enum.
|
||||||
|
*
|
||||||
|
* @param Enum&\ArchTech\Enums\Metadata $enum
|
||||||
|
* @return string[]|array<\class-string<MetaProperty>>
|
||||||
|
*/
|
||||||
|
public static function metaProperties(mixed $enum): array
|
||||||
|
{
|
||||||
|
$reflection = new ReflectionObject($enum);
|
||||||
|
|
||||||
|
// Attributes of the `Meta` type
|
||||||
|
$attributes = array_values(array_filter(
|
||||||
|
$reflection->getAttributes(),
|
||||||
|
fn (ReflectionAttribute $attr) => $attr->getName() === Meta::class,
|
||||||
|
));
|
||||||
|
|
||||||
|
if ($attributes) {
|
||||||
|
return $attributes[0]->newInstance()->metaProperties;
|
||||||
|
}
|
||||||
|
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get the value of a meta property on the provided enum.
|
||||||
|
*
|
||||||
|
* @param \class-string<MetaProperty> $property
|
||||||
|
* @param Enum $enum
|
||||||
|
* @return mixed
|
||||||
|
*/
|
||||||
|
public static function metaValue(string $metaProperty, mixed $enum): mixed
|
||||||
|
{
|
||||||
|
// Find the case used by $enum
|
||||||
|
$reflection = new ReflectionEnumUnitCase($enum::class, $enum->name);
|
||||||
|
$attributes = $reflection->getAttributes();
|
||||||
|
|
||||||
|
// Instantiate each ReflectionAttribute
|
||||||
|
/** @var MetaProperty[] $properties */
|
||||||
|
$properties = array_map(fn (ReflectionAttribute $attr) => $attr->newInstance(), $attributes);
|
||||||
|
|
||||||
|
// Find the property that matches the $metaProperty class
|
||||||
|
$properties = array_filter($properties, fn (MetaProperty $property) => $property::class === $metaProperty);
|
||||||
|
|
||||||
|
// Reset array index
|
||||||
|
$properties = array_values($properties);
|
||||||
|
|
||||||
|
if ($properties) {
|
||||||
|
return $properties[0]->value;
|
||||||
|
}
|
||||||
|
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
43
src/Metadata.php
Normal file
43
src/Metadata.php
Normal file
|
|
@ -0,0 +1,43 @@
|
||||||
|
<?php
|
||||||
|
|
||||||
|
namespace ArchTech\Enums;
|
||||||
|
|
||||||
|
use ArchTech\Enums\Meta\MetaProperty;
|
||||||
|
use ValueError;
|
||||||
|
|
||||||
|
trait Metadata
|
||||||
|
{
|
||||||
|
/** Try to get the first case with this meta property value. */
|
||||||
|
public static function tryFromMeta(MetaProperty $metaProperty): static|null
|
||||||
|
{
|
||||||
|
foreach (static::cases() as $case) {
|
||||||
|
if (Meta\Reflection::metaValue($metaProperty::class, $case) === $metaProperty->value) {
|
||||||
|
return $case;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Get the first case with this meta property value. */
|
||||||
|
public static function fromMeta(MetaProperty $metaProperty): static
|
||||||
|
{
|
||||||
|
return static::tryFromMeta($metaProperty) ?? throw new ValueError(
|
||||||
|
'Enum ' . static::class . ' does not have a case with a meta property "' .
|
||||||
|
$metaProperty::class . '" of value "' . $metaProperty->value . '"'
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function __call(string $property, $arguments): mixed
|
||||||
|
{
|
||||||
|
$metaProperties = Meta\Reflection::metaProperties($this);
|
||||||
|
|
||||||
|
foreach ($metaProperties as $metaProperty) {
|
||||||
|
if ($metaProperty::method() === $property) {
|
||||||
|
return Meta\Reflection::metaValue($metaProperty, $this);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -1,67 +1,63 @@
|
||||||
<?php
|
<?php
|
||||||
|
|
||||||
/*
|
use ArchTech\Enums\{InvokableCases, Options, Names, Values, From, Metadata};
|
||||||
|--------------------------------------------------------------------------
|
use ArchTech\Enums\Meta\Meta;
|
||||||
| Test Case
|
use ArchTech\Enums\Meta\MetaProperty;
|
||||||
|--------------------------------------------------------------------------
|
|
||||||
|
|
|
||||||
| The closure you provide to your test functions is always bound to a specific PHPUnit test
|
|
||||||
| case class. By default, that class is "PHPUnit\Framework\TestCase". Of course, you may
|
|
||||||
| need to change it using the "uses()" function to bind a different classes or traits.
|
|
||||||
|
|
|
||||||
*/
|
|
||||||
|
|
||||||
use ArchTech\Enums\From;
|
|
||||||
use ArchTech\Enums\InvokableCases;
|
|
||||||
use ArchTech\Enums\Names;
|
|
||||||
use ArchTech\Enums\Options;
|
|
||||||
use ArchTech\Enums\Values;
|
|
||||||
|
|
||||||
uses(ArchTech\Enums\Tests\TestCase::class)->in('Pest');
|
uses(ArchTech\Enums\Tests\TestCase::class)->in('Pest');
|
||||||
|
|
||||||
/*
|
#[Attribute]
|
||||||
|--------------------------------------------------------------------------
|
class Color extends MetaProperty {}
|
||||||
| Expectations
|
|
||||||
|--------------------------------------------------------------------------
|
|
||||||
|
|
|
||||||
| When you're writing tests, you often need to check that values meet certain conditions. The
|
|
||||||
| "expect()" function gives you access to a set of "expectations" methods that you can use
|
|
||||||
| to assert different things. Of course, you may extend the Expectation API at any time.
|
|
||||||
|
|
|
||||||
*/
|
|
||||||
|
|
||||||
expect()->extend('toBeOne', function () {
|
#[Attribute]
|
||||||
return $this->toBe(1);
|
class Desc extends MetaProperty
|
||||||
});
|
|
||||||
|
|
||||||
/*
|
|
||||||
|--------------------------------------------------------------------------
|
|
||||||
| Functions
|
|
||||||
|--------------------------------------------------------------------------
|
|
||||||
|
|
|
||||||
| While Pest is very powerful out-of-the-box, you may have some testing code specific to your
|
|
||||||
| project that you don't want to repeat in every file. Here you can also expose helpers as
|
|
||||||
| global functions to help you to reduce the number of lines of code in your test files.
|
|
||||||
|
|
|
||||||
*/
|
|
||||||
|
|
||||||
function something()
|
|
||||||
{
|
{
|
||||||
// ..
|
public static function method(): string
|
||||||
|
{
|
||||||
|
return 'description';
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[Attribute]
|
||||||
|
class Instructions extends MetaProperty
|
||||||
|
{
|
||||||
|
public static string $method = 'help';
|
||||||
|
|
||||||
|
protected function transform(mixed $value): mixed
|
||||||
|
{
|
||||||
|
return 'Help: ' . $value;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @method string description()
|
||||||
|
* @method string color()
|
||||||
|
*/
|
||||||
|
#[Meta(Color::class, Desc::class)] // variadic syntax
|
||||||
enum Status: int
|
enum Status: int
|
||||||
{
|
{
|
||||||
use InvokableCases, Options, Names, Values, From;
|
use InvokableCases, Options, Names, Values, From, Metadata;
|
||||||
|
|
||||||
|
#[Color('orange')] #[Desc('Incomplete task')]
|
||||||
case PENDING = 0;
|
case PENDING = 0;
|
||||||
|
|
||||||
|
#[Color('green')] #[Desc('Completed task')]
|
||||||
|
#[Instructions('Illegal meta property — not enabled on the enum')]
|
||||||
case DONE = 1;
|
case DONE = 1;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[Meta([Color::class, Desc::class, Instructions::class])] // array
|
||||||
enum Role
|
enum Role
|
||||||
{
|
{
|
||||||
use InvokableCases, Options, Names, Values, From;
|
use InvokableCases, Options, Names, Values, From, Metadata;
|
||||||
|
|
||||||
|
#[Color('indigo')]
|
||||||
|
#[Desc('Administrator')]
|
||||||
|
#[Instructions('Administrators can manage the entire account')]
|
||||||
case ADMIN;
|
case ADMIN;
|
||||||
|
|
||||||
|
#[Color('gray')]
|
||||||
|
#[Desc('Read-only guest')]
|
||||||
|
#[Instructions('Guest users can only view the existing records')]
|
||||||
case GUEST;
|
case GUEST;
|
||||||
}
|
}
|
||||||
|
|
|
||||||
63
tests/Pest/MetadataTest.php
Normal file
63
tests/Pest/MetadataTest.php
Normal file
|
|
@ -0,0 +1,63 @@
|
||||||
|
<?php
|
||||||
|
|
||||||
|
test('pure enums can have metadata on cases', function () {
|
||||||
|
expect(Role::ADMIN->color())->toBe('indigo');
|
||||||
|
expect(Role::GUEST->color())->toBe('gray');
|
||||||
|
|
||||||
|
expect(Role::ADMIN->description())->toBe('Administrator');
|
||||||
|
expect(Role::GUEST->description())->toBe('Read-only guest');
|
||||||
|
|
||||||
|
expect(Role::ADMIN->help())->toBe('Help: Administrators can manage the entire account');
|
||||||
|
expect(Role::GUEST->help())->toBe('Help: Guest users can only view the existing records');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('backed enums can have metadata on cases', function () {
|
||||||
|
expect(Status::DONE->color())->toBe('green');
|
||||||
|
expect(Status::PENDING->color())->toBe('orange');
|
||||||
|
|
||||||
|
expect(Status::PENDING->description())->toBe('Incomplete task');
|
||||||
|
expect(Status::DONE->description())->toBe('Completed task');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('meta properties must be enabled on the enum to be usable on cases', function () {
|
||||||
|
expect(Role::ADMIN->help())->not()->toBeNull(); // enabled
|
||||||
|
expect(Status::DONE->help())->toBeNull(); // not enabled
|
||||||
|
});
|
||||||
|
|
||||||
|
test('meta properties can transform arguments', function () {
|
||||||
|
expect(
|
||||||
|
Instructions::make('Administrators can manage the entire account')->value
|
||||||
|
)->toStartWith('Help: ');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('meta properties can customize the method name using a method', function () {
|
||||||
|
expect(Desc::method())->toBe('description');
|
||||||
|
expect(Status::DONE->desc())->toBeNull();
|
||||||
|
expect(Status::DONE->description())->not()->toBeNull();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('meta properties can customize the method name using a property', function () {
|
||||||
|
expect(Instructions::method())->toBe('help');
|
||||||
|
expect(Role::ADMIN->instructions())->toBeNull();
|
||||||
|
expect(Role::ADMIN->help())->not()->toBeNull();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('enums can be instantiated from metadata', function () {
|
||||||
|
expect(Role::fromMeta(Color::make('indigo')))->toBe(Role::ADMIN);
|
||||||
|
expect(Role::fromMeta(Color::make('gray')))->toBe(Role::GUEST);
|
||||||
|
|
||||||
|
expect(Status::fromMeta(Desc::make('Incomplete task')))->toBe(Status::PENDING);
|
||||||
|
expect(Status::fromMeta(Desc::make('Completed task')))->toBe(Status::DONE);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('enums can be instantiated from metadata using tryFromMeta')
|
||||||
|
->expect(Role::tryFromMeta(Color::make('indigo')))
|
||||||
|
->toBe(Role::ADMIN);
|
||||||
|
|
||||||
|
test('fromMeta throws an exception when the enum cannot be instantiated', function () {
|
||||||
|
Role::fromMeta(Color::make('foobar'));
|
||||||
|
})->throws(ValueError::class, 'Enum Role does not have a case with a meta property "Color" of value "foobar"');
|
||||||
|
|
||||||
|
test('tryFromMeta silently fails when the enum cannot be instantiated')
|
||||||
|
->expect(Role::tryFromMeta(Color::make('foobar')))
|
||||||
|
->toBe(null);
|
||||||
Loading…
Add table
Add a link
Reference in a new issue