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

nextras / orm / 42524199264

08 Nov 2026 09:14PM UTC coverage: 92.235% (+0.2%) from 92.065%
42524199264

Pull #849

github

web-flow
Merge 70aa36c18 into 8f6f66123
Pull Request #849: Support virtual entity properties with PHP property hooks [closes #684]

53 of 54 new or added lines in 4 files covered. (98.15%)

17 existing lines in 1 file now uncovered.

4466 of 4842 relevant lines covered (92.23%)

6.27 hits per line

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

92.63
/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);
3 ✔
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
                        $hooks = $reflectionProperty->getHooks();
3 ✔
243
                        if (!$reflectionProperty->isPublic() || !$reflectionProperty->isVirtual() || !isset($hooks['get'])) {
3 ✔
244
                                throw new NotSupportedException("Attribute VirtualEntityProperty on {$this->reflection->name}::\${$reflectionProperty->name} requires a public virtual property with a get hook.");
3 ✔
245
                        }
246

247
                        $this->currentReflection = $reflectionProperty->getDeclaringClass();
3 ✔
248
                        $property = new PropertyMetadata();
3 ✔
249
                        $property->name = $reflectionProperty->getName();
3 ✔
250
                        $property->containerClassname = $this->currentReflection->getName();
3 ✔
251
                        $property->isVirtual = true;
3 ✔
252
                        $property->hasPropertyHooks = true;
3 ✔
253
                        $property->isReadonly = !isset($hooks['set']) || $reflectionProperty->isProtectedSet() || $reflectionProperty->isPrivateSet();
3 ✔
254
                        $type = $this->getPropertyHookType($reflectionProperty->getType());
3 ✔
255
                        $property->types = $this->getPropertyHookTypeNames($type);
3 ✔
256
                        $property->isNullable = $reflectionProperty->getType()?->allowsNull() ?? true;
3 ✔
257

258
                        foreach ($this->extensions as $extension) {
3 ✔
259
                                $extension->configureEntityPropertyMetadata($this->metadata, $property, $type);
3 ✔
260
                        }
261
                        $this->metadata->setProperty($property->name, $property);
3 ✔
262
                }
263
        }
3 ✔
264

265

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

283

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

302

303
        /**
304
         * @param array<string, true> $methods
305
         */
306
        protected function parseProperty(
307
                PropertyTagValueNode $propertyNode,
308
                string $containerClassName,
309
                array $methods,
310
                bool $isReadonly,
311
        ): PropertyMetadata
312
        {
313
                $property = new PropertyMetadata();
7 ✔
314
                $property->name = substr($propertyNode->propertyName, 1);
7 ✔
315
                $property->containerClassname = $containerClassName;
7 ✔
316
                $property->isReadonly = $isReadonly;
7 ✔
317

318
                $this->parseAnnotationTypes($property, $propertyNode->type);
7 ✔
319
                $this->parseAnnotationValue($property, $propertyNode->description);
7 ✔
320
                $this->processPropertyGettersSetters($property, $methods);
7 ✔
321
                $this->processDefaultPropertyWrappers($property);
7 ✔
322

323
                foreach ($this->extensions as $extension) {
7 ✔
324
                        $extension->configureEntityPropertyMetadata($this->metadata, $property, $propertyNode->type);
3 ✔
325
                }
326

327
                return $property;
7 ✔
328
        }
329

330

331
        protected function parseAnnotationTypes(PropertyMetadata $property, TypeNode $type): void
