Passed
Pull Request — master (#149)
by Pierre
03:06
created

Constant::supports()   A

Complexity

Conditions 5
Paths 4

Size

Total Lines 21
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 11
CRAP Score 5

Importance

Changes 2
Bugs 0 Features 0
Metric Value
cc 5
eloc 10
c 2
b 0
f 0
nc 4
nop 1
dl 0
loc 21
ccs 11
cts 11
cp 1
crap 5
rs 9.6111
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Knp\DictionaryBundle\ValueTransformer;
6
7
use Knp\DictionaryBundle\ValueTransformer;
8
use ReflectionClass;
9
10
final class Constant implements ValueTransformer
11
{
12
    /**
13
     * @var string
14
     */
15
    private $pattern = '/^(?P<class>.*)::(?P<constant>.*)$/';
16
17 5
    public function supports($value): bool
18
    {
19 5
        if (!\is_string($value)) {
20 1
            return false;
21
        }
22
23 4
        $matches = [];
24
25 4
        if (0 === preg_match($this->pattern, $value, $matches)) {
26 1
            return false;
27
        }
28
29 3
        if (!class_exists($matches['class']) && !interface_exists($matches['class'])) {
30 1
            return false;
31
        }
32
33 2
        $constants = (new ReflectionClass($matches['class']))
34 2
            ->getConstants()
35
        ;
36
37 2
        return \array_key_exists($matches['constant'], $constants);
38
    }
39
40 1
    public function transform($value)
41
    {
42 1
        $matches = [];
43
44 1
        preg_match($this->pattern, $value, $matches);
45
46 1
        return (new ReflectionClass($matches['class']))
47 1
            ->getConstant($matches['constant'])
48
        ;
49
    }
50
}
51