From e7af5be18f8d5f701f9e062c4b258cc1374383e0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rub=C3=A9n=20Robles?= Date: Fri, 17 Nov 2023 12:39:22 +0100 Subject: [PATCH] change GetsAttributes to have public method getDescription --- src/Enums/GetsAttributes.php | 17 ++++++++++------- tests/EnumsTest.php | 9 ++++++++- tests/Fixtures/MyEnum.php | 2 ++ 3 files changed, 20 insertions(+), 8 deletions(-) diff --git a/src/Enums/GetsAttributes.php b/src/Enums/GetsAttributes.php index 67d87e1..16bf260 100644 --- a/src/Enums/GetsAttributes.php +++ b/src/Enums/GetsAttributes.php @@ -2,7 +2,6 @@ namespace OpenSoutheners\LaravelHelpers\Enums; -use Illuminate\Support\Collection; use Illuminate\Support\Str; use ReflectionClassConstant; @@ -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; @@ -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; } } diff --git a/tests/EnumsTest.php b/tests/EnumsTest.php index 750e26a..7931a05 100644 --- a/tests/EnumsTest.php +++ b/tests/EnumsTest.php @@ -73,7 +73,7 @@ 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(); @@ -81,6 +81,13 @@ public function test_described_enum_to_array(): void $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)); diff --git a/tests/Fixtures/MyEnum.php b/tests/Fixtures/MyEnum.php index 9c29b67..0d62dbf 100644 --- a/tests/Fixtures/MyEnum.php +++ b/tests/Fixtures/MyEnum.php @@ -5,6 +5,8 @@ enum MyEnum { case First; + case Second; + case Third; }