a5051cfb414ff612b7c4a47732388f5645f6a5c4
[yaffs-website] / web / core / modules / serialization / src / Normalizer / FieldNormalizer.php
1 <?php
2
3 namespace Drupal\serialization\Normalizer;
4
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;
9
10 /**
11  * Denormalizes data to Drupal field values.
12  *
13  * This class simply calls denormalize() on the individual FieldItems. The
14  * FieldItem normalizers are responsible for setting the field values for each
15  * item.
16  *
17  * @see \Drupal\serialization\Normalizer\FieldItemNormalizer.
18  */
19 class FieldNormalizer extends ListNormalizer implements DenormalizerInterface {
20
21   /**
22    * {@inheritdoc}
23    */
24   protected $supportedInterfaceOrClass = FieldItemListInterface::class;
25
26   /**
27    * {@inheritdoc}
28    */
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');
32     }
33
34     if ($context['target_instance']->getParent() == NULL) {
35       throw new InvalidArgumentException('The field passed in via $context[\'target_instance\'] must have a parent set.');
36     }
37
38     /** @var FieldItemListInterface $items */
39     $items = $context['target_instance'];
40     $item_class = $items->getItemDefinition()->getClass();
41
42     if (!is_array($data)) {
43       throw new UnexpectedValueException(sprintf('Field values for "%s" must use an array structure', $items->getName()));
44     }
45
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
49       // was called.
50       // @see \Drupal\serialization\Normalizer\ContentEntityNormalizer::denormalize().
51       $context['target_instance'] = $items->appendItem();
52       $this->serializer->denormalize($item_data, $item_class, $format, $context);
53     }
54     return $items;
55   }
56
57 }