Skip to content

[Serializer] Introduce named serializers #56823

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
Sep 19, 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
1 change: 1 addition & 0 deletions src/Symfony/Bundle/FrameworkBundle/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ CHANGELOG
* Register `Symfony\Component\Serializer\NameConverter\SnakeCaseToCamelCaseNameConverter` as a service named `serializer.name_converter.snake_case_to_camel_case` if available
* Deprecate `session.sid_length` and `session.sid_bits_per_character` config options
* Add the ability to use an existing service as a lock/semaphore resource
* Add support for configuring multiple serializer instances via the configuration

7.1
---
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1099,10 +1099,22 @@ private function addAnnotationsSection(ArrayNodeDefinition $rootNode): void

private function addSerializerSection(ArrayNodeDefinition $rootNode, callable $enableIfStandalone): void
{
$defaultContextNode = fn () => (new NodeBuilder())
->arrayNode('default_context')
->normalizeKeys(false)
->validate()
->ifTrue(fn () => $this->debug && class_exists(JsonParser::class))
->then(fn (array $v) => $v + [JsonDecode::DETAILED_ERROR_MESSAGES => true])
->end()
->defaultValue([])
->prototype('variable')->end()
;

$rootNode
->children()
->arrayNode('serializer')
->info('Serializer configuration')
->fixXmlConfig('named_serializer', 'named_serializers')
->{$enableIfStandalone('symfony/serializer', Serializer::class)}()
->children()
->booleanNode('enable_attributes')->{class_exists(FullStack::class) ? 'defaultFalse' : 'defaultTrue'}()->end()
Expand All @@ -1118,19 +1130,36 @@ private function addSerializerSection(ArrayNodeDefinition $rootNode, callable $e
->end()
->end()
->end()
->arrayNode('default_context')
->normalizeKeys(false)
->append($defaultContextNode())
->arrayNode('named_serializers')
->useAttributeAsKey('name')
->arrayPrototype()
->children()
->scalarNode('name_converter')->end()
->append($defaultContextNode())
->booleanNode('include_built_in_normalizers')
->info('Whether to include the built-in normalizers')
->defaultTrue()
->end()
->booleanNode('include_built_in_encoders')
->info('Whether to include the built-in encoders')
->defaultTrue()
->end()
->end()
->end()
->validate()
->ifTrue(fn () => $this->debug && class_exists(JsonParser::class))
->then(fn (array $v) => $v + [JsonDecode::DETAILED_ERROR_MESSAGES => true])
->ifTrue(fn ($v) => isset($v['default']))
->thenInvalid('"default" is a reserved name.')
->end()
->defaultValue([])
->prototype('variable')->end()
->end()
->end()
->validate()
->ifTrue(fn ($v) => $this->debug && class_exists(JsonParser::class) && !isset($v['default_context'][JsonDecode::DETAILED_ERROR_MESSAGES]))
->then(function ($v) { $v['default_context'][JsonDecode::DETAILED_ERROR_MESSAGES] = true; return $v; })
->then(function ($v) {
$v['default_context'][JsonDecode::DETAILED_ERROR_MESSAGES] = true;

return $v;
})
->end()
->end()
->end()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1906,6 +1906,7 @@ private function registerSerializerConfiguration(array $config, ContainerBuilder
$container->getDefinition('serializer.mapping.cache_warmer')->replaceArgument(0, $serializerLoaders);

if (isset($config['name_converter']) && $config['name_converter']) {
$container->setParameter('.serializer.name_converter', $config['name_converter']);
$container->getDefinition('serializer.name_converter.metadata_aware')->setArgument(1, new Reference($config['name_converter']));
}

Expand Down Expand Up @@ -1934,6 +1935,8 @@ private function registerSerializerConfiguration(array $config, ContainerBuilder
$container->getDefinition('serializer.normalizer.object')->setArgument(6, $context);

$container->getDefinition('serializer.normalizer.property')->setArgument(5, $defaultContext);

$container->setParameter('.serializer.named_serializers', $config['named_serializers'] ?? []);
}

private function registerPropertyInfoConfiguration(ContainerBuilder $container, PhpFileLoader $loader): void
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,7 @@
])

->set('serializer.normalizer.flatten_exception', FlattenExceptionNormalizer::class)
->tag('serializer.normalizer', ['priority' => -880])
->tag('serializer.normalizer', ['built_in' => true, 'priority' => -880])

->set('messenger.transport.native_php_serializer', PhpSerializer::class)
->alias('messenger.default_serializer', 'messenger.transport.native_php_serializer')
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -320,6 +320,7 @@
<xsd:choice minOccurs="0" maxOccurs="unbounded">
<xsd:element name="mapping" type="file_mapping" />
<xsd:element name="default-context" type="metadata" minOccurs="0" maxOccurs="1" />
<xsd:element name="named-serializer" type="named_serializer_options" />
</xsd:choice>
<xsd:attribute name="enabled" type="xsd:boolean" />
<xsd:attribute name="enable-attributes" type="xsd:boolean" />
Expand All @@ -332,6 +333,16 @@
<xsd:attribute name="enabled" type="xsd:boolean" />
</xsd:complexType>

<xsd:complexType name="named_serializer_options">
<xsd:sequence>
<xsd:element name="default-context" type="metadata" minOccurs="0" maxOccurs="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" />
<xsd:attribute name="name-converter" type="xsd:string" />
<xsd:attribute name="include-built-in-normalizers" type="xsd:boolean" />
<xsd:attribute name="include-built-in-encoders" type="xsd:boolean" />
</xsd:complexType>

<xsd:complexType name="property_info">
<xsd:attribute name="enabled" type="xsd:boolean" />
</xsd:complexType>
Expand Down
44 changes: 24 additions & 20 deletions src/Symfony/Bundle/FrameworkBundle/Resources/config/serializer.php
Original file line number Diff line number Diff line change
Expand Up @@ -80,46 +80,46 @@
->set('serializer.normalizer.constraint_violation_list', ConstraintViolationListNormalizer::class)
->args([1 => service('serializer.name_converter.metadata_aware')])
->autowire(true)
->tag('serializer.normalizer', ['priority' => -915])
->tag('serializer.normalizer', ['built_in' => true, 'priority' => -915])

->set('serializer.normalizer.mime_message', MimeMessageNormalizer::class)
->args([service('serializer.normalizer.property')])
->tag('serializer.normalizer', ['priority' => -915])
->tag('serializer.normalizer', ['built_in' => true, 'priority' => -915])

->set('serializer.normalizer.datetimezone', DateTimeZoneNormalizer::class)
->tag('serializer.normalizer', ['priority' => -915])
->tag('serializer.normalizer', ['built_in' => true, 'priority' => -915])

->set('serializer.normalizer.dateinterval', DateIntervalNormalizer::class)
->tag('serializer.normalizer', ['priority' => -915])
->tag('serializer.normalizer', ['built_in' => true, 'priority' => -915])

->set('serializer.normalizer.data_uri', DataUriNormalizer::class)
->args([service('mime_types')->nullOnInvalid()])
->tag('serializer.normalizer', ['priority' => -920])
->tag('serializer.normalizer', ['built_in' => true, 'priority' => -920])

->set('serializer.normalizer.datetime', DateTimeNormalizer::class)
->tag('serializer.normalizer', ['priority' => -910])
->tag('serializer.normalizer', ['built_in' => true, 'priority' => -910])

->set('serializer.normalizer.json_serializable', JsonSerializableNormalizer::class)
->args([null, null])
->tag('serializer.normalizer', ['priority' => -950])
->tag('serializer.normalizer', ['built_in' => true, 'priority' => -950])

->set('serializer.normalizer.problem', ProblemNormalizer::class)
->args([param('kernel.debug'), '$translator' => service('translator')->nullOnInvalid()])
->tag('serializer.normalizer', ['priority' => -890])
->tag('serializer.normalizer', ['built_in' => true, 'priority' => -890])

->set('serializer.denormalizer.unwrapping', UnwrappingDenormalizer::class)
->args([service('serializer.property_accessor')])
->tag('serializer.normalizer', ['priority' => 1000])
->tag('serializer.normalizer', ['built_in' => true, 'priority' => 1000])

->set('serializer.normalizer.uid', UidNormalizer::class)
->tag('serializer.normalizer', ['priority' => -890])
->tag('serializer.normalizer', ['built_in' => true, 'priority' => -890])

->set('serializer.normalizer.translatable', TranslatableNormalizer::class)
->args(['$translator' => service('translator')])
->tag('serializer.normalizer', ['priority' => -920])
->tag('serializer.normalizer', ['built_in' => true, 'priority' => -920])

->set('serializer.normalizer.form_error', FormErrorNormalizer::class)
->tag('serializer.normalizer', ['priority' => -915])
->tag('serializer.normalizer', ['built_in' => true, 'priority' => -915])

->set('serializer.normalizer.object', ObjectNormalizer::class)
->args([
Expand All @@ -132,7 +132,7 @@
null,
service('property_info')->ignoreOnInvalid(),
])
->tag('serializer.normalizer', ['priority' => -1000])
->tag('serializer.normalizer', ['built_in' => true, 'priority' => -1000])

->set('serializer.normalizer.property', PropertyNormalizer::class)
->args([
Expand All @@ -144,7 +144,7 @@
])

->set('serializer.denormalizer.array', ArrayDenormalizer::class)
->tag('serializer.normalizer', ['priority' => -990])
->tag('serializer.normalizer', ['built_in' => true, 'priority' => -990])

// Loader
->set('serializer.mapping.chain_loader', LoaderChain::class)
Expand Down Expand Up @@ -174,26 +174,30 @@

// Encoders
->set('serializer.encoder.xml', XmlEncoder::class)
->tag('serializer.encoder')
->tag('serializer.encoder', ['built_in' => true])

->set('serializer.encoder.json', JsonEncoder::class)
->args([null, null])
->tag('serializer.encoder')
->tag('serializer.encoder', ['built_in' => true])

->set('serializer.encoder.yaml', YamlEncoder::class)
->args([null, null])
->tag('serializer.encoder')
->tag('serializer.encoder', ['built_in' => true])

->set('serializer.encoder.csv', CsvEncoder::class)
->tag('serializer.encoder')
->tag('serializer.encoder', ['built_in' => true])

// Name converters
->set('serializer.name_converter.camel_case_to_snake_case', CamelCaseToSnakeCaseNameConverter::class)
->set('serializer.name_converter.snake_case_to_camel_case', SnakeCaseToCamelCaseNameConverter::class)

->set('serializer.name_converter.metadata_aware', MetadataAwareNameConverter::class)
->set('serializer.name_converter.metadata_aware.abstract', MetadataAwareNameConverter::class)
->abstract()
->args([service('serializer.mapping.class_metadata_factory')])

->set('serializer.name_converter.metadata_aware')
->parent('serializer.name_converter.metadata_aware.abstract')

// PropertyInfo extractor
->set('property_info.serializer_extractor', SerializerExtractor::class)
->args([service('serializer.mapping.class_metadata_factory')])
Expand All @@ -216,6 +220,6 @@
])

