public function EntityNormalizer::denormalize

Implements \Symfony\Component\Serializer\Normalizer\DenormalizerInterface::denormalize().

Throws

\Symfony\Component\Serializer\Exception\UnexpectedValueException

Overrides DenormalizerInterface::denormalize

File

drupal/core/modules/hal/lib/Drupal/hal/Normalizer/EntityNormalizer.php, line 71
Contains \Drupal\hal\Normalizer\EntityNormalizer.

Class

EntityNormalizer
Converts the Drupal entity object structure to a HAL array structure.

Namespace

Drupal\hal\Normalizer

Code

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.
  $typed_data_ids = $this
    ->getTypedDataIds($data['_links']['type']);

  // Figure out the language to use.
  if (isset($data['langcode'])) {
    $langcode = $data['langcode'][0]['value'];
  }
  elseif (module_exists('language')) {
    $langcode = language_get_default_langcode($typed_data_ids['entity_type'], $typed_data_ids['bundle']);
  }
  else {
    $langcode = Language::LANGCODE_NOT_SPECIFIED;
  }
  $entity = entity_create($typed_data_ids['entity_type'], array(
    'langcode' => $langcode,
    'type' => $typed_data_ids['bundle'],
  ));

  // Get links and remove from data array.
  $links = $data['_links'];
  unset($data['_links']);

  // Get embedded resources and remove from data array.
  $embedded = array();
  if (isset($data['_embedded'])) {
    $embedded = $data['_embedded'];
    unset($data['_embedded']);
  }

  // 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;
    }
  }

  // Iterate through remaining items in data array. These should all
  // correspond to fields.
  foreach ($data as $field_name => $field_data) {

    // Remove any values that were set as a part of entity creation (e.g
    // uuid). If this field is set to an empty array in the data, this will
    // also have the effect of marking the field for deletion in REST module.
    $entity->{$field_name} = array();
    $field = $entity
      ->get($field_name);

    // Get the class of the field. This will generally be the default Field
    // class.
    $field_class = get_class($field);

    // Pass in the empty field object as a target instance. Since the context
    // is already prepared for the field, any data added to it is
    // automatically added to the entity.
    $context['target_instance'] = $field;
    $this->serializer
      ->denormalize($field_data, $field_class, $format, $context);
  }
  return $entity;
}