Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: Add support for default values on metadata properties #23

Merged
merged 1 commit into from
Jul 15, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions src/Meta/MetaProperty.php
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,11 @@ final public function __construct(
$this->value = $this->transform($value);
}

public static function defaultValue(): mixed
{
return null;
}

public static function make(mixed $value): static
{
return new static($value);
Expand Down
2 changes: 1 addition & 1 deletion src/Meta/Reflection.php
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,6 @@ public static function metaValue(string $metaProperty, mixed $enum): mixed
return $properties[0]->value;
}

return null;
return $metaProperty::defaultValue() ?? null;
}
}
30 changes: 30 additions & 0 deletions tests/Pest.php
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,17 @@ protected function transform(mixed $value): mixed
}
}

#[Attribute]
class IsActive extends MetaProperty
{
public static string $method = 'isActive';

public static function defaultValue(): mixed
{
return false;
}
}

/**
* @method string description()
* @method string color()
Expand Down Expand Up @@ -62,6 +73,25 @@ enum Role
case GUEST;
}

#[Meta([IsActive::class])]
enum ReferenceType: int
{
use InvokableCases, Options, Names, Values, From, Metadata, Comparable;

#[IsActive(true)]
case ACTIVE_TYPE = 1;

case INACTIVE_TYPE = 0;
}

#[Meta([Desc::class])]
enum RoleWithoutAttribute
{
use InvokableCases, Options, Names, Values, From, Metadata, Comparable;

case ADMIN;
}

enum MultiWordSnakeCaseEnum
{
use Options;
Expand Down
10 changes: 9 additions & 1 deletion tests/Pest/MetadataTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -60,4 +60,12 @@

test('tryFromMeta silently fails when the enum cannot be instantiated')
->expect(Role::tryFromMeta(Color::make('foobar')))
->toBe(null);
->toBeNull();

test('metadata properties return null if missing on the case')
->expect(RoleWithoutAttribute::ADMIN->desc())
->toBeNull();

test('metadata can have default values')
->expect(ReferenceType::INACTIVE_TYPE->isActive())
->toBeFalse();
Loading