->set('serializer.normalizer.backed_enum', BackedEnumNormalizer::class)
->tag('serializer.normalizer', ['priority' => -915])
->tag('serializer.normalizer', ['built_in' => true, 'priority' => -915])
;
};
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
->args([
service('debug.serializer.inner'),
service('serializer.data_collector'),
'default',
])

->set('serializer.data_collector', SerializerDataCollector::class)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -784,6 +784,7 @@ protected static function getBundleDefaultConfig()
'enabled' => true,
'enable_attributes' => !class_exists(FullStack::class),
'mapping' => ['paths' => []],
'named_serializers' => [],
],
'property_access' => [
'enabled' => true,
Expand Down Expand Up @@ -958,4 +959,21 @@ class_exists(SemaphoreStore::class) && SemaphoreStore::isSupported() ? 'semaphor
],
];
}

public function testNamedSerializersReservedName()
{
$processor = new Processor();
$configuration = new Configuration(true);

$this->expectException(InvalidConfigurationException::class);
$this->expectExceptionMessage('Invalid configuration for path "framework.serializer.named_serializers": "default" is a reserved name.');

$processor->processConfiguration($configuration, [[
'serializer' => [
'named_serializers' => [
'default' => ['include_built_in_normalizers' => false],
],
],
]]);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,13 @@
'circular_reference_handler' => 'my.circular.reference.handler',
'max_depth_handler' => 'my.max.depth.handler',
'default_context' => ['enable_max_depth' => true],
'named_serializers' => [
'api' => [
'include_built_in_normalizers' => true,
'include_built_in_encoders' => true,
'default_context' => ['enable_max_depth' => false],
],
],
],
'property_info' => true,
'type_info' => true,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,11 @@
<framework:default-context>
<framework:enable_max_depth>true</framework:enable_max_depth>
</framework:default-context>
<framework:named-serializer name="api" include-built-in-normalizers="true" include-built-in-encoders="true">
<framework:default-context>
<framework:enable_max_depth>false</framework:enable_max_depth>
</framework:default-context>
</framework:named-serializer>
</framework:serializer>
<framework:property-info />
<framework:type-info />
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,12 @@ framework:
max_depth_handler: my.max.depth.handler
default_context:
enable_max_depth: true
named_serializers:
api:
include_built_in_normalizers: true
include_built_in_encoders: true
default_context:
enable_max_depth: false
type_info: ~
property_info: ~
ide: file%%link%%format
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1463,6 +1463,26 @@ public function testSerializerWithoutTranslator()
$this->assertFalse($container->hasDefinition('serializer.normalizer.translatable'));
}

