Skip to content

[Serializer] Add a ScalarDenormalizer #39140

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

Closed
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
5 changes: 5 additions & 0 deletions UPGRADE-5.3.md
Original file line number Diff line number Diff line change
Expand Up @@ -22,3 +22,8 @@ Security
--------

* Deprecated voters that do not return a valid decision when calling the `vote` method.

Serializer
----------

* Deprecated denormalizing scalar values without registering the `BuiltinTypeDenormalizer`
5 changes: 5 additions & 0 deletions UPGRADE-6.0.md
Original file line number Diff line number Diff line change
Expand Up @@ -226,6 +226,11 @@ Validator
->addDefaultDoctrineAnnotationReader();
```

Serializer
----------

* Removed the denormalization of scalar values without normalizer, add the `BuiltinTypeDenormalizer` to the `Serializer`

Yaml
----

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.3.0
-----

* [DEPRECATION] denormalizing scalar values without registering the `BuiltinTypeDenormalizer`

5.2.0
-----

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,117 @@
<?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\Normalizer;

use Symfony\Component\Serializer\Encoder\CsvEncoder;
use Symfony\Component\Serializer\Encoder\JsonEncoder;
use Symfony\Component\Serializer\Encoder\XmlEncoder;
use Symfony\Component\Serializer\Exception\InvalidArgumentException;
use Symfony\Component\Serializer\Exception\NotNormalizableValueException;

final class BuiltinTypeDenormalizer implements DenormalizerInterface, CacheableSupportsMethodInterface
{
private const TYPE_INT = 'int';
private const TYPE_FLOAT = 'float';
private const TYPE_STRING = 'string';
private const TYPE_BOOL = 'bool';
private const TYPE_RESOURCE = 'resource';
private const TYPE_CALLABLE = 'callable';

private const SUPPORTED_TYPES = [
self::TYPE_INT => true,
self::TYPE_BOOL => true,
self::TYPE_FLOAT => true,
self::TYPE_STRING => true,
self::TYPE_RESOURCE => true,
self::TYPE_CALLABLE => true,
];

/**
* {@inheritdoc}
*/
public function denormalize($data, string $type, string $format = null, array $context = [])
{
$dataType = get_debug_type($data);

if (!(isset(self::SUPPORTED_TYPES[$dataType]) || 0 === strpos($dataType, self::TYPE_RESOURCE) || \is_callable($data))) {
throw new InvalidArgumentException(sprintf('Data expected to be of one of the types in "%s" ("%s" given).', implode(', ', array_keys(self::SUPPORTED_TYPES)), get_debug_type($data)));
}

// In XML and CSV all basic datatypes are represented as strings, it is e.g. not possible to determine,
// if a value is meant to be a string, float, int or a boolean value from the serialized representation.
// That's why we have to transform the values, if one of these non-string basic datatypes is expected.
if (\is_string($data) && (XmlEncoder::FORMAT === $format || CsvEncoder::FORMAT === $format)) {
switch ($type) {
case self::TYPE_BOOL:
// according to https://www.w3.org/TR/xmlschema-2/#boolean, valid representations are "false", "true", "0" and "1"
if ('false' === $data || '0' === $data) {
return false;
}
if ('true' === $data || '1' === $data) {
return true;
}

throw new NotNormalizableValueException(sprintf('Data expected to be of type "%s" ("%s" given).', $type, $data));
case self::TYPE_INT:
if (ctype_digit($data) || '-' === $data[0] && ctype_digit(substr($data, 1))) {
return (int) $data;
}

throw new NotNormalizableValueException(sprintf('Data expected to be of type "%s" ("%s" given).', $type, $data));
case self::TYPE_FLOAT:
if (is_numeric($data)) {
return (float) $data;
}

switch ($data) {
case 'NaN':
return \NAN;
case 'INF':
return \INF;
case '-INF':
return -\INF;
default:
throw new NotNormalizableValueException(sprintf('Data expected to be of type "%s" ("%s" given).', $type, $data));
}
}
}

// JSON only has a Number type corresponding to both int and float PHP types.
// PHP's json_encode, JavaScript's JSON.stringify, Go's json.Marshal as well as most other JSON encoders convert
// floating-point numbers like 12.0 to 12 (the decimal part is dropped when possible).
// PHP's json_decode automatically converts Numbers without a decimal part to integers.
// To circumvent this behavior, integers are converted to floats when denormalizing JSON based formats and when
// a float is expected.
if (self::TYPE_FLOAT === $type && \is_int($data) && false !== strpos($format, JsonEncoder::FORMAT)) {
return (float) $data;
}

if (!('is_'.$type)($data)) {
throw new NotNormalizableValueException(sprintf('Data expected to be of type "%s" ("%s" given).', $type, get_debug_type($data)));
}

return $data;
}

/**
* {@inheritdoc}
*/
public function supportsDenormalization($data, string $type, string $format = null)
{
return isset(self::SUPPORTED_TYPES[$type]);
}

public function hasCacheableSupportsMethod(): bool
{
return true;
}
}
3 changes: 3 additions & 0 deletions src/Symfony/Component/Serializer/Serializer.php
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
use Symfony\Component\Serializer\Exception\NotEncodableValueException;
use Symfony\Component\Serializer\Exception\NotNormalizableValueException;
use Symfony\Component\Serializer\Normalizer\AbstractObjectNormalizer;
use Symfony\Component\Serializer\Normalizer\BuiltinTypeDenormalizer;
use Symfony\Component\Serializer\Normalizer\CacheableSupportsMethodInterface;
use Symfony\Component\Serializer\Normalizer\ContextAwareDenormalizerInterface;
use Symfony\Component\Serializer\Normalizer\ContextAwareNormalizerInterface;
Expand Down Expand Up @@ -193,6 +194,8 @@ public function denormalize($data, string $type, string $format = null, array $c

// Check for a denormalizer first, e.g. the data is wrapped
if (!$normalizer && isset(self::SCALAR_TYPES[$type])) {
trigger_deprecation('symfony/serializer', '5.2', 'Denormalizing scalar values without registering the "%s" is deprecated.', BuiltinTypeDenormalizer::class);

if (!('is_'.$type)($data)) {
throw new NotNormalizableValueException(sprintf('Data expected to be of type "%s" ("%s" given).', $type, get_debug_type($data)));
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,123 @@
<?php

namespace Symfony\Component\Serializer\Tests\Normalizer;

use PHPUnit\Framework\TestCase;
use Symfony\Component\Serializer\Exception\InvalidArgumentException;
use Symfony\Component\Serializer\Exception\NotNormalizableValueException;
use Symfony\Component\Serializer\Normalizer\BuiltinTypeDenormalizer;

class BuiltinTypeDenormalizerTest extends TestCase
{
/**
* @var BuiltinTypeDenormalizer
*/
private $denormalizer;

protected function setUp(): void
{
$this->denormalizer = new BuiltinTypeDenormalizer();
}

/**
* @dataProvider provideSupportedTypes
*/
public function testSupportsDenormalization(string $supportedType): void
{
$this->assertTrue($this->denormalizer->supportsDenormalization(null, $supportedType));
}

public function provideSupportedTypes(): iterable
{
return [['int'], ['float'], ['string'], ['bool'], ['resource'], ['callable']];
}

/**
* @dataProvider provideUnsupportedTypes
*/
public function testUnsupportsDenormalization(string $unsupportedType): void
{
$this->assertFalse($this->denormalizer->supportsDenormalization(null, $unsupportedType));
}

public function provideUnsupportedTypes(): iterable
{
return [['null'], ['array'], ['iterable'], ['object'], ['int[]']];
}

/**
* @dataProvider provideInvalidData
*/
public function testDenormalizeInvalidDataThrowsException($invalidData): void
{
$this->expectException(InvalidArgumentException::class);
$this->denormalizer->denormalize($invalidData, 'int');
}

public function provideInvalidData(): iterable
{
return [
'array' => [[1, 2]],
'object' => [new \stdClass()],
'null' => [null],
];
}

/**
* @dataProvider provideNotNormalizableData
*/
public function testDenormalizeNotNormalizableDataThrowsException($data, string $type, string $format): void
{
$this->expectException(NotNormalizableValueException::class);
$this->denormalizer->denormalize($data, $type, $format);
}

public function provideNotNormalizableData(): iterable
{
return [
'not a string' => [true, 'string', 'json'],
'not an integer' => [3.1, 'int', 'json'],
'not an integer (xml/csv)' => ['+12', 'int', 'xml'],
'not a float' => [false, 'float', 'json'],
'not a float (xml/csv)' => ['nan', 'float', 'xml'],
'not a boolean (json)' => [0, 'bool', 'json'],
'not a boolean (xml/csv)' => ['test', 'bool', 'xml'],
];
}

/**
* @dataProvider provideNormalizableData
*/
public function testDenormalize($expectedResult, $data, string $type, string $format = null): void
{
$result = $this->denormalizer->denormalize($data, $type, $format);

if (\is_float($expectedResult) && is_nan($expectedResult)) {
$this->assertNan($result);
} else {
$this->assertSame($expectedResult, $result);
}
}

public function provideNormalizableData(): iterable
{
return [
'string' => ['1', '1', 'string', 'json'],
'integer' => [-3, -3, 'int', 'json'],
'integer (xml/csv)' => [-12, '-12', 'int', 'xml'],
'float' => [3.14, 3.14, 'float', 'json'],
'float without decimals' => [3.0, 3, 'float', 'json'],
'NaN (xml/csv)' => [\NAN, 'NaN', 'float', 'xml'],
'INF (xml/csv)' => [\INF, 'INF', 'float', 'xml'],
'-INF (xml/csv)' => [-\INF, '-INF', 'float', 'xml'],
'boolean: true (json)' => [true, true, 'bool', 'json'],
'boolean: false (json)' => [false, false, 'bool', 'json'],
"boolean: 'true' (xml/csv)" => [true, 'true', 'bool', 'xml'],
"boolean: '1' (xml/csv)" => [true, '1', 'bool', 'xml'],
"boolean: 'false' (xml/csv)" => [false, 'false', 'bool', 'xml'],
"boolean: '0' (xml/csv)" => [false, '0', 'bool', 'xml'],
'callable' => [[$this, 'provideInvalidData'], [$this, 'provideInvalidData'], 'callable', null],
'resource' => [$r = fopen(__FILE__, 'r'), $r, 'resource', null],
];
}
}
Loading