3 namespace Drupal\serialization\Normalizer;
5 use Drupal\Core\Cache\CacheableDependencyInterface;
6 use Symfony\Component\Serializer\Normalizer\SerializerAwareNormalizer;
9 * Base class for Normalizers.
11 abstract class NormalizerBase extends SerializerAwareNormalizer implements CacheableNormalizerInterface {
14 * The interface or class that this Normalizer supports.
18 protected $supportedInterfaceOrClass;
21 * List of formats which supports (de-)normalization.
23 * @var string|string[]
30 public function supportsNormalization($data, $format = NULL) {
31 // If we aren't dealing with an object or the format is not supported return
33 if (!is_object($data) || !$this->checkFormat($format)) {
37 $supported = (array) $this->supportedInterfaceOrClass;
39 return (bool) array_filter($supported, function ($name) use ($data) {
40 return $data instanceof $name;
45 * Implements \Symfony\Component\Serializer\Normalizer\DenormalizerInterface::supportsDenormalization()
47 * This class doesn't implement DenormalizerInterface, but most of its child
48 * classes do, so this method is implemented at this level to reduce code
51 public function supportsDenormalization($data, $type, $format = NULL) {
52 // If the format is not supported return now.
53 if (!$this->checkFormat($format)) {
57 $supported = (array) $this->supportedInterfaceOrClass;
59 $subclass_check = function ($name) use ($type) {
60 return (class_exists($name) || interface_exists($name)) && is_subclass_of($type, $name, TRUE);
63 return in_array($type, $supported) || array_filter($supported, $subclass_check);
67 * Checks if the provided format is supported by this normalizer.
69 * @param string $format
70 * The format to check.
73 * TRUE if the format is supported, FALSE otherwise. If no format is
74 * specified this will return TRUE.
76 protected function checkFormat($format = NULL) {
77 if (!isset($format) || !isset($this->format)) {
81 return in_array($format, (array) $this->format, TRUE);
85 * Adds cacheability if applicable.
87 * @param array $context
88 * Context options for the normalizer.
90 * The data that might have cacheability information.
92 protected function addCacheableDependency(array $context, $data) {
93 if ($data instanceof CacheableDependencyInterface && isset($context[static::SERIALIZATION_CONTEXT_CACHEABILITY])) {
94 $context[static::SERIALIZATION_CONTEXT_CACHEABILITY]->addCacheableDependency($data);