Skip to content

[Serializer] Add CompiledClassMetadataFactory #29117

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
Aug 11, 2020
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
2 changes: 2 additions & 0 deletions .php_cs.dist
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,8 @@ return PhpCsFixer\Config::create()
->notPath('#Symfony/Bridge/PhpUnit/.*Legacy#')
// file content autogenerated by `var_export`
->notPath('Symfony/Component/Translation/Tests/fixtures/resources.php')
// file content autogenerated by `VarExporter::export`
->notPath('Symfony/Component/Serializer/Tests/Fixtures/serializer.class.metadata.php')
// test template
->notPath('Symfony/Bundle/FrameworkBundle/Tests/Templating/Helper/Resources/Custom/_name_entry_label.html.php')
// explicit trigger_error tests
Expand Down
5 changes: 5 additions & 0 deletions src/Symfony/Component/Serializer/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,11 @@
CHANGELOG
=========

5.2.0
-----

* added `CompiledClassMetadataFactory` and `ClassMetadataFactoryCompiler` for faster metadata loading.

5.1.0
-----

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
<?php

/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace Symfony\Component\Serializer\CacheWarmer;

use Symfony\Component\Filesystem\Filesystem;
use Symfony\Component\HttpKernel\CacheWarmer\CacheWarmerInterface;
use Symfony\Component\Serializer\Mapping\Factory\ClassMetadataFactoryCompiler;
use Symfony\Component\Serializer\Mapping\Factory\ClassMetadataFactoryInterface;

