Version 1
[yaffs-website] / web / core / modules / serialization / src / Normalizer / EntityNormalizer.php
1 <?php
2
3 namespace Drupal\serialization\Normalizer;
4
5 use Drupal\Core\Entity\EntityInterface;
6 use Drupal\Core\Entity\EntityManagerInterface;
7 use Drupal\Core\Entity\FieldableEntityInterface;
8 use Symfony\Component\Serializer\Normalizer\DenormalizerInterface;
9
10 /**
11  * Normalizes/denormalizes Drupal entity objects into an array structure.
12  */
13 class EntityNormalizer extends ComplexDataNormalizer implements DenormalizerInterface {
14
15   use FieldableEntityNormalizerTrait;
16
17   /**
18    * The interface or class that this Normalizer supports.
19    *
20    * @var array
21    */
22   protected $supportedInterfaceOrClass = [EntityInterface::class];
23
24   /**
25    * Constructs an EntityNormalizer object.
26    *
27    * @param \Drupal\Core\Entity\EntityManagerInterface $entity_manager
28    *   The entity manager.
29    */
30   public function __construct(EntityManagerInterface $entity_manager) {
31     $this->entityManager = $entity_manager;
32   }
33
34   /**
35    * {@inheritdoc}
36    */
37   public function denormalize($data, $class, $format = NULL, array $context = []) {
38     $entity_type_id = $this->determineEntityTypeId($class, $context);
39     $entity_type_definition = $this->getEntityTypeDefinition($entity_type_id);
40
41     // The bundle property will be required to denormalize a bundleable
42     // fieldable entity.
43     if ($entity_type_definition->hasKey('bundle') && $entity_type_definition->isSubclassOf(FieldableEntityInterface::class)) {
44       // Get an array containing the bundle only. This also remove the bundle
45       // key from the $data array.
46       $bundle_data = $this->extractBundleData($data, $entity_type_definition);
47
48       // Create the entity from bundle data only, then apply field values after.
49       $entity = $this->entityManager->getStorage($entity_type_id)->create($bundle_data);
50
51       $this->denormalizeFieldData($data, $entity, $format, $context);
52     }
53     else {
54       // Create the entity from all data.
55       $entity = $this->entityManager->getStorage($entity_type_id)->create($data);
56     }
57
58     // Pass the names of the fields whose values can be merged.
59     // @todo https://www.drupal.org/node/2456257 remove this.
60     $entity->_restSubmittedFields = array_keys($data);
61
62     return $entity;
63   }
64
65 }