diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 5f66c03d9..8d897ec6a 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -18,13 +18,28 @@ env: jobs: phpstan: - name: PHPStan + name: PHPStan (target PHP ${{ matrix.php-version }}) runs-on: ubuntu-latest strategy: matrix: - php-version: [ '8.1', '8.2', '8.3', '8.4', '8.5', '8.6' ] + include: + - php-version: '8.1' + php-version-id: 80100 + - php-version: '8.2' + php-version-id: 80200 + - php-version: '8.3' + php-version-id: 80300 + - php-version: '8.4' + php-version-id: 80400 + - php-version: '8.5' + php-version-id: 80500 + - php-version: '8.6' + php-version-id: 80600 + + env: + PHPSTAN_PHP_VERSION: ${{ matrix.php-version-id }} steps: - name: Checkout @@ -33,7 +48,7 @@ jobs: - name: Setup PHP with pecl extension uses: shivammathur/setup-php@v2 with: - php-version: ${{ matrix.php-version }} + php-version: '8.5' coverage: none - name: Omit DressCode dependencies diff --git a/.phpstan-version.php b/.phpstan-version.php new file mode 100644 index 000000000..6efec4a00 --- /dev/null +++ b/.phpstan-version.php @@ -0,0 +1,18 @@ + [ + 'phpVersion' => $targetPhpVersion, + 'excludePaths' => [ + 'analyse' => $targetPhpVersion < 80400 + ? [ + __DIR__ . '/tests/cases/unit/Entity/Entity.propertyHooks.phpt', + __DIR__ . '/tests/cases/unit/Entity/fixtures/PropertyHookEntity.php', + ] + : [], + ], + ], +]; diff --git a/.phpstan.neon b/.phpstan.neon index d045babe9..1aaaae5c1 100644 --- a/.phpstan.neon +++ b/.phpstan.neon @@ -1,5 +1,6 @@ includes: - phar://%rootDir%/phpstan.phar/conf/bleedingEdge.neon + - .phpstan-version.php parameters: level: 8 diff --git a/contributing.md b/contributing.md index d82dc98fb..7f0871b16 100644 --- a/contributing.md +++ b/contributing.md @@ -14,6 +14,7 @@ Please always open an issue first to be sure your work will be accepted (with th ## Testing code changes locally - PHPStan checks have to pass, run `composer phpstan`. +- CI runs all PHPStan jobs on PHP 8.5. Set `PHPSTAN_PHP_VERSION` to choose the analysis target, e.g. `PHPSTAN_PHP_VERSION=80100 composer phpstan`; it defaults to the local PHP version. Hook tests and fixtures are included automatically for targets PHP 8.4 and later. - Unit & integration have to pass, run `composer tests`. - Commit generated/changed SQLs for all tests. These SQL files are generated only for Postgres, so it is required to run tests at least for this database. diff --git a/docs/collection-filtering.md b/docs/collection-filtering.md index 2ddcf3502..18c2193eb 100644 --- a/docs/collection-filtering.md +++ b/docs/collection-filtering.md @@ -94,7 +94,7 @@ $authors = $orm->author->findBy([
-Filtering over virtual properties is generally unsupported and provides undefined behavior. +Computed virtual properties, including those registered with [`#[VirtualEntityProperty]`](entity#virtual), can be filtered in memory collections using the usual property expressions. Convert a database collection with `toMemoryCollection()` before filtering or sorting computed values. Using them in a DBAL collection expression throws `NotSupportedException` because PHP getters and hooks cannot be evaluated in SQL.
#### LIKE filtering diff --git a/docs/entity.md b/docs/entity.md index 995ccf157..0d1557ae8 100644 --- a/docs/entity.md +++ b/docs/entity.md @@ -2,7 +2,7 @@ Entity is a data container that basically contains data for one table row. Each entity must implement the `Nextras\Orm\Entity\IEntity` interface. Orm contains a predefined `Nextras\Orm\Entity\Entity` class; it implements the interface and provides other useful features. -Data is accessible through properties. You must annotate all properties that should be available. Properties are defined by Phpdoc annotations. Let's start with a basic entity: +Data is accessible through properties. Properties are defined by Phpdoc annotations; computed properties with PHP 8.4 hooks can instead be registered with the `#[VirtualEntityProperty]` attribute (see below). Let's start with a basic entity: ```php use Nextras\Orm\Entity\PropertyWrapper\DateWrapper; @@ -197,6 +197,44 @@ $member->born = new DateTimeImmutable('2000-01-01'); echo $member->age; ``` +On PHP 8.4 and later, computed entity properties can be declared as public virtual properties with a native `get` hook. Register each property in Orm metadata with the `#[VirtualEntityProperty]` attribute; neither a duplicate `@property` annotation nor the `{virtual}` modifier is needed: + +```php +use Nextras\Orm\Entity\VirtualEntityProperty; + +/** + * @property int $id {primary} + * @property DateTimeImmutable|null $born + */ +class Member extends Nextras\Orm\Entity\Entity +{ + #[VirtualEntityProperty] + public int $age { + get => $this->born === null ? 0 : (int) date('Y') - (int) $this->born->format('Y'); + } +} +``` + +Registering a hook in metadata also makes it available in collection filtering expressions. Filtering computed values runs in PHP, so use a memory collection: + +```php +$adults = $orm->members->findAll()->toMemoryCollection()->findBy(['age>=' => 18]); +``` + +These properties work with `getValue()`, `hasValue()`, and `toArray()`, and are excluded from persistence. A property with only a `get` hook is read-only. A public `set` hook is also supported by `setValue()`; it should update the underlying mapped properties: + +```php +#[VirtualEntityProperty] +public string $displayName { + get => $this->name; + set { + $this->name = $value; + } +} +``` + +The property must be [virtual in PHP](https://www.php.net/manual/en/language.oop5.property-hooks.php), meaning its hooks do not use its own backing value. Use a full `set` block as above: PHP's short `set => ...` form implicitly writes to the backing value. The attribute is supported only on public virtual properties with a `get` hook. Unmarked hooks remain ordinary PHP properties and are not added to Orm metadata. Types and nullability are taken from the native property declaration. Existing annotated virtual properties and custom getter/setter methods remain supported. + #### `{embeddable}` Encapsulates multiple properties into a wrapper container. Read more in [Embeddables tutorial](embeddables). diff --git a/docs/migrate_6.0.md b/docs/migrate_6.0.md index 963bad25e..7c50059ba 100644 --- a/docs/migrate_6.0.md +++ b/docs/migrate_6.0.md @@ -48,6 +48,8 @@ ### New Features +- **Virtual entity properties with PHP 8.4 hooks** - mark a public virtual property with `#[Nextras\Orm\Entity\VirtualEntityProperty]` to register it in Orm metadata without duplicating its type in PHPDoc. It supports entity value access and array export, and is excluded from persistence. Unmarked hooks are not registered. See [entity properties](entity#virtual). + - **`Nextras\Orm\Extension` entry point** - a new abstract class that lets bundled or third-party packages hook into the Orm setup. Override any of the methods you need and register the extension: ```php diff --git a/src/Collection/Functions/FetchPropertyFunction.php b/src/Collection/Functions/FetchPropertyFunction.php index 6d7af1748..124a7ef66 100644 --- a/src/Collection/Functions/FetchPropertyFunction.php +++ b/src/Collection/Functions/FetchPropertyFunction.php @@ -22,6 +22,7 @@ use Nextras\Orm\Entity\Reflection\PropertyRelationshipMetadata as Relationship; use Nextras\Orm\Exception\InvalidArgumentException; use Nextras\Orm\Exception\InvalidStateException; +use Nextras\Orm\Exception\NotSupportedException; use Nextras\Orm\Mapper\Dbal\Conventions\IConventions; use Nextras\Orm\Mapper\Dbal\DbalMapper; use Nextras\Orm\Mapper\IMapper; @@ -202,6 +203,7 @@ private function processTokens( foreach ($tokens as $tokenIndex => $token) { $property = $currentEntityMetadata->getProperty($token); + $this->checkPropertyIsQueryable($currentEntityMetadata, $property); if ($property->relationship !== null) { $relType = $property->relationship->type; @@ -249,6 +251,7 @@ private function processTokens( } $propertyMetadata = $currentEntityMetadata->getProperty($lastToken); + $this->checkPropertyIsQueryable($currentEntityMetadata, $propertyMetadata); if ($propertyMetadata->wrapper === EmbeddableContainer::class) { $propertyExpression = implode('->', array_merge($tokens, [$lastToken])); throw new InvalidArgumentException("Property expression '$propertyExpression' does not fetch specific property."); @@ -314,6 +317,17 @@ private function processTokens( } + private function checkPropertyIsQueryable(EntityMetadata $entityMetadata, PropertyMetadata $property): void + { + if (!$property->isVirtual || $property->isPrimary || $property->relationship !== null) return; + + throw new NotSupportedException( + "Virtual property {$entityMetadata->className}::\${$property->name} cannot be used in a DBAL collection expression. " + . 'Call toMemoryCollection() before filtering or sorting by this property.', + ); + } + + /** * @param array $tokens * @param list $joins diff --git a/src/Entity/AbstractEntity.php b/src/Entity/AbstractEntity.php index d68cf6d1c..324fd05d7 100644 --- a/src/Entity/AbstractEntity.php +++ b/src/Entity/AbstractEntity.php @@ -412,6 +412,11 @@ public function onAfterRemove(): void */ private function internalSetValue(PropertyMetadata $metadata, string $name, $value): void { + if ($metadata->hasPropertyHooks) { + $this->$name = $value; // @phpstan-ignore property.dynamicName (The property was verified by the metadata parser.) + return; + } + if (!isset($this->validated[$name])) { $this->initProperty($metadata, $name, initValue: false); } diff --git a/src/Entity/ImmutableDataTrait.php b/src/Entity/ImmutableDataTrait.php index 7c9c06c20..7445fb0f3 100644 --- a/src/Entity/ImmutableDataTrait.php +++ b/src/Entity/ImmutableDataTrait.php @@ -57,7 +57,9 @@ private function &internalGetValue(PropertyMetadata $metadata, string $name) return $this->data[$name]->getInjectedValue(); } - if ($metadata->hasGetter !== null) { + if ($metadata->hasPropertyHooks) { + $value = $this->$name; // @phpstan-ignore property.dynamicName (The property was verified by the metadata parser.) + } elseif ($metadata->hasGetter !== null) { $cb = [$this, $metadata->hasGetter]; assert(is_callable($cb)); $value = $cb( @@ -83,6 +85,8 @@ private function internalHasValue(PropertyMetadata $metadata, string $name): boo if ($this->data[$name] instanceof IPropertyContainer) { return $this->data[$name]->hasInjectedValue(); + } elseif ($metadata->hasPropertyHooks) { + return isset($this->$name); // @phpstan-ignore property.dynamicName (The property was verified by the metadata parser.) } elseif ($metadata->hasGetter !== null) { $cb = [$this, $metadata->hasGetter]; assert(is_callable($cb)); diff --git a/src/Entity/Reflection/MetadataParser.php b/src/Entity/Reflection/MetadataParser.php index 441d924da..c8dd900a6 100644 --- a/src/Entity/Reflection/MetadataParser.php +++ b/src/Entity/Reflection/MetadataParser.php @@ -16,6 +16,7 @@ use Nextras\Orm\Entity\PropertyWrapper\BackedEnumWrapper; use Nextras\Orm\Entity\PropertyWrapper\DateTimeWrapper; use Nextras\Orm\Entity\PropertyWrapper\PrimaryProxyWrapper; +use Nextras\Orm\Entity\VirtualEntityProperty; use Nextras\Orm\Exception\InvalidStateException; use Nextras\Orm\Exception\NotSupportedException; use Nextras\Orm\Extension; @@ -42,6 +43,10 @@ use PHPStan\PhpDocParser\Parser\TypeParser; use PHPStan\PhpDocParser\ParserConfig; use ReflectionClass; +use ReflectionIntersectionType; +use ReflectionNamedType; +use ReflectionType; +use ReflectionUnionType; use function array_keys; use function assert; use function class_exists; @@ -136,6 +141,7 @@ public function parseMetadata(string $entityClass, array|null &$fileDependencies $this->metadata = new EntityMetadata($entityClass); $this->loadProperties($fileDependencies); + $this->loadPropertyHooks(); $this->initPrimaryKey(); foreach ($this->extensions as $extension) { @@ -227,6 +233,80 @@ protected function parseAnnotations(ReflectionClass $reflection, array $methods) } + protected function loadPropertyHooks(): void + { + if (PHP_VERSION_ID < 80400 || !$this->reflection->implementsInterface(IEntity::class)) return; + + foreach ($this->reflection->getProperties() as $reflectionProperty) { + if ($reflectionProperty->getAttributes(VirtualEntityProperty::class) === []) continue; + // Refine the available APIs for PHPStan analysis targets below PHP 8.4. + if ( + !method_exists($reflectionProperty, 'getHooks') + || !method_exists($reflectionProperty, 'isVirtual') + || !method_exists($reflectionProperty, 'isProtectedSet') + || !method_exists($reflectionProperty, 'isPrivateSet') + ) return; + $hooks = $reflectionProperty->getHooks(); + if (!$reflectionProperty->isPublic() || !$reflectionProperty->isVirtual() || !isset($hooks['get'])) { + throw new NotSupportedException("Attribute VirtualEntityProperty on {$this->reflection->name}::\${$reflectionProperty->name} requires a public virtual property with a get hook."); + } + + $this->currentReflection = $reflectionProperty->getDeclaringClass(); + $property = new PropertyMetadata(); + $property->name = $reflectionProperty->getName(); + $property->containerClassname = $this->currentReflection->getName(); + $property->isVirtual = true; + $property->hasPropertyHooks = true; + $property->isReadonly = !isset($hooks['set']) || $reflectionProperty->isProtectedSet() || $reflectionProperty->isPrivateSet(); + $type = $this->getPropertyHookType($reflectionProperty->getType()); + $property->types = $this->getPropertyHookTypeNames($type); + $property->isNullable = $reflectionProperty->getType()?->allowsNull() ?? true; + + foreach ($this->extensions as $extension) { + $extension->configureEntityPropertyMetadata($this->metadata, $property, $type); + } + $this->metadata->setProperty($property->name, $property); + } + } + + + protected function getPropertyHookType(ReflectionType|null $type): TypeNode + { + if ($type instanceof ReflectionUnionType) { + return new UnionTypeNode(array_map($this->getPropertyHookType(...), $type->getTypes())); + } elseif ($type instanceof ReflectionIntersectionType) { + return new IntersectionTypeNode(array_map($this->getPropertyHookType(...), $type->getTypes())); + } elseif ($type instanceof ReflectionNamedType) { + $name = $type->getName(); + if (!$type->isBuiltin() && $name !== 'self' && $name !== 'parent') { + $name = '\\' . $name; + } + $node = new IdentifierTypeNode($name); + return $type->allowsNull() ? new NullableTypeNode($node) : $node; + } + return new IdentifierTypeNode('mixed'); + } + + + /** + * @return non-empty-array + */ + protected function getPropertyHookTypeNames(TypeNode $type): array + { + if ($type instanceof NullableTypeNode) { + return $this->getPropertyHookTypeNames($type->type); + } elseif ($type instanceof UnionTypeNode || $type instanceof IntersectionTypeNode) { + $types = []; + foreach ($type->types as $innerType) { + $types += $this->getPropertyHookTypeNames($innerType); + } + return $types !== [] ? $types : ['mixed' => true]; + } + assert($type instanceof IdentifierTypeNode); + return [Reflection::expandClassName($type->name, $this->currentReflection) => true]; + } + + /** * @param array $methods */ diff --git a/src/Entity/Reflection/PropertyMetadata.php b/src/Entity/Reflection/PropertyMetadata.php index c6e34360a..4810abb15 100644 --- a/src/Entity/Reflection/PropertyMetadata.php +++ b/src/Entity/Reflection/PropertyMetadata.php @@ -20,6 +20,7 @@ class PropertyMetadata public string|null $hasGetter = null; public string|null $hasSetter = null; + public bool $hasPropertyHooks = false; /** @var non-empty-array of allowed types defined as keys */ public array $types; @@ -76,6 +77,7 @@ public function __sleep() 'wrapper', 'hasGetter', 'hasSetter', + 'hasPropertyHooks', 'types', 'isPrimary', 'isNullable', diff --git a/src/Entity/VirtualEntityProperty.php b/src/Entity/VirtualEntityProperty.php new file mode 100644 index 000000000..dd6255e97 --- /dev/null +++ b/src/Entity/VirtualEntityProperty.php @@ -0,0 +1,15 @@ +section === Helper::SECTION_ARRAY) $this->skip(); + $message = 'Virtual property NextrasTests\Orm\Author::$age cannot be used in a DBAL collection expression. ' + . 'Call toMemoryCollection() before filtering or sorting by this property.'; + + Assert::throws(fn() => $this->orm->authors->findBy(['age>' => 18]), NotSupportedException::class, $message); + Assert::throws(fn() => $this->orm->books->findBy(['author->age>' => 18]), NotSupportedException::class, $message); + Assert::throws(fn() => $this->orm->authors->findBy(['age->name' => 'Jon']), NotSupportedException::class, $message); + } + + + public function testVirtualPropertyOrdering(): void + { + if ($this->section === Helper::SECTION_ARRAY) $this->skip(); + $message = 'Virtual property NextrasTests\Orm\Author::$age cannot be used in a DBAL collection expression. ' + . 'Call toMemoryCollection() before filtering or sorting by this property.'; + + Assert::throws(fn() => $this->orm->authors->findAll()->orderBy('age'), NotSupportedException::class, $message); + Assert::throws(fn() => $this->orm->books->findAll()->orderBy('author->age'), NotSupportedException::class, $message); + } + + public function testManyHasOneJoin(): void { if ($this->section === Helper::SECTION_ARRAY) $this->skip(); diff --git a/tests/cases/unit/Entity/Entity.propertyHooks.phpt b/tests/cases/unit/Entity/Entity.propertyHooks.phpt new file mode 100644 index 000000000..1c4a9c4b8 --- /dev/null +++ b/tests/cases/unit/Entity/Entity.propertyHooks.phpt @@ -0,0 +1,182 @@ += 8.4 + */ + +namespace NextrasTests\Orm\Entity\PropertyHooks; + + +use DateTimeImmutable; +use Mockery; +use Nextras\Orm\Collection\ArrayCollection; +use Nextras\Orm\Entity\Reflection\EntityMetadata; +use Nextras\Orm\Entity\Reflection\MetadataParser; +use Nextras\Orm\Entity\Reflection\PropertyMetadata; +use Nextras\Orm\Exception\InvalidArgumentException; +use Nextras\Orm\Exception\NotSupportedException; +use Nextras\Orm\Extension; +use Nextras\Orm\Mapper\IMapper; +use Nextras\Orm\Model\IModel; +use Nextras\Orm\Repository\Repository; +use PHPStan\PhpDocParser\Ast\Type\TypeNode; +use Tester\Assert; +use Tester\TestCase; + +require_once __DIR__ . '/../../../bootstrap.php'; +require_once __DIR__ . '/fixtures/PropertyHookEntity.php'; + + +class EntityPropertyHooksTest extends TestCase +{ + public function testMetadata(): void + { + $metadata = (new HookEntity())->getMetadata(); + $age = $metadata->getProperty('age'); + Assert::true($age->hasPropertyHooks); + Assert::true($age->isVirtual); + Assert::true($age->isReadonly); + Assert::same(['int' => true], $age->types); + Assert::null($age->wrapper); + Assert::false($metadata->getProperty('displayName')->isReadonly); + Assert::true($metadata->getProperty('restricted')->isReadonly); + Assert::same([DateTimeImmutable::class => true], $metadata->getProperty('birthDate')->types); + Assert::true($metadata->getProperty('birthDate')->isNullable); + Assert::null($metadata->getProperty('birthDate')->wrapper); + Assert::same(['string' => true, 'int' => true], $metadata->getProperty('identifier')->types); + Assert::same(['mixed' => true], $metadata->getProperty('untyped')->types); + Assert::true($metadata->getProperty('untyped')->isNullable); + Assert::same([HookEntity::class => true], $metadata->getProperty('myself')->types); + Assert::false($metadata->hasProperty('undocumented')); + Assert::false($metadata->hasProperty('backed')); + Assert::false($metadata->hasProperty('internal')); + } + + + public function testReadingAndWriting(): void + { + $entity = new HookEntity(); + $entity->id = 1; + $entity->name = 'Jon'; + Assert::same(0, $entity->age); + Assert::same(0, $entity->getValue('age')); + Assert::true($entity->hasValue('age')); + Assert::false(isset($entity->birthDate)); + Assert::false($entity->hasValue('birthDate')); + Assert::null($entity->getValue('birthDate')); + Assert::null($entity->getValue('untyped')); + $entity->born = new DateTimeImmutable('2000-01-01'); + Assert::same(26, $entity->getValue('age')); + Assert::same(26, $entity->getRawValue('age')); + Assert::true($entity->hasValue('birthDate')); + Assert::same($entity->born, $entity->getValue('birthDate')); + Assert::same($entity, $entity->getValue('myself')); + + $entity->onPersist(1); + $entity->displayName = 'Jan'; + Assert::true($entity->isModified('name')); + Assert::same('JAN', $entity->getValue('displayName')); + $entity->setValue('displayName', 'Eva'); + Assert::same('EVA', $entity->displayName); + $entity->setRawValue('displayName', 'Bob'); + Assert::same('BOB', $entity->getRawValue('displayName')); + Assert::same(3, $entity->nameLength); + $this->assertReadOnly($entity, 'age'); + $this->assertReadOnly($entity, 'restricted'); + } + + + public function testExportAndHydration(): void + { + $entity = new HookEntity(); + $entity->onLoad(['id' => 1, 'name' => 'Jon', 'born' => null, 'age' => 999]); + Assert::same(0, $entity->getValue('age')); + Assert::same(['id' => 1, 'name' => 'Jon', 'born' => null], $entity->getRawValues()); + $data = $entity->toArray(skipProperties: ['myself']); + Assert::same(0, $data['age']); + Assert::same('JON', $data['displayName']); + Assert::null($data['birthDate']); + Assert::null($data['untyped']); + $clone = clone $entity; + Assert::same('JON', $clone->getValue('displayName')); + } + + + public function testInheritance(): void + { + $entity = new ChildHookEntity(); + $entity->name = 'Jon'; + Assert::same(42, $entity->getValue('age')); + Assert::same('JON', $entity->getValue('displayName')); + Assert::same([HookEntity::class => true], $entity->getMetadata()->getProperty('myself')->types); + } + + + public function testExtensions(): void + { + $extension = new class extends Extension { + public function configureEntityPropertyMetadata( + EntityMetadata $entityMetadata, + PropertyMetadata $propertyMetadata, + TypeNode $propertyType, + ): void + { + if ($propertyMetadata->isVirtual) { + $propertyMetadata->args['nativeType'] = (string) $propertyType; + } + } + }; + $dependencies = []; + $parser = new MetadataParser([], [$extension]); + $metadata = $parser->parseMetadata(HookEntity::class, $dependencies); + Assert::same(['nativeType' => 'int'], $metadata->getProperty('age')->args); + Assert::contains(__DIR__ . '/fixtures/PropertyHookEntity.php', $dependencies ?? []); + } + + + public function testCollectionQueries(): void + { + $younger = new HookEntity(); + $younger->born = new DateTimeImmutable('2000-01-01'); + $older = new HookEntity(); + $older->born = new DateTimeImmutable('1980-01-01'); + $mapper = Mockery::mock(IMapper::class); + $mapper->shouldReceive('setRepository')->once(); + $repository = Mockery::mock(Repository::class, [$mapper])->makePartial(); + $repository->shouldReceive('getModel')->andReturn(Mockery::mock(IModel::class)); + $repository->shouldReceive('getEntityMetadata')->andReturn($younger->getMetadata()); + $collection = new ArrayCollection([$younger, $older], $repository); + Assert::same([$older], $collection->findBy(['age>' => 30])->fetchAll()); + Assert::same([$older, $younger], $collection->orderBy('age', 'DESC')->fetchAll()); + Assert::throws( + fn() => $collection->findBy(['undocumented' => 1])->fetchAll(), + InvalidArgumentException::class, + 'Undefined property %A%::$undocumented.', + ); + Mockery::close(); + } + + + public function testInvalidAttributes(): void + { + $parser = new MetadataParser([]); + foreach ([InvalidBackedHookEntity::class, InvalidProtectedHookEntity::class, InvalidWriteOnlyHookEntity::class] as $class) { + $dependencies = []; + Assert::throws( + fn() => $parser->parseMetadata($class, $dependencies), + NotSupportedException::class, + 'Attribute VirtualEntityProperty on %A%::$invalid requires a public virtual property with a get hook.', + ); + } + } + + + private function assertReadOnly(HookEntity $entity, string $name): void + { + Assert::throws(fn() => $entity->setValue($name, 12), InvalidArgumentException::class, "Property '$name' is read-only."); + } +} + + +(new EntityPropertyHooksTest())->run(); diff --git a/tests/cases/unit/Entity/fixtures/PropertyHookEntity.php b/tests/cases/unit/Entity/fixtures/PropertyHookEntity.php new file mode 100644 index 000000000..74e8f5179 --- /dev/null +++ b/tests/cases/unit/Entity/fixtures/PropertyHookEntity.php @@ -0,0 +1,137 @@ + $this->name; + set { + $this->name = $value; + } + } +} + + +/** + * @property int $id {primary} + * @property string $name + * @property DateTimeImmutable|null $born + * @property-read int $nameLength {virtual} + */ +class HookEntity extends Entity +{ + use NameHook; + + public int $undocumented { + get => 1; + } + + #[VirtualEntityProperty] + public int $age { + get => $this->born === null ? 0 : 2026 - (int) $this->born->format('Y'); + } + + #[VirtualEntityProperty] + public DateTimeImmutable|null $birthDate { + get => $this->born; + } + + #[VirtualEntityProperty] + public int|string $identifier { + get => $this->id; + } + + /** @var mixed */ + #[VirtualEntityProperty] + public $untyped { + get => null; + } + + #[VirtualEntityProperty] + public self $myself { + get => $this; + } + + public string $backed = 'initial' { + get => $this->backed; + } + + #[VirtualEntityProperty] + public protected(set) string $restricted { + get => $this->name; + set { + $this->name = $value; + } + } + + protected int $internal { + get => 1; + } + + + protected function getterName(string $value): string + { + return strtoupper($value); + } + + + protected function getterNameLength(): int + { + return strlen($this->name); + } + + + protected function createMetadata(): EntityMetadata + { + $dependencies = []; + $metadata = (new MetadataParser([]))->parseMetadata(static::class, $dependencies); + // Exercise the same serialized metadata used by the model cache. + return unserialize(serialize($metadata)); + } +} + + +class ChildHookEntity extends HookEntity +{ + #[VirtualEntityProperty] + public int $age { + get => 42; + } +} + + +class InvalidBackedHookEntity extends HookEntity +{ + #[VirtualEntityProperty] + public string $invalid = 'value'; +} + + +class InvalidProtectedHookEntity extends HookEntity +{ + #[VirtualEntityProperty] + protected int $invalid { + get => 1; + } +} + + +class InvalidWriteOnlyHookEntity extends HookEntity +{ + #[VirtualEntityProperty] + public string $invalid { + set { + $this->name = $value; + } + } +} diff --git a/tests/sqls/NextrasTests/Orm/Integration/Collection/Functions/FetchPropertyFunctionTest_testVirtualPropertyFiltering.sql b/tests/sqls/NextrasTests/Orm/Integration/Collection/Functions/FetchPropertyFunctionTest_testVirtualPropertyFiltering.sql new file mode 100644 index 000000000..8b1378917 --- /dev/null +++ b/tests/sqls/NextrasTests/Orm/Integration/Collection/Functions/FetchPropertyFunctionTest_testVirtualPropertyFiltering.sql @@ -0,0 +1 @@ + diff --git a/tests/sqls/NextrasTests/Orm/Integration/Collection/Functions/FetchPropertyFunctionTest_testVirtualPropertyOrdering.sql b/tests/sqls/NextrasTests/Orm/Integration/Collection/Functions/FetchPropertyFunctionTest_testVirtualPropertyOrdering.sql new file mode 100644 index 000000000..8b1378917 --- /dev/null +++ b/tests/sqls/NextrasTests/Orm/Integration/Collection/Functions/FetchPropertyFunctionTest_testVirtualPropertyOrdering.sql @@ -0,0 +1 @@ +