Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

[Serializer] Add support for auto generated custom normalizers#52905

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 ourterms of service andprivacy statement. We’ll occasionally send you account related emails.

Already on GitHub?Sign in to your account

Open
Nyholm wants to merge13 commits intosymfony:7.4
base:7.4
Choose a base branch
Loading
fromNyholm:better-serializer
Open
Show file tree
Hide file tree
Changes fromall 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
4 changes: 4 additions & 0 deletions.gitattributes
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -5,4 +5,8 @@
/src/Symfony/Component/Notifier/Bridge export-ignore
/src/Symfony/Component/Runtime export-ignore
/src/Symfony/Component/Translation/Bridge export-ignore

# Keep generated files from displaying in diffs by default
# https://docs.github.com/en/repositories/working-with-files/managing-files/customizing-how-changed-files-appear-on-github
/src/Symfony/Component/Intl/Resources/data/*/* linguist-generated=true
/src/Symfony/Component/Serializer/Tests/Fixtures/CustomNormalizer/*/ExpectedNormalizer/* linguist-generated=true
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -70,6 +70,7 @@ class UnusedTagsPass implements CompilerPassInterface
'monolog.logger',
'notifier.channel',
'property_info.access_extractor',
'property_info.constructor_argument_type_extractor',
'property_info.initializable_extractor',
'property_info.list_extractor',
'property_info.type_extractor',
Expand Down
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -1124,6 +1124,40 @@ private function addSerializerSection(ArrayNodeDefinition $rootNode, callable $e
->defaultValue([])
->prototype('variable')->end()
->end()
->arrayNode('auto_normalizer')
->addDefaultsIfNotSet()
->fixXmlConfig('path')
->children()
->arrayNode('paths')
->validate()
->ifTrue(function ($data): bool {
foreach ($data as $key => $value) {
if (!\is_string($key)) {
return true;
}
if (!\is_string($value)) {
return true;
}
}

return false;
})
->thenInvalid('The value must be an array with keys and values. Keys should be the start of a namespace and the values should be a file path.')
->end()
->info('Paths where we store classes we want to automatically create normalizers for.')
->normalizeKeys(false)
->defaultValue([])
->example(['App\\Model' => 'src/Model', 'App\\Entity' => 'src/Entity'])
->useAttributeAsKey('name')
->variablePrototype()
->validate()
->ifTrue(fn ($value): bool => !\is_string($value))
->thenInvalid('The value must be a string representing a path relative to the project root.')
->end()
->end()
->end()
->end()
->end()
->end()
->end()
->end()
Expand Down
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -390,6 +390,10 @@ public function load(array $configs, ContainerBuilder $container): void

if ($propertyInfoEnabled) {
$this->registerPropertyInfoConfiguration($container, $loader);
} else {
// Remove services depending on PropertyInfo
$container->removeDefinition('serializer.auto_normalizer.definition_extractor');
$container->removeDefinition('serializer.custom_normalizer_helper');
}

if ($this->readConfigEnabled('lock', $container, $config['lock'])) {
Expand DownExpand Up@@ -1861,6 +1865,8 @@ private function registerSerializerConfiguration(array $config, ContainerBuilder
$container->removeDefinition('serializer.normalizer.translatable');
}

$container->getDefinition('serializer.custom_normalizer_helper')->replaceArgument(2, $config['auto_normalizer']['paths']);

$serializerLoaders = [];
if (isset($config['enable_attributes']) && $config['enable_attributes']) {
$attributeLoader = new Definition(AttributeLoader::class);
Expand DownExpand Up@@ -1940,12 +1946,14 @@ private function registerPropertyInfoConfiguration(ContainerBuilder $container,
) {
$definition = $container->register('property_info.phpstan_extractor', PhpStanExtractor::class);
$definition->addTag('property_info.type_extractor', ['priority' => -1000]);
$definition->addTag('property_info.constructor_argument_type_extractor');
}

if (ContainerBuilder::willBeAvailable('phpdocumentor/reflection-docblock', DocBlockFactoryInterface::class, ['symfony/framework-bundle', 'symfony/property-info'], true)) {
$definition = $container->register('property_info.php_doc_extractor', PhpDocExtractor::class);
$definition->addTag('property_info.description_extractor', ['priority' => -1000]);
$definition->addTag('property_info.type_extractor', ['priority' => -1001]);
$definition->addTag('property_info.constructor_argument_type_extractor');
}

if ($container->getParameter('kernel.debug')) {
Expand Down
2 changes: 1 addition & 1 deletionsrc/Symfony/Bundle/FrameworkBundle/FrameworkBundle.php
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -150,8 +150,8 @@ public function build(ContainerBuilder $container): void
$this->addCompilerPassIfExists($container, TranslationExtractorPass::class);
$this->addCompilerPassIfExists($container, TranslationDumperPass::class);
$container->addCompilerPass(new FragmentRendererPass());
$this->addCompilerPassIfExists($container, SerializerPass::class);
$this->addCompilerPassIfExists($container, PropertyInfoPass::class);
$this->addCompilerPassIfExists($container, SerializerPass::class);
$container->addCompilerPass(new ControllerArgumentValueResolverPass());
$container->addCompilerPass(new CachePoolPass(), PassConfig::TYPE_BEFORE_OPTIMIZATION, 32);
$container->addCompilerPass(new CachePoolClearerPass(), PassConfig::TYPE_AFTER_REMOVING);
Expand Down
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -11,6 +11,8 @@

namespace Symfony\Component\DependencyInjection\Loader\Configurator;

use Symfony\Component\PropertyInfo\Extractor\ConstructorArgumentTypeExtractorAggregate;
use Symfony\Component\PropertyInfo\Extractor\ConstructorArgumentTypeExtractorInterface;
use Symfony\Component\PropertyInfo\Extractor\ReflectionExtractor;
use Symfony\Component\PropertyInfo\PropertyAccessExtractorInterface;
use Symfony\Component\PropertyInfo\PropertyDescriptionExtractorInterface;
Expand DownExpand Up@@ -45,8 +47,14 @@
->tag('property_info.type_extractor', ['priority' => -1002])
->tag('property_info.access_extractor', ['priority' => -1000])
->tag('property_info.initializable_extractor', ['priority' => -1000])
->tag('property_info.constructor_argument_type_extractor')

->alias(PropertyReadInfoExtractorInterface::class, 'property_info.reflection_extractor')
->alias(PropertyWriteInfoExtractorInterface::class, 'property_info.reflection_extractor')

->set('property_info.constructor_argument_type_extractor_aggregate', ConstructorArgumentTypeExtractorAggregate::class)
->args([tagged_iterator('property_info.constructor_argument_type_extractor')])
->alias(ConstructorArgumentTypeExtractorInterface::class, 'property_info.constructor_argument_type_extractor_aggregate')

;
};
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -16,7 +16,14 @@
use Symfony\Component\Cache\Adapter\PhpArrayAdapter;
use Symfony\Component\ErrorHandler\ErrorRenderer\HtmlErrorRenderer;
use Symfony\Component\ErrorHandler\ErrorRenderer\SerializerErrorRenderer;
use Symfony\Component\PropertyInfo\Extractor\ConstructorArgumentTypeExtractorInterface;
use Symfony\Component\PropertyInfo\Extractor\SerializerExtractor;
use Symfony\Component\PropertyInfo\PropertyInfoExtractorInterface;
use Symfony\Component\PropertyInfo\PropertyReadInfoExtractorInterface;
use Symfony\Component\PropertyInfo\PropertyWriteInfoExtractorInterface;
use Symfony\Component\Serializer\Builder\DefinitionExtractor;
use Symfony\Component\Serializer\Builder\NormalizerBuilder;
use Symfony\Component\Serializer\DependencyInjection\CustomNormalizerHelper;
use Symfony\Component\Serializer\Encoder\CsvEncoder;
use Symfony\Component\Serializer\Encoder\DecoderInterface;
use Symfony\Component\Serializer\Encoder\EncoderInterface;
Expand DownExpand Up@@ -169,6 +176,25 @@
service('serializer.mapping.cache.symfony'),
])

// Auto Normalizer Builder
->set('serializer.auto_normalizer.builder', NormalizerBuilder::class)
->set('serializer.auto_normalizer.definition_extractor', DefinitionExtractor::class)
->args([
service(PropertyInfoExtractorInterface::class),
service(PropertyReadInfoExtractorInterface::class),
service(PropertyWriteInfoExtractorInterface::class),
service(ConstructorArgumentTypeExtractorInterface::class),
])

->set('serializer.custom_normalizer_helper', CustomNormalizerHelper::class)
->args([
service('serializer.auto_normalizer.builder'),
service('serializer.auto_normalizer.definition_extractor'),
[],
param('kernel.project_dir'),
service('logger')->nullOnInvalid(),
])

// Encoders
->set('serializer.encoder.xml', XmlEncoder::class)
->tag('serializer.encoder')
Expand Down
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -615,6 +615,7 @@ protected static function getBundleDefaultConfig()
'enabled' => true,
'enable_attributes' => !class_exists(FullStack::class),
'mapping' => ['paths' => []],
'auto_normalizer' => ['paths' => []],
],
'property_access' => [
'enabled' => true,
Expand Down
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -64,6 +64,7 @@
'serializer' => [
'enabled' => true,
'enable_attributes' => true,
'auto_normalizer' => ['paths'=>[]],
'name_converter' => 'serializer.name_converter.camel_case_to_snake_case',
'circular_reference_handler' => 'my.circular.reference.handler',
'max_depth_handler' => 'my.max.depth.handler',
Expand Down
2 changes: 2 additions & 0 deletionssrc/Symfony/Component/PropertyInfo/CHANGELOG.md
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -5,6 +5,8 @@ CHANGELOG
---

* Introduce `PropertyDocBlockExtractorInterface` to extract a property's doc block
* Make ConstructorArgumentTypeExtractorInterface non-internal
* Add `ConstructorArgumentTypeExtractorAggregate` to aggregate multiple `ConstructorArgumentTypeExtractorInterface` implementations

6.4
---
Expand Down
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
<?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\PropertyInfo\Extractor;

/**
* @author Tobias Nyholm <tobias.nyholm@gmail.com>
*/
class ConstructorArgumentTypeExtractorAggregate implements ConstructorArgumentTypeExtractorInterface
{
/**
* @param iterable<int, ConstructorArgumentTypeExtractorInterface> $extractors
*/
public function __construct(
private readonly iterable $extractors = [],
) {
}

public function getTypesFromConstructor(string $class, string $property): ?array
{
$output = [];
foreach ($this->extractors as $extractor) {
$value = $extractor->getTypesFromConstructor($class, $property);
if (null !== $value) {
$output[] = $value;
}
}

if ([] === $output) {
return null;
}

return array_merge([], ...$output);
}
}
Original file line numberDiff line numberDiff line change
Expand Up@@ -17,8 +17,6 @@
* Infers the constructor argument type.
*
* @author Dmitrii Poddubnyi <dpoddubny@gmail.com>
*
* @internal
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others.Learn more.

