3 namespace Drupal\hal\Normalizer;
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;
14 * Converts the Drupal entity object structure to a HAL array structure.
16 class ContentEntityNormalizer extends NormalizerBase {
18 use FieldableEntityNormalizerTrait;
21 * The interface or class that this Normalizer supports.
25 protected $supportedInterfaceOrClass = 'Drupal\Core\Entity\ContentEntityInterface';
28 * The hypermedia link manager.
30 * @var \Drupal\hal\LinkManager\LinkManagerInterface
32 protected $linkManager;
37 * @var \Drupal\Core\Extension\ModuleHandlerInterface
39 protected $moduleHandler;
42 * Constructs an ContentEntityNormalizer object.
44 * @param \Drupal\hal\LinkManager\LinkManagerInterface $link_manager
45 * The hypermedia link manager.
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;
56 public function normalize($entity, $format = NULL, array $context = []) {
59 'included_fields' => NULL,
62 // Create the array of normalized fields, starting with the URI.
63 /** @var $entity \Drupal\Core\Entity\ContentEntityInterface */
67 'href' => $this->getEntityUri($entity),
70 'href' => $this->linkManager->getTypeUri($entity->getEntityTypeId(), $entity->bundle(), $context),
75 // If the fields to use were specified, only output those field values.
76 if (isset($context['included_fields'])) {
78 foreach ($context['included_fields'] as $field_name) {
79 $field_items[] = $entity->get($field_name);
83 $field_items = $entity->getFields();
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'])) {
91 $normalized_property = $this->serializer->normalize($field, $format, $context);
92 $normalized = NestedArray::mergeDeep($normalized, $normalized_property);
99 * Implements \Symfony\Component\Serializer\Normalizer\DenormalizerInterface::denormalize().
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
113 * @return \Drupal\Core\Entity\EntityInterface
114 * An unserialized entity object containing the data in $data.
116 * @throws \Symfony\Component\Serializer\Exception\UnexpectedValueException
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.');
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');
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'];
141 // Remove the default langcode so it does not get iterated over below.
142 unset($data[$default_langcode_key]);
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]);
152 $entity = $this->entityManager->getStorage($typed_data_ids['entity_type'])->create($values);
154 // Remove links from data array.
155 unset($data['_links']);
156 // Get embedded resources and remove from data array.
158 if (isset($data['_embedded'])) {
159 $embedded = $data['_embedded'];
160 unset($data['_embedded']);
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;
172 $this->denormalizeFieldData($data, $entity, $format, $context);
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);
182 * Constructs the entity URI.
184 * @param \Drupal\Core\Entity\EntityInterface $entity
189 protected function getEntityUri(EntityInterface $entity) {
190 // Some entity types don't provide a canonical link template, at least call
192 if ($entity->isNew() || !$entity->hasLinkTemplate('canonical')) {
193 return $entity->url('canonical', []);
195 $url = $entity->urlInfo('canonical', ['absolute' => TRUE]);
196 return $url->setRouteParameter('_format', 'hal_json')->toString();
200 * Gets the typed data IDs for a type URI.
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.
208 * The typed data IDs.
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'])) {
219 throw new UnexpectedValueException('No entity type(s) specified');
222 foreach ($types as $type) {
223 if (!isset($type['href'])) {
224 throw new UnexpectedValueException('Type must contain an \'href\' attribute.');
227 $type_uri = $type['href'];
229 // Check whether the URI corresponds to a known type on this site. Break
231 if ($typed_data_ids = $this->linkManager->getTypeInternalIds($type['href'], $context)) {
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));
242 return $typed_data_ids;