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

nextras / orm / 42516538376

08 Nov 2026 07:44PM UTC coverage: 91.931% (-0.08%) from 92.015%
42516538376

push

github

web-flow
fix(deps): update dependency nette/caching to v4 (#845)

Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>

4398 of 4784 relevant lines covered (91.93%)

6.29 hits per line

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

91.3
/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\Exception\InvalidStateException;
20
use Nextras\Orm\Exception\NotSupportedException;
21
use Nextras\Orm\Extension;
22
use Nextras\Orm\Relationships\HasMany;
23
use Nextras\Orm\Relationships\ManyHasMany;
24
use Nextras\Orm\Relationships\ManyHasOne;
25
use Nextras\Orm\Relationships\OneHasMany;
26
use Nextras\Orm\Relationships\OneHasOne;
27
use Nextras\Orm\Repository\IRepository;
28
use PHPStan\PhpDocParser\Ast\PhpDoc\PropertyTagValueNode;
29
use PHPStan\PhpDocParser\Ast\Type\ArrayShapeNode;
30
use PHPStan\PhpDocParser\Ast\Type\ArrayTypeNode;
31
use PHPStan\PhpDocParser\Ast\Type\GenericTypeNode;
32
use PHPStan\PhpDocParser\Ast\Type\IdentifierTypeNode;
33
use PHPStan\PhpDocParser\Ast\Type\IntersectionTypeNode;
34
use PHPStan\PhpDocParser\Ast\Type\NullableTypeNode;
35
use PHPStan\PhpDocParser\Ast\Type\ObjectShapeNode;
36
use PHPStan\PhpDocParser\Ast\Type\TypeNode;
37
use PHPStan\PhpDocParser\Ast\Type\UnionTypeNode;
38
use PHPStan\PhpDocParser\Lexer\Lexer;
39
use PHPStan\PhpDocParser\Parser\ConstExprParser;
40
use PHPStan\PhpDocParser\Parser\PhpDocParser;
41
use PHPStan\PhpDocParser\Parser\TokenIterator;
42
use PHPStan\PhpDocParser\Parser\TypeParser;
43
use PHPStan\PhpDocParser\ParserConfig;
44
use ReflectionClass;
45
use function array_keys;
46
use function assert;
47
use function class_exists;
48
use function count;
49
use function is_subclass_of;
50
use function substr;
51
use function trigger_error;
52

53

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

72
        /** @var ReflectionClass<object> */
73
        protected $reflection;
74

75
        /** @var ReflectionClass<object> */
76
        protected $currentReflection;
77

78
        /** @var EntityMetadata */
79
        protected $metadata;
80

81
        /** @var array<class-string<IEntity>, class-string<IRepository<*>>> */
82
        protected $entityClassesMap;
83

84
        /** @var ModifierParser */
85
        protected $modifierParser;
86

87
        /** @var array<string, PropertyMetadata[]> */
88
        protected $classPropertiesCache = [];
89

90
        protected PhpDocParser $phpDocParser;
91
        protected Lexer $phpDocLexer;
92

93

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

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

121

122
        /**
123
         * Adds modifier processor.
124
         * @return static
125
         */
126
        public function addModifier(string $modifier, callable $processor)
127
        {
128
                $this->modifiers[strtolower($modifier)] = $processor;
×
129
                return $this;
×
130
        }
131

132

133
        public function parseMetadata(string $entityClass, array|null &$fileDependencies): EntityMetadata
134
        {
135
                $this->reflection = new ReflectionClass($entityClass);
7 ✔
136
                $this->metadata = new EntityMetadata($entityClass);
7 ✔
137

138
                $this->loadProperties($fileDependencies);
7 ✔
139
                $this->initPrimaryKey();
7 ✔
140

141
                foreach ($this->extensions as $extension) {
7 ✔
142
                        $extension->configureEntityMetadata($this->metadata);
×
143
                }
144

145
                if ($fileDependencies !== null) {
7 ✔
146
                        $fileDependencies = array_values(array_unique($fileDependencies));
7 ✔
147
                }
148
                return $this->metadata;
7 ✔
149
        }
150

151

152
        /**
153
         * @param list<string>|null $fileDependencies
154
         */
155
        protected function loadProperties(array|null &$fileDependencies): void
156
        {
157
                $classTree = [$current = $this->reflection->name];
7 ✔
158
                while (($current = get_parent_class($current)) !== false) {
7 ✔
159
                        $classTree[] = $current;
7 ✔
160
                }
161

162
                $methods = [];
7 ✔
163
                foreach ($this->reflection->getMethods() as $method) {
7 ✔
164
                        $methods[strtolower($method->name)] = true;
7 ✔
165
                }
166

167
                foreach (array_reverse($classTree) as $class) {
7 ✔
168
                        if (!isset($this->classPropertiesCache[$class])) {
7 ✔
169
                                $traits = class_uses($class);
7 ✔
170
                                foreach ($traits !== false ? $traits : [] as $traitName) {
7 ✔
171
                                        assert(trait_exists($traitName));
172
                                        $reflectionTrait = new ReflectionClass($traitName);
7 ✔
173
                                        $file = $reflectionTrait->getFileName();
7 ✔
174
                                        if ($file !== false) $fileDependencies[] = $file;
7 ✔
175
                                        $this->currentReflection = $reflectionTrait;
7 ✔
176
                                        $this->classPropertiesCache[$traitName] = $this->parseAnnotations($reflectionTrait, $methods);
7 ✔
177
                                }
178

179
                                $reflection = new ReflectionClass($class);
7 ✔
180
                                $file = $reflection->getFileName();
7 ✔
181
                                if ($file !== false) $fileDependencies[] = $file;
7 ✔
182
                                $this->currentReflection = $reflection;
7 ✔
183
                                $this->classPropertiesCache[$class] = $this->parseAnnotations($reflection, $methods);
7 ✔
184
                        }
185

186
                        $traits = class_uses($class);
7 ✔
187
                        foreach ($traits !== false ? $traits : [] as $traitName) {
7 ✔
188
                                foreach ($this->classPropertiesCache[$traitName] as $name => $property) {
7 ✔
189
                                        $this->metadata->setProperty($name, $property);
7 ✔
190
                                }
191
                        }
192

193
                        foreach ($this->classPropertiesCache[$class] as $name => $property) {
7 ✔
194
                                $this->metadata->setProperty($name, $property);
7 ✔
195
                        }
196
                }
197
        }
7 ✔
198

199

200
        /**
201
         * @param ReflectionClass<object> $reflection
202
         * @param array<string, true> $methods
203
         * @return array<string, PropertyMetadata>
204
         */
205
        protected function parseAnnotations(ReflectionClass $reflection, array $methods): array
206
        {
207
                $docComment = $reflection->getDocComment();
7 ✔
208
                if ($docComment === false) return [];
7 ✔
209

210
                $tokens = new TokenIterator($this->phpDocLexer->tokenize($docComment));
7 ✔
211
                $phpDocNode = $this->phpDocParser->parse($tokens);
7 ✔
212

213
                $properties = [];
7 ✔
214
                foreach ($phpDocNode->getPropertyTagValues() as $propertyTagValue) {
7 ✔
215
                        $property = $this->parseProperty($propertyTagValue, $reflection->getName(), $methods, isReadonly: false);
7 ✔
216
                        $properties[$property->name] = $property;
7 ✔
217
                }
218
                foreach ($phpDocNode->getPropertyWriteTagValues() as $propertyTagValue) {
7 ✔
219
                        $property = $this->parseProperty($propertyTagValue, $reflection->getName(), $methods, isReadonly: false);
×
220
                        $properties[$property->name] = $property;
×
221
                }
222
                foreach ($phpDocNode->getPropertyReadTagValues() as $propertyTagValue) {
7 ✔
223
                        $property = $this->parseProperty($propertyTagValue, $reflection->getName(), $methods, isReadonly: true);
7 ✔
224
                        $properties[$property->name] = $property;
7 ✔
225
                }
226
                return $properties;
7 ✔
227
        }
228

229

230
        /**
231
         * @param array<string, true> $methods
232
         */
233
        protected function parseProperty(
234
                PropertyTagValueNode $propertyNode,
235
                string $containerClassName,
236
                array $methods,
237
                bool $isReadonly,
238
        ): PropertyMetadata
239
        {
240
                $property = new PropertyMetadata();
7 ✔
241
                $property->name = substr($propertyNode->propertyName, 1);
7 ✔
242
                $property->containerClassname = $containerClassName;
7 ✔
243
                $property->isReadonly = $isReadonly;
7 ✔
244

245
                $this->parseAnnotationTypes($property, $propertyNode->type);
7 ✔
246
                $this->parseAnnotationValue($property, $propertyNode->description);
7 ✔
247
                $this->processPropertyGettersSetters($property, $methods);
7 ✔
248
                $this->processDefaultPropertyWrappers($property);
7 ✔
249

250
                foreach ($this->extensions as $extension) {
7 ✔
251
                        $extension->configureEntityPropertyMetadata($this->metadata, $property, $propertyNode->type);
×
252
                }
253

254
                return $property;
7 ✔
255
        }
256

257

258
        protected function parseAnnotationTypes(PropertyMetadata $property, TypeNode $type): void
259
        {
260
                static $aliases = [
7 ✔
261
                        'double' => 'float',
262
                        'real' => 'float',
263
                        'numeric' => 'float',
264
                        'number' => 'float',
265
                        'integer' => 'int',
266
                ];
267

268
                if ($type instanceof UnionTypeNode) {
7 ✔
269
                        $types = $type->types;
7 ✔
270
                } elseif ($type instanceof IntersectionTypeNode) {
7 ✔
271
                        $types = $type->types;
×
272
                } else {
273
                        $types = [$type];
7 ✔
274
                }
275

276
                $parsedTypes = [];
7 ✔
277
                foreach ($types as $subType) {
7 ✔
278
                        if ($subType instanceof NullableTypeNode) {
7 ✔
279
                                $property->isNullable = true;
7 ✔
280
                                $subType = $subType->type;
7 ✔
281
                        }
282
                        if ($subType instanceof GenericTypeNode) {
7 ✔
283
                                $subType = $subType->type;
7 ✔
284
                        }
285

286
                        if ($subType instanceof IdentifierTypeNode) {
7 ✔
287
                                $subTypeName = $subType->name;
7 ✔
288
                                if ($subTypeName === 'boolean') $subTypeName = 'bool'; // avoid expansion, bug in Nette
7 ✔
289
                                $expandedSubType = Reflection::expandClassName($subTypeName, $this->currentReflection);
7 ✔
290
                                $expandedSubTypeLower = strtolower($expandedSubType);
7 ✔
291

292
                                if ($expandedSubTypeLower === 'null') {
7 ✔
293
                                        $property->isNullable = true;
7 ✔
294
                                        continue;
7 ✔
295
                                }
296
                                if ($expandedSubType === DateTime::class || is_subclass_of($expandedSubType, DateTime::class)) {
7 ✔
297
                                        throw new NotSupportedException("Type '{$expandedSubType}' in {$this->currentReflection->name}::\${$property->name} property is not supported anymore. Use \\DateTimeImmutable or \\Nextras\\Dbal\\Utils\\DateTimeImmutable type.");
×
298
                                }
299
                                if (isset($aliases[$expandedSubTypeLower])) {
7 ✔
300
                                        $expandedSubType = $aliases[$expandedSubTypeLower];
×
301
                                }
302
                                $parsedTypes[$expandedSubType] = true;
7 ✔
303
                        } elseif ($subType instanceof ArrayTypeNode) {
7 ✔
304
                                $parsedTypes['array'] = true;
7 ✔
305
                        } elseif ($subType instanceof ArrayShapeNode) {
7 ✔
306
                                $parsedTypes['array'] = true;
7 ✔
307
                        } elseif ($subType instanceof ObjectShapeNode) {
×
308
                                $parsedTypes['object'] = true;
×
309
                        } else {
310
                                throw new NotSupportedException("Type '{$type}' in {$this->currentReflection->name}::\${$property->name} property is not supported. For Nextras Orm purpose simplify it.");
×
311
                        }
312
                }
313

314
                if ($parsedTypes === []) {
7 ✔
315
                        throw new NotSupportedException("Property {$this->currentReflection->name}::\${$property->name} without a type definition is not supported.");
×
316
                }
317
                $property->types = $parsedTypes;
7 ✔
318
        }
7 ✔
319

320

321
        protected function parseAnnotationValue(PropertyMetadata $property, string $propertyComment): void
322
        {
323
                if ($propertyComment === '') {
7 ✔
324
                        return;
7 ✔
325
                }
326

327
                $matches = $this->modifierParser->matchModifiers($propertyComment);
7 ✔
328
                foreach ($matches as $macroContent) {
7 ✔
329
                        try {
330
                                $args = $this->modifierParser->parse($macroContent, $this->currentReflection);
7 ✔
331
                        } catch (InvalidModifierDefinitionException $e) {
7 ✔
332
                                throw new InvalidModifierDefinitionException(
7 ✔
333
                                        "Invalid modifier definition for {$this->currentReflection->name}::\${$property->name} property.",
7 ✔
334
                                        0,
7 ✔
335
                                        $e,
336
                                );
337
                        }
338
                        $this->processPropertyModifier($property, $args[0], $args[1]);
7 ✔
339
                }
340
        }
7 ✔
341

342

343
        /**
344
         * @param array<string, true> $methods
345
         */
346
        protected function processPropertyGettersSetters(PropertyMetadata $property, array $methods): void
347
        {
348
                $getter = 'getter' . strtolower($property->name);
7 ✔
349
                if (isset($methods[$getter])) {
7 ✔
350
                        $property->hasGetter = $getter;
7 ✔
351
                }
352
                $setter = 'setter' . strtolower($property->name);
7 ✔
353
                if (isset($methods[$setter])) {
7 ✔
354
                        $property->hasSetter = $setter;
×
355
                }
356
        }
7 ✔
357

358

359
        protected function processDefaultPropertyWrappers(PropertyMetadata $property): void
360
        {
361
                if ($property->wrapper !== null) return;
7 ✔
362
                if ($property->isVirtual) return;
7 ✔
363

364
                foreach ($property->types as $type => $_) {
7 ✔
365
                        if (is_subclass_of($type, \DateTimeImmutable::class) || $type === \DateTimeImmutable::class) {
7 ✔
366
                                $property->wrapper = DateTimeWrapper::class;
7 ✔
367
                        } elseif (is_subclass_of($type, BackedEnum::class)) {
7 ✔
368
                                $property->wrapper = BackedEnumWrapper::class;
7 ✔
369
                        }
370
                }
371
        }
7 ✔
372

373

374
        /**
375
         * @param array<int|string, mixed> $args
376
         */
377
        protected function processPropertyModifier(PropertyMetadata $property, string $modifier, array $args): void
378
        {
379
                $type = strtolower($modifier);
7 ✔
380
                if (!isset($this->modifiers[$type])) {
7 ✔
381
                        throw new InvalidModifierDefinitionException(
7 ✔
382
                                "Unknown modifier '$type' type for {$this->currentReflection->name}::\${$property->name} property.",
7 ✔
383
                        );
384
                }
385

386
                $callback = $this->modifiers[$type];
7 ✔
387
                if (!is_array($callback)) {
7 ✔
388
                        $callback = [$this, $callback];
7 ✔
389
                }
390
                assert(is_callable($callback));
391
                $callback($property, $args);
7 ✔
392
                if ($args !== []) {
7 ✔
393
                        $parts = [];
7 ✔
394
                        foreach ($args as $key => $val) {
7 ✔
395
                                if (is_numeric($key) && !is_array($val)) {
7 ✔
396
                                        $parts[] = $val;
7 ✔
397
                                        continue;
7 ✔
398
                                }
399
                                $parts[] = $key;
7 ✔
400
                        }
401
                        throw new InvalidModifierDefinitionException(
7 ✔
402
                                "Modifier {{$type}} in {$this->currentReflection->name}::\${$property->name} property has unknown arguments: "
7 ✔
403
                                . implode(', ', $parts)
7 ✔
404
                                . '.',
7 ✔
405
                        );
406
                }
407
        }
7 ✔
408

409

410
        /**
411
         * @param array<int|string, mixed> $args
412
         */
413
        protected function parseOneHasOneModifier(PropertyMetadata $property, array &$args): void
414
        {
415
                $property->relationship = new PropertyRelationshipMetadata();
7 ✔
416
                $property->relationship->type = PropertyRelationshipMetadata::ONE_HAS_ONE;
7 ✔
417
                $property->wrapper = OneHasOne::class;
7 ✔
418
                $this->processRelationshipIsMain($property, $args);
7 ✔
419
                $this->processRelationshipEntityProperty($property, $args);
7 ✔
420
                $this->processRelationshipCascade($property, $args);
7 ✔
421
                assert($property->relationship !== null);
422
                $property->isVirtual = !$property->relationship->isMain;
7 ✔
423
        }
7 ✔
424

425

426
        /**
427
         * @param array<int|string, mixed> $args
428
         */
429
        protected function parseOneHasManyModifier(PropertyMetadata $property, array &$args): void
430
        {
431
                $property->relationship = new PropertyRelationshipMetadata();
7 ✔
432
                $property->relationship->type = PropertyRelationshipMetadata::ONE_HAS_MANY;
7 ✔
433
                $property->wrapper = OneHasMany::class;
7 ✔
434
                $property->isVirtual = true;
7 ✔
435
                $this->processRelationshipEntityProperty($property, $args);
7 ✔
436
                $this->processRelationshipCascade($property, $args);
7 ✔
437
                $this->processRelationshipOrder($property, $args);
7 ✔
438
                $this->processRelationshipExposeCollection($property, $args);
7 ✔
439
        }
7 ✔
440

441

442
        /**
443
         * @param array<int|string, mixed> $args
444
         */
445
        protected function parseManyHasOneModifier(PropertyMetadata $property, array &$args): void
446
        {
447
                $property->relationship = new PropertyRelationshipMetadata();
7 ✔
448
                $property->relationship->type = PropertyRelationshipMetadata::MANY_HAS_ONE;
7 ✔
449
                $property->wrapper = ManyHasOne::class;
7 ✔
450
                $this->processRelationshipEntityProperty($property, $args);
7 ✔
451
                $this->processRelationshipCascade($property, $args);
7 ✔
452
        }
7 ✔
453

454

455
        /**
456
         * @param array<int|string, mixed> $args
457
         */
458
        protected function parseManyHasManyModifier(PropertyMetadata $property, array &$args): void
459
        {
460
                $property->relationship = new PropertyRelationshipMetadata();
7 ✔
461
                $property->relationship->type = PropertyRelationshipMetadata::MANY_HAS_MANY;
7 ✔
462
                $property->wrapper = ManyHasMany::class;
7 ✔
463
                $property->isVirtual = true;
7 ✔
464
                $this->processRelationshipIsMain($property, $args);
7 ✔
465
                $this->processRelationshipEntityProperty($property, $args);
7 ✔
466
                $this->processRelationshipCascade($property, $args);
7 ✔
467
                $this->processRelationshipOrder($property, $args);
7 ✔
468
                $this->processRelationshipExposeCollection($property, $args);
7 ✔
469
        }
7 ✔
470

471

472
        /**
473
         * @param array<int|string, mixed> $args
474
         */
475
        protected function parseEnumModifier(PropertyMetadata $property, array &$args): void
476
        {
477
                $property->enum = $args;
7 ✔
478
                $args = [];
7 ✔
479
        }
7 ✔
480

481

482
        protected function parseVirtualModifier(PropertyMetadata $property): void
483
        {
484
                $property->isVirtual = true;
7 ✔
485
        }
7 ✔
486

487

488
        /**
489
         * @param array<int|string, mixed> $args
490
         */
491
        protected function parseContainerModifier(PropertyMetadata $property, array &$args): void
492
        {
493
                trigger_error(
×
494
                        'Property modifier {container} is deprecated; rename it to {wrapper} modifier.',
495
                        E_USER_DEPRECATED,
×
496
                );
497
                $this->parseWrapperModifier($property, $args);
×
498
        }
×
499

500

501
        /**
502
         * @param array<int|string, mixed> $args
503
         */
504
        protected function parseWrapperModifier(PropertyMetadata $property, array &$args): void
505
        {
506
                $className = Reflection::expandClassName(array_shift($args), $this->currentReflection);
7 ✔
507
                if (!class_exists($className)) {
7 ✔
508
                        throw new InvalidModifierDefinitionException("Class '$className' in {wrapper} for {$this->currentReflection->name}::\${$property->name} property does not exist.");
7 ✔
509
                }
510
                $implements = class_implements($className);
7 ✔
511
                if ($implements !== false && !isset($implements[IProperty::class])) {
7 ✔
512
                        throw new InvalidModifierDefinitionException("Class '$className' in {wrapper} for {$this->currentReflection->name}::\${$property->name} property does not implement Nextras\\Orm\\Entity\\IProperty interface.");
7 ✔
513
                }
514
                $property->wrapper = $className;
7 ✔
515
        }
7 ✔
516

517

518
        /**
519
         * @param array<int|string, mixed> $args
520
         */
521
        protected function parseDefaultModifier(PropertyMetadata $property, array &$args): void
522
        {
523
                $property->defaultValue = array_shift($args);
7 ✔
524
        }
7 ✔
525

526

527
        protected function parsePrimaryModifier(PropertyMetadata $property): void
528
        {
529
                $property->isPrimary = true;
7 ✔
530
        }
7 ✔
531

532

533
        protected function parsePrimaryProxyModifier(PropertyMetadata $property): void
534
        {
535
                $property->isVirtual = true;
7 ✔
536
                $property->isPrimary = true;
7 ✔
537
                if ($property->hasGetter === null && $property->hasSetter === null) {
7 ✔
538
                        $property->wrapper = PrimaryProxyWrapper::class;
7 ✔
539
                }
540
        }
7 ✔
541

542

543
        protected function parseEmbeddableModifier(PropertyMetadata $property): void
544
        {
545
                if (count($property->types) !== 1) {
7 ✔
546
                        $num = count($property->types);
×
547
                        throw new InvalidModifierDefinitionException("Embeddable modifer requries only one class type definition, optionally nullable. $num types detected in {$this->currentReflection->name}::\${$property->name} property.");
×
548
                }
549
                $className = array_keys($property->types)[0];
7 ✔
550
                if (!class_exists($className)) {
7 ✔
551
                        throw new InvalidModifierDefinitionException("Class '$className' in {embeddable} for {$this->currentReflection->name}::\${$property->name} property does not exist.");
×
552
                }
553
                if (!is_subclass_of($className, IEmbeddable::class)) {
7 ✔
554
                        throw new InvalidModifierDefinitionException("Class '$className' in {embeddable} for {$this->currentReflection->name}::\${$property->name} property does not implement " . IEmbeddable::class . ' interface.');
×
555
                }
556

557
                $property->wrapper = EmbeddableContainer::class;
7 ✔
558
                $property->args[EmbeddableContainer::class] = ['class' => $className];
7 ✔
559
        }
7 ✔
560

561

562
        protected function initPrimaryKey(): void
563
        {
564
                if ($this->reflection->isSubclassOf(IEmbeddable::class)) {
7 ✔
565
                        return;
7 ✔
566
                }
567

568
                $primaryKey = [];
7 ✔
569
                foreach ($this->metadata->getProperties() as $metadata) {
7 ✔
570
                        if ($metadata->isPrimary && !$metadata->isVirtual) {
7 ✔
571
                                $primaryKey[] = $metadata->name;
7 ✔
572
                        }
573
                }
574

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

581
                $this->metadata->setPrimaryKey($primaryKey);
7 ✔
582
        }
7 ✔
583

584

585
        /**
586
         * @param array<int|string, mixed> $args
587
         */
588
        protected function processRelationshipEntityProperty(PropertyMetadata $property, array &$args): void
589
        {
590
                assert($property->relationship !== null);
591
                static $modifiersMap = [
7 ✔
592
                        PropertyRelationshipMetadata::ONE_HAS_MANY => '1:m',
4 ✔
593
                        PropertyRelationshipMetadata::ONE_HAS_ONE => '1:1',
4 ✔
594
                        PropertyRelationshipMetadata::MANY_HAS_ONE => 'm:1',
4 ✔
595
                        PropertyRelationshipMetadata::MANY_HAS_MANY => 'm:m',
4 ✔
596
                ];
597
                $modifier = $modifiersMap[$property->relationship->type];
7 ✔
598
                $class = array_shift($args);
7 ✔
599

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

604
                $pos = strpos($class, '::');
7 ✔
605
                if ($pos === false) {
7 ✔
606
                        if (preg_match('#^[a-z0-9_\\\\]+$#i', $class) !== 1) {
7 ✔
607
                                throw new InvalidModifierDefinitionException("Relationship {{$modifier}} in {$this->currentReflection->name}::\${$property->name} has invalid class name of the target entity. Use Entity::\$property format.");
7 ✔
608
                        } elseif (!(isset($args['oneSided']) && $args['oneSided'] === true)) {
7 ✔
609
                                throw new InvalidModifierDefinitionException("Relationship {{$modifier}} in {$this->currentReflection->name}::\${$property->name} has not defined target property name.");
7 ✔
610
                        } else {
611
                                $targetProperty = null;
7 ✔
612
                                unset($args['oneSided']);
7 ✔
613
                        }
614
                } else {
615
                        $targetProperty = substr($class, $pos + 3); // skip ::$
7 ✔
616
                        assert($targetProperty !== false); // @phpstan-ignore-line
617
                        $class = substr($class, 0, $pos);
7 ✔
618

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

624
                /** @var class-string<IEntity> $entity */
625
                $entity = Reflection::expandClassName($class, $this->currentReflection);
7 ✔
626
                if (!isset($this->entityClassesMap[$entity])) {
7 ✔
627
                        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 ✔
628
                }
629

630
                $property->relationship->entity = $entity;
7 ✔
631
                $property->relationship->repository = $this->entityClassesMap[$entity];
7 ✔
632
                $property->relationship->property = $targetProperty;
7 ✔
633
        }
7 ✔
634

635

636
        /**
637
         * @param array<int|string, mixed> $args
638
         */
639
        protected function processRelationshipCascade(PropertyMetadata $property, array &$args): void
640
        {
641
                assert($property->relationship !== null);
642
                $property->relationship->cascade = $defaults = [
7 ✔
643
                        'persist' => false,
644
                        'remove' => false,
645
                        'removeOrphan' => false,
646
                ];
647

648
                if (!isset($args['cascade'])) {
7 ✔
649
                        $property->relationship->cascade['persist'] = true;
7 ✔
650
                        return;
7 ✔
651
                }
652

653
                foreach ((array) $args['cascade'] as $cascade) {
7 ✔
654
                        if (!isset($defaults[$cascade])) {
7 ✔
655
                                throw new InvalidModifierDefinitionException();
×
656
                        }
657
                        $property->relationship->cascade[$cascade] = true;
7 ✔
658
                }
659
                unset($args['cascade']);
7 ✔
660
        }
7 ✔
661

662

663
        /**
664
         * @param array<int|string, mixed> $args
665
         */
666
        protected function processRelationshipOrder(PropertyMetadata $property, array &$args): void
667
        {
668
                assert($property->relationship !== null);
669
                if (!isset($args['orderBy'])) {
7 ✔
670
                        return;
7 ✔
671
                }
672

673
                if (is_string($args['orderBy'])) {
7 ✔
674
                        $order = [$args['orderBy'] => ICollection::ASC];
7 ✔
675
                } elseif (is_array($args['orderBy']) && isset($args['orderBy'][0])) {
7 ✔
676
                        $order = [$args['orderBy'][0] => $args['orderBy'][1] ?? ICollection::ASC];
×
677
                } else {
678
                        $order = $args['orderBy'];
7 ✔
679
                }
680

681
                $property->relationship->order = $order;
7 ✔
682
                unset($args['orderBy']);
7 ✔
683
        }
7 ✔
684

685

686
        /**
687
         * @param array<int|string, mixed> $args
688
         */
689
        protected function processRelationshipExposeCollection(PropertyMetadata $property, array &$args): void
690
        {
691
                if (isset($args['exposeCollection']) && $args['exposeCollection'] === true) {
7 ✔
692
                        $property->args[HasMany::class]['exposeCollection'] = true;
7 ✔
693
                }
694
                unset($args['exposeCollection']);
7 ✔
695
        }
7 ✔
696

697

698
        /**
699
         * @param array<int|string, mixed> $args
700
         */
701
        protected function processRelationshipIsMain(PropertyMetadata $property, array &$args): void
702
        {
703
                assert($property->relationship !== null);
704
                $property->relationship->isMain = isset($args['isMain']) && $args['isMain'] === true;
7 ✔
705
                unset($args['isMain']);
7 ✔
706
        }
7 ✔
707
}
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