Passed
Push — feature/second-release ( 8aa292...512416 )
by Andrea Marco
03:19
created

Enums::translateFrom()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 1
c 1
b 0
f 0
dl 0
loc 3
ccs 2
cts 2
cp 1
rs 10
cc 1
nc 1
nop 1
crap 1
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
0 ignored issues
show
Documentation Bug introduced by
The doc comment array<array-key, mixed> at position 2 could not be parsed: Unknown type name 'array-key' at position 2 in array<array-key, mixed>.
Loading history...
49
     */
50 5
    public static function handleCall(object $case, string $name, array $arguments): mixed
51
    {
52 5
        if (static::$onCall) {
53 1
            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
            /** @var UnitEnum $case */
61 4
            $key = static::resolveTranslationKey($case) . ".{$name}";
62
63
            /** @var array{array<string, mixed>, ?string, bool} $arguments */
64 4
            return ($key === $translation = Lang::get($key, ...$arguments)) ? throw $e : $translation;
65
        }
66
    }
67
}
68