Constant::extract()   A
last analyzed

Complexity

Conditions 4
Paths 5

Size

Total Lines 11
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 4

Importance

Changes 2
Bugs 0 Features 0
Metric Value
cc 4
eloc 6
c 2
b 0
f 0
nc 5
nop 1
dl 0
loc 11
ccs 2
cts 2
cp 1
crap 4
rs 10
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Knp\DictionaryBundle\ValueTransformer;
6
7
use Knp\DictionaryBundle\ValueTransformer;
8
9
final class Constant implements ValueTransformer
10
{
11
    private const PATTERN = '/^(.*)::(.*)$/';
12
13
    public function supports(mixed $value): bool
14
    {
15
        if (!\is_string($value)) {
16
            return false;
17 5
        }
18
19 5
        $matches = [];
0 ignored issues
show
Unused Code introduced by
The assignment to $matches is dead and can be removed.
Loading history...
20 1
21
        if (null === $matches = $this->extract($value)) {
22
            return false;
23 4
        }
24
25 4
        [$class, $constant] = $matches;
26 1
27
        $constants = (new \ReflectionClass($class))->getConstants();
28
29 3
        return \array_key_exists($constant, $constants);
30 1
    }
31
32
    public function transform(mixed $value): mixed
33 2
    {
34 2
        if (null === $matches = $this->extract($value)) {
35
            throw new \Exception(\sprintf('Unable to resolve constant %s.', $value));
36
        }
37 2
38
        [$class, $constant] = $matches;
39
40 1
        return (new \ReflectionClass($class))->getConstant($constant);
41
    }
42 1
43
    /**
44 1
     * @return ?array{class-string, string}
0 ignored issues
show
Documentation Bug introduced by
The doc comment ?array{class-string, string} at position 2 could not be parsed: Expected ':' at position 2, but found 'class-string'.
Loading history...
45
     */
46 1
    private function extract(string $value): ?array
47 1
    {
48
        if (preg_match(self::PATTERN, $value, $matches)) {
49
            [, $class, $constant] = $matches;
50
51
            return class_exists($class) || interface_exists($class)
52
                ? [$class, $constant]
53
                : null;
54
        }
55
56
        return null;
57
    }
58
}
59