90d9b752581649e90c35e251f3fff3daf5bfa688
[yaffs-website] / web / core / modules / serialization / src / Normalizer / NormalizerBase.php
1 <?php
2
3 namespace Drupal\serialization\Normalizer;
4
5 use Symfony\Component\Serializer\Normalizer\NormalizerInterface;
6 use Symfony\Component\Serializer\Normalizer\SerializerAwareNormalizer;
7
8 /**
9  * Base class for Normalizers.
10  */
11 abstract class NormalizerBase extends SerializerAwareNormalizer implements NormalizerInterface {
12
13   /**
14    * The interface or class that this Normalizer supports.
15    *
16    * @var string|array
17    */
18   protected $supportedInterfaceOrClass;
19
20   /**
21    * {@inheritdoc}
22    */
23   public function supportsNormalization($data, $format = NULL) {
24     // If we aren't dealing with an object or the format is not supported return
25     // now.
26     if (!is_object($data) || !$this->checkFormat($format)) {
27       return FALSE;
28     }
29
30     $supported = (array) $this->supportedInterfaceOrClass;
31
32     return (bool) array_filter($supported, function($name) use ($data) {
33       return $data instanceof $name;
34     });
35   }
36
37   /**
38    * Implements \Symfony\Component\Serializer\Normalizer\DenormalizerInterface::supportsDenormalization()
39    *
40    * This class doesn't implement DenormalizerInterface, but most of its child
41    * classes do, so this method is implemented at this level to reduce code
42    * duplication.
43    */
44   public function supportsDenormalization($data, $type, $format = NULL) {
45     // If the format is not supported return now.
46     if (!$this->checkFormat($format)) {
47       return FALSE;
48     }
49
50     $supported = (array) $this->supportedInterfaceOrClass;
51
52     $subclass_check = function($name) use ($type) {
53       return (class_exists($name) || interface_exists($name)) && is_subclass_of($type, $name, TRUE);
54     };
55
56     return in_array($type, $supported) || array_filter($supported, $subclass_check);
57   }
58
59   /**
60    * Checks if the provided format is supported by this normalizer.
61    *
62    * @param string $format
63    *   The format to check.
64    *
65    * @return bool
66    *   TRUE if the format is supported, FALSE otherwise. If no format is
67    *   specified this will return TRUE.
68    */
69   protected function checkFormat($format = NULL) {
70     if (!isset($format) || !isset($this->format)) {
71       return TRUE;
72     }
73
74     return in_array($format, (array) $this->format);
75   }
76
77 }