3 namespace Drupal\serialization\Normalizer;
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;
11 * Normalizes/denormalizes Drupal entity objects into an array structure.
13 class EntityNormalizer extends ComplexDataNormalizer implements DenormalizerInterface {
15 use FieldableEntityNormalizerTrait;
18 * The interface or class that this Normalizer supports.
22 protected $supportedInterfaceOrClass = [EntityInterface::class];
25 * Constructs an EntityNormalizer object.
27 * @param \Drupal\Core\Entity\EntityManagerInterface $entity_manager
30 public function __construct(EntityManagerInterface $entity_manager) {
31 $this->entityManager = $entity_manager;
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);
41 // The bundle property will be required to denormalize a bundleable
43 if ($entity_type_definition->entityClassImplements(FieldableEntityInterface::class)) {
44 // Extract bundle data to pass into entity creation if the entity type uses
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);
55 // Create the entity from bundle data only, then apply field values after.
56 $entity = $this->entityManager->getStorage($entity_type_id)->create($create_params);
58 $this->denormalizeFieldData($data, $entity, $format, $context);
61 // Create the entity from all data.
62 $entity = $this->entityManager->getStorage($entity_type_id)->create($data);
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);