You are here

protected function EntityNormalizerTrait::prepareInput in JSON:API Extras 8

Same name and namespace in other branches
  1. 8.2 src/Normalizer/EntityNormalizerTrait.php \Drupal\jsonapi_extras\Normalizer\EntityNormalizerTrait::prepareInput()

Prepares the input data to create the entity.

Parameters

array $data: The input data to modify.

\Drupal\jsonapi\ResourceType\ResourceType $resource_type: Contains the info about the resource type.

Return value

array The modified input data.

File

src/Normalizer/EntityNormalizerTrait.php, line 23

Class

EntityNormalizerTrait
Common code for entity normalizers.

Namespace

Drupal\jsonapi_extras\Normalizer

Code

protected function prepareInput(array $data, ResourceType $resource_type) {

  /** @var \Drupal\Core\Field\FieldStorageDefinitionInterface[] $field_storage_definitions */
  $field_storage_definitions = \Drupal::service('entity_field.manager')
    ->getFieldStorageDefinitions($resource_type
    ->getEntityTypeId());
  $data_internal = [];

  /** @var \Drupal\jsonapi_extras\ResourceType\ConfigurableResourceType $resource_type */

  // Translate the public fields into the entity fields.
  foreach ($data as $public_field_name => $field_value) {

    // Skip any disabled field.
    if (!$resource_type
      ->isFieldEnabled($public_field_name)) {
      continue;
    }
    $internal_name = $resource_type
      ->getInternalName($public_field_name);
    $enhancer = $resource_type
      ->getFieldEnhancer($public_field_name, 'publicName');
    if (isset($field_storage_definitions[$internal_name])) {
      $field_storage_definition = $field_storage_definitions[$internal_name];
      if ($field_storage_definition
        ->getCardinality() === 1) {
        $field_value = $enhancer ? $enhancer
          ->prepareForInput($field_value) : $field_value;
      }
      elseif (is_array($field_value)) {
        foreach ($field_value as $key => $individual_field_value) {
          $field_value[$key] = $enhancer ? $enhancer
            ->prepareForInput($individual_field_value) : $individual_field_value;
        }
      }
    }
    $data_internal[$internal_name] = $field_value;
  }
  return $data_internal;
}