FieldNormalizer.php in Drupal 9
File
core/modules/hal/src/Normalizer/FieldNormalizer.php
View source
<?php
namespace Drupal\hal\Normalizer;
use Drupal\Component\Utility\NestedArray;
use Drupal\serialization\Normalizer\FieldNormalizer as SerializationFieldNormalizer;
class FieldNormalizer extends SerializationFieldNormalizer {
protected $format = [
'hal_json',
];
public function normalize($field_items, $format = NULL, array $context = []) {
$normalized_field_items = [];
$entity = $field_items
->getEntity();
$field_name = $field_items
->getName();
$field_definition = $field_items
->getFieldDefinition();
if (!$field_definition
->isTranslatable()) {
$normalized_field_items = $this
->normalizeFieldItems($field_items, $format, $context);
}
else {
foreach ($entity
->getTranslationLanguages() as $language) {
$context['langcode'] = $language
->getId();
$translation = $entity
->getTranslation($language
->getId());
$translated_field_items = $translation
->get($field_name);
$normalized_field_items = array_merge($normalized_field_items, $this
->normalizeFieldItems($translated_field_items, $format, $context));
}
}
return NestedArray::mergeDeepArray($normalized_field_items);
}
protected function normalizeFieldItems($field_items, $format, $context) {
$normalized_field_items = [];
if (!$field_items
->isEmpty()) {
foreach ($field_items as $field_item) {
$normalized_field_items[] = $this->serializer
->normalize($field_item, $format, $context);
}
}
return $normalized_field_items;
}
}