Skip to content

Commit

Permalink
change GetsAttributes to have public method getDescription
Browse files Browse the repository at this point in the history
  • Loading branch information
d8vjork committed Nov 17, 2023
1 parent 4745f91 commit e7af5be
Show file tree
Hide file tree
Showing 3 changed files with 20 additions and 8 deletions.
17 changes: 10 additions & 7 deletions src/Enums/GetsAttributes.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@

namespace OpenSoutheners\LaravelHelpers\Enums;

use Illuminate\Support\Collection;
use Illuminate\Support\Str;
use ReflectionClassConstant;

Expand All @@ -14,14 +13,14 @@ trait GetsAttributes
/**
* Get description from enum case's attributes.
*/
private static function getDescription(self $enum): string
public function getDescription(): string
{
$reflection = new ReflectionClassConstant(self::class, $enum->name);
$reflection = new ReflectionClassConstant($this, $this->name);

$classAttributes = $reflection->getAttributes(Description::class);

if (count($classAttributes) === 0) {
return Str::headline($enum->value);
return Str::headline($this->value);
}

return $classAttributes[0]->newInstance()->description;
Expand All @@ -34,8 +33,12 @@ private static function getDescription(self $enum): string
*/
public static function asSelectArray(): array
{
return Collection::make(self::cases())
->mapWithKeys(fn ($case, $key): array => [$case->value => self::getDescription($case)])
->toArray();
$selectArray = [];

foreach (self::cases() as $case) {
$selectArray[$case->value] = $case->getDescription($case);
}

return $selectArray;
}
}
9 changes: 8 additions & 1 deletion tests/EnumsTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -73,14 +73,21 @@ public function test_enum_to_array(): void
enum_to_array(Post::class);
}

public function test_described_enum_to_array(): void
public function test_described_enum_using_as_select_array(): void
{
$myBackedEnumArr = MyBackedEnum::asSelectArray();

$this->assertIsArray($myBackedEnumArr);
$this->assertEmpty(array_diff($myBackedEnumArr, ['first' => 'First point', 'second' => 'Second point', 'third' => 'Third point']));
}

public function test_described_enum_case_get_description()
{
$this->assertEquals('First point', MyBackedEnum::First->getDescription());
$this->assertEquals('Second point', MyBackedEnum::Second->getDescription());
$this->assertEquals('Third point', MyBackedEnum::Third->getDescription());
}

public function test_enum_values(): void
{
$this->assertFalse(enum_values(MyEnum::First));
Expand Down
2 changes: 2 additions & 0 deletions tests/Fixtures/MyEnum.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@
enum MyEnum
{
case First;

case Second;

case Third;
}

0 comments on commit e7af5be

Please sign in to comment.