Skip to content

[JsonEncoder] Add native lazyghost support #59177

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Dec 18, 2024
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
Original file line number Diff line number Diff line change
Expand Up @@ -2032,6 +2032,10 @@ private function registerJsonEncoderConfiguration(array $config, ContainerBuilde
foreach ($config['paths'] as $namespace => $path) {
$loader->registerClasses($encodableDefinition, $namespace, $path);
}

if (\PHP_VERSION_ID >= 80400) {
$container->removeDefinition('.json_encoder.cache_warmer.lazy_ghost');
}
}

private function registerPropertyInfoConfiguration(ContainerBuilder $container, PhpFileLoader $loader): void
Expand Down
1 change: 1 addition & 0 deletions src/Symfony/Component/JsonEncoder/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,3 +5,4 @@ CHANGELOG
---

* Introduce the component as experimental
* Add native PHP lazy ghost support
33 changes: 18 additions & 15 deletions src/Symfony/Component/JsonEncoder/Decode/LazyInstantiator.php
Original file line number Diff line number Diff line change
Expand Up @@ -12,23 +12,23 @@
namespace Symfony\Component\JsonEncoder\Decode;

use Symfony\Component\Filesystem\Filesystem;
use Symfony\Component\JsonEncoder\Exception\InvalidArgumentException;
use Symfony\Component\JsonEncoder\Exception\RuntimeException;
use Symfony\Component\VarExporter\ProxyHelper;