332
        {
333
                static $aliases = [
7 ✔
334
                        'double' => 'float',
335
                        'real' => 'float',
336
                        'numeric' => 'float',
337
                        'number' => 'float',
338
                        'integer' => 'int',
339
                ];
340

341
                if ($type instanceof UnionTypeNode) {
7 ✔
342
                        $types = $type->types;
7 ✔
343
                } elseif ($type instanceof IntersectionTypeNode) {
7 ✔
UNCOV
344
                        $types = $type->types;
×
345
                } else {
346
                        $types = [$type];
7 ✔
347
                }
348

349
                $parsedTypes = [];
7 ✔
350
                foreach ($types as $subType) {
7 ✔
351
                        if ($subType instanceof NullableTypeNode) {
7 ✔
352
                                $property->isNullable = true;
7 ✔
353
                                $subType = $subType->type;
7 ✔
354
                        }
355
                        if ($subType instanceof GenericTypeNode) {
7 ✔
356
                                $subType = $subType->type;
7 ✔
357
                        }
358

359
                        if ($subType instanceof IdentifierTypeNode) {
7 ✔
360
                                $subTypeName = $subType->name;
7 ✔
361
                                if ($subTypeName === 'boolean') $subTypeName = 'bool'; // avoid expansion, bug in Nette
7 ✔
362
                                $expandedSubType = Reflection::expandClassName($subTypeName, $this->currentReflection);
7 ✔
363
                                $expandedSubTypeLower = strtolower($expandedSubType);
7 ✔
364

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

387
                if ($parsedTypes === []) {
7 ✔
388
                        throw new NotSupportedException("Property {$this->currentReflection->name}::\${$property->name} without a type definition is not supported.");
×
389
                }
390
                $property->types = $parsedTypes;
7 ✔
391
        }
7 ✔
392

393

394
        protected function parseAnnotationValue(PropertyMetadata $property, string $propertyComment): void
395
        {
396
                if ($propertyComment === '') {
7 ✔
397
                        return;
7 ✔
398
                }
399

400
                $matches = $this->modifierParser->matchModifiers($propertyComment);
7 ✔
401
                foreach ($matches as $macroContent) {
7 ✔
402
                        try {
403
                                $args = $this->modifierParser->parse($macroContent, $this->currentReflection);
7 ✔
404
                        } catch (InvalidModifierDefinitionException $e) {
7 ✔
405
                                throw new InvalidModifierDefinitionException(
7 ✔
406
                                        "Invalid modifier definition for {$this->currentReflection->name}::\${$property->name} property.",
7 ✔
407
                                        0,
7 ✔
408
                                        $e,
409
                                );
410
                        }
411
                        $this->processPropertyModifier($property, $args[0], $args[1]);
7 ✔
412
                }
413
        }
7 ✔
414

415

416
        /**
417
         * @param array<string, true> $methods
418
         */
419
        protected function processPropertyGettersSetters(PropertyMetadata $property, array $methods): void
420
        {
421
                $getter = 'getter' . strtolower($property->name);
7 ✔
422
                if (isset($methods[$getter])) {
7 ✔
423
                        $property->hasGetter = $getter;
7 ✔
424
                }
425
                $setter = 'setter' . strtolower($property->name);
7 ✔
426
                if (isset($methods[$setter])) {
7 ✔
UNCOV
427
                        $property->hasSetter = $setter;
×
428
                }
429
        }
7 ✔
430

431

432
        protected function processDefaultPropertyWrappers(PropertyMetadata $property): void
433
        {
434
                if ($property->wrapper !== null) return;
7 ✔
435
                if ($property->isVirtual) return;
7 ✔
436

437
                foreach ($property->types as $type => $_) {
7 ✔
438
                        if (is_subclass_of($type, \DateTimeImmutable::class) || $type === \DateTimeImmutable::class) {
7 ✔
439
                                $property->wrapper = DateTimeWrapper::class;
7 ✔
440
                        } elseif (is_subclass_of($type, BackedEnum::class)) {
7 ✔
441
                                $property->wrapper = BackedEnumWrapper::class;
7 ✔
442
                        }
443
                }
444
        }
7 ✔
445

446

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

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

482

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

498

499
        /**
500
         * @param array<int|string, mixed> $args
501
         */
502
        protected function parseOneHasManyModifier(PropertyMetadata $property, array &$args): void
503
        {
504
                $property->relationship = new PropertyRelationshipMetadata();
7 ✔
505
                $property->relationship->type = PropertyRelationshipMetadata::ONE_HAS_MANY;
7 ✔
506
                $property->wrapper = OneHasMany::class;
7 ✔
507
                $property->isVirtual = true;
7 ✔
508
                $this->processRelationshipEntityProperty($property, $args);
7 ✔
509
                $this->processRelationshipCascade($property, $args);
7 ✔
510
                $this->processRelationshipOrder($property, $args);
7 ✔
511
                $this->processRelationshipExposeCollection($property, $args);
7 ✔
512
        }
7 ✔
513

514

515
        /**
516
         * @param array<int|string, mixed> $args
517
         */
518
        protected function parseManyHasOneModifier(PropertyMetadata $property, array &$args): void
519
        {
520
                $property->relationship = new PropertyRelationshipMetadata();
7 ✔
521
                $property->relationship->type = PropertyRelationshipMetadata::MANY_HAS_ONE;
7 ✔
522
                $property->wrapper = ManyHasOne::class;
7 ✔
523
                $this->processRelationshipEntityProperty($property, $args);
7 ✔
524
                $this->processRelationshipCascade($property, $args);
7 ✔
525
        }
7 ✔
526

527

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

544

545
        /**
546
         * @param array<int|string, mixed> $args
547
         */
548
        protected function parseEnumModifier(PropertyMetadata $property, array &$args): void
549
        {
550
                $property->enum = $args;
7 ✔
551
                $args = [];
7 ✔
552
        }
7 ✔
553

554

555
        protected function parseVirtualModifier(PropertyMetadata $property): void
556
        {
557
                $property->isVirtual = true;
7 ✔
558
        }
7 ✔
559

560

561
        /**
562
         * @param array<int|string, mixed> $args
563
         */
564
        protected function parseContainerModifier(PropertyMetadata $property, array &$args): void
565
        {
UNCOV
566
                trigger_error(
×
567
                        'Property modifier {container} is deprecated; rename it to {wrapper} modifier.',
UNCOV
568
                        E_USER_DEPRECATED,
×
569
                );
UNCOV
570
                $this->parseWrapperModifier($property, $args);
×
UNCOV
571
        }
×
572

573

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

590

591
        /**
592
         * @param array<int|string, mixed> $args
593
         */
594
        protected function parseDefaultModifier(PropertyMetadata $property, array &$args): void
595
        {
596
                $property->defaultValue = array_shift($args);
7 ✔
597
        }
7 ✔
598

599

600
        protected function parsePrimaryModifier(PropertyMetadata $property): void
601
        {
602
                $property->isPrimary = true;
7 ✔
603
        }
7 ✔
604

605

606
        protected function parsePrimaryProxyModifier(PropertyMetadata $property): void
607
        {
608
                $property->isVirtual = true;
7 ✔
609
                $property->isPrimary = true;
7 ✔
610
                if ($property->hasGetter === null && $property->hasSetter === null) {
7 ✔
611
                        $property->wrapper = PrimaryProxyWrapper::class;
7 ✔
612
                }
613
        }
7 ✔
614

615

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

630
                $property->wrapper = EmbeddableContainer::class;
7 ✔
631
                $property->args[EmbeddableContainer::class] = ['class' => $className];
7 ✔
632
        }
7 ✔
633

634

635
        protected function initPrimaryKey(): void
636
        {
637
                if ($this->reflection->isSubclassOf(IEmbeddable::class)) {
7 ✔
638
                        return;
7 ✔
639
                }
640

641
                $primaryKey = [];
7 ✔
642
                foreach ($this->metadata->getProperties() as $metadata) {
7 ✔
643
                        if ($metadata->isPrimary && !$metadata->isVirtual) {
7 ✔
644
                                $primaryKey[] = $metadata->name;
7 ✔
645
                        }
646
                }
647

648
                if ($primaryKey === []) {
7 ✔
649
                        throw new InvalidStateException("Entity {$this->reflection->name} does not have defined any primary key.");
7 ✔
650
                } elseif (!$this->metadata->hasProperty('id') || !$this->metadata->getProperty('id')->isPrimary) {
7 ✔
UNCOV
651
                        throw new InvalidStateException("Entity {$this->reflection->name} has to have defined \$id property as {primary} or {primary-proxy}.");
×
652
                }
653

654
                $this->metadata->setPrimaryKey($primaryKey);
7 ✔
655
        }
7 ✔
656

657

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

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

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

692
                        if (isset($args['oneSided'])) {
7 ✔
UNCOV
693
                                throw new InvalidModifierDefinitionException("Relationship {{$modifier}} in {$this->currentReflection->name}::\${$property->name} has set oneSided property but it also specifies target property \${$targetProperty}.");
×
694
                        }
695
                }
