Skip to content

Commit

Permalink
- make status_slug and status_name attributes work
Browse files Browse the repository at this point in the history
  • Loading branch information
athphane committed Mar 7, 2024
1 parent 7f8332f commit 27b5fcd
Show file tree
Hide file tree
Showing 3 changed files with 110 additions and 0 deletions.
10 changes: 10 additions & 0 deletions src/Enums/IsEnum.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
<?php

namespace Javaabu\Helpers\Enums;

interface IsEnum
{
public static function labels(): array;

public function getLabel(): string;
}
56 changes: 56 additions & 0 deletions src/Enums/NativeEnumsTrait.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
<?php

namespace Javaabu\Helpers\Enums;


use BackedEnum;

trait NativeEnumsTrait
{
public function getLabel(): string
{
return self::labels()[$this->value];
}

public static function getLabelFromKey(string $key): string
{
return self::labels()[$key] ?? '';
}

public static function getKeys(): array
{
return array_column(self::cases(), 'value');
}

public static function slugs(string|BackedEnum $input)
{
if ($input instanceof BackedEnum) {
$input = $input->value;
}

$status_slugs = [];
$cases = self::cases();

foreach ($cases as $case) {
$status_slugs[$case->value] = $case->value;
}

return $status_slugs[$input] ?? '';
}

public static function names(string|BackedEnum $input)
{
if ($input instanceof BackedEnum) {
$input = $input->value;
}

$status_names = [];
$cases = self::cases();

foreach ($cases as $case) {
$status_names[$case->value] = $case->getLabel();
}

return $status_names[$input] ?? '';
}
}
44 changes: 44 additions & 0 deletions src/Enums/UserStatuses.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
<?php

namespace Javaabu\Helpers\Enums;


enum UserStatuses: string implements IsEnum
{
use NativeEnumsTrait;

case APPROVED = 'approved';
case PENDING = 'pending';
case BANNED = 'banned';

/**
* Initialize Messages
*/
public static function messages(): array
{
return [
self::APPROVED->value => __('Your account is approved.'),
self::PENDING->value => __('Your account needs to be approved before you can access it.'),
self::BANNED->value => __('Your account has been banned.'),
];
}

public function getMessage(): string
{
return self::messages()[$this->value];
}

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"),
];
}
}

0 comments on commit 27b5fcd

Please sign in to comment.