ContentEntityNormalizer.php 8.32 KB
Newer Older
1 2 3 4
<?php

/**
 * @file
5
 * Contains \Drupal\hal\Normalizer\ContentEntityNormalizer.
6 7 8 9 10
 */

namespace Drupal\hal\Normalizer;

use Drupal\Component\Utility\NestedArray;
11
use Drupal\Core\Entity\EntityInterface;
12 13
use Drupal\Core\Entity\EntityManagerInterface;
use Drupal\Core\Extension\ModuleHandlerInterface;
14
use Drupal\rest\LinkManager\LinkManagerInterface;
15
use Symfony\Component\Serializer\Exception\UnexpectedValueException;
16 17 18 19

/**
 * Converts the Drupal entity object structure to a HAL array structure.
 */
20
class ContentEntityNormalizer extends NormalizerBase {
21 22 23 24 25 26

  /**
   * The interface or class that this Normalizer supports.
   *
   * @var string
   */
27
  protected $supportedInterfaceOrClass = 'Drupal\Core\Entity\ContentEntityInterface';
28

29 30 31 32 33 34 35 36
  /**
   * The hypermedia link manager.
   *
   * @var \Drupal\rest\LinkManager\LinkManagerInterface
   */
  protected $linkManager;

  /**
37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52
   * The entity manager.
   *
   * @var \Drupal\Core\Entity\EntityManagerInterface
   */
  protected $entityManager;

  /**
   * The module handler.
   *
   * @var \Drupal\Core\Extension\ModuleHandlerInterface
   */
  protected $moduleHandler;


