Passed
Push — master ( 2d5896...727481 )
by Andrea Marco
15:11 queued 12:24
created

SelfAware::resolveTranslation()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 11
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 2

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 2
eloc 5
c 1
b 0
f 0
nc 2
nop 1
dl 0
loc 11
ccs 6
cts 6
cp 1
crap 2
rs 10
1
<?php
2
3
namespace Cerbero\LaravelEnum\Concerns;
4
5
use Cerbero\Enum\Concerns\SelfAware as BaseSelfAware;
6
use Cerbero\LaravelEnum\Enums;
7
use Illuminate\Support\Facades\Lang;
8
use ValueError;
9
10
/**
11
 * The trait to make an enum self-aware.
12
 */
13
trait SelfAware
14
{
15
    use BaseSelfAware {
16
        BaseSelfAware::resolveItem as baseResolveItem;
17
    }
18
19
    /**
20
     * Retrieve the given item of this case.
21
     *
22
     * @template TItemValue
23
     *
24
     * @param (callable(self): TItemValue)|string $item
0 ignored issues
show
Documentation Bug introduced by
The doc comment (callable(self): TItemValue)|string at position 1 could not be parsed: Expected ')' at position 1, but found 'callable'.
Loading history...
25
     * @return TItemValue
26
     * @throws ValueError
27
     */
28 2
    public function resolveItem(callable|string $item): mixed
29
    {
30
        try {
31 2
            return $this->baseResolveItem($item);
32 2
        } catch (ValueError $e) {
33
            try {
34
                /** @var string $item */
35 2
                return $this->resolveTranslation($item);
36 1
            } catch (ValueError) {
37 1
                throw $e;
38
            }
39
        }
40
    }
41
42
    /**
43
     * Retrieve the translation of the given key for this case.
44
     *
45
     * @throws ValueError
46
     */
47 2
    public function resolveTranslation(string $key): string
48
    {
49 2
        $translationKey = Enums::resolveTranslationKey($this, $key);
50
        /** @var string */
51 2
        $translation = Lang::get($translationKey);
52
53 2
        if ($translation !== $translationKey) {
54 1
            return $translation;
55
        }
56
57 1
        throw new ValueError(sprintf('The case %s::%s has no "%s" translation set', self::class, $this->name, $key));
58
    }
59
}
60