EntityNormalizer.php in Zircon Profile 8
File
core/modules/serialization/src/Normalizer/EntityNormalizer.php
View source
<?php
namespace Drupal\serialization\Normalizer;
use Drupal\Core\Entity\EntityManagerInterface;
use Symfony\Component\Serializer\Exception\UnexpectedValueException;
use Symfony\Component\Serializer\Normalizer\DenormalizerInterface;
class EntityNormalizer extends ComplexDataNormalizer implements DenormalizerInterface {
protected $supportedInterfaceOrClass = array(
'Drupal\\Core\\Entity\\EntityInterface',
);
protected $entityManager;
public function __construct(EntityManagerInterface $entity_manager) {
$this->entityManager = $entity_manager;
}
public function denormalize($data, $class, $format = NULL, array $context = []) {
$entity_type_id = !empty($context['entity_type']) ? $context['entity_type'] : $this->entityManager
->getEntityTypeFromClass($class);
$entity_type_definition = $this->entityManager
->getDefinition($entity_type_id, FALSE);
if (!$entity_type_definition) {
throw new UnexpectedValueException(sprintf('The specified entity type "%s" does not exist. A valid etnity type is required for denormalization', $entity_type_id));
}
if ($entity_type_definition
->hasKey('bundle')) {
$bundle_key = $entity_type_definition
->getKey('bundle');
$base_field_definitions = $this->entityManager
->getBaseFieldDefinitions($entity_type_id);
$key_id = isset($base_field_definitions[$bundle_key]) ? $base_field_definitions[$bundle_key]
->getFieldStorageDefinition()
->getMainPropertyName() : 'value';
$data[$bundle_key] = isset($data[$bundle_key][0][$key_id]) ? $data[$bundle_key][0][$key_id] : (isset($data[$bundle_key]) ? $data[$bundle_key] : NULL);
$bundle_type_id = $entity_type_definition
->getBundleEntityType();
$bundle_types = $bundle_type_id ? $this->entityManager
->getStorage($bundle_type_id)
->getQuery()
->execute() : [];
if (!is_string($data[$bundle_key])) {
throw new UnexpectedValueException('A string must be provided as a bundle value.');
}
if ($bundle_types && !in_array($data[$bundle_key], $bundle_types)) {
throw new UnexpectedValueException(sprintf('"%s" is not a valid bundle type for denormalization.', $data[$bundle_key]));
}
}
$entity = $this->entityManager
->getStorage($entity_type_id)
->create($data);
$entity->_restSubmittedFields = array_keys($data);
return $entity;
}
}
Classes
Name |
Description |
EntityNormalizer |
Normalizes/denormalizes Drupal entity objects into an array structure. |