Updated Drupal to 8.6. This goes with the following updates because it's possible...
[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->entityClassImplements(FieldableEntityInterface::class)) {
44       // Extract bundle data to pass into entity creation if the entity type uses
45       // bundles.
46       if ($entity_type_definition->hasKey('bundle')) {
47         // Get an array containing the bundle only. This also remove the bundle
48         // key from the $data array.
49         $create_params = $this->extractBundleData($data, $entity_type_definition);
50       }
51       else {
52         $create_params = [];
53       }
54
55       // Create the entity from bundle data only, then apply field values after.
56       $entity = $this->entityManager->getStorage($entity_type_id)->create($create_params);
57
58       $this->denormalizeFieldData($data, $entity, $format, $context);
59     }
60     else {
61       // Create the entity from all data.
62       $entity = $this->entityManager->getStorage($entity_type_id)->create($data);
63     }
64
65     // Pass the names of the fields whose values can be merged.
66     // @todo https://www.drupal.org/node/2456257 remove this.
67     $entity->_restSubmittedFields = array_keys($data);
68
69     return $entity;
70   }
71
72 }