/**
* Instantiates a new $className lazy ghost {@see \Symfony\Component\VarExporter\LazyGhostTrait}.
*
* The $className class must not be final.
*
* A property must be a callable that returns the actual value when being called.
* Prior to PHP 8.4, the "$className" argument class must not be final.
* The $initializer must be a callable that sets the actual object values when being called.
*
* @author Mathias Arlaud <mathias.arlaud@gmail.com>
*
* @internal
*/
final class LazyInstantiator
{
private Filesystem $fs;
private ?Filesystem $fs = null;

/**
* @var array{reflection: array<class-string, \ReflectionClass<object>>, lazy_class_name: array<class-string, class-string>}
Expand All @@ -44,34 +44,37 @@
private static array $lazyClassesLoaded = [];

public function __construct(
private string $lazyGhostsDir,
private ?string $lazyGhostsDir = null,
) {
$this->fs = new Filesystem();
if (null === $this->lazyGhostsDir && \PHP_VERSION_ID < 80400) {
throw new InvalidArgumentException('The "$lazyGhostsDir" argument cannot be null when using PHP < 8.4.');
}
}

/**
* @template T of object
*
* @param class-string<T> $className
* @param array<string, callable(): mixed> $propertiesCallables
* @param class-string<T> $className
* @param callable(T): void $initializer
*
* @return T
*/
public function instantiate(string $className, array $propertiesCallables): object
public function instantiate(string $className, callable $initializer): object
{
try {
$classReflection = self::$cache['reflection'][$className] ??= new \ReflectionClass($className);
} catch (\ReflectionException $e) {
throw new RuntimeException($e->getMessage(), $e->getCode(), $e);
}

$lazyClassName = self::$cache['lazy_class_name'][$className] ??= \sprintf('%sGhost', preg_replace('/\\\\/', '', $className));
// use native lazy ghosts if available
if (\PHP_VERSION_ID >= 80400) {
return $classReflection->newLazyGhost($initializer);

Check failure on line 72 in src/Symfony/Component/JsonEncoder/Decode/LazyInstantiator.php

View workflow job for this annotation

GitHub Actions / Psalm

UndefinedMethod

src/Symfony/Component/JsonEncoder/Decode/LazyInstantiator.php:72:38: UndefinedMethod: Method ReflectionClass::newLazyGhost does not exist (see https://psalm.dev/022)

Check failure on line 72 in src/Symfony/Component/JsonEncoder/Decode/LazyInstantiator.php

View workflow job for this annotation

GitHub Actions / Psalm

UndefinedMethod

src/Symfony/Component/JsonEncoder/Decode/LazyInstantiator.php:72:38: UndefinedMethod: Method ReflectionClass::newLazyGhost does not exist (see https://psalm.dev/022)
}

$initializer = function (object $object) use ($propertiesCallables) {
foreach ($propertiesCallables as $name => $propertyCallable) {
$object->{$name} = $propertyCallable();
}
};
$this->fs ??= new Filesystem();

$lazyClassName = self::$cache['lazy_class_name'][$className] ??= \sprintf('%sGhost', preg_replace('/\\\\/', '', $className));

if (isset(self::$lazyClassesLoaded[$className]) && class_exists($lazyClassName)) {
return $lazyClassName::createLazyGhost($initializer);
Expand Down
49 changes: 24 additions & 25 deletions src/Symfony/Component/JsonEncoder/Decode/PhpAstBuilder.php
Original file line number Diff line number Diff line change
Expand Up @@ -53,8 +53,8 @@
use Symfony\Component\TypeInfo\Type\BackedEnumType;
use Symfony\Component\TypeInfo\Type\CollectionType;
use Symfony\Component\TypeInfo\Type\ObjectType;
use Symfony\Component\TypeInfo\TypeIdentifier;
use Symfony\Component\TypeInfo\Type\WrappingTypeInterface;
use Symfony\Component\TypeInfo\TypeIdentifier;

/**
* Builds a PHP syntax tree that decodes JSON.
Expand Down Expand Up @@ -445,21 +445,8 @@ private function buildObjectNodeStatements(ObjectNode $node, bool $decodeFromStr
);

$streamPropertiesValuesStmts[] = new MatchArm([$this->builder->val($encodedName)], new Assign(
new ArrayDimFetch($this->builder->var('properties'), $this->builder->val($property['name'])),
new Closure([
'static' => true,
'uses' => [
new ClosureUse($this->builder->var('stream')),
new ClosureUse($this->builder->var('v')),
new ClosureUse($this->builder->var('options')),
new ClosureUse($this->builder->var('denormalizers')),
new ClosureUse($this->builder->var('instantiator')),
new ClosureUse($this->builder->var('providers'), byRef: true),
],
'stmts' => [
new Return_($property['accessor'](new PhpExprDataAccessor($propertyValueStmt))->toPhpExpr()),
],
]),
$this->builder->propertyFetch($this->builder->var('object'), $property['name']),
$property['accessor'](new PhpExprDataAccessor($propertyValueStmt))->toPhpExpr(),
));
} else {
$propertyValueStmt = $this->nodeOnlyNeedsDecode($property['value'], $decodeFromStream)
Expand Down Expand Up @@ -494,17 +481,29 @@ private function buildObjectNodeStatements(ObjectNode $node, bool $decodeFromStr

if ($decodeFromStream) {
$instantiateStmts = [
new Expression(new Assign($this->builder->var('properties'), new Array_([], ['kind' => Array_::KIND_SHORT]))),
new Foreach_($this->builder->var('data'), $this->builder->var('v'), [
'keyVar' => $this->builder->var('k'),
'stmts' => [new Expression(new Match_(
$this->builder->var('k'),
[...$streamPropertiesValuesStmts, new MatchArm(null, $this->builder->val(null))],
))],
]),
new Return_($this->builder->methodCall($this->builder->var('instantiator'), 'instantiate', [
new ClassConstFetch(new FullyQualified($node->getType()->getClassName()), 'class'),
$this->builder->var('properties'),
new Closure([
'static' => true,
'params' => [new Param($this->builder->var('object'))],
'uses' => [
new ClosureUse($this->builder->var('stream')),
new ClosureUse($this->builder->var('data')),
new ClosureUse($this->builder->var('options')),
new ClosureUse($this->builder->var('denormalizers')),
new ClosureUse($this->builder->var('instantiator')),
new ClosureUse($this->builder->var('providers'), byRef: true),
],
'stmts' => [
new Foreach_($this->builder->var('data'), $this->builder->var('v'), [
'keyVar' => $this->builder->var('k'),
'stmts' => [new Expression(new Match_(
$this->builder->var('k'),
[...$streamPropertiesValuesStmts, new MatchArm(null, $this->builder->val(null))],
))],
]),
],
]),
])),
];
} else {
Expand Down
2 changes: 1 addition & 1 deletion src/Symfony/Component/JsonEncoder/Encode/PhpAstBuilder.php
Original file line number Diff line number Diff line change
Expand Up @@ -45,8 +45,8 @@
use Symfony\Component\JsonEncoder\Exception\RuntimeException;
use Symfony\Component\JsonEncoder\Exception\UnexpectedValueException;
use Symfony\Component\TypeInfo\Type\ObjectType;
use Symfony\Component\TypeInfo\TypeIdentifier;
use Symfony\Component\TypeInfo\Type\WrappingTypeInterface;
use Symfony\Component\TypeInfo\TypeIdentifier;

/**
* Builds a PHP syntax tree that encodes data to JSON.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,8 +18,8 @@
use Symfony\Component\TypeInfo\Type\IntersectionType;
use Symfony\Component\TypeInfo\Type\ObjectType;
use Symfony\Component\TypeInfo\Type\UnionType;
use Symfony\Component\TypeInfo\TypeContext\TypeContextFactory;
use Symfony\Component\TypeInfo\Type\WrappingTypeInterface;
use Symfony\Component\TypeInfo\TypeContext\TypeContextFactory;

/**
* Enhances properties encoding/decoding metadata based on properties' generic type.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@

use PHPUnit\Framework\TestCase;
use Symfony\Component\JsonEncoder\Decode\LazyInstantiator;
use Symfony\Component\JsonEncoder\Exception\InvalidArgumentException;
use Symfony\Component\JsonEncoder\Tests\Fixtures\Model\ClassicDummy;
use Symfony\Component\JsonEncoder\Tests\Fixtures\Model\DummyWithNormalizerAttributes;

Expand All @@ -32,17 +33,46 @@ protected function setUp(): void
}
}

public function testCreateLazyGhost()
/**
* @requires PHP < 8.4
*/
public function testCreateLazyGhostUsingVarExporter()
{
$ghost = (new LazyInstantiator($this->lazyGhostsDir))->instantiate(ClassicDummy::class, []);
$ghost = (new LazyInstantiator($this->lazyGhostsDir))->instantiate(ClassicDummy::class, function (ClassicDummy $object): void {
$object->id = 123;
});

$this->assertArrayHasKey(\sprintf("\0%sGhost\0lazyObjectState", preg_replace('/\\\\/', '', ClassicDummy::class)), (array) $ghost);
$this->assertSame(123, $ghost->id);
}

/**
* @requires PHP < 8.4
*/
public function testCreateCacheFile()
{
(new LazyInstantiator($this->lazyGhostsDir))->instantiate(DummyWithNormalizerAttributes::class, []);
(new LazyInstantiator($this->lazyGhostsDir))->instantiate(DummyWithNormalizerAttributes::class, function (ClassicDummy $object): void {});

$this->assertCount(1, glob($this->lazyGhostsDir.'/*'));
}

/**
* @requires PHP < 8.4
*/
public function testThrowIfLazyGhostDirNotDefined()
{
$this->expectException(InvalidArgumentException::class);
new LazyInstantiator();
}

/**
* @requires PHP 8.4
*/
public function testCreateLazyGhostUsingPhp()
{
$ghost = (new LazyInstantiator())->instantiate(ClassicDummy::class, function (ClassicDummy $object): void {
$object->id = 123;
});

$this->assertSame(123, $ghost->id);
}
}

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading
Loading