Debian Codegraph @

vendor/doctrine/collections/src/Expr/ClosureExpressionVisitor.php

raw
1 <?php
2
3 declare(strict_types=1);
4
5 namespace Doctrine\Common\Collections\Expr;
6
7 use ArrayAccess;
8 use Closure;
9 use Doctrine\Deprecations\Deprecation;
10 use ReflectionClass;
11 use RuntimeException;
12
13 use function array_all;
14 use function array_any;
15 use function explode;
16 use function func_get_arg;
17 use function func_num_args;
18 use function in_array;
19 use function is_array;
20 use function is_scalar;
21 use function iterator_to_array;
22 use function method_exists;
23 use function preg_match;
24 use function preg_replace_callback;
25 use function sprintf;
26 use function str_contains;
27 use function str_ends_with;
28 use function str_starts_with;
29 use function strtoupper;
30
31 use const PHP_VERSION_ID;
32
33 /**
34 * Walks an expression graph and turns it into a PHP closure.
35 *
36 * This closure can be used with {@Collection#filter()} and is used internally
37 * by {@ArrayCollection#select()}.
38 *
39 * @final since 2.5
40 */
41 class ClosureExpressionVisitor extends ExpressionVisitor
42 {
43 public function __construct(
44 private readonly bool $accessRawFieldValues = false,
45 ) {
46 }
47
48 /**
49 * Accesses the field of a given object. This field has to be public
50 * directly or indirectly (through an accessor get*, is*, or a magic
51 * method, __get, __call).
52 *
53 * @param object|mixed[] $object
54 *
55 * @return mixed
56 */
57 public static function getObjectFieldValue(object|array $object, string $field, /* bool $accessRawFieldValues = false */)
58 {
59 $accessRawFieldValues = 3 <= func_num_args() ? func_get_arg(2) : false;
60
61 if (str_contains($field, '.')) {
62 [$field, $subField] = explode('.', $field, 2);
63 $object = self::getObjectFieldValue($object, $field, $accessRawFieldValues);
64
65 return self::getObjectFieldValue($object, $subField, $accessRawFieldValues);
66 }
67
68 if (is_array($object)) {
69 return $object[$field];
70 }
71
72 if ($accessRawFieldValues) {
73 return self::getNearestFieldValue($object, $field);
74 }
75
76 Deprecation::trigger(
77 'doctrine/collections',
78 'https://github.com/doctrine/collections/pull/472',
79 'Not enabling raw field value access for %s is deprecated. Raw field access will be the only supported method in 3.0',
80 __METHOD__,
81 );
82
83 $accessors = ['get', 'is', ''];
84
85 foreach ($accessors as $accessor) {
86 $accessor .= $field;
87
88 if (method_exists($object, $accessor)) {
89 return $object->$accessor();
90 }
91 }
92
93 if (preg_match('/^is[A-Z]+/', $field) === 1 && method_exists($object, $field)) {
94 return $object->$field();
95 }
96
97 // __call should be triggered for get.
98 $accessor = $accessors[0] . $field;
99
100 if (method_exists($object, '__call')) {
101 return $object->$accessor();
102 }
103
104 if ($object instanceof ArrayAccess) {
105 return $object[$field];
106 }
107
108 if (isset($object->$field)) {
109 return $object->$field;
110 }
111
112 // camelcase field name to support different variable naming conventions
113 $ccField = preg_replace_callback('/_(.?)/', static fn ($matches) => strtoupper((string) $matches[1]), $field);
114
115 foreach ($accessors as $accessor) {
116 $accessor .= $ccField;
117
118 if (method_exists($object, $accessor)) {
119 return $object->$accessor();
120 }
121 }
122
123 return $object->$field;
124 }
125
126 private static function getNearestFieldValue(object $object, string $field): mixed
127 {
128 $reflectionClass = new ReflectionClass($object);
129
130 while ($reflectionClass && ! $reflectionClass->hasProperty($field)) {
131 $reflectionClass = $reflectionClass->getParentClass();
132 }
133
134 if ($reflectionClass === false) {
135 throw new RuntimeException(sprintf('Field "%s" does not exist in class "%s"', $field, $object::class));
136 }
137
138 $property = $reflectionClass->getProperty($field);
139
140 if (PHP_VERSION_ID >= 80400) {
141 return $property->getRawValue($object);
142 }
143
144 return $property->getValue($object);
145 }
146
147 /**
148 * Helper for sorting arrays of objects based on multiple fields + orientations.
149 *
150 * @return Closure
151 */
152 public static function sortByField(string $name, int $orientation = 1, Closure|null $next = null, /* bool $accessRawFieldValues = false */)
153 {
154 $accessRawFieldValues = 4 <= func_num_args() ? func_get_arg(3) : false;
155
156 if (! $accessRawFieldValues) {
157 Deprecation::trigger(
158 'doctrine/collections',
159 'https://github.com/doctrine/collections/pull/472',
160 'Not enabling raw field value access for %s is deprecated. Raw field access will be the only supported method in 3.0',
161 __METHOD__,
162 );
163 }
164
165 if (! $next) {
166 $next = static fn (): int => 0;
167 }
168
169 return static function ($a, $b) use ($name, $next, $orientation, $accessRawFieldValues): int {
170 $aValue = ClosureExpressionVisitor::getObjectFieldValue($a, $name, $accessRawFieldValues);
171 $bValue = ClosureExpressionVisitor::getObjectFieldValue($b, $name, $accessRawFieldValues);
172
173 if ($aValue === $bValue) {
174 return $next($a, $b);
175 }
176
177 return ($aValue > $bValue ? 1 : -1) * $orientation;
178 };
179 }
180
181 /**
182 * {@inheritDoc}
183 */
184 public function walkComparison(Comparison $comparison)
185 {
186 $field = $comparison->getField();
187 $value = $comparison->getValue()->getValue();
188
189 return match ($comparison->getOperator()) {
190 Comparison::EQ => fn ($object): bool => self::getObjectFieldValue($object, $field, $this->accessRawFieldValues) === $value,
191 Comparison::NEQ => fn ($object): bool => self::getObjectFieldValue($object, $field, $this->accessRawFieldValues) !== $value,
192 Comparison::LT => fn ($object): bool => self::getObjectFieldValue($object, $field, $this->accessRawFieldValues) < $value,
193 Comparison::LTE => fn ($object): bool => self::getObjectFieldValue($object, $field, $this->accessRawFieldValues) <= $value,
194 Comparison::GT => fn ($object): bool => self::getObjectFieldValue($object, $field, $this->accessRawFieldValues) > $value,
195 Comparison::GTE => fn ($object): bool => self::getObjectFieldValue($object, $field, $this->accessRawFieldValues) >= $value,
196 Comparison::IN => function ($object) use ($field, $value): bool {
197 $fieldValue = ClosureExpressionVisitor::getObjectFieldValue($object, $field, $this->accessRawFieldValues);
198
199 return in_array($fieldValue, $value, is_scalar($fieldValue));
200 },
201 Comparison::NIN => function ($object) use ($field, $value): bool {
202 $fieldValue = ClosureExpressionVisitor::getObjectFieldValue($object, $field, $this->accessRawFieldValues);
203
204 return ! in_array($fieldValue, $value, is_scalar($fieldValue));
205 },
206 Comparison::CONTAINS => fn ($object): bool => str_contains((string) self::getObjectFieldValue($object, $field, $this->accessRawFieldValues), (string) $value),
207 Comparison::MEMBER_OF => function ($object) use ($field, $value): bool {
208 $fieldValues = ClosureExpressionVisitor::getObjectFieldValue($object, $field, $this->accessRawFieldValues);
209
210 if (! is_array($fieldValues)) {
211 $fieldValues = iterator_to_array($fieldValues);
212 }
213
214 return in_array($value, $fieldValues, true);
215 },
216 Comparison::STARTS_WITH => fn ($object): bool => str_starts_with((string) self::getObjectFieldValue($object, $field, $this->accessRawFieldValues), (string) $value),
217 Comparison::ENDS_WITH => fn ($object): bool => str_ends_with((string) self::getObjectFieldValue($object, $field, $this->accessRawFieldValues), (string) $value),
218 default => throw new RuntimeException('Unknown comparison operator: ' . $comparison->getOperator()),
219 };
220 }
221
222 /**
223 * {@inheritDoc}
224 */
225 public function walkValue(Value $value)
226 {
227 return $value->getValue();
228 }
229
230 /**
231 * {@inheritDoc}
232 */
233 public function walkCompositeExpression(CompositeExpression $expr)
234 {
235 $expressionList = [];
236
237 foreach ($expr->getExpressionList() as $child) {
238 $expressionList[] = $this->dispatch($child);
239 }
240
241 return match ($expr->getType()) {
242 CompositeExpression::TYPE_AND => $this->andExpressions($expressionList),
243 CompositeExpression::TYPE_OR => $this->orExpressions($expressionList),
244 CompositeExpression::TYPE_NOT => $this->notExpression($expressionList),
245 default => throw new RuntimeException('Unknown composite ' . $expr->getType()),
246 };
247 }
248
249 /** @param callable[] $expressions */
250 private function andExpressions(array $expressions): Closure
251 {
252 return static fn ($object): bool => array_all(
253 $expressions,
254 static fn (callable $expression): bool => (bool) $expression($object),
255 );
256 }
257
258 /** @param callable[] $expressions */
259 private function orExpressions(array $expressions): Closure
260 {
261 return static fn ($object): bool => array_any(
262 $expressions,
263 static fn (callable $expression): bool => (bool) $expression($object),
264 );
265 }
266
267 /** @param callable[] $expressions */
268 private function notExpression(array $expressions): Closure
269 {
270 return static fn ($object) => ! $expressions[0]($object);
271 }
272 }