Passed
Pull Request — master (#323)
by
unknown
03:11
created

ObjectDataSet::getObject()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
eloc 1
c 0
b 0
f 0
dl 0
loc 3
ccs 2
cts 2
cp 1
rs 10
cc 1
nc 1
nop 0
crap 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\Validator\DataSet;
6
7
use JetBrains\PhpStorm\ArrayShape;
8
use JetBrains\PhpStorm\ExpectedValues;
9
use ReflectionAttribute;
10
use ReflectionObject;
11
use ReflectionProperty;
12
use stdClass;
13
use Yiisoft\Validator\AttributeEventInterface;
14
use Yiisoft\Validator\DataSetInterface;
15
use Yiisoft\Validator\RuleInterface;
16
use Yiisoft\Validator\RulesProviderInterface;
17
18
use function array_key_exists;
19
20
/**
21
 * This data set makes use of attributes introduced in PHP 8. It simplifies rules configuration process, especially for
22
 * nested data and relations. Please refer to the guide for examples.
23
 *
24
 * @link https://www.php.net/manual/en/language.attributes.overview.php
25
 */
26
final class ObjectDataSet implements RulesProviderInterface, DataSetInterface
27
{
28
    private bool $dataSetProvided;
29
    private bool $rulesProvided;
30
31
    #[ArrayShape([
32
        [
33
            'rules' => 'iterable',
34
            'reflectionAttributes' => 'array',
35
        ],
36
    ])]
37
    private static array $cache = [];
38
    private string|null $cacheKey = null;
39
40 49
    public function __construct(
41
        private object $object,
42
        private int $propertyVisibility = ReflectionProperty::IS_PRIVATE |
43
        ReflectionProperty::IS_PROTECTED |
44
        ReflectionProperty::IS_PUBLIC
45
    ) {
46 49
        $this->dataSetProvided = $this->object instanceof DataSetInterface;
47 49
        $this->rulesProvided = $this->object instanceof RulesProviderInterface;
48
49 49
        if ($this->canCache()) {
50 45
            $this->cacheKey = $this->object::class . '_' . $this->propertyVisibility;
51
        }
52
    }
53
54 54
    public function getRules(): iterable
55
    {
56 54
        if ($this->rulesProvided) {
57 13
            return $this->object->getRules();
58
        }
59
60
        // Providing data set assumes object has its own attributes and rules getting logic. So further parsing of
61
        // Reflection properties and rules is skipped intentionally.
62 41
        if ($this->dataSetProvided) {
63 5
            return [];
64
        }
65
66 36
        if ($this->hasCacheItem('rules')) {
67 7
            return $this->getCacheItem('rules');
68
        }
69
70 31
        $rules = [];
71 31
        foreach ($this->getReflectionProperties() as $property) {
72
            // TODO: use Generator to collect attributes.
73 30
            $attributes = $property->getAttributes(RuleInterface::class, ReflectionAttribute::IS_INSTANCEOF);
74 30
            foreach ($attributes as $attribute) {
75 28
                $rule = $attribute->newInstance();
76 28
                $rules[$property->getName()][] = $rule;
77
78 28
                if ($rule instanceof AttributeEventInterface) {
79 4
                    $rule->afterInitAttribute($this);
80
                }
81
            }
82
        }
83
84 28
        if ($this->canCache()) {
85 28
            $this->setCacheItem('rules', $rules);
86
        }
87
88 28
        return $rules;
89
    }
90
91 57
    private function getReflectionProperties(): array
92
    {
93 57
        if ($this->hasCacheItem('reflectionProperties')) {
94 36
            return $this->getCacheItem('reflectionProperties');
95
        }
96
97 46
        $reflection = new ReflectionObject($this->object);
98 46
        $reflectionProperties = [];
99
100 46
        foreach ($reflection->getProperties($this->propertyVisibility) as $property) {
101 42
            if (PHP_VERSION_ID < 80100) {
102 42
                $property->setAccessible(true);
103
            }
104
105 42
            $reflectionProperties[$property->getName()] = $property;
106
        }
107
108 46
        if ($this->canCache()) {
109 42
            $this->setCacheItem('reflectionProperties', $reflectionProperties);
110
        }
111
112 46
        return $reflectionProperties;
113
    }
114
115 4
    public function getObject(): object
116
    {
117 4
        return $this->object;
118
    }
119
120 44
    public function getAttributeValue(string $attribute): mixed
121
    {
122 44
        if ($this->dataSetProvided) {
123 8
            return $this->object->getAttributeValue($attribute);
124
        }
125
126 36
        return $this->getData()[$attribute] ?? null;
127
    }
128
129 26
    public function hasAttribute(string $attribute): bool
130
    {
131 26
        return $this->dataSetProvided
132
            ? $this->object->hasAttribute($attribute)
133 26
            : array_key_exists($attribute, $this->getReflectionProperties());
134
    }
135
136 57
    public function getData(): array
137
    {
138 57
        if ($this->dataSetProvided) {
139 12
            return $this->object->getData();
140
        }
141
142 45
        $data = [];
143 45
        foreach ($this->getReflectionProperties() as $name => $property) {
144 42
            $data[$name] = $property->getValue($this->object);
145
        }
146
147 45
        return $data;
148
    }
149
150 53
    private function canCache(): bool
151
    {
152 53
        return !$this->object instanceof stdClass;
153
    }
154
155 57
    private function hasCacheItem(#[ExpectedValues(['rules', 'reflectionProperties'])] string $name): bool
156
    {
157 57
        if (!array_key_exists($this->cacheKey, self::$cache)) {
158 46
            return false;
159
        }
160
161 36
        return array_key_exists($name, self::$cache[$this->cacheKey]);
162
    }
163
164 36
    private function getCacheItem(#[ExpectedValues(['rules', 'reflectionProperties'])] string $name): array
165
    {
166 36
        return self::$cache[$this->cacheKey][$name];
167
    }
168
169 42
    private function setCacheItem(#[ExpectedValues(['rules', 'reflectionProperties'])] string $name, array $rules): void
170
    {
171 42
        self::$cache[$this->cacheKey][$name] = $rules;
172
    }
173
}
174