3 namespace Drupal\serialization\Normalizer;
5 use Drupal\Core\Field\FieldItemListInterface;
6 use Symfony\Component\Serializer\Exception\InvalidArgumentException;
7 use Symfony\Component\Serializer\Exception\UnexpectedValueException;
8 use Symfony\Component\Serializer\Normalizer\DenormalizerInterface;
11 * Denormalizes data to Drupal field values.
13 * This class simply calls denormalize() on the individual FieldItems. The
14 * FieldItem normalizers are responsible for setting the field values for each
17 * @see \Drupal\serialization\Normalizer\FieldItemNormalizer.
19 class FieldNormalizer extends ListNormalizer implements DenormalizerInterface {
24 protected $supportedInterfaceOrClass = FieldItemListInterface::class;
29 public function denormalize($data, $class, $format = NULL, array $context = []) {
30 if (!isset($context['target_instance'])) {
31 throw new InvalidArgumentException('$context[\'target_instance\'] must be set to denormalize with the FieldNormalizer');
34 if ($context['target_instance']->getParent() == NULL) {
35 throw new InvalidArgumentException('The field passed in via $context[\'target_instance\'] must have a parent set.');
38 /** @var \Drupal\Core\Field\FieldItemListInterface $items */
39 $items = $context['target_instance'];
40 $item_class = $items->getItemDefinition()->getClass();
42 if (!is_array($data)) {
43 throw new UnexpectedValueException(sprintf('Field values for "%s" must use an array structure', $items->getName()));
46 foreach ($data as $item_data) {
47 // Create a new item and pass it as the target for the unserialization of
48 // $item_data. All items in field should have removed before this method
50 // @see \Drupal\serialization\Normalizer\ContentEntityNormalizer::denormalize().
51 $context['target_instance'] = $items->appendItem();
52 $this->serializer->denormalize($item_data, $item_class, $format, $context);