View source
<?php
namespace Drupal\hal\Normalizer;
use Drupal\Component\Utility\NestedArray;
use Drupal\Core\Entity\ContentEntityInterface;
use Drupal\Core\DependencyInjection\DeprecatedServicePropertyTrait;
use Drupal\Core\Entity\EntityFieldManagerInterface;
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Entity\EntityTypeRepositoryInterface;
use Drupal\Core\Extension\ModuleHandlerInterface;
use Drupal\Core\TypedData\TypedDataInternalPropertiesHelper;
use Drupal\Core\Url;
use Drupal\hal\LinkManager\LinkManagerInterface;
use Drupal\serialization\Normalizer\FieldableEntityNormalizerTrait;
use Symfony\Component\Serializer\Exception\UnexpectedValueException;
class ContentEntityNormalizer extends NormalizerBase {
use FieldableEntityNormalizerTrait;
use DeprecatedServicePropertyTrait;
protected $deprecatedProperties = [
'entityManager' => 'entity.manager',
];
protected $supportedInterfaceOrClass = ContentEntityInterface::class;
protected $linkManager;
protected $moduleHandler;
public function __construct(LinkManagerInterface $link_manager, EntityTypeManagerInterface $entity_type_manager, ModuleHandlerInterface $module_handler, EntityTypeRepositoryInterface $entity_type_repository = NULL, EntityFieldManagerInterface $entity_field_manager = NULL) {
$this->linkManager = $link_manager;
$this->entityTypeManager = $entity_type_manager;
$this->moduleHandler = $module_handler;
$this->entityTypeRepository = $entity_type_repository;
if (!$entity_type_repository) {
@trigger_error('The entity_type.repository service must be passed to ContentEntityNormalizer::__construct(), it is required before Drupal 9.0.0. See https://www.drupal.org/node/2549139.', E_USER_DEPRECATED);
$entity_type_repository = \Drupal::service('entity_type.repository');
}
$this->entityTypeRepository = $entity_type_repository;
if (!$entity_field_manager) {
@trigger_error('The entity_field.manager service must be passed to ContentEntityNormalizer::__construct(), it is required before Drupal 9.0.0. See https://www.drupal.org/node/2549139.', E_USER_DEPRECATED);
$entity_field_manager = \Drupal::service('entity_field.manager');
}
$this->entityFieldManager = $entity_field_manager;
}
public function normalize($entity, $format = NULL, array $context = []) {
$context += [
'account' => NULL,
'included_fields' => NULL,
];
$normalized = [
'_links' => [
'self' => [
'href' => $this
->getEntityUri($entity),
],
'type' => [
'href' => $this->linkManager
->getTypeUri($entity
->getEntityTypeId(), $entity
->bundle(), $context),
],
],
];
$field_items = TypedDataInternalPropertiesHelper::getNonInternalProperties($entity
->getTypedData());
if (isset($context['included_fields'])) {
$field_items = array_intersect_key($field_items, array_flip($context['included_fields']));
}
foreach ($field_items as $field) {
if (!$field
->access('view', $context['account'])) {
continue;
}
$normalized_property = $this->serializer
->normalize($field, $format, $context);
$normalized = NestedArray::mergeDeep($normalized, $normalized_property);
}
return $normalized;
}
public function denormalize($data, $class, $format = NULL, array $context = []) {
if (!isset($data['_links']['type'])) {
throw new UnexpectedValueException('The type link relation must be specified.');
}
$typed_data_ids = $this
->getTypedDataIds($data['_links']['type'], $context);
$entity_type = $this
->getEntityTypeDefinition($typed_data_ids['entity_type']);
$default_langcode_key = $entity_type
->getKey('default_langcode');
$langcode_key = $entity_type
->getKey('langcode');
$values = [];
if (isset($data[$default_langcode_key])) {
foreach ($data[$default_langcode_key] as $item) {
if (!empty($item['value']) && isset($item['lang'])) {
$values[$langcode_key] = $item['lang'];
break;
}
}
unset($data[$default_langcode_key]);
}
if ($entity_type
->hasKey('bundle')) {
$bundle_key = $entity_type
->getKey('bundle');
$values[$bundle_key] = $typed_data_ids['bundle'];
unset($data[$bundle_key]);
}
$entity = $this->entityTypeManager
->getStorage($typed_data_ids['entity_type'])
->create($values);
unset($data['_links']);
$embedded = [];
if (isset($data['_embedded'])) {
$embedded = $data['_embedded'];
unset($data['_embedded']);
}
foreach ($embedded as $relation => $field) {
$field_ids = $this->linkManager
->getRelationInternalIds($relation);
if (!empty($field_ids)) {
$field_name = $field_ids['field_name'];
$data[$field_name] = $field;
}
}
$this
->denormalizeFieldData($data, $entity, $format, $context);
$entity->_restSubmittedFields = array_keys($data);
return $entity;
}
protected function getEntityUri(EntityInterface $entity, array $context = []) {
if ($entity
->isNew()) {
return '';
}
$route_name = 'rest.entity.' . $entity
->getEntityTypeId() . '.GET';
if ($entity
->hasLinkTemplate('canonical')) {
$url = $entity
->toUrl('canonical');
}
elseif (\Drupal::service('router.route_provider')
->getRoutesByNames([
$route_name,
])) {
$url = Url::fromRoute('rest.entity.' . $entity
->getEntityTypeId() . '.GET', [
$entity
->getEntityTypeId() => $entity
->id(),
]);
}
else {
return '';
}
$url
->setAbsolute(TRUE);
if (!$url
->isExternal()) {
$url
->setRouteParameter('_format', 'hal_json');
}
$generated_url = $url
->toString(TRUE);
$this
->addCacheableDependency($context, $generated_url);
return $generated_url
->getGeneratedUrl();
}
protected function getTypedDataIds($types, $context = []) {
if (isset($types['href'])) {
$types = [
$types,
];
}
if (empty($types)) {
throw new UnexpectedValueException('No entity type(s) specified');
}
foreach ($types as $type) {
if (!isset($type['href'])) {
throw new UnexpectedValueException('Type must contain an \'href\' attribute.');
}
$type_uri = $type['href'];
if ($typed_data_ids = $this->linkManager
->getTypeInternalIds($type['href'], $context)) {
break;
}
}
if (empty($typed_data_ids)) {
throw new UnexpectedValueException(sprintf('Type %s does not correspond to an entity on this site.', $type_uri));
}
return $typed_data_ids;
}
}