3 namespace Drupal\serialization\Normalizer;
5 use Drupal\Core\Cache\CacheableDependencyInterface;
6 use Symfony\Component\Serializer\SerializerAwareInterface;
7 use Symfony\Component\Serializer\SerializerAwareTrait;
10 * Base class for Normalizers.
12 abstract class NormalizerBase implements SerializerAwareInterface, CacheableNormalizerInterface {
14 use SerializerAwareTrait;
17 * The interface or class that this Normalizer supports.
21 protected $supportedInterfaceOrClass;
24 * List of formats which supports (de-)normalization.
26 * @var string|string[]
33 public function supportsNormalization($data, $format = NULL) {
34 // If we aren't dealing with an object or the format is not supported return
36 if (!is_object($data) || !$this->checkFormat($format)) {
40 $supported = (array) $this->supportedInterfaceOrClass;
42 return (bool) array_filter($supported, function ($name) use ($data) {
43 return $data instanceof $name;
48 * Implements \Symfony\Component\Serializer\Normalizer\DenormalizerInterface::supportsDenormalization()
50 * This class doesn't implement DenormalizerInterface, but most of its child
51 * classes do, so this method is implemented at this level to reduce code
54 public function supportsDenormalization($data, $type, $format = NULL) {
55 // If the format is not supported return now.
56 if (!$this->checkFormat($format)) {
60 $supported = (array) $this->supportedInterfaceOrClass;
62 $subclass_check = function ($name) use ($type) {
63 return (class_exists($name) || interface_exists($name)) && is_subclass_of($type, $name, TRUE);
66 return in_array($type, $supported) || array_filter($supported, $subclass_check);
70 * Checks if the provided format is supported by this normalizer.
72 * @param string $format
73 * The format to check.
76 * TRUE if the format is supported, FALSE otherwise. If no format is
77 * specified this will return TRUE.
79 protected function checkFormat($format = NULL) {
80 if (!isset($format) || !isset($this->format)) {
84 return in_array($format, (array) $this->format, TRUE);
88 * Adds cacheability if applicable.
90 * @param array $context
91 * Context options for the normalizer.
93 * The data that might have cacheability information.
95 protected function addCacheableDependency(array $context, $data) {
96 if ($data instanceof CacheableDependencyInterface && isset($context[static::SERIALIZATION_CONTEXT_CACHEABILITY])) {
97 $context[static::SERIALIZATION_CONTEXT_CACHEABILITY]->addCacheableDependency($data);