• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

nextras / orm / 42787499477

10 Nov 2026 09:03AM UTC coverage: 92.222% (+0.2%) from 92.015%
42787499477

Pull #841

github

web-flow
Merge 12c574381 into 3bc5585da
Pull Request #841: Update dependency nette/neon to v4

4470 of 4847 relevant lines covered (92.22%)

6.27 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

92.44
/src/Entity/Reflection/MetadataParser.php
1
<?php declare(strict_types = 1);
2

3
/** @noinspection PhpUnused */
4

5
namespace Nextras\Orm\Entity\Reflection;
6

7

8
use BackedEnum;
9
use DateTime;
10
use Nette\Utils\Reflection;
11
use Nextras\Orm\Collection\ICollection;
12
use Nextras\Orm\Entity\Embeddable\EmbeddableContainer;
13
use Nextras\Orm\Entity\Embeddable\IEmbeddable;
14
use Nextras\Orm\Entity\IEntity;
15
use Nextras\Orm\Entity\IProperty;
16
use Nextras\Orm\Entity\PropertyWrapper\BackedEnumWrapper;
17
use Nextras\Orm\Entity\PropertyWrapper\DateTimeWrapper;
18
use Nextras\Orm\Entity\PropertyWrapper\PrimaryProxyWrapper;
19
use Nextras\Orm\Entity\VirtualEntityProperty;
20
use Nextras\Orm\Exception\InvalidStateException;
21
use Nextras\Orm\Exception\NotSupportedException;
22
use Nextras\Orm\Extension;
23
use Nextras\Orm\Relationships\HasMany;
24
use Nextras\Orm\Relationships\ManyHasMany;
25
use Nextras\Orm\Relationships\ManyHasOne;
26
use Nextras\Orm\Relationships\OneHasMany;
27
use Nextras\Orm\Relationships\OneHasOne;
28
use Nextras\Orm\Repository\IRepository;
29
use PHPStan\PhpDocParser\Ast\PhpDoc\PropertyTagValueNode;
30
use PHPStan\PhpDocParser\Ast\Type\ArrayShapeNode;
31
use PHPStan\PhpDocParser\Ast\Type\ArrayTypeNode;
32
use PHPStan\PhpDocParser\Ast\Type\GenericTypeNode;
33
use PHPStan\PhpDocParser\Ast\Type\IdentifierTypeNode;
34
use PHPStan\PhpDocParser\Ast\Type\IntersectionTypeNode;
35
use PHPStan\PhpDocParser\Ast\Type\NullableTypeNode;
36
use PHPStan\PhpDocParser\Ast\Type\ObjectShapeNode;
37
use PHPStan\PhpDocParser\Ast\Type\TypeNode;
38
use PHPStan\PhpDocParser\Ast\Type\UnionTypeNode;
39
use PHPStan\PhpDocParser\Lexer\Lexer;
40
use PHPStan\PhpDocParser\Parser\ConstExprParser;
41
use PHPStan\PhpDocParser\Parser\PhpDocParser;
42
use PHPStan\PhpDocParser\Parser\TokenIterator;
43
use PHPStan\PhpDocParser\Parser\TypeParser;
44
use PHPStan\PhpDocParser\ParserConfig;
45
use ReflectionClass;
46
use ReflectionIntersectionType;
47
use ReflectionNamedType;
48
use ReflectionType;
49
use ReflectionUnionType;
50
use function array_keys;
51
use function assert;
52
use function class_exists;
53
use function count;
54
use function is_subclass_of;
55
use function substr;
56
use function trigger_error;
57

58