696

697
                /** @var class-string<IEntity> $entity */
698
                $entity = Reflection::expandClassName($class, $this->currentReflection);
7 ✔
699
                if (!isset($this->entityClassesMap[$entity])) {
7 ✔
700
                        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 ✔
701
                }
702

703
                $property->relationship->entity = $entity;
7 ✔
704
                $property->relationship->repository = $this->entityClassesMap[$entity];
7 ✔
705
                $property->relationship->property = $targetProperty;
7 ✔
706
        }
7 ✔
707

708

709
        /**
710
         * @param array<int|string, mixed> $args
711
         */
712
        protected function processRelationshipCascade(PropertyMetadata $property, array &$args): void
713
        {
714
                assert($property->relationship !== null);
715
                $property->relationship->cascade = $defaults = [
7 ✔
716
                        'persist' => false,
717
                        'remove' => false,
718
                        'removeOrphan' => false,
719
                ];
720

721
                if (!isset($args['cascade'])) {
7 ✔
722
                        $property->relationship->cascade['persist'] = true;
7 ✔
723
                        return;
7 ✔
724
                }
725

726
                foreach ((array) $args['cascade'] as $cascade) {
7 ✔
727
                        if (!isset($defaults[$cascade])) {
7 ✔
UNCOV
728
                                throw new InvalidModifierDefinitionException();
×
729
                        }
730
                        $property->relationship->cascade[$cascade] = true;
7 ✔
731
                }
732
                unset($args['cascade']);
7 ✔
733
        }
