Code Coverage |
||||||||||
Lines |
Functions and Methods |
Classes and Traits |
||||||||
| Total | |
52.63% |
10 / 19 |
|
50.00% |
1 / 2 |
CRAP | |
0.00% |
0 / 1 |
| UseContextKey | |
52.63% |
10 / 19 |
|
50.00% |
1 / 2 |
27.30 | |
0.00% |
0 / 1 |
| getContextKey | |
100.00% |
8 / 8 |
|
100.00% |
1 / 1 |
6 | |||
| getContextKeyForType | |
18.18% |
2 / 11 |
|
0.00% |
0 / 1 |
25.72 | |||
| 1 | <?php |
| 2 | namespace Apie\Core\Metadata\Concerns; |
| 3 | |
| 4 | use Apie\Core\Attributes\Context; |
| 5 | use Apie\Core\Context\ApieContext; |
| 6 | use Apie\Core\Exceptions\IndexNotFoundException; |
| 7 | use Apie\Core\Exceptions\InvalidTypeException; |
| 8 | use ReflectionNamedType; |
| 9 | use ReflectionParameter; |
| 10 | use ReflectionType; |
| 11 | use ReflectionUnionType; |
| 12 | |
| 13 | trait UseContextKey |
| 14 | { |
| 15 | /** |
| 16 | * @phpstan-return ($returnNull is true ? string|null : string) |
| 17 | */ |
| 18 | private function getContextKey(ApieContext $apieContext, ReflectionParameter $parameter, bool $returnNull = true): ?string |
| 19 | { |
| 20 | foreach ($parameter->getAttributes(Context::class) as $attribute) { |
| 21 | $contextKey = $attribute->newInstance()->contextKey; |
| 22 | if (null !== $contextKey) { |
| 23 | return $contextKey; |
| 24 | } |
| 25 | } |
| 26 | $type = $parameter->getType(); |
| 27 | if ($type === null || ($type instanceof ReflectionNamedType && $type->isBuiltin())) { |
| 28 | return $parameter->name; |
| 29 | } |
| 30 | |
| 31 | return $this->getContextKeyForType($apieContext, $type, $returnNull); |
| 32 | } |
| 33 | |
| 34 | private function getContextKeyForType(ApieContext $apieContext, ReflectionType $type, bool $returnNull = true): ?string |
| 35 | { |
| 36 | if ($type instanceof ReflectionNamedType) { |
| 37 | return $type->getName(); |
| 38 | } |
| 39 | if ($type instanceof ReflectionUnionType) { |
| 40 | foreach ($type->getTypes() as $subtype) { |
| 41 | $key = $this->getContextKeyForType($apieContext, $subtype); |
| 42 | if ($key !== null) { |
| 43 | return $key; |
| 44 | } |
| 45 | } |
| 46 | if ($returnNull) { |
| 47 | return null; |
| 48 | } |
| 49 | throw new IndexNotFoundException((string) $type); |
| 50 | } |
| 51 | throw new InvalidTypeException($type, 'ReflectionNamedType|ReflectionUnionType'); |
| 52 | } |
| 53 | } |