1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace Cerbero\LaravelEnum; |
6
|
|
|
|
7
|
|
|
use Cerbero\Enum\Enums as BaseEnums; |
8
|
|
|
use Closure; |
9
|
|
|
use Illuminate\Support\Facades\Lang; |
10
|
|
|
use Throwable; |
11
|
|
|
use UnitEnum; |
12
|
|
|
|
13
|
|
|
/** |
14
|
|
|
* The global behavior for all enums. |
15
|
|
|
*/ |
16
|
|
|
class Enums extends BaseEnums |
17
|
|
|
{ |
18
|
|
|
/** |
19
|
|
|
* The logic to resolve the translation key. |
20
|
|
|
* |
21
|
|
|
* @var ?Closure(UnitEnum $case): string |
22
|
|
|
*/ |
23
|
|
|
protected static ?Closure $translateFrom = null; |
24
|
|
|
|
25
|
|
|
/** |
26
|
|
|
* Set the logic to resolve the translation key. |
27
|
|
|
* |
28
|
|
|
* @param Closure(UnitEnum $case): string $callback |
29
|
|
|
*/ |
30
|
1 |
|
public static function translateFrom(Closure $callback): void |
31
|
|
|
{ |
32
|
1 |
|
static::$translateFrom = $callback; |
33
|
|
|
} |
34
|
|
|
|
35
|
|
|
/** |
36
|
|
|
* Retrieve the translation key for the given case. |
37
|
|
|
*/ |
38
|
4 |
|
public static function resolveTranslationKey(UnitEnum $case): string |
39
|
|
|
{ |
40
|
4 |
|
return static::$translateFrom |
41
|
1 |
|
? (static::$translateFrom)($case) |
42
|
4 |
|
: sprintf('enums.%s.%s', $case::class, $case->name); |
|
|
|
|
43
|
|
|
} |
44
|
|
|
|
45
|
|
|
/** |
46
|
|
|
* Handle the call to an inaccessible case method. |
47
|
|
|
* |
48
|
|
|
* @param array<array-key, mixed> $arguments |
|
|
|
|
49
|
|
|
*/ |
50
|
4 |
|
public static function handleCall(object $case, string $name, array $arguments): mixed |
51
|
|
|
{ |
52
|
4 |
|
if (static::$onCall) { |
53
|
|
|
return (static::$onCall)($case, $name, $arguments); |
54
|
|
|
} |
55
|
|
|
|
56
|
|
|
try { |
57
|
|
|
/** @phpstan-ignore method.notFound */ |
58
|
4 |
|
return $case->resolveMetaAttribute($name); |
59
|
4 |
|
} catch (Throwable $e) { |
60
|
4 |
|
$key = static::resolveTranslationKey($case) . ".{$name}"; |
61
|
|
|
|
62
|
4 |
|
return ($key === $translation = Lang::get($key, ...$arguments)) ? throw $e : $translation; |
|
|
|
|
63
|
|
|
} |
64
|
|
|
} |
65
|
|
|
} |
66
|
|
|
|