8000 feature #31390 [Serializer] UnwrappingDenormalizer (nonanerz) · symfony/serializer@0d866f1 · GitHub
[go: up one dir, main page]

Skip to content

Commit 0d866f1

Browse files
committed
feature #31390 [Serializer] UnwrappingDenormalizer (nonanerz)
This PR was merged into the 5.1-dev branch. Discussion ---------- [Serializer] UnwrappingDenormalizer | Q | A | ------------- | --- | Branch? | master | Bug fix? | no | New feature? | yes | BC breaks? | no | Deprecations? | no | Tests pass? | yes | Fixed tickets | n/a | License | MIT | Doc PR | n/a UnwrappingDenormalizer, registered with very high priority. Unwrapping the data if UNWRAP_PATH is provided. Very often some APIs give nested responses in which we need only the child object. With UnwrappingDenormalizer we can get the needed object without creating unnecessary Model class that we don't really need. Regarding to symfony/symfony#28887 and symfony/symfony#30894 Usage: `$serialiser->deserialize('{"baz": {"foo": "bar", "inner": {"title": "value", "numbers": [5,3]}}}', Object::class, ['UnwrappingDenormalizer::UNWRAP_PATH' => '[baz][inner]'])` Commits ------- 00d103d5f7 UnwrappingDenormalizer
2 parents 5cc9079 + caf94a4 commit 0d866f1

File tree

3 files changed

+168
-0
lines changed

3 files changed

+168
-0
lines changed

Normalizer/UnwrappingDenormalizer.php

Lines changed: 69 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,69 @@
1+
<?php
2+
3+
/*
4+
* This file is part of the Symfony package.
5+
*
6+
* (c) Fabien Potencier <fabien@symfony.com>
7+
*
8+
* For the full copyright and license information, please view the LICENSE
9+
* file that was distributed with this source code.
10+
*/
11+
12+
namespace Symfony\Component\Serializer\Normalizer;
13+
14+
use Symfony\Component\PropertyAccess\PropertyAccess;
15+
use Symfony\Component\PropertyAccess\PropertyAccessorInterface;
16+
use Symfony\Component\Serializer\SerializerAwareInterface;
17+
use Symfony\Component\Serializer\SerializerAwareTrait;
18+
19+
/**
20+
* @author Eduard Bulava <bulavaeduard@gmail.com>
21+
*/
22+
final class UnwrappingDenormalizer implements DenormalizerInterface, SerializerAwareInterface, CacheableSupportsMethodInterface
23+
{
24+
use SerializerAwareTrait;
25+
26+
const UNWRAP_PATH = 'unwrap_path';
27+
28+
private $propertyAccessor;
29+
30+
public function __construct(PropertyAccessorInterface $propertyAccessor = null)
31+
{
32+
$this->propertyAccessor = $propertyAccessor ?? PropertyAccess::createPropertyAccessor();
33+
}
34+
35+
/**
36+
* {@inheritdoc}
37+
*/
38+
public function denormalize($data, $class, string $format = null, array $context = [])
39+
{
40+
$propertyPath = $context[self::UNWRAP_PATH];
41+
$context['unwrapped'] = true;
42+
43+
if ($propertyPath) {
44+
if (!$this->propertyAccessor->isReadable($data, $propertyPath)) {
45+
return null;
46+
}
47+
48+
$data = $this->propertyAccessor->getValue($data, $propertyPath);
49+
}
50+
51+
return $this->serializer->denormalize($data, $class, $format, $context);
52+
}
53+
54+
/**
55+
* {@inheritdoc}
56+
*/
57+
public function supportsDenormalization($data, $type, string $format = null, array $context = [])
58+
{
59+
return \array_key_exists(self::UNWRAP_PATH, $context) && !isset($context['unwrapped']);
60+
}
61+
62+
/**
63+
* {@inheritdoc}
64+
*/
65+
public function hasCacheableSupportsMethod(): bool
66+
{
67+
return $this->serializer instanceof CacheableSupportsMethodInterface && $this->serializer->hasCacheableSupportsMethod();
68+
}
69+
}
Lines changed: 83 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,83 @@
1+
<?php
2+
3+
/*
4+
* This file is part of the Symfony package.
5+
*
6+
* (c) Fabien Potencier <fabien@symfony.com>
7+
*
8+
* For the full copyright and license information, please view the LICENSE
9+
* file that was distributed with this source code.
10+
*/
11+
12+
namespace Symfony\Component\Serializer\Tests\Normalizer;
13+
14+
use PHPUnit\Framework\TestCase;
15+
use Symfony\Component\Serializer\Normalizer\UnwrappingDenormalizer;
16+
use Symfony\Component\Serializer\Tests\Normalizer\Features\ObjectDummy;
17+
18+
/**
19+
* @author Eduard Bulava <bulavaeduard@gmail.com>
20+
*/
21+
class UnwrappinDenormalizerTest extends TestCase
22+
{
23+
private $denormalizer;
24+
25+
private $serializer;
26+
27+
protected function setUp(): void
28+
{
29+
$this->serializer = $this->getMockBuilder('Symfony\Component\Serializer\Serializer')->getMock();
30+
$this->denormalizer = new UnwrappingDenormalizer();
31+
$this->denormalizer->setSerializer($this->serializer);
32+
}
33+
34+
public function testSupportsNormalization()
35+
{
36+
$this->assertTrue($this->denormalizer->supportsDenormalization([], new \stdClass(), 'any', [UnwrappingDenormalizer::UNWRAP_PATH => '[baz][inner]']));
37+
$this->assertFalse($this->denormalizer->supportsDenormalization([], new \stdClass(), 'any', [UnwrappingDenormalizer::UNWRAP_PATH => '[baz][inner]', 'unwrapped' => true]));
38+
$this->assertFalse($this->denormalizer->supportsDenormalization([], new \stdClass(), 'any', []));
39+
}
40+
41+
public function testDenormalize()
42+
{
43+
$expected = new ObjectDummy();
44+
$expected->setBaz(true);
45+
$expected->bar = 'bar';
46+
$expected->setFoo('foo');
47+
48+
$this->serializer->expects($this->exactly(1))
49+
->method('denormalize')
50+
->with(['foo' => 'foo', 'bar' => 'bar', 'baz' => true])
51+
->willReturn($expected);
52+
53+
$result = $this->denormalizer->denormalize(
54+
['data' => ['foo' => 'foo', 'bar' => 'bar', 'baz' => true]],
55+
ObjectDummy::class,
56+
'any',
57+
[UnwrappingDenormalizer::UNWRAP_PATH => '[data]']
58+
);
59+
60+
$this->assertEquals('foo', $result->getFoo());
61+
$this->assertEquals('bar', $result->bar);
62+
$this->assertTrue($result->isBaz());
63+
}
64+
65+
public function testDenormalizeInvalidPath()
66+
{
67+
$this->serializer->expects($this->exactly(1))
68+
->method('denormalize')
69+
->with(null)
70+
->willReturn(new ObjectDummy());
71+
72+
$obj = $this->denormalizer->denormalize(
73+
['data' => ['foo' => 'foo', 'bar' => 'bar', 'baz' => true]],
74+
ObjectDummy::class,
75+
'any',
76+
[UnwrappingDenormalizer::UNWRAP_PATH => '[invalid]']
77+
);
78+
79+
$this->assertNull($obj->getFoo());
80+
$this->assertNull($obj->bar);
81+
$this->assertNull($obj->isBaz());
82+
}
83+
}