59
class MetadataParser implements IMetadataParser
60
{
61
        /** @var array<string, callable|string> */
62
        protected array $modifiers = [
63
                '1:1' => 'parseOneHasOneModifier',
64
                '1:m' => 'parseOneHasManyModifier',
65
                'm:1' => 'parseManyHasOneModifier',
66
                'm:m' => 'parseManyHasManyModifier',
67
                'enum' => 'parseEnumModifier',
68
                'virtual' => 'parseVirtualModifier',
69
                'container' => 'parseContainerModifier',
70
                'wrapper' => 'parseWrapperModifier',
71
                'default' => 'parseDefaultModifier',
72
                'primary' => 'parsePrimaryModifier',
73
                'primary-proxy' => 'parsePrimaryProxyModifier',
74
                'embeddable' => 'parseEmbeddableModifier',
75
        ];
76

77
        /** @var ReflectionClass<object> */
78
        protected $reflection;
79

80
        /** @var ReflectionClass<object> */
81
        protected $currentReflection;
82

83
        /** @var EntityMetadata */
84
        protected $metadata;
85

86
        /** @var array<class-string<IEntity>, class-string<IRepository<*>>> */
87
        protected $entityClassesMap;
88

89
        /** @var ModifierParser */
90
        protected $modifierParser;
91

92
        /** @var array<string, PropertyMetadata[]> */
93
        protected $classPropertiesCache = [];
94

95
        protected PhpDocParser $phpDocParser;
96
        protected Lexer $phpDocLexer;
97

98

99
        /**
100
         * @param array<class-string<IEntity>, class-string<IRepository<*>>> $entityClassesMap
101
         */
102
        public function __construct(
5 ✔
103
                array $entityClassesMap,
104
                /** @var list<Extension> */
105
                protected array $extensions = [],
2 ✔
106
        )
107
        {
108
                $this->entityClassesMap = $entityClassesMap;
7 ✔
109
                $this->modifierParser = new ModifierParser();
7 ✔
110

111
                // phpdoc-parser 2.0
112
                if (class_exists(ParserConfig::class)) {
7 ✔
113
                        $config = new ParserConfig(usedAttributes: []); // @phpstan-ignore-line
6 ✔
114
                        $this->phpDocLexer = new Lexer($config); // @phpstan-ignore-line
6 ✔
115
                        $constExprParser = new ConstExprParser($config); // @phpstan-ignore-line
6 ✔
116
                        $typeParser = new TypeParser($config, $constExprParser); // @phpstan-ignore-line
6 ✔
117
                        $this->phpDocParser = new PhpDocParser($config, $typeParser, $constExprParser); // @phpstan-ignore-line
6 ✔
118
                } else {
119
                        $this->phpDocLexer = new Lexer(); // @phpstan-ignore-line
1 ✔
120
                        $constExprParser = new ConstExprParser(); // @phpstan-ignore-line
1 ✔
121
                        $typeParser = new TypeParser($constExprParser); // @phpstan-ignore-line
1 ✔
122
                        $this->phpDocParser = new PhpDocParser($typeParser, $constExprParser); // @phpstan-ignore-line
1 ✔
123
                }
124
        }
7 ✔
125

126

127
        /**
128
         * Adds modifier processor.
129
         * @return static
130
         */
131
        public function addModifier(string $modifier, callable $processor)
132
        {
133
                $this->modifiers[strtolower($modifier)] = $processor;
×
134
                return $this;
×
135
        }
136

137

138
        public function parseMetadata(string $entityClass, array|null &$fileDependencies): EntityMetadata
139
        {
140
                $this->reflection = new ReflectionClass($entityClass);
7 ✔
141
                $this->metadata = new EntityMetadata($entityClass);
7 ✔
142

143
                $this->loadProperties($fileDependencies);
7 ✔
144
                $this->loadPropertyHooks();
7 ✔
145
                $this->initPrimaryKey();
7 ✔
146

147
                foreach ($this->extensions as $extension) {
7 ✔
148
                        $extension->configureEntityMetadata($this->metadata);
4 ✔
149
                }
150

151
                if ($fileDependencies !== null) {
7 ✔
152
                        $fileDependencies = array_values(array_unique($fileDependencies));
7 ✔
153
                }
154
                return $this->metadata;
7 ✔
155
        }
156

157

158
        /**
159
         * @param list<string>|null $fileDependencies
160
         */
161
        protected function loadProperties(array|null &$fileDependencies): void
162
        {
163
                $classTree = [$current = $this->reflection->name];
7 ✔
164
                while (($current = get_parent_class($current)) !== false) {
7 ✔
165
                        $classTree[] = $current;
7 ✔
166
                }
167

168
                $methods = [];
7 ✔
169
                foreach ($this->reflection->getMethods() as $method) {
7 ✔
170
                        $methods[strtolower($method->name)] = true;
7 ✔
171
                }
172

173
                foreach (array_reverse($classTree) as $class) {
7 ✔
174
                        if (!isset($this->classPropertiesCache[$class])) {
7 ✔
175
                                $traits = class_uses($class);
7 ✔
176
                                foreach ($traits !== false ? $traits : [] as $traitName) {
7 ✔
177
                                        assert(trait_exists($traitName));
178
                                        $reflectionTrait = new ReflectionClass($traitName);
7 ✔
179
                                        $file = $reflectionTrait->getFileName();
7 ✔
180
                                        if ($file !== false) $fileDependencies[] = $file;
7 ✔
181
                                        $this->currentReflection = $reflectionTrait;
7 ✔
182
                                        $this->classPropertiesCache[$traitName] = $this->parseAnnotations($reflectionTrait, $methods);
7 ✔
183
                                }
184

185
                                $reflection = new ReflectionClass($class);
7 ✔
186
                                $file = $reflection->getFileName();
7 ✔
187
                                if ($file !== false) $fileDependencies[] = $file;
7 ✔
188
                                $this->currentReflection = $reflection;
7 ✔
189
                                $this->classPropertiesCache[$class] = $this->parseAnnotations($reflection, $methods);
7 ✔
190
                        }
191

192
                        $traits = class_uses($class);
7 ✔
193
                        foreach ($traits !== false ? $traits : [] as $traitName) {
7 ✔
194
                                foreach ($this->classPropertiesCache[$traitName] as $name => $property) {
7 ✔
195
                                        $this->metadata->setProperty($name, $property);
7 ✔
196
                                }
197
                        }
198

199
                        foreach ($this->classPropertiesCache[$class] as $name => $property) {
7 ✔
200
                                $this->metadata->setProperty($name, $property);
7 ✔
201
                        }
202
                }
203
        }
7 ✔
204

205

206
        /**
207
         * @param ReflectionClass<object> $reflection
208
         * @param array<string, true> $methods
209
         * @return array<string, PropertyMetadata>
210
         */
211
        protected function parseAnnotations(ReflectionClass $reflection, array $methods): array
212
        {
213
                $docComment = $reflection->getDocComment();
7 ✔
214
                if ($docComment === false) return [];
7 ✔
215

216
                $tokens = new TokenIterator($this->phpDocLexer->tokenize($docComment));
7 ✔
217
                $phpDocNode = $this->phpDocParser->parse($tokens);
7 ✔
218

219
                $properties = [];
7 ✔
220
                foreach ($phpDocNode->getPropertyTagValues() as $propertyTagValue) {
7 ✔
221
                        $property = $this->parseProperty($propertyTagValue, $reflection->getName(), $methods, isReadonly: false);
7 ✔
222
                        $properties[$property->name] = $property;
7 ✔
223
                }
224
                foreach ($phpDocNode->getPropertyWriteTagValues() as $propertyTagValue) {
7 ✔
225
                        $property = $this->parseProperty($propertyTagValue, $reflection->getName(), $methods, isReadonly: false);
×
226
                        $properties[$property->name] = $property;
×
227
                }
228
                foreach ($phpDocNode->getPropertyReadTagValues() as $propertyTagValue) {
7 ✔
229
                        $property = $this->parseProperty($propertyTagValue, $reflection->getName(), $methods, isReadonly: true);
7 ✔
230
                        $properties[$property->name] = $property;
7 ✔
231
                }
232
                return $properties;
7 ✔
233
        }
234

235

236
        protected function loadPropertyHooks(): void
237
        {
238
                if (PHP_VERSION_ID < 80400 || !$this->reflection->implementsInterface(IEntity::class)) return;
7 ✔
239

240
                foreach ($this->reflection->getProperties() as $reflectionProperty) {
3 ✔
241
                        if ($reflectionProperty->getAttributes(VirtualEntityProperty::class) === []) continue;
3 ✔
242
                        // Refine the available APIs for PHPStan analysis targets below PHP 8.4.
243
                        if (
244
                                !method_exists($reflectionProperty, 'getHooks')
3 ✔
245
                                || !method_exists($reflectionProperty, 'isVirtual')
3 ✔
246
                                || !method_exists($reflectionProperty, 'isProtectedSet')
3 ✔
247
                                || !method_exists($reflectionProperty, 'isPrivateSet')
3 ✔
248
                        ) return;
×
249
                        $hooks = $reflectionProperty->getHooks();
3 ✔
250
                        if (!$reflectionProperty->isPublic() || !$reflectionProperty->isVirtual() || !isset($hooks['get'])) {
3 ✔
251
                                throw new NotSupportedException("Attribute VirtualEntityProperty on {$this->reflection->name}::\${$reflectionProperty->name} requires a public virtual property with a get hook.");
3 ✔
252
                        }
253

254
                        $this->currentReflection = $reflectionProperty->getDeclaringClass();
3 ✔
255
                        $property = new PropertyMetadata();
3 ✔
256
                        $property->name = $reflectionProperty->getName();
3 ✔
257
                        $property->containerClassname = $this->currentReflection->getName();
3 ✔
258
                        $property->isVirtual = true;
3 ✔
259
                        $property->hasPropertyHooks = true;
3 ✔
260
                        $property->isReadonly = !isset($hooks['set']) || $reflectionProperty->isProtectedSet() || $reflectionProperty->isPrivateSet();
3 ✔
261
                        $type = $this->getPropertyHookType($reflectionProperty->getType());
3 ✔
262
                        $property->types = $this->getPropertyHookTypeNames($type);
3 ✔
263
                        $property->isNullable = $reflectionProperty->getType()?->allowsNull() ?? true;
3 ✔
264

265
                        foreach ($this->extensions as $extension) {
3 ✔
266
                                $extension->configureEntityPropertyMetadata($this->metadata, $property, $type);
3 ✔
267
                        }
268
                        $this->metadata->setProperty($property->name, $property);
3 ✔
269
                }
270
        }
3 ✔
271

272

273
        protected function getPropertyHookType(ReflectionType|null $type): TypeNode
274
        {
275
                if ($type instanceof ReflectionUnionType) {
3 ✔
276
                        return new UnionTypeNode(array_map($this->getPropertyHookType(...), $type->getTypes()));
3 ✔
277
                } elseif ($type instanceof ReflectionIntersectionType) {
3 ✔
278
                        return new IntersectionTypeNode(array_map($this->getPropertyHookType(...), $type->getTypes()));
×
279
                } elseif ($type instanceof ReflectionNamedType) {
3 ✔
280
                        $name = $type->getName();
3 ✔
281
                        if (!$type->isBuiltin() && $name !== 'self' && $name !== 'parent') {
3 ✔
282
                                $name = '\\' . $name;
3 ✔
283
                        }
284
                        $node = new IdentifierTypeNode($name);
3 ✔
285
                        return $type->allowsNull() ? new NullableTypeNode($node) : $node;
3 ✔
286
                }
287
                return new IdentifierTypeNode('mixed');
3 ✔
288
        }
289

290

291
        /**
292
         * @return non-empty-array<string, bool>
293
         */
294
        protected function getPropertyHookTypeNames(TypeNode $type): array
295
        {
296
                if ($type instanceof NullableTypeNode) {
3 ✔
297
                        return $this->getPropertyHookTypeNames($type->type);
3 ✔
298
                } elseif ($type instanceof UnionTypeNode || $type instanceof IntersectionTypeNode) {
3 ✔
299
                        $types = [];
3 ✔
300
                        foreach ($type->types as $innerType) {
3 ✔
301
                                $types += $this->getPropertyHookTypeNames($innerType);
3 ✔
302
                        }
303
                        return $types !== [] ? $types : ['mixed' => true];
3 ✔
304
                }
305
                assert($type instanceof IdentifierTypeNode);
306
                return [Reflection::expandClassName($type->name, $this->currentReflection) => true];
3 ✔
307
        }
308

309

310
        /**
311
         * @param array<string, true> $methods
312
         */
313
        protected function parseProperty(
314
                PropertyTagValueNode $propertyNode,
315
                string $containerClassName,
316
                array $methods,
317
                bool $isReadonly,
318
        ): PropertyMetadata
319
        {
320
                $property = new PropertyMetadata();
7 ✔
321
                $property->name = substr($propertyNode->propertyName, 1);
7 ✔
322
                $property->containerClassname = $containerClassName;
7 ✔
323
                $property->isReadonly = $isReadonly;
7 ✔
324

325
                $this->parseAnnotationTypes($property, $propertyNode->type);
7 ✔
326
                $this->parseAnnotationValue($property, $propertyNode->description);
7 ✔
327
                $this->processPropertyGettersSetters($property, $methods);
7 ✔
328
                $this->processDefaultPropertyWrappers($property);
7 ✔
329

330
                foreach ($this->extensions as $extension) {
7 ✔
331
                        $extension->configureEntityPropertyMetadata($this->metadata, $property, $propertyNode->type);
4 ✔
332
                }
333

334
                return $property;
7 ✔
335
        }
336

337

338
        protected function parseAnnotationTypes(PropertyMetadata $property, TypeNode $type): void
339
        {
340
                static $aliases = [
7 ✔
341
                        'double' => 'float',
342
                        'real' => 'float',
343
                        'numeric' => 'float',
344
                        'number' => 'float',
345
                        'integer' => 'int',
346
                ];
347

348
                if ($type instanceof UnionTypeNode) {
7 ✔
349
                        $types = $type->types;
7 ✔
350
                } elseif ($type instanceof IntersectionTypeNode) {
7 ✔
351
                        $types = $type->types;
×
352
                } else {
353
                        $types = [$type];
7 ✔
354
                }
355

356
                $parsedTypes = [];
7 ✔
357
                foreach ($types as $subType) {
7 ✔
358
                        if ($subType instanceof NullableTypeNode) {
7 ✔
359
                                $property->isNullable = true;
7 ✔
360
                                $subType = $subType->type;
7 ✔
361
                        }
362
                        if ($subType instanceof GenericTypeNode) {
7 ✔
363
                                $subType = $subType->type;
7 ✔
364
                        }
365

366
                        if ($subType instanceof IdentifierTypeNode) {
7 ✔
367
                                $subTypeName = $subType->name;
7 ✔
368
                                if ($subTypeName === 'boolean') $subTypeName = 'bool'; // avoid expansion, bug in Nette
7 ✔
369
                                $expandedSubType = Reflection::expandClassName($subTypeName, $this->currentReflection);
7 ✔
370
                                $expandedSubTypeLower = strtolower($expandedSubType);
7 ✔
371

372
                                if ($expandedSubTypeLower === 'null') {
7 ✔
373
                                        $property->isNullable = true;
7 ✔
374
                                        continue;
7 ✔
375
                                }
376
                                if ($expandedSubType === DateTime::class || is_subclass_of($expandedSubType, DateTime::class)) {
7 ✔
377
                                        throw new NotSupportedException("Type '{$expandedSubType}' in {$this->currentReflection->name}::\${$property->name} property is not supported anymore. Use \\DateTimeImmutable or \\Nextras\\Dbal\\Utils\\DateTimeImmutable type.");
×
378
                                }
379
                                if (isset($aliases[$expandedSubTypeLower])) {
7 ✔
380
                                        $expandedSubType = $aliases[$expandedSubTypeLower];
×
381
                                }
382
                                $parsedTypes[$expandedSubType] = true;
7 ✔
383
                        } elseif ($subType instanceof ArrayTypeNode) {
7 ✔
384
                                $parsedTypes['array'] = true;
7 ✔
385
                        } elseif ($subType instanceof ArrayShapeNode) {
7 ✔
386
                                $parsedTypes['array'] = true;
7 ✔
387
                        } elseif ($subType instanceof ObjectShapeNode) {
×
388
                                $parsedTypes['object'] = true;
×
389
                        } else {
390
                                throw new NotSupportedException("Type '{$type}' in {$this->currentReflection->name}::\${$property->name} property is not supported. For Nextras Orm purpose simplify it.");
×
391
                        }
392
                }
393

394
                if ($parsedTypes === []) {
7 ✔
395
                        throw new NotSupportedException("Property {$this->currentReflection->name}::\${$property->name} without a type definition is not supported.");
×
396
                }
397
                $property->types = $parsedTypes;
7 ✔
398
        }
7 ✔
399

400

401
        protected function parseAnnotationValue(PropertyMetadata $property, string $propertyComment): void
402
        {
403
                if ($propertyComment === '') {
7 ✔
404
                        return;
7 ✔
405
                }
406

407
                $matches = $this->modifierParser->matchModifiers($propertyComment);
7 ✔
408
                foreach ($matches as $macroContent) {
7 ✔
409
                        try {
410
                                $args = $this->modifierParser->parse($macroContent, $this->currentReflection);
7 ✔
411
                        } catch (InvalidModifierDefinitionException $e) {
7 ✔
412
                                throw new InvalidModifierDefinitionException(
7 ✔
413
                                        "Invalid modifier definition for {$this->currentReflection->name}::\${$property->name} property.",
7 ✔
414
                                        0,
7 ✔
415
                                        $e,
416
                                );
417
                        }
418
                        $this->processPropertyModifier($property, $args[0], $args[1]);
7 ✔
419
                }
420
        }
7 ✔
421

422

423
        /**
424
         * @param array<string, true> $methods
425
         */
426
        protected function processPropertyGettersSetters(PropertyMetadata $property, array $methods): void
427
        {
428
                $getter = 'getter' . strtolower($property->name);
7 ✔
429
                if (isset($methods[$getter])) {
7 ✔
430
                        $property->hasGetter = $getter;
7 ✔
431
                }
432
                $setter = 'setter' . strtolower($property->name);
7 ✔
433
                if (isset($methods[$setter])) {
7 ✔
434
                        $property->hasSetter = $setter;
×
435
                }
436
        }
7 ✔
437

438

439
        protected function processDefaultPropertyWrappers(PropertyMetadata $property): void
440
        {
441
                if ($property->wrapper !== null) return;
7 ✔
442
                if ($property->isVirtual) return;
7 ✔
443

444
                foreach ($property->types as $type => $_) {
7 ✔
445
                        if (is_subclass_of($type, \DateTimeImmutable::class) || $type === \DateTimeImmutable::class) {
7 ✔
446
                                $property->wrapper = DateTimeWrapper::class;
7 ✔
447
                        } elseif (is_subclass_of($type, BackedEnum::class)) {
7 ✔
448
                                $property->wrapper = BackedEnumWrapper::class;
7 ✔
449
                        }
450
                }
451
        }
7 ✔
452

453

454
        /**
455
         * @param array<int|string, mixed> $args
456
         */
457
        protected function processPropertyModifier(PropertyMetadata $property, string $modifier, array $args): void
458
        {
459
                $type = strtolower($modifier);
7 ✔
460
                if (!isset($this->modifiers[$type])) {
7 ✔
461
                        throw new InvalidModifierDefinitionException(
7 ✔
462
                                "Unknown modifier '$type' type for {$this->currentReflection->name}::\${$property->name} property.",
7 ✔
463
                        );
464
                }
465

466
                $callback = $this->modifiers[$type];
7 ✔
467
                if (!is_array($callback)) {
7 ✔
468
                        $callback = [$this, $callback];
7 ✔
469
                }
470
                assert(is_callable($callback));
471
                $callback($property, $args);
7 ✔
472
                if ($args !== []) {
7 ✔
473
                        $parts = [];
7 ✔
474
                        foreach ($args as $key => $val) {
7 ✔
475
                                if (is_numeric($key) && !is_array($val)) {
7 ✔
476
                                        $parts[] = $val;
7 ✔
477
                                        continue;
7 ✔
478
                                }
479
                                $parts[] = $key;
7 ✔
480
                        }
481
                        throw new InvalidModifierDefinitionException(
7 ✔
482
                                "Modifier {{$type}} in {$this->currentReflection->name}::\${$property->name} property has unknown arguments: "
7 ✔
483
                                . implode(', ', $parts)
7 ✔
484
                                . '.',
7 ✔
485
                        );
486
                }
487
        }
7 ✔
488

489

490
        /**
491
         * @param array<int|string, mixed> $args
492
         */
493
        protected function parseOneHasOneModifier(PropertyMetadata $property, array &$args): void
494
        {
495
                $property->relationship = new PropertyRelationshipMetadata();
7 ✔
496
                $property->relationship->type = PropertyRelationshipMetadata::ONE_HAS_ONE;
7 ✔
497
                $property->wrapper = OneHasOne::class;
7 ✔
498
                $this->processRelationshipIsMain($property, $args);
7 ✔
499
                $this->processRelationshipEntityProperty($property, $args);
7 ✔
500
                $this->processRelationshipCascade($property, $args);
7 ✔
501
                assert($property->relationship !== null);
502
                $property->isVirtual = !$property->relationship->isMain;
7 ✔
503
        }
7 ✔
504

505

506
        /**
507
         * @param array<int|string, mixed> $args
508
         */
509
        protected function parseOneHasManyModifier(PropertyMetadata $property, array &$args): void
510
        {
511
                $property->relationship = new PropertyRelationshipMetadata();
7 ✔
512
                $property->relationship->type = PropertyRelationshipMetadata::ONE_HAS_MANY;
7 ✔
513
                $property->wrapper = OneHasMany::class;
7 ✔
514
                $property->isVirtual = true;
7 ✔
515
                $this->processRelationshipEntityProperty($property, $args);
7 ✔
516
                $this->processRelationshipCascade($property, $args);
7 ✔
517
                $this->processRelationshipOrder($property, $args);
7 ✔
518
                $this->processRelationshipExposeCollection($property, $args);
7 ✔
519
        }
7 ✔
520

521

522
        /**
523
         * @param array<int|string, mixed> $args
524
         */
525
        protected function parseManyHasOneModifier(PropertyMetadata $property, array &$args): void
526
        {
527
                $property->relationship = new PropertyRelationshipMetadata();
7 ✔
528
                $property->relationship->type = PropertyRelationshipMetadata::MANY_HAS_ONE;
7 ✔
529
                $property->wrapper = ManyHasOne::class;
7 ✔
530
                $this->processRelationshipEntityProperty($property, $args);
7 ✔
531
                $this->processRelationshipCascade($property, $args);
7 ✔
532
        }
7 ✔
533

534

535
        /**
536
         * @param array<int|string, mixed> $args
537
         */
538
        protected function parseManyHasManyModifier(PropertyMetadata $property, array &$args): void
539
        {
540
                $property->relationship = new PropertyRelationshipMetadata();
7 ✔
541
                $property->relationship->type = PropertyRelationshipMetadata::MANY_HAS_MANY;
7 ✔
542
                $property->wrapper = ManyHasMany::class;
7 ✔
543
                $property->isVirtual = true;
7 ✔
544
                $this->processRelationshipIsMain($property, $args);
7 ✔
545
                $this->processRelationshipEntityProperty($property, $args);
7 ✔
546
                $this->processRelationshipCascade($property, $args);
7 ✔
547
                $this->processRelationshipOrder($property, $args);
7 ✔
548
                $this->processRelationshipExposeCollection($property, $args);
7 ✔
549
        }
7 ✔
550

551

552
        /**
553
         * @param array<int|string, mixed> $args
554
         */
555
        protected function parseEnumModifier(PropertyMetadata $property, array &$args): void
556
        {
557
                $property->enum = $args;
7 ✔
558
                $args = [];
7 ✔
559
        }
7 ✔
560

561

562
        protected function parseVirtualModifier(PropertyMetadata $property): void
563
        {
564
                $property->isVirtual = true;
7 ✔
565
        }
7 ✔
566

567

568
        /**
569
         * @param array<int|string, mixed> $args
570
         */
571
        protected function parseContainerModifier(PropertyMetadata $property, array &$args): void
572
        {
573
                trigger_error(
×
574
                        'Property modifier {container} is deprecated; rename it to {wrapper} modifier.',
575
                        E_USER_DEPRECATED,
×
576
                );
577
                $this->parseWrapperModifier($property, $args);
×
578
        }
×
579

580

581
        /**
582
         * @param array<int|string, mixed> $args
583
         */
584
        protected function parseWrapperModifier(PropertyMetadata $property, array &$args): void
585
        {
586
                $className = Reflection::expandClassName(array_shift($args), $this->currentReflection);
7 ✔
587
                if (!class_exists($className)) {
7 ✔
588
                        throw new InvalidModifierDefinitionException("Class '$className' in {wrapper} for {$this->currentReflection->name}::\${$property->name} property does not exist.");
7 ✔
589
                }
590
                $implements = class_implements($className);
7 ✔
591
                if ($implements !== false && !isset($implements[IProperty::class])) {
7 ✔
592
                        throw new InvalidModifierDefinitionException("Class '$className' in {wrapper} for {$this->currentReflection->name}::\${$property->name} property does not implement Nextras\\Orm\\Entity\\IProperty interface.");
7 ✔
593
                }
594
                $property->wrapper = $className;
7 ✔
595
        }
7 ✔
596

597

598
        /**
599
         * @param array<int|string, mixed> $args
600
         */
601
        protected function parseDefaultModifier(PropertyMetadata $property, array &$args): void
602
        {
603
                $property->defaultValue = array_shift($args);
7 ✔
604
        }
7 ✔
605

606

607
        protected function parsePrimaryModifier(PropertyMetadata $property): void
608
        {
609
                $property->isPrimary = true;
7 ✔
610
        }
7 ✔
611

612

613
        protected function parsePrimaryProxyModifier(PropertyMetadata $property): void
614
        {
615
                $property->isVirtual = true;
7 ✔
616
                $property->isPrimary = true;
7 ✔
617
                if ($property->hasGetter === null && $property->hasSetter === null) {
7 ✔
618
                        $property->wrapper = PrimaryProxyWrapper::class;
7 ✔
619
                }
620
        }
7 ✔
621

622

623
        protected function parseEmbeddableModifier(PropertyMetadata $property): void
624
        {
625
                if (count($property->types) !== 1) {
7 ✔
626
                        $num = count($property->types);
×
627
                        throw new InvalidModifierDefinitionException("Embeddable modifer requries only one class type definition, optionally nullable. $num types detected in {$this->currentReflection->name}::\${$property->name} property.");
×
628
                }
629
                $className = array_keys($property->types)[0];
7 ✔
630
                if (!class_exists($className)) {
7 ✔
631
                        throw new InvalidModifierDefinitionException("Class '$className' in {embeddable} for {$this->currentReflection->name}::\${$property->name} property does not exist.");
×
632
                }
633
                if (!is_subclass_of($className, IEmbeddable::class)) {
7 ✔
634
                        throw new InvalidModifierDefinitionException("Class '$className' in {embeddable} for {$this->currentReflection->name}::\${$property->name} property does not implement " . IEmbeddable::class . ' interface.');
×
635
                }
636

637
                $property->wrapper = EmbeddableContainer::class;
7 ✔
638
                $property->args[EmbeddableContainer::class] = ['class' => $className];
7 ✔
639
        }
7 ✔
640

641

642
        protected function initPrimaryKey(): void
643
        {
644
                if ($this->reflection->isSubclassOf(IEmbeddable::class)) {
7 ✔
645
                        return;
7 ✔
646
                }
647

648
                $primaryKey = [];
7 ✔
649
                foreach ($this->metadata->getProperties() as $metadata) {
7 ✔
650
                        if ($metadata->isPrimary && !$metadata->isVirtual) {
7 ✔
651
                                $primaryKey[] = $metadata->name;
7 ✔
652
                        }
653
                }
654

655
                if ($primaryKey === []) {
7 ✔
656
                        throw new InvalidStateException("Entity {$this->reflection->name} does not have defined any primary key.");
7 ✔
657
                } elseif (!$this->metadata->hasProperty('id') || !$this->metadata->getProperty('id')->isPrimary) {
7 ✔
658
                        throw new InvalidStateException("Entity {$this->reflection->name} has to have defined \$id property as {primary} or {primary-proxy}.");
×
659
                }
660

661
                $this->metadata->setPrimaryKey($primaryKey);
7 ✔
662
        }
7 ✔
663

664

665
        /**
666
         * @param array<int|string, mixed> $args
667
         */
668
        protected function processRelationshipEntityProperty(PropertyMetadata $property, array &$args): void
669
        {
670
                assert($property->relationship !== null);
671
                static $modifiersMap = [
7 ✔
672
                        PropertyRelationshipMetadata::ONE_HAS_MANY => '1:m',
4 ✔
673
                        PropertyRelationshipMetadata::ONE_HAS_ONE => '1:1',
4 ✔
674
                        PropertyRelationshipMetadata::MANY_HAS_ONE => 'm:1',
4 ✔
675
                        PropertyRelationshipMetadata::MANY_HAS_MANY => 'm:m',
4 ✔
676
                ];
677
                $modifier = $modifiersMap[$property->relationship->type];
7 ✔
678
                $class = array_shift($args);
7 ✔
679

680
                if ($class === null) {
7 ✔
681
                        throw new InvalidModifierDefinitionException("Relationship {{$modifier}} in {$this->currentReflection->name}::\${$property->name} has not defined target entity and its property name.");
7 ✔
682
                }
683

684
                $pos = strpos($class, '::');
7 ✔
685
                if ($pos === false) {
7 ✔
686
                        if (preg_match('#^[a-z0-9_\\\\]+$#i', $class) !== 1) {
7 ✔
687
                                throw new InvalidModifierDefinitionException("Relationship {{$modifier}} in {$this->currentReflection->name}::\${$property->name} has invalid class name of the target entity. Use Entity::\$property format.");
7 ✔
688
                        } elseif (!(isset($args['oneSided']) && $args['oneSided'] === true)) {
7 ✔
689
                                throw new InvalidModifierDefinitionException("Relationship {{$modifier}} in {$this->currentReflection->name}::\${$property->name} has not defined target property name.");
7 ✔
690
                        } else {
691
                                $targetProperty = null;
7 ✔
692
                                unset($args['oneSided']);
7 ✔
693
                        }
694
                } else {
695
                        $targetProperty = substr($class, $pos + 3); // skip ::$
7 ✔
696
                        assert($targetProperty !== false); // @phpstan-ignore-line
697
                        $class = substr($class, 0, $pos);
7 ✔
698

699
                        if (isset($args['oneSided'])) {
7 ✔
700
                                throw new InvalidModifierDefinitionException("Relationship {{$modifier}} in {$this->currentReflection->name}::\${$property->name} has set oneSided property but it also specifies target property \${$targetProperty}.");
×
701
                        }
702
                }
703

704
                /** @var class-string<IEntity> $entity */
705
                $entity = Reflection::expandClassName($class, $this->currentReflection);
7 ✔
706
                if (!isset($this->entityClassesMap[$entity])) {
7 ✔
707
                        throw new InvalidModifierDefinitionException("Relationship {{$modifier}} in {$this->currentReflection->name}::\${$property->name} points to unknown '{$entity}' entity. Don't forget to return it in IRepository::getEntityClassNames() and register its repository.");
7 ✔
708
                }
709

710
                $property->relationship->entity = $entity;
7 ✔
711
                $property->relationship->repository = $this->entityClassesMap[$entity];
7 ✔
712
                $property->relationship->property = $targetProperty;
7 ✔
713
        }
7 ✔
714

715

716
        /**
717
         * @param array<int|string, mixed> $args
718
         */
719
        protected function processRelationshipCascade(PropertyMetadata $property, array &$args): void
720
        {
721
                assert($property->relationship !== null);
722
                $property->relationship->cascade = $defaults = [
7 ✔
723
                        'persist' => false,
724
                        'remove' => false,
725
                        'removeOrphan' => false,
726
                ];
727

728
                if (!isset($args['cascade'])) {
7 ✔
729
                        $property->relationship->cascade['persist'] = true;
7 ✔
730
                        return;
7 ✔
731
                }
732

733
                foreach ((array) $args['cascade'] as $cascade) {
7 ✔
734
                        if (!isset($defaults[$cascade])) {
7 ✔
735
                                throw new InvalidModifierDefinitionException();
×
736
                        }
737
                        $property->relationship->cascade[$cascade] = true;
7 ✔
738
                }
739
                unset($args['cascade']);
7 ✔
740
        }
7 ✔
741

742

743
        /**
744
         * @param array<int|string, mixed> $args
745
         */
746
        protected function processRelationshipOrder(PropertyMetadata $property, array &$args): void
747
        {
748
                assert($property->relationship !== null);
749
                if (!isset($args['orderBy'])) {
7 ✔
750
                        return;
7 ✔
751
                }
752

753
                if (is_string($args['orderBy'])) {
7 ✔
754
                        $order = [$args['orderBy'] => ICollection::ASC];
7 ✔
755
                } elseif (is_array($args['orderBy']) && isset($args['orderBy'][0])) {
7 ✔
756
                        $order = [$args['orderBy'][0] => $args['orderBy'][1] ?? ICollection::ASC];
×
757
                } else {
758
                        $order = $args['orderBy'];
7 ✔
759
                }
760

761
                $property->relationship->order = $order;
7 ✔
762
                unset($args['orderBy']);
7 ✔
763
        }
7 ✔
764

765

766
        /**
767
         * @param array<int|string, mixed> $args
768
         */
769
        protected function processRelationshipExposeCollection(PropertyMetadata $property, array &$args): void
770
        {
771
                if (isset($args['exposeCollection']) && $args['exposeCollection'] === true) {
7 ✔
772
                        $property->args[HasMany::class]['exposeCollection'] = true;
7 ✔
773
                }
774
                unset($args['exposeCollection']);
7 ✔
775
        }
7 ✔
776

777

778
        /**
779
         * @param array<int|string, mixed> $args
780
         */
781
        protected function processRelationshipIsMain(PropertyMetadata $property, array &$args): void
782
        {
783
                assert($property->relationship !== null);
784
                $property->relationship->isMain = isset($args['isMain']) && $args['isMain'] === true;
7 ✔
785
                unset($args['isMain']);
7 ✔
786
        }
7 ✔
787
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE TRIAL · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc