protected function EntityNormalizer::prepareInput in JSON:API 8
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.
1 call to EntityNormalizer::prepareInput()
- EntityNormalizer::denormalize in src/
Normalizer/ EntityNormalizer.php - Denormalizes data back into an object of the given class.
File
- src/
Normalizer/ EntityNormalizer.php, line 234
Class
- EntityNormalizer
- Converts the Drupal entity object to a JSON API array structure.
Namespace
Drupal\jsonapi\NormalizerCode
protected function prepareInput(array $data, ResourceType $resource_type) {
$data_internal = [];
// 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);
if ($resource_type
->getDeserializationTargetClass() instanceof FieldableEntityInterface) {
// If $field_value contains items (recognizable by numerical array keys
// which Drupal's Field API calls "deltas"), then it already is itemized;
// it's not using the simplified JSON structure that JSON:API generates.
$is_already_itemized = is_array($field_value) && array_reduce(array_keys($field_value), function ($carry, $index) {
return $carry && is_numeric($index);
}, TRUE);
$itemized_data = $is_already_itemized ? $field_value : [
0 => $field_value,
];
try {
$field_item = $this
->getFieldItemInstance($resource_type, $internal_name);
foreach ($itemized_data as $delta => $field_item_value) {
$this
->checkForSerializedStrings($field_item_value, get_class($field_item), $field_item);
$serialized_property_names = $this
->getCustomSerializedPropertyNames($field_item);
// Explicitly serialize the input, unlike properties that rely on
// being automatically serialized, manually managed serialized
// properties expect to receive serialized input.
if (is_array($field_item_value)) {
foreach ($serialized_property_names as $serialized_property_name) {
if (!empty($field_item_value[$serialized_property_name])) {
$itemized_data[$delta][$serialized_property_name] = serialize($field_item_value[$serialized_property_name]);
}
}
}
elseif (in_array($field_item
->getDataDefinition()
->getMainPropertyName(), $serialized_property_names, TRUE)) {
$itemized_data[$delta] = serialize($field_item_value);
}
}
} catch (\InvalidArgumentException $e) {
// The field does not exist, so there is no processing to be done. A
// helpful error will be shown by EntityResource::createIndividual() or
// EntityResource::patchIndividual().
}
$data_internal[$internal_name] = $is_already_itemized ? $itemized_data : $itemized_data[0];
}
else {
$data_internal[$internal_name] = $field_value;
}
}
return $data_internal;
}