Skip to content

Commit

Permalink
- Added automatic enum label generation for enums
Browse files Browse the repository at this point in the history
  • Loading branch information
dash8x committed Mar 26, 2024
1 parent ff1f070 commit bcabbde
Show file tree
Hide file tree
Showing 5 changed files with 42 additions and 19 deletions.
2 changes: 2 additions & 0 deletions src/Enums/IsEnum.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,5 +6,7 @@ interface IsEnum
{
public static function labels(): array;

public static function getLabels(): array;

public function getLabel(): string;
}
20 changes: 20 additions & 0 deletions src/Enums/NativeEnumsTrait.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@


use BackedEnum;
use Illuminate\Support\Str;

trait NativeEnumsTrait
{
Expand All @@ -22,6 +23,25 @@ public static function getKeys(): array
return array_column(self::cases(), 'value');
}

public static function labels(): array
{
return static::getLabels();
}

public static function getLabels(): array
{
$cases = static::cases();

$labels = [];

/** @var static $case */
foreach ($cases as $case) {
$labels[$case->value] = __(slug_to_title($case->name));
}

return $labels;
}

public static function slugs(string|BackedEnum $input)
{
if ($input instanceof BackedEnum) {
Expand Down
10 changes: 0 additions & 10 deletions src/Enums/PublishStatuses.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,14 +11,4 @@ enum PublishStatuses: string implements IsEnum
const PENDING = 'pending';
const PUBLISHED = 'published';
const REJECTED = 'rejected';

public static function labels(): array
{
return [
self::DRAFT->value => __("Draft"),
self::PENDING->value => __("Pending"),
self::PUBLISHED->value => __("Published"),
self::REJECTED->value => __("Rejected"),
];
}
}
9 changes: 0 additions & 9 deletions src/Enums/UserStatuses.php
Original file line number Diff line number Diff line change
Expand Up @@ -32,13 +32,4 @@ public static function getMessageFromKey(string $key): string
{
return self::messages()[$key] ?? '';
}

public static function labels(): array
{
return [
self::APPROVED->value => __("Approved"),
self::PENDING->value => __("Pending"),
self::BANNED->value => __("Banned"),
];
}
}
20 changes: 20 additions & 0 deletions tests/Unit/EnumsTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
<?php

namespace Javaabu\Helpers\Tests\Unit;

use Javaabu\Helpers\Enums\UserStatuses;
use Javaabu\Helpers\Tests\TestCase;

class EnumsTest extends TestCase
{
/** @test */
public function it_can_generate_enum_label()
{
$this->assertEquals('Pending', UserStatuses::PENDING->getLabel());
$this->assertEquals([
'approved' => 'Approved',
'pending' => 'Pending',
'banned' => 'Banned'
], UserStatuses::getLabels());
}
}

0 comments on commit bcabbde

Please sign in to comment.