forked from jolicode/automapper
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPropertyConditionsGenerator.php
More file actions
312 lines (268 loc) · 11.3 KB
/
PropertyConditionsGenerator.php
File metadata and controls
312 lines (268 loc) · 11.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
<?php
declare(strict_types=1);
namespace AutoMapper\Generator;
use AutoMapper\Exception\CompileException;
use AutoMapper\MapperContext;
use AutoMapper\Metadata\GeneratorMetadata;
use AutoMapper\Metadata\PropertyMetadata;
use PhpParser\Node\Arg;
use PhpParser\Node\Expr;
use PhpParser\Node\Name;
use PhpParser\Node\Scalar;
use PhpParser\Node\Stmt;
use PhpParser\Parser;
use PhpParser\ParserFactory;
use Symfony\Component\ExpressionLanguage\ExpressionLanguage;
use function AutoMapper\PhpParser\create_expr_array_item;
use function AutoMapper\PhpParser\create_scalar_int;
/**
* We generate a list of conditions that will allow the field to be mapped to the target.
*
* @internal
*/
final readonly class PropertyConditionsGenerator
{
private Parser $parser;
public function __construct(
private ExpressionLanguage $expressionLanguage,
?Parser $parser = null,
) {
$this->parser = $parser ?? (new ParserFactory())->createForHostVersion();
}
public function generate(GeneratorMetadata $metadata, PropertyMetadata $propertyMetadata, bool $onlyExists = false): ?Expr
{
$conditions = [];
$conditions[] = $this->customCondition($metadata, $propertyMetadata);
$conditions[] = $this->propertyExistsForStdClass($metadata, $propertyMetadata);
$conditions[] = $this->propertyExistsForArray($metadata, $propertyMetadata);
if (!$onlyExists) {
$conditions[] = $this->isAllowedAttribute($metadata, $propertyMetadata);
if (!$propertyMetadata->disableGroupsCheck) {
$conditions[] = $this->groupsCheck($metadata->variableRegistry, $propertyMetadata->groups); // Property groups
if ($propertyMetadata->groups === null) {
$conditions[] = $this->groupsCheck($metadata->variableRegistry, $propertyMetadata->source->groups); // Source groups
$conditions[] = $this->groupsCheck($metadata->variableRegistry, $propertyMetadata->target->groups); // Target groups
}
$conditions[] = $this->noGroupsCheck($metadata, $propertyMetadata);
}
$conditions[] = $this->maxDepthCheck($metadata, $propertyMetadata);
}
$conditions = array_values(array_filter($conditions));
if (!$conditions) {
return null;
}
/**
* If there is any conditions generated we encapsulate the mapping into it.
*
* ```php
* if (condition1 && condition2 && ...) {
* ... // mapping statements
* }
* ```
*/
$condition = array_shift($conditions);
while ($conditions) {
$condition = new Expr\BinaryOp\BooleanAnd($condition, array_shift($conditions));
}
return $condition;
}
/**
* In case of source is an \stdClass we ensure that the property exists.
*
* ```php
* property_exists($source, 'propertyName')
* ```
*/
private function propertyExistsForStdClass(GeneratorMetadata $metadata, PropertyMetadata $propertyMetadata): ?Expr
{
if (!$propertyMetadata->source->checkExists || \stdClass::class !== $metadata->mapperMetadata->source) {
return null;
}
return new Expr\FuncCall(new Name('property_exists'), [
new Arg($metadata->variableRegistry->getSourceInput()),
new Arg(new Scalar\String_($propertyMetadata->source->property)),
]);
}
/**
* In case of source is an array we ensure that the key exists.
*
* ```php
* array_key_exists('propertyName', $source).
* ```
*/
private function propertyExistsForArray(GeneratorMetadata $metadata, PropertyMetadata $propertyMetadata): ?Expr
{
if (!$propertyMetadata->source->checkExists || 'array' !== $metadata->mapperMetadata->source) {
return null;
}
return new Expr\FuncCall(new Name('array_key_exists'), [
new Arg(new Scalar\String_($propertyMetadata->source->property)),
new Arg($metadata->variableRegistry->getSourceInput()),
]);
}
/**
* In case of supporting attributes checking, we check if the property is allowed to be mapped.
*
* ```php
* MapperContext::isAllowedAttribute($context, 'propertyName', isset($source->field)).
* ```
*/
private function isAllowedAttribute(GeneratorMetadata $metadata, PropertyMetadata $propertyMetadata): ?Expr
{
if (!$propertyMetadata->source->accessor || !$metadata->checkAttributes) {
return null;
}
$variableRegistry = $metadata->variableRegistry;
return new Expr\StaticCall(new Name\FullyQualified(MapperContext::class), 'isAllowedAttribute', [
new Arg($variableRegistry->getContext()),
new Arg(new Scalar\String_($propertyMetadata->source->property)),
new Arg(new Expr\Closure([
'uses' => [new Expr\ClosureUse($variableRegistry->getSourceInput())],
'stmts' => [new Stmt\Return_($propertyMetadata->source->accessor->getIsNullExpression($variableRegistry->getSourceInput()))],
])),
new Arg($propertyMetadata->source->accessor->getIsUndefinedExpression($variableRegistry->getSourceInput())),
]);
}
/**
* When there is groups associated we check if the context has the same groups.
*
* ```php
* (null !== $context[MapperContext::GROUPS] ?? null && array_intersect($context[MapperContext::GROUPS] ?? [], ['group1', 'group2']))
* ```
*
* @param string[]|null $groups
*/
private function groupsCheck(VariableRegistry $variableRegistry, ?array $groups = []): ?Expr
{
if (!$groups) {
return null;
}
return new Expr\BinaryOp\BooleanAnd(
new Expr\BinaryOp\NotIdentical(
new Expr\ConstFetch(new Name('null')),
new Expr\BinaryOp\Coalesce(
new Expr\ArrayDimFetch($variableRegistry->getContext(), new Scalar\String_(MapperContext::GROUPS)),
new Expr\Array_()
)
),
new Expr\FuncCall(new Name('array_intersect'), [
new Arg(
new Expr\BinaryOp\Coalesce(
new Expr\ArrayDimFetch($variableRegistry->getContext(), new Scalar\String_(MapperContext::GROUPS)),
new Expr\Array_()
)
),
new Arg(new Expr\Array_(array_map(function (string $group) {
return create_expr_array_item(new Scalar\String_($group));
}, $groups))),
])
);
}
/**
* When there is no groups associated to the target property or source property we check if the context has the same groups.
*
* ```php
* (!array_key_exists(MapperContext::GROUPS, $context) || !$context[MapperContext::GROUPS])
* ```
*/
private function noGroupsCheck(GeneratorMetadata $metadata, PropertyMetadata $propertyMetadata): ?Expr
{
if ($propertyMetadata->groups || $propertyMetadata->target->groups || $propertyMetadata->source->groups) {
return null;
}
return new Expr\BinaryOp\BooleanOr(
new Expr\BooleanNot(
new Expr\FuncCall(new Name('array_key_exists'), [
new Arg(new Scalar\String_(MapperContext::GROUPS)),
new Arg($metadata->variableRegistry->getContext()),
])
),
new Expr\BooleanNot(
new Expr\ArrayDimFetch($metadata->variableRegistry->getContext(), new Scalar\String_(MapperContext::GROUPS))
)
);
}
/**
* When there is a max depth for this property we check if the context has a depth lower or equal to the max depth.
*
* ```php
* ($context[MapperContext::DEPTH] ?? 0) <= $maxDepth
* ```
*/
private function maxDepthCheck(GeneratorMetadata $metadata, PropertyMetadata $propertyMetadata): ?Expr
{
if (!$propertyMetadata->maxDepth) {
return null;
}
$variableRegistry = $metadata->variableRegistry;
return new Expr\BinaryOp\SmallerOrEqual(
new Expr\BinaryOp\Coalesce(
new Expr\ArrayDimFetch($variableRegistry->getContext(), new Scalar\String_(MapperContext::DEPTH)),
new Expr\ConstFetch(new Name('0'))
),
create_scalar_int($propertyMetadata->maxDepth),
);
}
/**
* When there is a if condition we check if the condition is true.
*/
private function customCondition(GeneratorMetadata $metadata, PropertyMetadata $propertyMetadata): ?Expr
{
if (null === $propertyMetadata->if) {
return null;
}
$callableName = null;
if (\is_callable($propertyMetadata->if, false, $callableName)) {
if (\function_exists($callableName)) {
// Get arguments count of the function
$reflectionFunction = new \ReflectionFunction($callableName);
$argumentsCount = $reflectionFunction->getNumberOfRequiredParameters();
if ($argumentsCount === 1) {
return new Expr\FuncCall(
new Name($callableName),
[
new Arg(new Expr\Variable('value')),
]
);
}
if ($argumentsCount > 2) {
throw new CompileException('Callable condition must have 1 or 2 arguments required, but it has ' . $argumentsCount);
}
}
return new Expr\FuncCall(
new Name($callableName),
[
new Arg(new Expr\Variable('value')),
new Arg(new Expr\Variable('context')),
]
);
}
if ($metadata->mapperMetadata->sourceReflectionClass !== null && $metadata->mapperMetadata->sourceReflectionClass->hasMethod($propertyMetadata->if)) {
$reflectionMethod = $metadata->mapperMetadata->sourceReflectionClass->getMethod($propertyMetadata->if);
if ($reflectionMethod->isStatic()) {
return new Expr\StaticCall(
new Name\FullyQualified($metadata->mapperMetadata->source),
$propertyMetadata->if,
[
new Arg(new Expr\Variable('value')),
new Arg(new Expr\Variable('context')),
]
);
}
return new Expr\MethodCall(
new Expr\Variable('value'),
$propertyMetadata->if,
[
new Arg(new Expr\Variable('value')),
new Arg(new Expr\Variable('context')),
]
);
}
$expression = $this->expressionLanguage->compile($propertyMetadata->if, ['value' => 'source', 'context']);
$expr = $this->parser->parse('<?php ' . $expression . ';')[0] ?? null;
if ($expr instanceof Stmt\Expression) {
return $expr->expr;
}
throw new CompileException('Cannot use callback or create expression language condition from expression "' . $propertyMetadata->if . "'");
}
}