bug #40004 [Serializer] Prevent access to private properties without getters (julienfalque)

This PR was merged into the 4.4 branch.

Discussion
----------

[Serializer] Prevent access to private properties without getters

| Q             | A
| ------------- | ---
| Branch?       | 4.4
| Bug fix?      | yes
| New feature?  | no
| Deprecations? | no
| Tickets       | -
| License       | MIT
| Doc PR        | -

When upgrading `symfony/serializer` from `v5.2.1` to `v5.2.2`, the serializer starts throwing exceptions because it cannot access some private properties that don't have a getter. This looks related to #38900.

Commits
-------

f0409b403f [Serializer] Prevent access to private properties without getters
This commit is contained in:
Nicolas Grekas 2021-01-27 19:11:59 +01:00
commit 8533ea223e
3 changed files with 39 additions and 4 deletions

View File

@ -107,8 +107,9 @@ class ObjectNormalizer extends AbstractObjectNormalizer
// properties
foreach ($reflClass->getProperties() as $reflProperty) {
$isPublic = $reflProperty->isPublic();
if ($checkPropertyInitialization) {
$isPublic = $reflProperty->isPublic();
if (!$isPublic) {
$reflProperty->setAccessible(true);
}
@ -116,9 +117,10 @@ class ObjectNormalizer extends AbstractObjectNormalizer
unset($attributes[$reflProperty->name]);
continue;
}
if (!$isPublic) {
continue;
}
}
if (!$isPublic) {
continue;
}
if ($reflProperty->isStatic() || !$this->isAllowedAttribute($object, $reflProperty->name, $format, $context)) {

View File

@ -0,0 +1,23 @@
<?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;
final class DummyPrivatePropertyWithoutGetter
{
private $foo = 'foo';
private $bar = 'bar';
public function getBar()
{
return $this->bar;
}
}

View File

@ -33,6 +33,7 @@ use Symfony\Component\Serializer\Normalizer\ObjectNormalizer;
use Symfony\Component\Serializer\Serializer;
use Symfony\Component\Serializer\SerializerInterface;
use Symfony\Component\Serializer\Tests\Fixtures\CircularReferenceDummy;
use Symfony\Component\Serializer\Tests\Fixtures\DummyPrivatePropertyWithoutGetter;
use Symfony\Component\Serializer\Tests\Fixtures\GroupDummy;
use Symfony\Component\Serializer\Tests\Fixtures\MaxDepthDummy;
use Symfony\Component\Serializer\Tests\Fixtures\OtherSerializedNameDummy;
@ -143,6 +144,15 @@ class ObjectNormalizerTest extends TestCase
);
}
public function testNormalizeObjectWithPrivatePropertyWithoutGetter()
{
$obj = new DummyPrivatePropertyWithoutGetter();
$this->assertEquals(
['bar' => 'bar'],
$this->normalizer->normalize($obj, 'any')
);
}
public function testDenormalize()
{
$obj = $this->normalizer->denormalize(