FieldItemNormalizer.php in Drupal 8
File
core/modules/hal/src/Normalizer/FieldItemNormalizer.php
View source
<?php
namespace Drupal\hal\Normalizer;
use Drupal\Core\Field\FieldItemInterface;
use Drupal\Core\TypedData\TypedDataInternalPropertiesHelper;
use Drupal\serialization\Normalizer\FieldableEntityNormalizerTrait;
use Drupal\serialization\Normalizer\SerializedColumnNormalizerTrait;
use Symfony\Component\Serializer\Exception\InvalidArgumentException;
class FieldItemNormalizer extends NormalizerBase {
use FieldableEntityNormalizerTrait;
use SerializedColumnNormalizerTrait;
protected $supportedInterfaceOrClass = FieldItemInterface::class;
public function normalize($field_item, $format = NULL, array $context = []) {
$field = $field_item
->getParent();
return [
$field
->getName() => [
$this
->normalizedFieldValues($field_item, $format, $context),
],
];
}
public function denormalize($data, $class, $format = NULL, array $context = []) {
if (!isset($context['target_instance'])) {
throw new InvalidArgumentException('$context[\'target_instance\'] must be set to denormalize with the FieldItemNormalizer');
}
if ($context['target_instance']
->getParent() == NULL) {
throw new InvalidArgumentException('The field item passed in via $context[\'target_instance\'] must have a parent set.');
}
$field_item = $context['target_instance'];
$this
->checkForSerializedStrings($data, $class, $field_item);
if (isset($data['lang'])) {
$langcode = $data['lang'];
unset($data['lang']);
$field_definition = $field_item
->getFieldDefinition();
if ($field_definition
->isTranslatable()) {
$field_item = $this
->createTranslatedInstance($field_item, $langcode);
}
}
$field_item
->setValue($this
->constructValue($data, $context));
return $field_item;
}
protected function normalizedFieldValues(FieldItemInterface $field_item, $format, array $context) {
$normalized = [];
$field_properties = !empty($field_item
->getProperties(TRUE)) ? TypedDataInternalPropertiesHelper::getNonInternalProperties($field_item) : $field_item
->getValue();
foreach ($field_properties as $property_name => $property) {
$normalized[$property_name] = $this->serializer
->normalize($property, $format, $context);
}
if (isset($context['langcode'])) {
$normalized['lang'] = $context['langcode'];
}
return $normalized;
}
protected function createTranslatedInstance(FieldItemInterface $item, $langcode) {
$items = $item
->getParent();
$delta = $item
->getName();
unset($items[$delta]);
$entity = $item
->getEntity();
$entity_translation = $entity
->hasTranslation($langcode) ? $entity
->getTranslation($langcode) : $entity
->addTranslation($langcode);
$field_name = $item
->getFieldDefinition()
->getName();
return $entity_translation
->get($field_name)
->appendItem();
}
}