7 ✔
734

735

736
        /**
737
         * @param array<int|string, mixed> $args
738
         */
739
        protected function processRelationshipOrder(PropertyMetadata $property, array &$args): void
740
        {
741
                assert($property->relationship !== null);
742
                if (!isset($args['orderBy'])) {
7 ✔
743
                        return;
7 ✔
744
                }
745

746
                if (is_string($args['orderBy'])) {
7 ✔
747
                        $order = [$args['orderBy'] => ICollection::ASC];
7 ✔
748
                } elseif (is_array($args['orderBy']) && isset($args['orderBy'][0])) {
7 ✔
UNCOV
749
                        $order = [$args['orderBy'][0] => $args['orderBy'][1] ?? ICollection::ASC];
×
750
                } else {
751
                        $order = $args['orderBy'];
7 ✔
752
                }
753

754
                $property->relationship->order = $order;
7 ✔
755
                unset($args['orderBy']);
7 ✔
756
        }
7 ✔
757

758

759
        /**
760
         * @param array<int|string, mixed> $args
761
         */
762
        protected function processRelationshipExposeCollection(PropertyMetadata $property, array &$args): void
763
        {
764
                if (isset($args['exposeCollection']) && $args['exposeCollection'] === true) {
7 ✔
765
                        $property->args[HasMany::class]['exposeCollection'] = true;
7 ✔
766
                }
767
                unset($args['exposeCollection']);
7 ✔
768
        }
7 ✔
769

770

771
        /**
772
         * @param array<int|string, mixed> $args
773
         */
774
        protected function processRelationshipIsMain(PropertyMetadata $property, array &$args): void
775
        {
776
                assert($property->relationship !== null);
777
                $property->relationship->isMain = isset($args['isMain']) && $args['isMain'] === true;
7 ✔
778
                unset($args['isMain']);
7 ✔
779
        }
7 ✔
780
}
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