8000 [Serializer] UnwrappingDenormalizer by nonanerz · Pull Request #31390 · symfony/symfony · GitHub
[go: up one dir, main page]

Skip to content

[Serializer] UnwrappingDenormalizer #31390

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
Apr 12, 2020
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
Original file line number Diff line number Diff line change
Expand Up @@ -109,6 +109,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\Slugger\SluggerInterface;
use Symfony\Component\Translation\Command\XliffLintCommand as BaseXliffLintCommand;
Expand Down Expand Up @@ -1412,6 +1413,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
Original file line number Diff line number Diff line change
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
Original file line number Diff line number Diff line change
@@ -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();
}
}
Original file line number Diff line number Diff line change
@@ -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
Original file line number Diff line number Diff line change
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 @@ -34,6 +35,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 @@ -494,6 +496,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