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

Appearance settings

Commit dad04d0

Browse filesBrowse files
committed
Added scalar denormalization in Serializer + added scalar normalization tests
1 parent de4c45c commit dad04d0
Copy full SHA for dad04d0

File tree

3 files changed

+103
-2
lines changed
Filter options

3 files changed

+103
-2
lines changed

‎src/Symfony/Component/Serializer/CHANGELOG.md

Copy file name to clipboardExpand all lines: src/Symfony/Component/Serializer/CHANGELOG.md
+6-1Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,11 @@
11
CHANGELOG
22
=========
33

4+
5.1.0
5+
-----
6+
7+
* added support for scalar values denormalization
8+
49
5.0.0
510
-----
611

@@ -12,7 +17,7 @@ CHANGELOG
1217
`AbstractNormalizer::$camelizedAttributes`, `AbstractNormalizer::setCircularReferenceLimit()`,
1318
`AbstractNormalizer::setCircularReferenceHandler()`, `AbstractNormalizer::setCallbacks()` and
1419
`AbstractNormalizer::setIgnoredAttributes()`, use the default context instead.
15-
* removed `AbstractObjectNormalizer::$maxDepthHandler` and `AbstractObjectNormalizer::setMaxDepthHandler()`,
20+
* removed `AbstractObjectNormalizer::$maxDepthHandler` and `AbstractObjectNormalizer::setMaxDepthHandler()`,
1621
use the default context instead.
1722
* removed `XmlEncoder::setRootNodeName()` & `XmlEncoder::getRootNodeName()`, use the default context instead.
1823
* removed individual encoders/normalizers options as constructor arguments.

‎src/Symfony/Component/Serializer/Serializer.php

