Passed
Pull Request — master (#364)
by
unknown
02:47
created

ObjectDataSet::getCacheItem()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 7
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 2.0625

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 3
c 1
b 0
f 0
dl 0
loc 7
ccs 3
cts 4
cp 0.75
rs 10
cc 2
nc 2
nop 1
crap 2.0625
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 RuntimeException;
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
    /**
32
     * @var array<string, array<string, mixed>>
33
     */
34
    #[ArrayShape([
35
        [
36
            'rules' => 'iterable',
37
            'reflectionAttributes' => 'array',
38
        ],
39
    ])]
40
    private static array $cache = [];
41
    private string|null $cacheKey = null;
42
43 47
    public function __construct(
44
        private object $object,
45
        private int $propertyVisibility = ReflectionProperty::IS_PRIVATE |
46
        ReflectionProperty::IS_PROTECTED |
47
        ReflectionProperty::IS_PUBLIC,
48
        private bool $useCache = true
49
    ) {
50 47
        $this->dataSetProvided = $this->object instanceof DataSetInterface;
51 47
        $this->rulesProvided = $this->object instanceof RulesProviderInterface;
52
53 47
        if ($this->canCache()) {
54 47
            $this->cacheKey = $this->object::class . '_' . $this->propertyVisibility;
55
        }
56
    }
57
58 53
    public function getRules(): iterable
59
    {
60 53
        if ($this->rulesProvided) {
61
            /** @var RulesProviderInterface $object */
62 13
            $object = $this->object;
63
64 13
            return $object->getRules();
65
        }
66
67
        // Providing data set assumes object has its own attributes and rules getting logic. So further parsing of
68
        // Reflection properties and rules is skipped intentionally.
69 40
        if ($this->dataSetProvided) {
70 5
            return [];
71
        }
72
73 35
        if ($this->hasCacheItem('rules')) {
74
            /** @var iterable $rules */
75 9
            $rules = $this->getCacheItem('rules');
76
        } else {
77 33
            $rules = [];
78 33
            foreach ($this->getReflectionProperties() as $property) {
79
                // TODO: use Generator to collect attributes.
80 32
                $attributes = $property->getAttributes(RuleInterface::class, ReflectionAttribute::IS_INSTANCEOF);
81 32
                foreach ($attributes as $attribute) {
82 30
                    $rule = $attribute->newInstance();
83 30
                    $rules[$property->getName()][] = $rule;
84
85 30
                    if ($rule instanceof AttributeEventInterface) {
86 3
                        $rule->afterInitAttribute($this);
87
                    }
88
                }
89
            }
90
91 32
            if ($this->canCache()) {
92 32
                $this->setCacheItem('rules', $rules);
93
            }
94
        }
95
96 34
        return $rules;
97
    }
98
99 39
    public function getObject(): object
100
    {
101 39
        return $this->object;
102
    }
103
104 45
    public function getAttributeValue(string $attribute): mixed
105
    {
106 45
        if ($this->dataSetProvided) {
107
            /** @var DataSetInterface $object */
108 8
            $object = $this->object;
109
110 8
            return $object->getAttributeValue($attribute);
111
        }
112
113 37
        return ($this->getReflectionProperties()[$attribute] ?? null)?->getValue($this->getObject());
114
    }
115
116 27
    public function hasAttribute(string $attribute): bool
117
    {
118 27
        if (!$this->dataSetProvided) {
119 27
            return array_key_exists($attribute, $this->getReflectionProperties());
120
        }
121
122
        /** @var DataSetInterface $object */
123
        $object = $this->object;
124
125
        return $object->hasAttribute($attribute);
126
    }
127
128 32
    public function getData(): mixed
129
    {
130 32
        if ($this->dataSetProvided) {
131
            /** @var DataSetInterface $object */
132 12
            $object = $this->object;
133
134 12
            return $object->getData();
135
        }
136
137 20
        $data = [];
138 20
        foreach ($this->getReflectionProperties() as $name => $property) {
139
            /** @psalm-suppress MixedAssignment */
140 17
            $data[$name] = $property->getValue($this->object);
141
        }
142
143 20
        return $data;
144
    }
145
146
    /**
147
     * @psalm-return array<string, ReflectionProperty>
148
     */
149 56
    private function getReflectionProperties(): array
150
    {
151 56
        if ($this->hasCacheItem('reflectionProperties')) {
152
            /** @var array<string, ReflectionProperty> $reflectionProperties */
153 39
            $reflectionProperties = $this->getCacheItem('reflectionProperties');
154
        } else {
155 46
            $reflection = new ReflectionObject($this->object);
156 46
            $reflectionProperties = [];
157
158 46
            foreach ($reflection->getProperties($this->propertyVisibility) as $property) {
159 44
                if (PHP_VERSION_ID < 80100) {
160 44
                    $property->setAccessible(true);
161
                }
162
163 44
                $reflectionProperties[$property->getName()] = $property;
164
            }
165
166 46
            if ($this->canCache()) {
167 45
                $this->setCacheItem('reflectionProperties', $reflectionProperties);
168
            }
169
        }
170
171 56
        return $reflectionProperties;
172
    }
173
174 53
    private function canCache(): bool
175
    {
176 53
        return $this->useCache === true;
177
    }
178
179 56
    private function hasCacheItem(#[ExpectedValues(['rules', 'reflectionProperties'])] string $name): bool
180
    {
181 56
        if ($this->cacheKey === null) {
182 1
            return false;
183
        }
184
185 55
        if (!array_key_exists($this->cacheKey, self::$cache)) {
186 45
            return false;
187
        }
188
189 39
        return array_key_exists($name, self::$cache[$this->cacheKey]);
190
    }
191
192 39
    private function getCacheItem(#[ExpectedValues(['rules', 'reflectionProperties'])] string $name): mixed
193
    {
194 39
        if ($this->cacheKey === null) {
195
            return null;
196
        }
197
198 39
        return self::$cache[$this->cacheKey][$name];
199
    }
200
201 45
    private function setCacheItem(#[ExpectedValues(['rules', 'reflectionProperties'])] string $name, mixed $value): void
202
    {
203 45
        if ($this->cacheKey === null) {
204
            throw new RuntimeException('$cacheKey is not set.');
205
        }
206
207
        /** @psalm-suppress MixedAssignment */
208 45
        self::$cache[$this->cacheKey][$name] = $value;
209
    }
210
}
211