Skip to content

Commit 7f404b7

Browse files
committed
[Serializer] Catch \Throwable in getCacheKey()
1 parent 5da141b commit 7f404b7

File tree

2 files changed

+37
-4
lines changed

2 files changed

+37
-4
lines changed

src/Symfony/Component/Serializer/Normalizer/AbstractObjectNormalizer.php

Lines changed: 18 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -401,12 +401,26 @@ protected function createChildContext(array $parentContext, $attribute/*, string
401401
private function getCacheKey($format, array $context)
402402
{
403403
unset($context['cache_key']); // avoid artificially different keys
404+
405+
if (interface_exists(\Throwable::class)) {
406+
try {
407+
return md5($format.serialize([
408+
'context' => $context,
409+
'ignored' => $this->ignoredAttributes,
410+
'camelized' => $this->camelizedAttributes,
411+
]));
412+
} catch (\Throwable $exception) {
413+
// The context cannot be serialized, skip the cache
414+
return false;
415+
}
416+
}
417+
404418
try {
405419
return md5($format.serialize([
406-
'context' => $context,
407-
'ignored' => $this->ignoredAttributes,
408-
'camelized' => $this->camelizedAttributes,
409-
]));
420+
'context' => $context,
421+
'ignored' => $this->ignoredAttributes,
422+
'camelized' => $this->camelizedAttributes,
423+
]));
410424
} catch (\Exception $exception) {
411425
// The context cannot be serialized, skip the cache
412426
return false;

src/Symfony/Component/Serializer/Tests/Normalizer/AbstractObjectNormalizerTest.php

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -194,6 +194,13 @@ public function testExtraAttributesException()
194194
'allow_extra_attributes' => false,
195195
]);
196196
}
197+
198+
public function testContextNotSerializable()
199+
{
200+
$normalizer = new ObjectNormalizer();
201+
$result = $normalizer->normalize(new Dummy(), null, ['not_serializable' => new NotSerializable()]);
202+
$this->assertIsArray($result);
203+
}
197204
}
198205

199206
class AbstractObjectNormalizerDummy extends AbstractObjectNormalizer
@@ -379,3 +386,15 @@ public function setSerializer(SerializerInterface $serializer)
379386
$this->serializer = $serializer;
380387
}
381388
}
389+
390+
class NotSerializable
391+
{
392+
function __sleep()
393+
{
394+
if (class_exists(\Error::class)) {
395+
throw new \Error('not serializable');
396+
}
397+
398+
throw new \Exception('not serializable');
399+
}
400+
}

0 commit comments

Comments
 (0)