Version 1
[yaffs-website] / web / core / modules / serialization / src / Normalizer / FieldItemNormalizer.php
1 <?php
2
3 namespace Drupal\serialization\Normalizer;
4
5 use Drupal\Core\Field\FieldItemInterface;
6 use Symfony\Component\Serializer\Exception\InvalidArgumentException;
7 use Symfony\Component\Serializer\Normalizer\DenormalizerInterface;
8
9 /**
10  * Denormalizes field item object structure by updating the entity field values.
11  */
12 class FieldItemNormalizer extends ComplexDataNormalizer implements DenormalizerInterface {
13
14   /**
15    * {@inheritdoc}
16    */
17   protected $supportedInterfaceOrClass = FieldItemInterface::class;
18
19   /**
20    * {@inheritdoc}
21    */
22   public function denormalize($data, $class, $format = NULL, array $context = []) {
23     if (!isset($context['target_instance'])) {
24       throw new InvalidArgumentException('$context[\'target_instance\'] must be set to denormalize with the FieldItemNormalizer');
25     }
26
27     if ($context['target_instance']->getParent() == NULL) {
28       throw new InvalidArgumentException('The field item passed in via $context[\'target_instance\'] must have a parent set.');
29     }
30
31     /** @var \Drupal\Core\Field\FieldItemInterface $field_item */
32     $field_item = $context['target_instance'];
33
34     $field_item->setValue($this->constructValue($data, $context));
35     return $field_item;
36   }
37
38   /**
39    * Build the field item value using the incoming data.
40    *
41    * Most normalizers that extend this class can simply use this method to
42    * construct the denormalized value without having to override denormalize()
43    * and reimplementing its validation logic or its call to set the field value.
44    *
45    * @param mixed $data
46    *   The incoming data for this field item.
47    * @param array $context
48    *   The context passed into the Normalizer.
49    *
50    * @return mixed
51    *   The value to use in Entity::setValue().
52    */
53   protected function constructValue($data, $context) {
54     return $data;
55   }
56
57 }