Skip to content

Commit 9e6ba9a

Browse files
committed
Added protected Serializer#supportsNormalization
This is very useful for cleaning up the logic in Serializer#normalize and allow easy checking of both the cache & stored normalizers
1 parent fc97472 commit 9e6ba9a

File tree

1 file changed

+29
-7
lines changed

1 file changed

+29
-7
lines changed

src/Symfony/Component/Serializer/Serializer.php

Lines changed: 29 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -153,17 +153,14 @@ private function normalizeObject($object, $format = null)
153153
if (!$this->normalizers) {
154154
throw new LogicException('You must register at least one normalizer to be able to normalize objects.');
155155
}
156+
156157
$class = get_class($object);
157-
if (isset($this->normalizerCache[$class][$format])) {
158+
159+
// If normalization is supported, cached normalizer will exist
160+
if ($this->supportsNormalization($object, $format)) {
158161
return $this->normalizerCache[$class][$format]->normalize($object, $format);
159162
}
160-
foreach ($this->normalizers as $normalizer) {
161-
if ($normalizer->supportsNormalization($object, $class, $format)) {
162-
$this->normalizerCache[$class][$format] = $normalizer;
163163

164-
return $normalizer->normalize($object, $format);
165-
}
166-
}
167164
throw new UnexpectedValueException('Could not normalize object of type '.$class.', no supporting normalizer found.');
168165
}
169166

@@ -193,6 +190,31 @@ private function denormalizeObject($data, $class, $format = null)
193190
throw new UnexpectedValueException('Could not denormalize object of type '.$class.', no supporting normalizer found.');
194191
}
195192

193+
/**
194+
* Check if normalizer cache or normalizers supports provided object, which will then be cached
195+
*
196+
* @param object $object Object to test for normalization support
197+
* @param string $format Format name, needed for normalizers to pivot on
198+
*/
199+
protected function supportsNormalization($object, $format)
200+
{
201+
$class = get_class($object);
202+
203+
if (isset($this->normalizerCache[$class][$format])) {
204+
return true;
205+
}
206+
207+
foreach ($this->normalizers as $normalizer) {
208+
if ($normalizer->supportsNormalization($object, $format)) {
209+
$this->normalizerCache[$class][$format] = $normalizer;
210+
211+
return true;
212+
}
213+
}
214+
215+
return false;
216+
}
217+
196218
/**
197219
* {@inheritdoc}
198220
*/

0 commit comments

Comments
 (0)