function FieldableEntityNormalizerTrait::extractBundleData

Denormalizes the bundle property so entity creation can use it.

Parameters

array $data: The data being denormalized.

\Drupal\Core\Entity\EntityTypeInterface $entity_type_definition: The entity type definition.

Return value

string The valid bundle name.

Throws

\Symfony\Component\Serializer\Exception\UnexpectedValueException

1 call to FieldableEntityNormalizerTrait::extractBundleData()
EntityNormalizer::denormalize in core/modules/serialization/src/Normalizer/EntityNormalizer.php

File

core/modules/serialization/src/Normalizer/FieldableEntityNormalizerTrait.php, line 94

Class

FieldableEntityNormalizerTrait
A trait for providing fieldable entity normalization/denormalization methods.

Namespace

Drupal\serialization\Normalizer

Code

protected function extractBundleData(array &$data, EntityTypeInterface $entity_type_definition) {
  $bundle_key = $entity_type_definition->getKey('bundle');
  // Get the base field definitions for this entity type.
  $base_field_definitions = $this->getEntityFieldManager()
    ->getBaseFieldDefinitions($entity_type_definition->id());
  // Get the ID key from the base field definition for the bundle key or
  // default to 'value'.
  $key_id = isset($base_field_definitions[$bundle_key]) ? $base_field_definitions[$bundle_key]->getFieldStorageDefinition()
    ->getMainPropertyName() : 'value';
  // Normalize the bundle if it is not explicitly set.
  $bundle_value = isset($data[$bundle_key][0][$key_id]) ? $data[$bundle_key][0][$key_id] : (isset($data[$bundle_key]) ? $data[$bundle_key] : NULL);
  // Unset the bundle from the data.
  unset($data[$bundle_key]);
  // Get the bundle entity type from the entity type definition.
  $bundle_type_id = $entity_type_definition->getBundleEntityType();
  $bundle_types = $bundle_type_id ? $this->getEntityTypeManager()
    ->getStorage($bundle_type_id)
    ->getQuery()
    ->execute() : [];
  // Make sure a bundle has been provided.
  if (!is_string($bundle_value)) {
    throw new UnexpectedValueException(sprintf('Could not determine entity type bundle: "%s" field is missing.', $bundle_key));
  }
  // Make sure the submitted bundle is a valid bundle for the entity type.
  if ($bundle_types && !in_array($bundle_value, $bundle_types)) {
    throw new UnexpectedValueException(sprintf('"%s" is not a valid bundle type for denormalization.', $bundle_value));
  }
  return [
    $bundle_key => $bundle_value,
  ];
}

Buggy or inaccurate documentation? Please file an issue. Need support? Need help programming? Connect with the Drupal community.