Copy file name to clipboardExpand all lines: src/Symfony/Component/Serializer/Serializer.php
+16-1Lines changed: 16 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -46,6 +46,13 @@
4646
*/
4747
class Serializer implements SerializerInterface, ContextAwareNormalizerInterface, ContextAwareDenormalizerInterface, ContextAwareEncoderInterface, ContextAwareDecoderInterface
4848
{
49+
private const SCALAR_TYPES = [
50+
'int' => true,
51+
'bool' => true,
52+
'float' => true,
53+
'string' => true,
54+
];
55+
4956
/**
5057
* @var Encoder\ChainEncoder
5158
*/
@@ -177,6 +184,14 @@ public function normalize($data, string $format = null, array $context = [])
177184
*/
178185
public function denormalize($data, string $type, string $format = null, array $context = [])
179186
{
187+
if (isset(self::SCALAR_TYPES[$type])) {
188+
if (!('is_'.$type)($data)) {
189+
throw new NotNormalizableValueException(sprintf('Data expected to be of type "%s" ("%s" given)', $type, \is_object($data) ? \get_class($data) : \gettype($data)));
190+
}
191+
192+
return $data;
193+
}
194+
180195
if (!$this->normalizers) {
181196
throw new LogicException('You must register at least one normalizer to be able to denormalize objects.');
182197
}
@@ -201,7 +216,7 @@ public function supportsNormalization($data, string $format = null, array $conte
201216
*/
202217
public function supportsDenormalization($data, string $type, string $format = null, array $context = [])
203218
{
204-
return null !== $this->getDenormalizer($data, $type, $format, $context);
219+
return isset(self::SCALAR_TYPES[$type]) || null !== $this->getDenormalizer($data, $type, $format, $context);
205220
}
206221

207222
/**

‎src/Symfony/Component/Serializer/Tests/SerializerTest.php

Copy file name to clipboardExpand all lines: src/Symfony/Component/Serializer/Tests/SerializerTest.php
+81Lines changed: 81 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@
1717
use Symfony\Component\PropertyInfo\Extractor\ReflectionExtractor;
1818
use Symfony\Component\Serializer\Encoder\JsonEncoder;
1919
use Symfony\Component\Serializer\Exception\InvalidArgumentException;
20+
use Symfony\Component\Serializer\Exception\LogicException;
2021
use Symfony\Component\Serializer\Exception\NotNormalizableValueException;
2122
use Symfony\Component\Serializer\Mapping\ClassDiscriminatorFromClassMetadata;
2223
use Symfony\Component\Serializer\Mapping\ClassDiscriminatorMapping;
@@ -488,6 +489,86 @@ public function testNotNormalizableValueExceptionMessageForAResource()
488489
(new Serializer())->normalize(tmpfile());
489490
}
490491

492+
public function testNormalizeScalar()
493+
{
494+
$serializer = new Serializer([], ['json' => new JsonEncoder()]);
495+
496+
$this->assertSame('42', $serializer->serialize(42, 'json'));
497+
$this->assertSame('true', $serializer->serialize(true, 'json'));
498+
$this->assertSame('false', $serializer->serialize(false, 'json'));
499+
$this->assertSame('3.14', $serializer->serialize(3.14, 'json'));
500+
$this->assertSame('3.14', $serializer->serialize(31.4e-1, 'json'));
501+
$this->assertSame('" spaces "', $serializer->serialize(' spaces ', 'json'));
502+
$this->assertSame('"@Ca$e%"', $serializer->serialize('@Ca$e%', 'json'));
503+
}
504+
505+
public function testNormalizeScalarArray()
506+
{
507+
$serializer = new Serializer([], ['json' => new JsonEncoder()]);
508+
509+
$this->assertSame('[42]', $serializer->serialize([42], 'json'));
510+
$this->assertSame('[true,false]', $serializer->serialize([true, false], 'json'));
511+
$this->assertSame('[3.14,3.24]', $serializer->serialize([3.14, 32.4e-1], 'json'));
512+
$this->assertSame('[" spaces ","@Ca$e%"]', $serializer->serialize([' spaces ', '@Ca$e%'], 'json'));
513+
}
514+
515+
public function testDeserializeScalar()
516+
{
517+
$serializer = new Serializer([], ['json' => new JsonEncoder()]);
518+
519+
$this->assertSame(42, $serializer->deserialize('42', 'int', 'json'));
520+
$this->assertTrue($serializer->deserialize('true', 'bool', 'json'));
521+
$this->assertSame(3.14, $serializer->deserialize('3.14', 'float', 'json'));
522+
$this->assertSame(3.14, $serializer->deserialize('31.4e-1', 'float', 'json'));
523+
$this->assertSame(' spaces ', $serializer->deserialize('" spaces "', 'string', 'json'));
524+
$this->assertSame('@Ca$e%', $serializer->deserialize('"@Ca$e%"', 'string', 'json'));
525+
}
526+
527+
public function testDeserializeLegacyScalarType()
528+
{
529+
$this->expectException(LogicException::class);
530+
$serializer = new Serializer([], ['json' => new JsonEncoder()]);
531+
$serializer->deserialize('42', 'integer', 'json');
532+
}
533+
534+
public function testDeserializeScalarTypeToCustomType()
535+
{
536+
$this->expectException(LogicException::class);
537+
$serializer = new Serializer([], ['json' => new JsonEncoder()]);
538+
$serializer->deserialize('"something"', Foo::class, 'json');
539+
}
540+
541+
public function testDeserializeNonscalarTypeToScalar()
542+
{
543+
$this->expectException(NotNormalizableValueException::class);
544+
$serializer = new Serializer([], ['json' => new JsonEncoder()]);
545+
$serializer->deserialize('{"foo":true}', 'string', 'json');
546+
}
547+
548+
public function testDeserializeInconsistentScalarType()
549+
{
550+
$this->expectException(NotNormalizableValueException::class);
551+
$serializer = new Serializer([], ['json' => new JsonEncoder()]);
552+
$serializer->deserialize('"42"', 'int', 'json');
553+
}
554+
555+
public function testDeserializeScalarArray()
556+
{
557+
$serializer = new Serializer([new ArrayDenormalizer()], ['json' => new JsonEncoder()]);
558+
559+
$this->assertSame([42], $serializer->deserialize('[42]', 'int[]', 'json'));
560+
$this->assertSame([true, false], $serializer->deserialize('[true,false]', 'bool[]', 'json'));
561+
$this->assertSame([3.14, 3.24], $serializer->deserialize('[3.14,32.4e-1]', 'float[]', 'json'));
562+
$this->assertSame([' spaces ', '@Ca$e%'], $serializer->deserialize('[" spaces ","@Ca$e%"]', 'string[]', 'json'));
563+
}
564+
565+
public function testDeserializeInconsistentScalarArray()
566+
{
567+
$this->expectException(NotNormalizableValueException::class);
568+
$serializer = new Serializer([new ArrayDenormalizer()], ['json' => new JsonEncoder()]);
569+
$serializer->deserialize('["42"]', 'int[]', 'json');
570+
}
571+
491572
private function serializerWithClassDiscriminator()
492573
{
493574
$classMetadataFactory = new ClassMetadataFactory(new AnnotationLoader(new AnnotationReader()));

0 commit comments

Comments
0 (0)
Morty Proxy This is a proxified and sanitized view of the page, visit original site.