Passed
Push — master ( 44846f...2a05cb )
by Andrea Marco
02:04 queued 14s
created

SelfAware::resolveItem()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 1

Importance

Changes 0
Metric Value
eloc 4
c 0
b 0
f 0
dl 0
loc 6
ccs 4
cts 4
cp 1
rs 10
cc 1
nc 1
nop 1
crap 1
1
<?php
2
3
namespace Cerbero\Enum\Concerns;
4
5
use BackedEnum;
0 ignored issues
show
Bug introduced by
The type BackedEnum was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
6
use Cerbero\Enum\Attributes\Meta;
7
use ReflectionAttribute;
8
use ReflectionEnum;
0 ignored issues
show
Bug introduced by
The type ReflectionEnum was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
9
use ReflectionEnumUnitCase;
0 ignored issues
show
Bug introduced by
The type ReflectionEnumUnitCase was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
10
use ReflectionMethod;
11
use ValueError;
12
13
/**
14
 * The trait to make an enum self-aware.
15
 */
16
trait SelfAware
17
{
18
    /**
19
     * Determine whether the enum is pure.
20
     */
21 98
    public static function isPure(): bool
22
    {
23 98
        return !self::isBacked();
24
    }
25
26
    /**
27
     * Determine whether the enum is backed.
28
     */
29 98
    public static function isBacked(): bool
30
    {
31 98
        return is_subclass_of(self::class, BackedEnum::class);
32
    }
33
34
    /**
35
     * Determine whether the enum is backed by integer.
36
     */
37 1
    public static function isBackedByInteger(): bool
38
    {
39 1
        return (new ReflectionEnum(self::class))->getBackingType()?->getName() === 'int';
40
    }
41
42
    /**
43
     * Determine whether the enum is backed by string.
44
     */
45 1
    public static function isBackedByString(): bool
46
    {
47 1
        return (new ReflectionEnum(self::class))->getBackingType()?->getName() === 'string';
48
    }
49
50
    /**
51
     * Retrieve all the meta names of the enum.
52
     *
53
     * @return string[]
54
     */
55 3
    public static function metaNames(): array
56
    {
57 3
        $meta = [];
58 3
        $enum = new ReflectionEnum(self::class);
59
60 3
        foreach ($enum->getAttributes(Meta::class, ReflectionAttribute::IS_INSTANCEOF) as $attribute) {
61 3
            array_push($meta, ...$attribute->newInstance()->names());
62
        }
63
64 2
        foreach ($enum->getCases() as $case) {
65 2
            foreach ($case->getAttributes(Meta::class, ReflectionAttribute::IS_INSTANCEOF) as $attribute) {
66 2
                array_push($meta, ...$attribute->newInstance()->names());
67
            }
68
        }
69
70 2
        foreach ($enum->getMethods(ReflectionMethod::IS_PUBLIC) as $method) {
71 2
            if (! $method->isStatic() && $method->getFileName() == $enum->getFileName()) {
72 2
                $meta[] = $method->getShortName();
73
            }
74
        }
75
76 2
        return array_values(array_unique($meta));
77
    }
78
79
    /**
80
     * Retrieve the given item of this case.
81
     *
82
     * @template TItemValue
83
     *
84
     * @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...
85
     * @return TItemValue
86
     * @throws ValueError
87
     */
88 44
    public function resolveItem(callable|string $item): mixed
89
    {
90
        return match (true) {
91 44
            is_callable($item) => $item($this),
92 34
            property_exists($this, $item) => $this->$item,
0 ignored issues
show
Bug introduced by
It seems like $item can also be of type callable; however, parameter $property of property_exists() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

92
            property_exists($this, /** @scrutinizer ignore-type */ $item) => $this->$item,
Loading history...
93 44
            default => $this->resolveMeta($item),
0 ignored issues
show
Bug introduced by
It seems like $item can also be of type callable; however, parameter $meta of Cerbero\Enum\Concerns\SelfAware::resolveMeta() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

93
            default => $this->resolveMeta(/** @scrutinizer ignore-type */ $item),
Loading history...
94
        };
95
    }
96
97
    /**
98
     * Retrieve the given meta of this case.
99
     *
100
     * @throws ValueError
101
     */
102 35
    public function resolveMeta(string $meta): mixed
103
    {
104 35
        $enum = new ReflectionEnum($this);
105 35
        $enumFileName = $enum->getFileName();
106
107 35
        foreach ($enum->getMethods(ReflectionMethod::IS_PUBLIC) as $method) {
108 35
            if (! $method->isStatic() && $method->getFileName() == $enumFileName && $method->getShortName() == $meta) {
109 7
                return $this->$meta();
110
            }
111
        }
112
113 28
        return $this->resolveMetaAttribute($meta);
114
    }
115
116
    /**
117
     * Retrieve the given meta from the attributes.
118
     *
119
     * @throws ValueError
120
     */
121 40
    public function resolveMetaAttribute(string $meta): mixed
122
    {
123 40
        $case = new ReflectionEnumUnitCase($this, $this->name);
124
125 40
        foreach ($case->getAttributes(Meta::class, ReflectionAttribute::IS_INSTANCEOF) as $attribute) {
126 40
            if (($metadata = $attribute->newInstance())->has($meta)) {
127 36
                return $metadata->get($meta);
128
            }
129
        }
130
131 36
        foreach ($case->getEnum()->getAttributes(Meta::class, ReflectionAttribute::IS_INSTANCEOF) as $attribute) {
132 36
            if (($metadata = $attribute->newInstance())->has($meta)) {
133 32
                return $metadata->get($meta);
134
            }
135
        }
136
137 4
        throw new ValueError(sprintf('"%s" is not a valid meta for enum "%s"', $meta, self::class));
138
    }
139
140
    /**
141
     * Retrieve the value of a backed case or the name of a pure case.
142
     */
143 2
    public function value(): string|int
144
    {
145 2
        return $this->value ?? $this->name;
146
    }
147
}
148