Skip to content

Add support for serializing stdClass objects #33894

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
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
1 change: 1 addition & 0 deletions src/Symfony/Component/Serializer/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ CHANGELOG
* deprecated the `XmlEncoder::TYPE_CASE_ATTRIBUTES` constant, use `XmlEncoder::TYPE_CAST_ATTRIBUTES` instead
* added option to output a UTF-8 BOM in CSV encoder via `CsvEncoder::OUTPUT_UTF8_BOM_KEY` context option
* added `ProblemNormalizer` to normalize errors according to the API Problem spec (RFC 7807)
* added support for serializing `stdClass` objects

4.3.0
-----
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -139,6 +139,10 @@ public function supportsNormalization($data, $format = null)
*/
public function normalize($object, $format = null, array $context = [])
{
if (\stdClass::class === \get_class($object)) {
return $this->normalizeStdClassObject($object, $format, $context);
}

if (!isset($context['cache_key'])) {
$context['cache_key'] = $this->getCacheKey($format, $context);
}
Expand Down Expand Up @@ -630,4 +634,25 @@ private function getCacheKey(?string $format, array $context)
return false;
}
}

/**
* @param string|null $format
*
* @return array
*
* @throws LogicException
*/
private function normalizeStdClassObject(\stdClass $object, $format = null, array $context = [])
{
$normalized = [];
foreach ($object as $key => $val) {
if (!$this->serializer instanceof NormalizerInterface) {
throw new LogicException(sprintf('Cannot normalize value for attribute "%s" because the injected serializer is not a normalizer', $key));
}

$normalized[$key] = $this->serializer->normalize($val, $format, $context);
}

return $normalized;
}
}
17 changes: 17 additions & 0 deletions src/Symfony/Component/Serializer/Tests/Fixtures/EmptyDummy.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
<?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\Fixtures;

class EmptyDummy
{

}
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@
use Symfony\Component\Serializer\Tests\Fixtures\AbstractDummyFirstChild;
use Symfony\Component\Serializer\Tests\Fixtures\AbstractDummySecondChild;
use Symfony\Component\Serializer\Tests\Fixtures\DummySecondChildQuux;
use Symfony\Component\Serializer\Tests\Fixtures\EmptyDummy;

class AbstractObjectNormalizerTest extends TestCase
{
Expand Down Expand Up @@ -252,6 +253,18 @@ public function testNormalizeEmptyObject()
$normalizedData = $normalizer->normalize(new EmptyDummy(), 'any', ['preserve_empty_objects' => true]);
$this->assertEquals(new \ArrayObject(), $normalizedData);
}

public function testNormalizeStdClassObjectLogicException()
{
$this->expectException('Symfony\Component\Serializer\Exception\LogicException');
$this->expectExceptionMessage('Cannot normalize value for attribute "foo" because the injected serializer is not a normalizer');

$std = new \stdClass();
$std->foo = 'bar';
$normalizer = new ObjectNormalizer();

$normalizer->normalize($std);
}
}

class AbstractObjectNormalizerDummy extends AbstractObjectNormalizer
Expand Down Expand Up @@ -291,10 +304,6 @@ class Dummy
public $baz;
}

class EmptyDummy
{
}

class AbstractObjectNormalizerWithMetadata extends AbstractObjectNormalizer
{
public function __construct()
Expand Down
23 changes: 22 additions & 1 deletion src/Symfony/Component/Serializer/Tests/SerializerTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@
use Symfony\Component\Serializer\Tests\Fixtures\DummyMessageInterface;
use Symfony\Component\Serializer\Tests\Fixtures\DummyMessageNumberOne;
use Symfony\Component\Serializer\Tests\Fixtures\DummyMessageNumberTwo;
use Symfony\Component\Serializer\Tests\Fixtures\EmptyDummy;
use Symfony\Component\Serializer\Tests\Fixtures\NormalizableTraversableDummy;
use Symfony\Component\Serializer\Tests\Fixtures\TraversableDummy;
use Symfony\Component\Serializer\Tests\Normalizer\TestDenormalizer;
Expand Down Expand Up @@ -189,6 +190,26 @@ public function testSerializeScalar()
$this->assertEquals('"foo"', $result);
}

public function testSerializeStdClass()
{
$std = new \stdClass();
$std->foo = ['bar', 'baz'];
$serializer = new Serializer([new ObjectNormalizer()], ['json' => new JsonEncoder()]);
$result = $serializer->serialize($std, 'json');
$this->assertEquals('{"foo":["bar","baz"]}', $result);
}

public function testSerializeArrayStdClass()
{
$stdFoo = new \stdClass();
$stdFoo->foo = 'bar';
$stdBar = new \stdClass();
$stdBar->bar = 'baz';
$serializer = new Serializer([new ObjectNormalizer()], ['json' => new JsonEncoder()]);
$result = $serializer->serialize([$stdFoo, $stdBar], 'json');
$this->assertEquals('[{"foo":"bar"},{"bar":"baz"}]', $result);
}

public function testSerializeArrayOfScalars()
{
$serializer = new Serializer([], ['json' => new JsonEncoder()]);
Expand All @@ -200,7 +221,7 @@ public function testSerializeArrayOfScalars()
public function testSerializeEmpty()
{
$serializer = new Serializer([new ObjectNormalizer()], ['json' => new JsonEncoder()]);
$data = ['foo' => new \stdClass()];
$data = ['foo' => new EmptyDummy()];

//Old buggy behaviour
$result = $serializer->serialize($data, 'json');
Expand Down