/**
* @author Fabien Bourigault <bourigaultfabien@gmail.com>
*/
final class CompiledClassMetadataCacheWarmer implements CacheWarmerInterface
{
private $classesToCompile;

private $classMetadataFactory;

private $classMetadataFactoryCompiler;

private $filesystem;

public function __construct(array $classesToCompile, ClassMetadataFactoryInterface $classMetadataFactory, ClassMetadataFactoryCompiler $classMetadataFactoryCompiler, Filesystem $filesystem)
{
$this->classesToCompile = $classesToCompile;
$this->classMetadataFactory = $classMetadataFactory;
$this->classMetadataFactoryCompiler = $classMetadataFactoryCompiler;
$this->filesystem = $filesystem;
}

/**
* {@inheritdoc}
*/
public function warmUp($cacheDir)
{
$metadatas = [];

foreach ($this->classesToCompile as $classToCompile) {
$metadatas[] = $this->classMetadataFactory->getMetadataFor($classToCompile);
}

$code = $this->classMetadataFactoryCompiler->compile($metadatas);

$this->filesystem->dumpFile("{$cacheDir}/serializer.class.metadata.php", $code);
}

/**
* {@inheritdoc}
*/
public function isOptional()
{
return true;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
<?php

/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace Symfony\Component\Serializer\Mapping\Factory;

use Symfony\Component\Serializer\Mapping\ClassMetadataInterface;
use Symfony\Component\VarExporter\VarExporter;

/**
* @author Fabien Bourigault <bourigaultfabien@gmail.com>
*/
final class ClassMetadataFactoryCompiler
{
/**
* @param ClassMetadataInterface[] $classMetadatas
*/
public function compile(array $classMetadatas): string
{
return <<<EOF
<?php

// This file has been auto-generated by the Symfony Serializer Component.

return [{$this->generateDeclaredClassMetadata($classMetadatas)}
];
EOF;
}

/**
* @param ClassMetadataInterface[] $classMetadatas
*/
private function generateDeclaredClassMetadata(array $classMetadatas): string
{
$compiled = '';

foreach ($classMetadatas as $classMetadata) {
$attributesMetadata = [];
foreach ($classMetadata->getAttributesMetadata() as $attributeMetadata) {
$attributesMetadata[$attributeMetadata->getName()] = [
$attributeMetadata->getGroups(),
$attributeMetadata->getMaxDepth(),
$attributeMetadata->getSerializedName(),
];
}

$classDiscriminatorMapping = $classMetadata->getClassDiscriminatorMapping() ? [
$classMetadata->getClassDiscriminatorMapping()->getTypeProperty(),
$classMetadata->getClassDiscriminatorMapping()->getTypesMapping(),
] : null;

$compiled .= sprintf("\n'%s' => %s,", $classMetadata->getName(), VarExporter::export([
$attributesMetadata,
$classDiscriminatorMapping,
]));
}

return $compiled;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
<?php

/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace Symfony\Component\Serializer\Mapping\Factory;

use Symfony\Component\Serializer\Mapping\AttributeMetadata;
use Symfony\Component\Serializer\Mapping\ClassDiscriminatorMapping;
use Symfony\Component\Serializer\Mapping\ClassMetadata;

/**
* @author Fabien Bourigault <bourigaultfabien@gmail.com>
*/
final class CompiledClassMetadataFactory implements ClassMetadataFactoryInterface
{
private $compiledClassMetadata = [];

private $loadedClasses = [];

private $classMetadataFactory;

public function __construct(string $compiledClassMetadataFile, ClassMetadataFactoryInterface $classMetadataFactory)
{
if (!file_exists($compiledClassMetadataFile)) {
throw new \RuntimeException("File \"{$compiledClassMetadataFile}\" could not be found.");
}

$compiledClassMetadata = require $compiledClassMetadataFile;
if (!\is_array($compiledClassMetadata)) {
throw new \RuntimeException(sprintf('Compiled metadata must be of the type array, %s given.', \gettype($compiledClassMetadata)));
}

$this->compiledClassMetadata = $compiledClassMetadata;
$this->classMetadataFactory = $classMetadataFactory;
}

/**
* {@inheritdoc}
*/
public function getMetadataFor($value)
{
$className = \is_object($value) ? \get_class($value) : $value;

if (!isset($this->compiledClassMetadata[$className])) {
return $this->classMetadataFactory->getMetadataFor($value);
}

if (!isset($this->loadedClasses[$className])) {
$classMetadata = new ClassMetadata($className);
foreach ($this->compiledClassMetadata[$className][0] as $name => $compiledAttributesMetadata) {
$classMetadata->attributesMetadata[$name] = $attributeMetadata = new AttributeMetadata($name);
[$attributeMetadata->groups, $attributeMetadata->maxDepth, $attributeMetadata->serializedName] = $compiledAttributesMetadata;
}
$classMetadata->classDiscriminatorMapping = $this->compiledClassMetadata[$className][1]
? new ClassDiscriminatorMapping(...$this->compiledClassMetadata[$className][1])
: null
;

$this->loadedClasses[$className] = $classMetadata;
}

return $this->loadedClasses[$className];
}

/**
* {@inheritdoc}
*/
public function hasMetadataFor($value)
{
$className = \is_object($value) ? \get_class($value) : $value;

return isset($this->compiledClassMetadata[$className]) || $this->classMetadataFactory->hasMetadataFor($value);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
<?php

namespace Symfony\Component\Serializer\Tests\CacheWarmer;

use PHPUnit\Framework\TestCase;
use Symfony\Component\Filesystem\Filesystem;
use Symfony\Component\HttpKernel\CacheWarmer\CacheWarmerInterface;
use Symfony\Component\Serializer\CacheWarmer\CompiledClassMetadataCacheWarmer;
use Symfony\Component\Serializer\Mapping\Factory\ClassMetadataFactoryCompiler;
use Symfony\Component\Serializer\Mapping\Factory\ClassMetadataFactoryInterface;

final class CompiledClassMetadataCacheWarmerTest extends TestCase
{
public function testItImplementsCacheWarmerInterface()
{
$classMetadataFactory = $this->createMock(ClassMetadataFactoryInterface::class);
$filesystem = $this->createMock(Filesystem::class);

$compiledClassMetadataCacheWarmer = new CompiledClassMetadataCacheWarmer([], $classMetadataFactory, new ClassMetadataFactoryCompiler(), $filesystem);

$this->assertInstanceOf(CacheWarmerInterface::class, $compiledClassMetadataCacheWarmer);
}

public function testItIsAnOptionalCacheWarmer()
{
$classMetadataFactory = $this->createMock(ClassMetadataFactoryInterface::class);
$filesystem = $this->createMock(Filesystem::class);

$compiledClassMetadataCacheWarmer = new CompiledClassMetadataCacheWarmer([], $classMetadataFactory, new ClassMetadataFactoryCompiler(), $filesystem);

$this->assertTrue($compiledClassMetadataCacheWarmer->isOptional());
}

public function testItDumpCompiledClassMetadatas()
{
$classMetadataFactory = $this->createMock(ClassMetadataFactoryInterface::class);

$code = <<<EOF
<?php

// This file has been auto-generated by the Symfony Serializer Component.

return [
];
EOF;

$filesystem = $this->createMock(Filesystem::class);
$filesystem
->expects($this->once())
->method('dumpFile')
->with('/var/cache/prod/serializer.class.metadata.php', $code)
;

$compiledClassMetadataCacheWarmer = new CompiledClassMetadataCacheWarmer([], $classMetadataFactory, new ClassMetadataFactoryCompiler(), $filesystem);

$compiledClassMetadataCacheWarmer->warmUp('/var/cache/prod');
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
<?php

return new DateTime();
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
<?php

// This file has been auto-generated by the Symfony Serializer Component.

return [
'Symfony\Component\Serializer\Tests\Fixtures\Dummy' => [
[
'foo' => [[], null, null],
'bar' => [[], null, null],
'baz' => [[], null, null],
'qux' => [[], null, null],
],
null,
],
];
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
<?php

namespace Symfony\Component\Serializer\Tests\Mapping\Factory;

use Doctrine\Common\Annotations\AnnotationReader;
use PHPUnit\Framework\TestCase;
use Symfony\Component\Serializer\Mapping\Factory\ClassMetadataFactory;
use Symfony\Component\Serializer\Mapping\Factory\ClassMetadataFactoryCompiler;
use Symfony\Component\Serializer\Mapping\Loader\AnnotationLoader;
use Symfony\Component\Serializer\Tests\Fixtures\Dummy;
use Symfony\Component\Serializer\Tests\Fixtures\MaxDepthDummy;
use Symfony\Component\Serializer\Tests\Fixtures\SerializedNameDummy;

final class ClassMetadataFactoryCompilerTest extends TestCase
{
/**
* @var string
*/
private $dumpPath;

protected function setUp()
{
$this->dumpPath = sys_get_temp_dir().\DIRECTORY_SEPARATOR.'php_serializer_metadata.'.uniqid('CompiledClassMetadataFactory').'.php';
}

protected function tearDown()
{
@unlink($this->dumpPath);
}

public function testItDumpMetadata()
{
$classMetatadataFactory = new ClassMetadataFactory(new AnnotationLoader(new AnnotationReader()));

$dummyMetadata = $classMetatadataFactory->getMetadataFor(Dummy::class);
$maxDepthDummyMetadata = $classMetatadataFactory->getMetadataFor(MaxDepthDummy::class);
$serializedNameDummyMetadata = $classMetatadataFactory->getMetadataFor(SerializedNameDummy::class);

$code = (new ClassMetadataFactoryCompiler())->compile([
$dummyMetadata,
$maxDepthDummyMetadata,
$serializedNameDummyMetadata,
]);

file_put_contents($this->dumpPath, $code);
$compiledMetadata = require $this->dumpPath;

$this->assertCount(3, $compiledMetadata);

$this->assertArrayHasKey(Dummy::class, $compiledMetadata);
$this->assertEquals([
[
'foo' => [[], null, null],
'bar' => [[], null, null],
'baz' => [[], null, null],
'qux' => [[], null, null],
],
null,
], $compiledMetadata[Dummy::class]);

$this->assertArrayHasKey(MaxDepthDummy::class, $compiledMetadata);
$this->assertEquals([
[
'foo' => [[], 2, null],
'bar' => [[], 3, null],
'child' => [[], null, null],
],
null,
], $compiledMetadata[MaxDepthDummy::class]);

$this->assertArrayHasKey(SerializedNameDummy::class, $compiledMetadata);
$this->assertEquals([
[
'foo' => [[], null, 'baz'],
'bar' => [[], null, 'qux'],
'quux' => [[], null, null],
'child' => [[], null, null],
],
null,
], $compiledMetadata[SerializedNameDummy::class]);
}
}
Loading