PropertyVisibilityReduced::__invoke()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 18
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 11
nc 2
nop 2
dl 0
loc 18
rs 9.9
c 0
b 0
f 0
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Roave\BackwardCompatibility\DetectChanges\BCBreak\PropertyBased;
6
7
use Roave\BackwardCompatibility\Change;
8
use Roave\BackwardCompatibility\Changes;
9
use Roave\BackwardCompatibility\Formatter\ReflectionPropertyName;
10
use Roave\BetterReflection\Reflection\ReflectionProperty;
11
use function Safe\sprintf;
12
13
final class PropertyVisibilityReduced implements PropertyBased
14
{
15
    /** @var ReflectionPropertyName */
16
    private $formatProperty;
17
18
    public function __construct()
19
    {
20
        $this->formatProperty = new ReflectionPropertyName();
21
    }
22
23
    private const VISIBILITY_PRIVATE = 'private';
24
25
    private const VISIBILITY_PROTECTED = 'protected';
26
27
    private const VISIBILITY_PUBLIC = 'public';
28
29
    public function __invoke(ReflectionProperty $fromProperty, ReflectionProperty $toProperty) : Changes
30
    {
31
        $visibilityFrom = $this->propertyVisibility($fromProperty);
32
        $visibilityTo   = $this->propertyVisibility($toProperty);
33
34
        // Works because private, protected and public are sortable:
35
        if ($visibilityFrom <= $visibilityTo) {
36
            return Changes::empty();
37
        }
38
39
        return Changes::fromList(Change::changed(
40
            sprintf(
41
                'Property %s visibility reduced from %s to %s',
42
                $this->formatProperty->__invoke($fromProperty),
43
                $visibilityFrom,
44
                $visibilityTo
45
            ),
46
            true
47
        ));
48
    }
49
50
    private function propertyVisibility(ReflectionProperty $property) : string
51
    {
52
        if ($property->isPublic()) {
53
            return self::VISIBILITY_PUBLIC;
54
        }
55
56
        if ($property->isProtected()) {
57
            return self::VISIBILITY_PROTECTED;
58
        }
59
60
        return self::VISIBILITY_PRIVATE;
61
    }
62
}
63