Skip to content

Commit

Permalink
feature #31390 [Serializer] UnwrappingDenormalizer (nonanerz)
Browse files Browse the repository at this point in the history
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 #28887 and #30894

Usage:

`$serialiser->deserialize('{"baz": {"foo": "bar", "inner": {"title": "value", "numbers": [5,3]}}}', Object::class, ['UnwrappingDenormalizer::UNWRAP_PATH' => '[baz][inner]'])`

Commits
-------

00d103d UnwrappingDenormalizer
  • Loading branch information
fabpot committed Apr 12, 2020
2 parents 607e8d6 + 00d103d commit 7c98954
Show file tree
Hide file tree
Showing 5 changed files with 179 additions and 0 deletions.
Expand Up @@ -119,6 +119,7 @@
use Symfony\Component\Serializer\Encoder\EncoderInterface;
use Symfony\Component\Serializer\Normalizer\DenormalizerInterface;
use Symfony\Component\Serializer\Normalizer\NormalizerInterface;
use Symfony\Component\Serializer\Normalizer\UnwrappingDenormalizer;
use Symfony\Component\Stopwatch\Stopwatch;
use Symfony\Component\String\LazyString;
use Symfony\Component\String\Slugger\SluggerInterface;
Expand Down Expand Up @@ -1471,6 +1472,10 @@ private function registerSerializerConfiguration(array $config, ContainerBuilder
$container->removeDefinition('serializer.encoder.yaml');
}

if (!class_exists(UnwrappingDenormalizer::class)) {
$container->removeDefinition('serializer.denormalizer.unwrapping');
}

