Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 18 additions & 3 deletions .github/workflows/build.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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
Expand Down
18 changes: 18 additions & 0 deletions .phpstan-version.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
<?php declare(strict_types = 1);

$targetPhpVersion = getenv('PHPSTAN_PHP_VERSION');
$targetPhpVersion = $targetPhpVersion !== false ? (int) $targetPhpVersion : PHP_VERSION_ID;

return [
'parameters' => [
'phpVersion' => $targetPhpVersion,
'excludePaths' => [
'analyse' => $targetPhpVersion < 80400
? [
__DIR__ . '/tests/cases/unit/Entity/Entity.propertyHooks.phpt',
__DIR__ . '/tests/cases/unit/Entity/fixtures/PropertyHookEntity.php',
]
: [],
],
],
];
1 change: 1 addition & 0 deletions .phpstan.neon
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
includes:
- phar://%rootDir%/phpstan.phar/conf/bleedingEdge.neon
- .phpstan-version.php

parameters:
level: 8
Expand Down
1 change: 1 addition & 0 deletions contributing.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand Down
2 changes: 1 addition & 1 deletion docs/collection-filtering.md
Original file line number Diff line number Diff line change
Expand Up @@ -94,7 +94,7 @@ $authors = $orm->author->findBy([

<div class="note">

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.
</div>

#### LIKE filtering
Expand Down
40 changes: 39 additions & 1 deletion docs/entity.md
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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).
Expand Down
2 changes: 2 additions & 0 deletions docs/migrate_6.0.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
14 changes: 14 additions & 0 deletions src/Collection/Functions/FetchPropertyFunction.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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;

Expand Down Expand Up @@ -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.");
Expand Down Expand Up @@ -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<string> $tokens
* @param list<DbalTableJoin> $joins
Expand Down
5 changes: 5 additions & 0 deletions src/Entity/AbstractEntity.php
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}
Expand Down
6 changes: 5 additions & 1 deletion src/Entity/ImmutableDataTrait.php
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand All @@ -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));
Expand Down
80 changes: 80 additions & 0 deletions src/Entity/Reflection/MetadataParser.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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;
Expand Down Expand Up @@ -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) {
Expand Down Expand Up @@ -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<string, bool>
*/
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<string, true> $methods
*/
Expand Down
2 changes: 2 additions & 0 deletions src/Entity/Reflection/PropertyMetadata.php
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ class PropertyMetadata

public string|null $hasGetter = null;
public string|null $hasSetter = null;
public bool $hasPropertyHooks = false;

/** @var non-empty-array<string, bool> of allowed types defined as keys */
public array $types;
Expand Down Expand Up @@ -76,6 +77,7 @@ public function __sleep()
'wrapper',
'hasGetter',
'hasSetter',
'hasPropertyHooks',
'types',
'isPrimary',
'isNullable',
Expand Down
15 changes: 15 additions & 0 deletions src/Entity/VirtualEntityProperty.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
<?php declare(strict_types = 1);

namespace Nextras\Orm\Entity;


use Attribute;


/**
* Registers a public virtual property with native PHP hooks in entity metadata.
*/
#[Attribute(Attribute::TARGET_PROPERTY)]
final class VirtualEntityProperty
{
}
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
use Nextras\Orm\Collection\Aggregations\AnyAggregator;
use Nextras\Orm\Collection\Functions\FetchPropertyFunction;
use Nextras\Orm\Collection\Helpers\DbalQueryBuilderHelper;
use Nextras\Orm\Exception\NotSupportedException;
use Nextras\Orm\Mapper\Dbal\DbalMapper;
use NextrasTests\Orm\Author;
use NextrasTests\Orm\Book;
Expand All @@ -25,6 +26,29 @@

class FetchPropertyFunctionTest extends DataTestCase
{
public function testVirtualPropertyFiltering(): 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->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();
Expand Down
Loading
Loading