webapp_json-8.x-1.0-beta3/src/Normalizer/ContentEntityNormalizer.php
src/Normalizer/ContentEntityNormalizer.php
<?php
namespace Drupal\webapp\Normalizer;
use Drupal;
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\webapp\Helpers\MenuLoader;
use Drupal\serialization\Normalizer\FieldableEntityNormalizerTrait;
use Symfony\Component\Serializer\Exception\UnexpectedValueException;
/**
* Converts the Drupal entity object structure to a WEBAPP array structure.
*/
class ContentEntityNormalizer extends NormalizerBase {
use FieldableEntityNormalizerTrait;
use DeprecatedServicePropertyTrait;
/**
* {@inheritdoc}
*/
protected $deprecatedProperties = ['entityManager' => 'entity.manager'];
/**
* {@inheritdoc}
*/
protected $supportedInterfaceOrClass = ContentEntityInterface::class;
/**
* The module handler.
*
* @var \Drupal\Core\Extension\ModuleHandlerInterface
*/
protected $moduleHandler;
/**
* The menu loader.
*
* @var \Drupal\webapp\Helpers\MenuLoader
*/
protected $menuLoader;
/**
* Constructs an ContentEntityNormalizer object.
*
* @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
* The entity type manager.
* @param \Drupal\Core\Extension\ModuleHandlerInterface $module_handler
* The module handler.
* @param \Drupal\Core\Entity\EntityTypeRepositoryInterface $entity_type_repository
* The entity type repository.
* @param \Drupal\Core\Entity\EntityFieldManagerInterface $entity_field_manager
* The entity field manager.
* @param \Drupal\webapp\Helpers\MenuLoader $menu_loader
* The entity field manager.
*/
public function __construct(EntityTypeManagerInterface $entity_type_manager, ModuleHandlerInterface $module_handler, EntityTypeRepositoryInterface $entity_type_repository = NULL, EntityFieldManagerInterface $entity_field_manager = NULL, MenuLoader $menu_loader = NULL) {
$this->entityTypeManager = $entity_type_manager;
$this->moduleHandler = $module_handler;
$this->entityTypeRepository = $entity_type_repository;
$this->menuLoader = $menu_loader;
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;
}
/**
* {@inheritdoc}
*/
public function normalize($entity, $format = NULL, array $context = []) {
$context += [
'account' => NULL,
'included_fields' => NULL,
'excluded_fields' => [
'uuid',
'vid',
'revision_timestamp',
'created',
//'changed',
'default_langcode',
'revision_id',
'parent_id',
'parent_type',
'behaviour_settings',
'behavior_settings',
'revision_translation_affected',
'revision_created',
'content_translation_source',
'content_translation_outdated'
],
];
// To store normalized content.
/** @var $entity \Drupal\Core\Entity\ContentEntityInterface */
$normalized = [];
// add webapp version only to nodes
$entityTypeId = $entity->getEntityTypeId();
if ($entityTypeId === 'node') {
$normalized['webapp_version'] = 1;
$normalized['menus'] = $this->menuLoader->getMenuTree();
}
$field_items = TypedDataInternalPropertiesHelper::getNonInternalProperties($entity->getTypedData());
// Chose fields to output.
if (isset($context['included_fields'])) {
$field_items = array_intersect_key($field_items, array_flip($context['included_fields']));
}
// Chose fields to not output.
if (isset($context['excluded_fields'])) {
$field_items = array_diff_key($field_items, array_flip($context['excluded_fields']));
}
/** @var \Drupal\Core\Field\FieldItemList $field */
foreach ($field_items as $fieldKey => $field) {
// Continue if the current user does not have access to view this field.
if (!$field->access('view', $context['account'])) {
continue;
}
// Don't load the user related to the entity. That will cause loop loading.
if ($fieldKey === 'uid') {
continue;
}
$normalized_property = $this->serializer->normalize($field, $format, $context);
if (($field->getName() === 'changed') && ($entityTypeId === 'file')) {
if (is_array($normalized_property['changed'])) {
$normalized_property['date']['0']['value'] = date('d.m.Y', strtotime($normalized_property['changed']['0']['value']));
} else {
$normalized_property['date'] = date('d.m.Y', strtotime($normalized_property['changed']));
}
}
$normalized = NestedArray::mergeDeep($normalized, $normalized_property);
}
// add fields for taxonomy pages
if (false && ($entityTypeId === 'taxonomy_term')) {
$term_id = $entity->id();
$term_vid = $entity->getVocabularyId();
$nodes = \Drupal::entityTypeManager()->getStorage('node')->loadByProperties([
'field_' . $term_vid => $term_id,
]);
$taxNodes = [];
foreach ($nodes as $nodeItem) {
$nodeUrl = $nodeItem->toUrl()->toString();
$taxNodes[] = [
'id' => $nodeItem->id(),
'type' => $nodeItem->getType(),
'title' => $nodeItem->getTitle(),
'url' => $nodeUrl
];
}
$normalized['nodes'] = $taxNodes;
}
return $normalized;
}
/**
* Implements
* \Symfony\Component\Serializer\Normalizer\DenormalizerInterface::denormalize().
*
* @param array $data
* Entity data to restore.
* @param string $class
* Unused, entity_create() is used to instantiate entity objects.
* @param string $format
* Format the given data was extracted from.
* @param array $context
* Options available to the denormalizer. Keys that can be used:
* - request_method: if set to "patch" the denormalization will clear out
* all default values for entity fields before applying $data to the
* entity.
*
* @return \Drupal\Core\Entity\EntityInterface
* An unserialized entity object containing the data in $data.
*
* @throws \Symfony\Component\Serializer\Exception\UnexpectedValueException
*/
public function denormalize($data, $class, $format = NULL, array $context = []) {
// Get type, necessary for determining which bundle to create.
if (!isset($data['_links']['type'])) {
throw new UnexpectedValueException('The type link relation must be specified.');
}
// Create the entity.
$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 = [];
// Figure out the language to use.
if (isset($data[$default_langcode_key])) {
// Find the field item for which the default_langcode value is set to 1 and
// set the langcode the right default language.
foreach ($data[$default_langcode_key] as $item) {
if (!empty($item['value']) && isset($item['lang'])) {
$values[$langcode_key] = $item['lang'];
break;
}
}
// Remove the default langcode so it does not get iterated over below.
unset($data[$default_langcode_key]);
}
if ($entity_type->hasKey('bundle')) {
$bundle_key = $entity_type->getKey('bundle');
$values[$bundle_key] = $typed_data_ids['bundle'];
// Unset the bundle key from data, if it's there.
unset($data[$bundle_key]);
}
$entity = $this->entityTypeManager->getStorage($typed_data_ids['entity_type'])->create($values);
// Remove links from data array.
unset($data['_links']);
// Get embedded resources and remove from data array.
$embedded = [];
if (isset($data['_embedded'])) {
$embedded = $data['_embedded'];
unset($data['_embedded']);
}
// Flatten the embedded values.
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;
}
/**
* Constructs the entity URI.
*
* @param \Drupal\Core\Entity\EntityInterface $entity
* The entity.
* @param array $context
* Normalization/serialization context.
*
* @return string
* The entity URI.
*/
protected function getEntityUri(EntityInterface $entity, array $context = []) {
// Some entity types don't provide a canonical link template.
if ($entity->isNew() || !$entity->hasLinkTemplate('canonical')) {
return '';
}
$url = $entity->toUrl('canonical', ['absolute' => TRUE]);
if (!$url->isExternal()) {
$url->setRouteParameter('_format', 'webapp_json');
}
$generated_url = $url->toString(TRUE);
$this->addCacheableDependency($context, $generated_url);
return $generated_url->getGeneratedUrl();
}
/**
* Gets the typed data IDs for a type URI.
*
* @param array $types
* The type array(s) (value of the 'type' attribute of the incoming data).
* @param array $context
* Context from the normalizer/serializer operation.
*
* @return array
* The typed data IDs.
*/
protected function getTypedDataIds($types, $context = []) {
// The 'type' can potentially contain an array of type objects. By default,
// Drupal only uses a single type in serializing, but allows for multiple
// types when deserializing.
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'];
// Check whether the URI corresponds to a known type on this site. Break
// once one does.
if ($typed_data_ids = $this->linkManager->getTypeInternalIds($type['href'], $context)) {
break;
}
}
// If none of the URIs correspond to an entity type on this site, no entity
// can be created. Throw an exception.
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;
}
}