$serializerLoaders = [];
if (isset($config['enable_annotations']) && $config['enable_annotations']) {
if (!$this->annotationsConfigEnabled) {
Expand Down
Expand Up @@ -70,6 +70,12 @@
<tag name="serializer.normalizer" priority="-890" />
</service>

<service id="serializer.denormalizer.unwrapping" class="Symfony\Component\Serializer\Normalizer\UnwrappingDenormalizer">
<argument type="service" id="serializer.property_accessor" />
<!-- Run before serializer.normalizer.object -->
<tag name="serializer.normalizer" priority="1000" />
</service>

<service id="serializer.normalizer.object" class="Symfony\Component\Serializer\Normalizer\ObjectNormalizer">
<argument type="service" id="serializer.mapping.class_metadata_factory" />
<argument type="service" id="serializer.name_converter.metadata_aware" />
Expand Down
@@ -0,0 +1,69 @@
<?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\PropertyAccess\PropertyAccess;
use Symfony\Component\PropertyAccess\PropertyAccessorInterface;
use Symfony\Component\Serializer\SerializerAwareInterface;
use Symfony\Component\Serializer\SerializerAwareTrait;

/**
* @author Eduard Bulava <bulavaeduard@gmail.com>
*/
final class UnwrappingDenormalizer implements DenormalizerInterface, SerializerAwareInterface, CacheableSupportsMethodInterface
{
use SerializerAwareTrait;

const UNWRAP_PATH = 'unwrap_path';

private $propertyAccessor;

public function __construct(PropertyAccessorInterface $propertyAccessor = null)
{
$this->propertyAccessor = $propertyAccessor ?? PropertyAccess::createPropertyAccessor();
}

/**
* {@inheritdoc}
*/
public function denormalize($data, $class, string $format = null, array $context = [])
{
$propertyPath = $context[self::UNWRAP_PATH];
$context['unwrapped'] = true;

if ($propertyPath) {
if (!$this->propertyAccessor->isReadable($data, $propertyPath)) {
return null;
}

$data = $this->propertyAccessor->getValue($data, $propertyPath);
}

return $this->serializer->denormalize($data, $class, $format, $context);
}

/**
* {@inheritdoc}
*/
public function supportsDenormalization($data, $type, string $format = null, array $context = [])
{
return \array_key_exists(self::UNWRAP_PATH, $context) && !isset($context['unwrapped']);
}

/**
* {@inheritdoc}
*/
public function hasCacheableSupportsMethod(): bool
{
return $this->serializer instanceof CacheableSupportsMethodInterface && $this->serializer->hasCacheableSupportsMethod();
}
}
@@ -0,0 +1,83 @@
<?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\Tests\Normalizer;

use PHPUnit\Framework\TestCase;
use Symfony\Component\Serializer\Normalizer\UnwrappingDenormalizer;
use Symfony\Component\Serializer\Tests\Normalizer\Features\ObjectDummy;

/**
* @author Eduard Bulava <bulavaeduard@gmail.com>
*/
class UnwrappinDenormalizerTest extends TestCase
{
private $denormalizer;

private $serializer;

protected function setUp(): void
{
$this->serializer = $this->getMockBuilder('Symfony\Component\Serializer\Serializer')->getMock();
$this->denormalizer = new UnwrappingDenormalizer();
$this->denormalizer->setSerializer($this->serializer);
}

public function testSupportsNormalization()
{
$this->assertTrue($this->denormalizer->supportsDenormalization([], new \stdClass(), 'any', [UnwrappingDenormalizer::UNWRAP_PATH => '[baz][inner]']));
$this->assertFalse($this->denormalizer->supportsDenormalization([], new \stdClass(), 'any', [UnwrappingDenormalizer::UNWRAP_PATH => '[baz][inner]', 'unwrapped' => true]));
$this->assertFalse($this->denormalizer->supportsDenormalization([], new \stdClass(), 'any', []));
}

public function testDenormalize()
{
$expected = new ObjectDummy();
$expected->setBaz(true);
$expected->bar = 'bar';
$expected->setFoo('foo');

$this->serializer->expects($this->exactly(1))
->method('denormalize')
->with(['foo' => 'foo', 'bar' => 'bar', 'baz' => true])
->willReturn($expected);

$result = $this->denormalizer->denormalize(
['data' => ['foo' => 'foo', 'bar' => 'bar', 'baz' => true]],
ObjectDummy::class,
'any',
[UnwrappingDenormalizer::UNWRAP_PATH => '[data]']
);

$this->assertEquals('foo', $result->getFoo());
$this->assertEquals('bar', $result->bar);
$this->assertTrue($result->isBaz());
}

public function testDenormalizeInvalidPath()
{
$this->serializer->expects($this->exactly(1))
->method('denormalize')
->with(null)
->willReturn(new ObjectDummy());

$obj = $this->denormalizer->denormalize(
['data' => ['foo' => 'foo', 'bar' => 'bar', 'baz' => true]],
ObjectDummy::class,
'any',
[UnwrappingDenormalizer::UNWRAP_PATH => '[invalid]']
);

$this->assertNull($obj->getFoo());
$this->assertNull($obj->bar);
$this->assertNull($obj->isBaz());
}
}
16 changes: 16 additions & 0 deletions src/Symfony/Component/Serializer/Tests/SerializerTest.php
Expand Up @@ -13,6 +13,7 @@

use Doctrine\Common\Annotations\AnnotationReader;
use PHPUnit\Framework\TestCase;
use Symfony\Component\PropertyAccess\PropertyAccessor;
use Symfony\Component\PropertyInfo\Extractor\PhpDocExtractor;
use Symfony\Component\PropertyInfo\Extractor\ReflectionExtractor;
use Symfony\Component\Serializer\Encoder\JsonEncoder;
Expand All @@ -35,6 +36,7 @@
use Symfony\Component\Serializer\Normalizer\NormalizerInterface;
use Symfony\Component\Serializer\Normalizer\ObjectNormalizer;
use Symfony\Component\Serializer\Normalizer\PropertyNormalizer;
use Symfony\Component\Serializer\Normalizer\UnwrappingDenormalizer;
use Symfony\Component\Serializer\Serializer;
use Symfony\Component\Serializer\Tests\Fixtures\AbstractDummy;
use Symfony\Component\Serializer\Tests\Fixtures\AbstractDummyFirstChild;
Expand Down Expand Up @@ -575,6 +577,20 @@ private function serializerWithClassDiscriminator()

return new Serializer([new ObjectNormalizer($classMetadataFactory, null, null, new ReflectionExtractor(), new ClassDiscriminatorFromClassMetadata($classMetadataFactory))], ['json' => new JsonEncoder()]);
}

public function testDeserializeAndUnwrap()
{
$jsonData = '{"baz": {"foo": "bar", "inner": {"title": "value", "numbers": [5,3]}}}';

$expectedData = Model::fromArray(['title' => 'value', 'numbers' => [5, 3]]);

$serializer = new Serializer([new UnwrappingDenormalizer(new PropertyAccessor()), new ObjectNormalizer()], ['json' => new JsonEncoder()]);

$this->assertEquals(
$expectedData,
$serializer->deserialize($jsonData, __NAMESPACE__.'\Model', 'json', [UnwrappingDenormalizer::UNWRAP_PATH => '[baz][inner]'])
);
}
}

class Model
Expand Down

0 comments on commit 7c98954

Please sign in to comment.