I'm not a huge fan, you did this because it's used in another component? Just ignore the error for internal use between components it's fine no?

Copy link
MemberAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others.Learn more.

Yes. It is because I used it in another component.

Do you know the reason why it is internal in the first place?

*/
interface ConstructorArgumentTypeExtractorInterface
{
Expand Down
9 changes: 9 additions & 0 deletionssrc/Symfony/Component/Serializer/.editorconfig
View file
Open in desktop
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
# Ignore paths
[Tests/CodeGenerator/Fixtures/**]
trim_trailing_whitespace = false

[Tests/Fixtures/CustomNormalizer/**/ExpectedNormalizer/**]
trim_trailing_whitespace = false
insert_final_newline = false
indent_size = unset
indent_style = unset
1 change: 1 addition & 0 deletionssrc/Symfony/Component/Serializer/.gitignore
View file
Open in desktop
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
vendor/
composer.lock
phpunit.xml
Tests/_output
21 changes: 21 additions & 0 deletionssrc/Symfony/Component/Serializer/Annotation/Serializable.php
View file
Open in desktop
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
<?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\Annotation;

class_exists(\Symfony\Component\Serializer\Attribute\Serializable::class);

if (false) {
#[\Attribute(\Attribute::TARGET_CLASS)]
class Serializable extends \Symfony\Component\Serializer\Attribute\Serializable
{
}
}
27 changes: 27 additions & 0 deletionssrc/Symfony/Component/Serializer/Attribute/Serializable.php
View file
Open in desktop
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
<?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\Attribute;

/**
* Classes with this attribute will get a custom normalizer to improve speed when
* serializing/deserializing.
*
* @author Tobias Nyholm <tobias.nyholm@gmail.com>
*/
#[\Attribute(\Attribute::TARGET_CLASS)]
class Serializable
{
}

if (!class_exists(\Symfony\Component\Serializer\Annotation\Serializable::class, false)) {
class_alias(Serializable::class, \Symfony\Component\Serializer\Annotation\Serializable::class);
}
35 changes: 35 additions & 0 deletionssrc/Symfony/Component/Serializer/Builder/BuildResult.php
View file
Open in desktop
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
<?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\Builder;

/**
* @author Tobias Nyholm <tobias.nyholm@gmail.com>
*
* @experimental in 7.1
*/
class BuildResult
{
public function __construct(
// The full file location where the class is stored
public readonly string $filePath,
// Just the class name
public readonly string $className,
// Class name with namespace
public readonly string $classNs,
) {
}

public function loadClass(): void
{
require_once $this->filePath;
}
}
Loading

[8]ページ先頭

©2009-2025 Movatter.jp