Tests/SerializerTest.php

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@
1313

1414
use Doctrine\Common\Annotations\AnnotationReader;
1515
use PHPUnit\Framework\TestCase;
16+
use Symfony\Component\PropertyAccess\PropertyAccessor;
1617
use Symfony\Component\PropertyInfo\Extractor\PhpDocExtractor;
1718
use Symfony\Component\PropertyInfo\Extractor\ReflectionExtractor;
1819
use Symfony\Component\Serializer\Encoder\JsonEncoder;
@@ -35,6 +36,7 @@
3536
use Symfony\Component\Serializer\Normalizer\NormalizerInterface;
3637
use Symfony\Component\Serializer\Normalizer\ObjectNormalizer;
3738
use Symfony\Component\Serializer\Normalizer\PropertyNormalizer;
39+
use Symfony\Component\Serializer\Normalizer\UnwrappingDenormalizer;
3840
use Symfony\Component\Serializer\Serializer;
3941
use Symfony\Component\Serializer\Tests\Fixtures\AbstractDummy;
4042
use Symfony\Component\Serializer\Tests\Fixtures\AbstractDummyFirstChild;
@@ -575,6 +577,20 @@ private function serializerWithClassDiscriminator()
575577

576578
return new Serializer([new ObjectNormalizer($classMetadataFactory, null, null, new ReflectionExtractor(), new ClassDiscriminatorFromClassMetadata($classMetadataFactory))], ['json' => new JsonEncoder()]);
577579
}
580+
581+
public function testDeserializeAndUnwrap()
582+
{
583+
$jsonData = '{"baz": {"foo": "bar", "inner": {"title": "value", "numbers": [5,3]}}}';
584+
585+
$expectedData = Model::fromArray(['title' => 'value', 'numbers' => [5, 3]]);
586+
587+
$serializer = new Serializer([new UnwrappingDenormalizer(new PropertyAccessor()), new ObjectNormalizer()], ['json' => new JsonEncoder()]);
588+
589+
$this->assertEquals(
590+
$expectedData,
591+
$serializer->deserialize($jsonData, __NAMESPACE__.'\Model', 'json', [UnwrappingDenormalizer::UNWRAP_PATH => '[baz][inner]'])
592+
);
593+
}
578594
}
579595

580596
class Model

0 commit comments

Comments
 (0)
0