Completed
Pull Request — master (#33)
by Marco
01:51
created

ConstantValueChanged::compare()   A

Complexity

Conditions 2
Paths 1

Size

Total Lines 19
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 19
c 0
b 0
f 0
rs 9.4285
cc 2
eloc 13
nc 1
nop 2
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Roave\ApiCompare\Comparator\BackwardsCompatibility\ClassBased;
6
7
use Assert\Assert;
8
use Roave\ApiCompare\Change;
9
use Roave\ApiCompare\Changes;
10
use Roave\BetterReflection\Reflection\ReflectionClass;
11
use Roave\BetterReflection\Reflection\ReflectionClassConstant;
12
13
final class ConstantValueChanged implements ClassBased
14
{
15
    public function compare(ReflectionClass $fromClass, ReflectionClass $toClass) : Changes
16
    {
17
        Assert::that($fromClass->getName())->same($toClass->getName());
18
19
        $fromValues = $this->accessibleConstantValues($fromClass);
20
        $toValues   = $this->accessibleConstantValues($toClass);
21
22
        $changedConstants = array_keys(array_filter($fromValues, function ($constantValue, string $constantName) use (
23
            $toValues
24
        ) : bool {
25
            return array_key_exists($constantName, $toValues) && $constantValue !== $toValues[$constantName];
26
        }, \ARRAY_FILTER_USE_BOTH));
27
28
        return Changes::fromArray(array_values(array_map(function (string $constantName) use ($fromClass) : Change {
29
            return Change::changed(
30
                sprintf('Value of constant %s::%s changed', $fromClass->getName(), $constantName),
31
                true
32
            );
33
        }, $changedConstants)));
34
    }
35
36
    /** @return ReflectionClassConstant[] */
37
    private function accessibleConstantValues(ReflectionClass $class) : array
38
    {
39
        $accessibleConstants = array_filter(
40
            $class->getReflectionConstants(),
41
            function (ReflectionClassConstant $constant) : bool {
42
                return $constant->isPublic() || $constant->isProtected();
43
            }
44
        );
45
46
        return array_map(function (ReflectionClassConstant $constant) {
47
            return $constant->getValue();
48
        }, $accessibleConstants);
49
    }
50
}