5e829f65e701a0b7b3f2c2a24713fbe1cc0e9691
[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    * List of formats which supports (de-)normalization.
22    *
23    * @var string|string[]
24    */
25   protected $format;
26
27   /**
28    * {@inheritdoc}
29    */
30   public function supportsNormalization($data, $format = NULL) {
31     // If we aren't dealing with an object or the format is not supported return
32     // now.
33     if (!is_object($data) || !$this->checkFormat($format)) {
34       return FALSE;
35     }
36
37     $supported = (array) $this->supportedInterfaceOrClass;
38
39     return (bool) array_filter($supported, function ($name) use ($data) {
40       return $data instanceof $name;
41     });
42   }
43
44   /**
45    * Implements \Symfony\Component\Serializer\Normalizer\DenormalizerInterface::supportsDenormalization()
46    *
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
49    * duplication.
50    */
51   public function supportsDenormalization($data, $type, $format = NULL) {
52     // If the format is not supported return now.
53     if (!$this->checkFormat($format)) {
54       return FALSE;
55     }
56
57     $supported = (array) $this->supportedInterfaceOrClass;
58
59     $subclass_check = function ($name) use ($type) {
60       return (class_exists($name) || interface_exists($name)) && is_subclass_of($type, $name, TRUE);
61     };
62
63     return in_array($type, $supported) || array_filter($supported, $subclass_check);
64   }
65
66   /**
67    * Checks if the provided format is supported by this normalizer.
68    *
69    * @param string $format
70    *   The format to check.
71    *
72    * @return bool
73    *   TRUE if the format is supported, FALSE otherwise. If no format is
74    *   specified this will return TRUE.
75    */
76   protected function checkFormat($format = NULL) {
77     if (!isset($format) || !isset($this->format)) {
78       return TRUE;
79     }
80
81     return in_array($format, (array) $this->format, TRUE);
82   }
83
84 }