  /**
   * Constructs an ContentEntityNormalizer object.
53 54 55 56
   *
   * @param \Drupal\rest\LinkManager\LinkManagerInterface $link_manager
   *   The hypermedia link manager.
   */
57
  public function __construct(LinkManagerInterface $link_manager, EntityManagerInterface $entity_manager, ModuleHandlerInterface $module_handler) {
58
    $this->linkManager = $link_manager;
59 60
    $this->entityManager = $entity_manager;
    $this->moduleHandler = $module_handler;
61 62
  }

63 64 65 66
  /**
   * Implements \Symfony\Component\Serializer\Normalizer\NormalizerInterface::normalize()
   */
  public function normalize($entity, $format = NULL, array $context = array()) {
67 68 69 70 71
    $context += array(
      'account' => NULL,
      'included_fields' => NULL,
    );

72
    // Create the array of normalized fields, starting with the URI.
73
    /** @var $entity \Drupal\Core\Entity\ContentEntityInterface */
74 75 76 77 78 79
    $normalized = array(
      '_links' => array(
        'self' => array(
          'href' => $this->getEntityUri($entity),
        ),
        'type' => array(
80
          'href' => $this->linkManager->getTypeUri($entity->getEntityTypeId(), $entity->bundle(), $context),
81 82 83 84
        ),
      ),
    );

85 86
    // If the fields to use were specified, only output those field values.
    // Otherwise, output all field values except internal ID.
87
    if (isset($context['included_fields'])) {
88 89 90
      $fields = array();
      foreach ($context['included_fields'] as $field_name) {
        $fields[] = $entity->get($field_name);
91 92 93
      }
    }
    else {
94
      $fields = $entity->getFields();
95
    }
96 97 98
    // Ignore the entity ID and revision ID.
    $exclude = array($entity->getEntityType()->getKey('id'), $entity->getEntityType()->getKey('revision'));
    foreach ($fields as $field) {
99 100 101
      // Continue if this is an excluded field or the current user does not have
      // access to view it.
      if (in_array($field->getFieldDefinition()->getName(), $exclude) || !$field->access('view', $context['account'])) {
102 103
        continue;
      }
104

105
      $normalized_property = $this->serializer->normalize($field, $format, $context);
106 107 108 109 110 111
      $normalized = NestedArray::mergeDeep($normalized, $normalized_property);
    }

    return $normalized;
  }

112 113 114
  /**
   * Implements \Symfony\Component\Serializer\Normalizer\DenormalizerInterface::denormalize().
   *
115 116 117 118 119 120 121 122 123 124 125 126
   * @param array $data
   *   Entity data to restore.
   * @param string $class
   *   Unused, entity_create() is used to instantiate entity objects.
   * @param string $format
   *   Format the given data was extracted from.
   * @param array $context
   *   Options available to the denormalizer. Keys that can be used:
   *   - request_method: if set to "patch" the denormalization will clear out
   *     all default values for entity fields before applying $data to the
   *     entity.
   *
127 128 129 130 131 132 133 134 135
   * @throws \Symfony\Component\Serializer\Exception\UnexpectedValueException
   */
  public function denormalize($data, $class, $format = NULL, array $context = array()) {
    // Get type, necessary for determining which bundle to create.
    if (!isset($data['_links']['type'])) {
      throw new UnexpectedValueException('The type link relation must be specified.');
    }

    // Create the entity.
136
    $typed_data_ids = $this->getTypedDataIds($data['_links']['type'], $context);
137 138
    $entity_type = $this->entityManager->getDefinition($typed_data_ids['entity_type']);
    $langcode_key = $entity_type->getKey('langcode');
139
    $values = array();
140

141
    // Figure out the language to use.
142 143
    if (isset($data[$langcode_key])) {
      $values[$langcode_key] = $data[$langcode_key][0]['value'];
144
      // Remove the langcode so it does not get iterated over below.
145
      unset($data[$langcode_key]);
146 147
    }

148 149 150 151 152 153 154
    if ($entity_type->hasKey('bundle')) {
      $bundle_key = $entity_type->getKey('bundle');
      $values[$bundle_key] = $typed_data_ids['bundle'];
      // Unset the bundle key from data, if it's there.
      unset($data[$bundle_key]);
    }

155
    $entity = $this->entityManager->getStorage($typed_data_ids['entity_type'])->create($values);
156

157
    // Remove links from data array.
158 159 160 161 162 163 164 165
    unset($data['_links']);
    // Get embedded resources and remove from data array.
    $embedded = array();
    if (isset($data['_embedded'])) {
      $embedded = $data['_embedded'];
      unset($data['_embedded']);
    }

166 167 168 169 170 171 172 173 174
    // Flatten the embedded values.
    foreach ($embedded as $relation => $field) {
      $field_ids = $this->linkManager->getRelationInternalIds($relation);
      if (!empty($field_ids)) {
        $field_name = $field_ids['field_name'];
        $data[$field_name] = $field;
      }
    }

175 176
    // Pass the names of the fields whose values can be merged.
    $entity->_restSubmittedFields = array_keys($data);
177

178 179 180
    // Iterate through remaining items in data array. These should all
    // correspond to fields.
    foreach ($data as $field_name => $field_data) {
181
      $items = $entity->get($field_name);
182
      // Remove any values that were set as a part of entity creation (e.g
183 184 185 186 187 188 189 190
      // uuid). If the incoming field data is set to an empty array, this will
      // also have the effect of emptying the field in REST module.
      $items->setValue(array());
      if ($field_data) {
        // Denormalize the field data into the FieldItemList object.
        $context['target_instance'] = $items;
        $this->serializer->denormalize($field_data, get_class($items), $format, $context);
      }
191 192 193 194 195
    }

    return $entity;
  }

196 197 198
  /**
   * Constructs the entity URI.
   *
199
   * @param \Drupal\Core\Entity\EntityInterface
200 201 202 203
   *   The entity.
   * @return string
   *   The entity URI.
   */
204 205 206 207 208 209 210 211
  protected function getEntityUri(EntityInterface $entity) {
    // Some entity types don't provide a canonical link template, at least call
    // out to ->url().
    if ($entity->isNew() || !$entity->hasLinkTemplate('canonical')) {
      return $entity->url('canonical', []);
    }
    $url = $entity->urlInfo('canonical', ['absolute' => TRUE]);
    return $url->setRouteParameter('_format', 'hal_json')->toString();
212 213
  }

214 215 216 217 218
  /**
   * Gets the typed data IDs for a type URI.
   *
   * @param array $types
   *   The type array(s) (value of the 'type' attribute of the incoming data).
219 220
   * @param array $context
   *   Context from the normalizer/serializer operation.
221 222 223 224 225
   *
   * @return array
   *   The typed data IDs.
   *
   */
226
  protected function getTypedDataIds($types, $context = array()) {
227 228 229 230 231 232 233 234 235 236 237 238 239 240
    // The 'type' can potentially contain an array of type objects. By default,
    // Drupal only uses a single type in serializing, but allows for multiple
    // types when deserializing.
    if (isset($types['href'])) {
      $types = array($types);
    }

    foreach ($types as $type) {
      if (!isset($type['href'])) {
        throw new UnexpectedValueException('Type must contain an \'href\' attribute.');
      }
      $type_uri = $type['href'];
      // Check whether the URI corresponds to a known type on this site. Break
      // once one does.
241
      if ($typed_data_ids = $this->linkManager->getTypeInternalIds($type['href'], $context)) {
242 243 244 245 246 247 248 249 250 251 252 253
        break;
      }
    }

    // If none of the URIs correspond to an entity type on this site, no entity
    // can be created. Throw an exception.
    if (empty($typed_data_ids)) {
      throw new UnexpectedValueException(sprintf('Type %s does not correspond to an entity on this site.', $type_uri));
    }

    return $typed_data_ids;
  }
254
}