public function testSerializerDefaultParameters()
{
$container = $this->createContainerFromFile('serializer_enabled');
$this->assertFalse($container->hasParameter('.serializer.name_converter'));
$this->assertFalse($container->hasParameter('serializer.default_context'));
$this->assertTrue($container->hasParameter('.serializer.named_serializers'));
$this->assertSame([], $container->getParameter('.serializer.named_serializers'));
}

public function testSerializerParametersAreSet()
{
$container = $this->createContainerFromFile('full');
$this->assertTrue($container->hasParameter('.serializer.name_converter'));
$this->assertSame('serializer.name_converter.camel_case_to_snake_case', $container->getParameter('.serializer.name_converter'));
$this->assertTrue($container->hasParameter('serializer.default_context'));
$this->assertSame(['enable_max_depth' => true], $container->getParameter('serializer.default_context'));
$this->assertTrue($container->hasParameter('.serializer.named_serializers'));
$this->assertSame(['api' => ['include_built_in_normalizers' => true, 'include_built_in_encoders' => true, 'default_context' => ['enable_max_depth' => false]]], $container->getParameter('.serializer.named_serializers'));
}

public function testRegisterSerializerExtractor()
{
$container = $this->createContainerFromFile('full');
Expand Down
5 changes: 5 additions & 0 deletions src/Symfony/Bundle/WebProfilerBundle/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,11 @@
CHANGELOG
=========

7.2
---

* Add support for displaying profiles of multiple serializer instances

7.1
---

Expand Down
Loading
Loading