Security update for Core, with self-updated composer
[yaffs-website] / web / core / modules / hal / src / Normalizer / ContentEntityNormalizer.php
1 <?php
2
3 namespace Drupal\hal\Normalizer;
4
5 use Drupal\Component\Utility\NestedArray;
6 use Drupal\Core\Entity\EntityInterface;
7 use Drupal\Core\Entity\EntityManagerInterface;
8 use Drupal\Core\Extension\ModuleHandlerInterface;
9 use Drupal\hal\LinkManager\LinkManagerInterface;
10 use Drupal\serialization\Normalizer\FieldableEntityNormalizerTrait;
11 use Symfony\Component\Serializer\Exception\UnexpectedValueException;
12
13 /**
14  * Converts the Drupal entity object structure to a HAL array structure.
15  */
16 class ContentEntityNormalizer extends NormalizerBase {
17
18   use FieldableEntityNormalizerTrait;
19
20   /**
21    * The interface or class that this Normalizer supports.
22    *
23    * @var string
24    */
25   protected $supportedInterfaceOrClass = 'Drupal\Core\Entity\ContentEntityInterface';
26
27   /**
28    * The hypermedia link manager.
29    *
30    * @var \Drupal\hal\LinkManager\LinkManagerInterface
31    */
32   protected $linkManager;
33
34   /**
35    * The module handler.
36    *
37    * @var \Drupal\Core\Extension\ModuleHandlerInterface
38    */
39   protected $moduleHandler;
40
41   /**
42    * Constructs an ContentEntityNormalizer object.
43    *
44    * @param \Drupal\hal\LinkManager\LinkManagerInterface $link_manager
45    *   The hypermedia link manager.
46    */
47   public function __construct(LinkManagerInterface $link_manager, EntityManagerInterface $entity_manager, ModuleHandlerInterface $module_handler) {
48     $this->linkManager = $link_manager;
49     $this->entityManager = $entity_manager;
50     $this->moduleHandler = $module_handler;
51   }
52
53   /**
54    * {@inheritdoc}
55    */
56   public function normalize($entity, $format = NULL, array $context = []) {
57     $context += [
58       'account' => NULL,
59       'included_fields' => NULL,
60     ];
61
62     // Create the array of normalized fields, starting with the URI.
63     /** @var $entity \Drupal\Core\Entity\ContentEntityInterface */
64     $normalized = [
65       '_links' => [
66         'self' => [
67           'href' => $this->getEntityUri($entity),
68         ],
69         'type' => [
70           'href' => $this->linkManager->getTypeUri($entity->getEntityTypeId(), $entity->bundle(), $context),
71         ],
72       ],
73     ];
74
75     // If the fields to use were specified, only output those field values.
76     if (isset($context['included_fields'])) {
77       $field_items = [];
78       foreach ($context['included_fields'] as $field_name) {
79         $field_items[] = $entity->get($field_name);
80       }
81     }
82     else {
83       $field_items = $entity->getFields();
84     }
85     foreach ($field_items as $field) {
86       // Continue if the current user does not have access to view this field.
87       if (!$field->access('view', $context['account'])) {
88         continue;
89       }
90
91       $normalized_property = $this->serializer->normalize($field, $format, $context);
92       $normalized = NestedArray::mergeDeep($normalized, $normalized_property);
93     }
94
95     return $normalized;
96   }
97
98   /**
99    * Implements \Symfony\Component\Serializer\Normalizer\DenormalizerInterface::denormalize().
100    *
101    * @param array $data
102    *   Entity data to restore.
103    * @param string $class
104    *   Unused, entity_create() is used to instantiate entity objects.
105    * @param string $format
106    *   Format the given data was extracted from.
107    * @param array $context
108    *   Options available to the denormalizer. Keys that can be used:
109    *   - request_method: if set to "patch" the denormalization will clear out
110    *     all default values for entity fields before applying $data to the
111    *     entity.
112    *
113    * @return \Drupal\Core\Entity\EntityInterface
114    *   An unserialized entity object containing the data in $data.
115    *
116    * @throws \Symfony\Component\Serializer\Exception\UnexpectedValueException
117    */
118   public function denormalize($data, $class, $format = NULL, array $context = []) {
119     // Get type, necessary for determining which bundle to create.
120     if (!isset($data['_links']['type'])) {
121       throw new UnexpectedValueException('The type link relation must be specified.');
122     }
123
124     // Create the entity.
125     $typed_data_ids = $this->getTypedDataIds($data['_links']['type'], $context);
126     $entity_type = $this->getEntityTypeDefinition($typed_data_ids['entity_type']);
127     $default_langcode_key = $entity_type->getKey('default_langcode');
128     $langcode_key = $entity_type->getKey('langcode');
129     $values = [];
130
131     // Figure out the language to use.
132     if (isset($data[$default_langcode_key])) {
133       // Find the field item for which the default_lancode value is set to 1 and
134       // set the langcode the right default language.
135       foreach ($data[$default_langcode_key] as $item) {
136         if (!empty($item['value']) && isset($item['lang'])) {
137           $values[$langcode_key] = $item['lang'];
138           break;
139         }
140       }
141       // Remove the default langcode so it does not get iterated over below.
142       unset($data[$default_langcode_key]);
143     }
144
145     if ($entity_type->hasKey('bundle')) {
146       $bundle_key = $entity_type->getKey('bundle');
147       $values[$bundle_key] = $typed_data_ids['bundle'];
148       // Unset the bundle key from data, if it's there.
149       unset($data[$bundle_key]);
150     }
151
152     $entity = $this->entityManager->getStorage($typed_data_ids['entity_type'])->create($values);
153
154     // Remove links from data array.
155     unset($data['_links']);
156     // Get embedded resources and remove from data array.
157     $embedded = [];
158     if (isset($data['_embedded'])) {
159       $embedded = $data['_embedded'];
160       unset($data['_embedded']);
161     }
162
163     // Flatten the embedded values.
164     foreach ($embedded as $relation => $field) {
165       $field_ids = $this->linkManager->getRelationInternalIds($relation);
166       if (!empty($field_ids)) {
167         $field_name = $field_ids['field_name'];
168         $data[$field_name] = $field;
169       }
170     }
171
172     $this->denormalizeFieldData($data, $entity, $format, $context);
173
174     // Pass the names of the fields whose values can be merged.
175     // @todo https://www.drupal.org/node/2456257 remove this.
176     $entity->_restSubmittedFields = array_keys($data);
177
178     return $entity;
179   }
180
181   /**
182    * Constructs the entity URI.
183    *
184    * @param \Drupal\Core\Entity\EntityInterface $entity
185    *   The entity.
186    * @return string
187    *   The entity URI.
188    */
189   protected function getEntityUri(EntityInterface $entity) {
190     // Some entity types don't provide a canonical link template, at least call
191     // out to ->url().
192     if ($entity->isNew() || !$entity->hasLinkTemplate('canonical')) {
193       return $entity->url('canonical', []);
194     }
195     $url = $entity->urlInfo('canonical', ['absolute' => TRUE]);
196     return $url->setRouteParameter('_format', 'hal_json')->toString();
197   }
198
199   /**
200    * Gets the typed data IDs for a type URI.
201    *
202    * @param array $types
203    *   The type array(s) (value of the 'type' attribute of the incoming data).
204    * @param array $context
205    *   Context from the normalizer/serializer operation.
206    *
207    * @return array
208    *   The typed data IDs.
209    */
210   protected function getTypedDataIds($types, $context = []) {
211     // The 'type' can potentially contain an array of type objects. By default,
212     // Drupal only uses a single type in serializing, but allows for multiple
213     // types when deserializing.
214     if (isset($types['href'])) {
215       $types = [$types];
216     }
217
218     if (empty($types)) {
219       throw new UnexpectedValueException('No entity type(s) specified');
220     }
221
222     foreach ($types as $type) {
223       if (!isset($type['href'])) {
224         throw new UnexpectedValueException('Type must contain an \'href\' attribute.');
225       }
226
227       $type_uri = $type['href'];
228
229       // Check whether the URI corresponds to a known type on this site. Break
230       // once one does.
231       if ($typed_data_ids = $this->linkManager->getTypeInternalIds($type['href'], $context)) {
232         break;
233       }
234     }
235
236     // If none of the URIs correspond to an entity type on this site, no entity
237     // can be created. Throw an exception.
238     if (empty($typed_data_ids)) {
239       throw new UnexpectedValueException(sprintf('Type %s does not correspond to an entity on this site.', $type_uri));
240     }
241
242     return $typed_data_ids;
243   }
244
245 }