Move into nested docroot
This commit is contained in:
parent
83a0d3a149
commit
c8b70abde9
13405 changed files with 0 additions and 0 deletions
35
web/core/modules/hal/src/Encoder/JsonEncoder.php
Normal file
35
web/core/modules/hal/src/Encoder/JsonEncoder.php
Normal file
|
@ -0,0 +1,35 @@
|
|||
<?php
|
||||
|
||||
namespace Drupal\hal\Encoder;
|
||||
|
||||
use Symfony\Component\Serializer\Encoder\JsonEncoder as SymfonyJsonEncoder;
|
||||
|
||||
/**
|
||||
* Encodes HAL data in JSON.
|
||||
*
|
||||
* Simply respond to hal_json format requests using the JSON encoder.
|
||||
*/
|
||||
class JsonEncoder extends SymfonyJsonEncoder {
|
||||
|
||||
/**
|
||||
* The formats that this Encoder supports.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
protected $format = 'hal_json';
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function supportsEncoding($format) {
|
||||
return $format == $this->format;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function supportsDecoding($format) {
|
||||
return $format == $this->format;
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,19 @@
|
|||
<?php
|
||||
|
||||
namespace Drupal\hal\EventSubscriber;
|
||||
|
||||
use Drupal\Core\EventSubscriber\ExceptionJsonSubscriber;
|
||||
|
||||
/**
|
||||
* Handle HAL JSON exceptions the same as JSON exceptions.
|
||||
*/
|
||||
class ExceptionHalJsonSubscriber extends ExceptionJsonSubscriber {
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
protected function getHandledFormats() {
|
||||
return ['hal_json'];
|
||||
}
|
||||
|
||||
}
|
22
web/core/modules/hal/src/HalServiceProvider.php
Normal file
22
web/core/modules/hal/src/HalServiceProvider.php
Normal file
|
@ -0,0 +1,22 @@
|
|||
<?php
|
||||
|
||||
namespace Drupal\hal;
|
||||
|
||||
use Drupal\Core\DependencyInjection\ContainerBuilder;
|
||||
use Drupal\Core\DependencyInjection\ServiceModifierInterface;
|
||||
|
||||
/**
|
||||
* Adds hal+json as known format.
|
||||
*/
|
||||
class HalServiceProvider implements ServiceModifierInterface {
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function alter(ContainerBuilder $container) {
|
||||
if ($container->has('http_middleware.negotiation') && is_a($container->getDefinition('http_middleware.negotiation')->getClass(), '\Drupal\Core\StackMiddleware\NegotiationMiddleware', TRUE)) {
|
||||
$container->getDefinition('http_middleware.negotiation')->addMethodCall('registerFormat', ['hal_json', ['application/hal+json']]);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
262
web/core/modules/hal/src/Normalizer/ContentEntityNormalizer.php
Normal file
262
web/core/modules/hal/src/Normalizer/ContentEntityNormalizer.php
Normal file
|
@ -0,0 +1,262 @@
|
|||
<?php
|
||||
|
||||
namespace Drupal\hal\Normalizer;
|
||||
|
||||
use Drupal\Component\Utility\NestedArray;
|
||||
use Drupal\Core\Entity\EntityInterface;
|
||||
use Drupal\Core\Entity\EntityManagerInterface;
|
||||
use Drupal\Core\Extension\ModuleHandlerInterface;
|
||||
use Drupal\rest\LinkManager\LinkManagerInterface;
|
||||
use Symfony\Component\Serializer\Exception\UnexpectedValueException;
|
||||
|
||||
/**
|
||||
* Converts the Drupal entity object structure to a HAL array structure.
|
||||
*/
|
||||
class ContentEntityNormalizer extends NormalizerBase {
|
||||
|
||||
/**
|
||||
* The interface or class that this Normalizer supports.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
protected $supportedInterfaceOrClass = 'Drupal\Core\Entity\ContentEntityInterface';
|
||||
|
||||
/**
|
||||
* The hypermedia link manager.
|
||||
*
|
||||
* @var \Drupal\rest\LinkManager\LinkManagerInterface
|
||||
*/
|
||||
protected $linkManager;
|
||||
|
||||
/**
|
||||
* The entity manager.
|
||||
*
|
||||
* @var \Drupal\Core\Entity\EntityManagerInterface
|
||||
*/
|
||||
protected $entityManager;
|
||||
|
||||
/**
|
||||
* The module handler.
|
||||
*
|
||||
* @var \Drupal\Core\Extension\ModuleHandlerInterface
|
||||
*/
|
||||
protected $moduleHandler;
|
||||
|
||||
|
||||
/**
|
||||
* Constructs an ContentEntityNormalizer object.
|
||||
*
|
||||
* @param \Drupal\rest\LinkManager\LinkManagerInterface $link_manager
|
||||
* The hypermedia link manager.
|
||||
*/
|
||||
public function __construct(LinkManagerInterface $link_manager, EntityManagerInterface $entity_manager, ModuleHandlerInterface $module_handler) {
|
||||
$this->linkManager = $link_manager;
|
||||
$this->entityManager = $entity_manager;
|
||||
$this->moduleHandler = $module_handler;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function normalize($entity, $format = NULL, array $context = array()) {
|
||||
$context += array(
|
||||
'account' => NULL,
|
||||
'included_fields' => NULL,
|
||||
);
|
||||
|
||||
// Create the array of normalized fields, starting with the URI.
|
||||
/** @var $entity \Drupal\Core\Entity\ContentEntityInterface */
|
||||
$normalized = array(
|
||||
'_links' => array(
|
||||
'self' => array(
|
||||
'href' => $this->getEntityUri($entity),
|
||||
),
|
||||
'type' => array(
|
||||
'href' => $this->linkManager->getTypeUri($entity->getEntityTypeId(), $entity->bundle(), $context),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
// If the fields to use were specified, only output those field values.
|
||||
if (isset($context['included_fields'])) {
|
||||
$fields = array();
|
||||
foreach ($context['included_fields'] as $field_name) {
|
||||
$fields[] = $entity->get($field_name);
|
||||
}
|
||||
}
|
||||
else {
|
||||
$fields = $entity->getFields();
|
||||
}
|
||||
foreach ($fields as $field) {
|
||||
// Continue if the current user does not have access to view this field.
|
||||
if (!$field->access('view', $context['account'])) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$normalized_property = $this->serializer->normalize($field, $format, $context);
|
||||
$normalized = NestedArray::mergeDeep($normalized, $normalized_property);
|
||||
}
|
||||
|
||||
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 = array()) {
|
||||
// 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->entityManager->getDefinition($typed_data_ids['entity_type']);
|
||||
$default_langcode_key = $entity_type->getKey('default_langcode');
|
||||
$langcode_key = $entity_type->getKey('langcode');
|
||||
$values = array();
|
||||
|
||||
// Figure out the language to use.
|
||||
if (isset($data[$default_langcode_key])) {
|
||||
// Find the field item for which the default_lancode 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->entityManager->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 = array();
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
// Pass the names of the fields whose values can be merged.
|
||||
$entity->_restSubmittedFields = array_keys($data);
|
||||
|
||||
// Iterate through remaining items in data array. These should all
|
||||
// correspond to fields.
|
||||
foreach ($data as $field_name => $field_data) {
|
||||
$items = $entity->get($field_name);
|
||||
// Remove any values that were set as a part of entity creation (e.g
|
||||
// uuid). If the incoming field data is set to an empty array, this will
|
||||
// also have the effect of emptying the field in REST module.
|
||||
$items->setValue(array());
|
||||
if ($field_data) {
|
||||
// Denormalize the field data into the FieldItemList object.
|
||||
$context['target_instance'] = $items;
|
||||
$this->serializer->denormalize($field_data, get_class($items), $format, $context);
|
||||
}
|
||||
}
|
||||
|
||||
return $entity;
|
||||
}
|
||||
|
||||
/**
|
||||
* Constructs the entity URI.
|
||||
*
|
||||
* @param \Drupal\Core\Entity\EntityInterface $entity
|
||||
* The entity.
|
||||
* @return string
|
||||
* The entity URI.
|
||||
*/
|
||||
protected function getEntityUri(EntityInterface $entity) {
|
||||
// Some entity types don't provide a canonical link template, at least call
|
||||
// out to ->url().
|
||||
if ($entity->isNew() || !$entity->hasLinkTemplate('canonical')) {
|
||||
return $entity->url('canonical', []);
|
||||
}
|
||||
$url = $entity->urlInfo('canonical', ['absolute' => TRUE]);
|
||||
return $url->setRouteParameter('_format', 'hal_json')->toString();
|
||||
}
|
||||
|
||||
/**
|
||||
* 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 = array()) {
|
||||
// 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 = array($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;
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,122 @@
|
|||
<?php
|
||||
|
||||
namespace Drupal\hal\Normalizer;
|
||||
|
||||
use Drupal\Core\Entity\FieldableEntityInterface;
|
||||
use Drupal\rest\LinkManager\LinkManagerInterface;
|
||||
use Drupal\serialization\EntityResolver\EntityResolverInterface;
|
||||
use Drupal\serialization\EntityResolver\UuidReferenceInterface;
|
||||
|
||||
/**
|
||||
* Converts the Drupal entity reference item object to HAL array structure.
|
||||
*/
|
||||
class EntityReferenceItemNormalizer extends FieldItemNormalizer implements UuidReferenceInterface {
|
||||
|
||||
/**
|
||||
* The interface or class that this Normalizer supports.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
protected $supportedInterfaceOrClass = 'Drupal\Core\Field\Plugin\Field\FieldType\EntityReferenceItem';
|
||||
|
||||
/**
|
||||
* The hypermedia link manager.
|
||||
*
|
||||
* @var \Drupal\rest\LinkManager\LinkManagerInterface
|
||||
*/
|
||||
protected $linkManager;
|
||||
|
||||
/**
|
||||
* The entity resolver.
|
||||
*
|
||||
* @var \Drupal\serialization\EntityResolver\EntityResolverInterface
|
||||
*/
|
||||
protected $entityResolver;
|
||||
|
||||
/**
|
||||
* Constructs an EntityReferenceItemNormalizer object.
|
||||
*
|
||||
* @param \Drupal\rest\LinkManager\LinkManagerInterface $link_manager
|
||||
* The hypermedia link manager.
|
||||
* @param \Drupal\serialization\EntityResolver\EntityResolverInterface $entity_Resolver
|
||||
* The entity resolver.
|
||||
*/
|
||||
public function __construct(LinkManagerInterface $link_manager, EntityResolverInterface $entity_Resolver) {
|
||||
$this->linkManager = $link_manager;
|
||||
$this->entityResolver = $entity_Resolver;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function normalize($field_item, $format = NULL, array $context = array()) {
|
||||
/** @var $field_item \Drupal\Core\Field\FieldItemInterface */
|
||||
$target_entity = $field_item->get('entity')->getValue();
|
||||
|
||||
// If this is not a content entity, let the parent implementation handle it,
|
||||
// only content entities are supported as embedded resources.
|
||||
if (!($target_entity instanceof FieldableEntityInterface)) {
|
||||
return parent::normalize($field_item, $format, $context);
|
||||
}
|
||||
|
||||
// If the parent entity passed in a langcode, unset it before normalizing
|
||||
// the target entity. Otherwise, untranslatable fields of the target entity
|
||||
// will include the langcode.
|
||||
$langcode = isset($context['langcode']) ? $context['langcode'] : NULL;
|
||||
unset($context['langcode']);
|
||||
$context['included_fields'] = array('uuid');
|
||||
|
||||
// Normalize the target entity.
|
||||
$embedded = $this->serializer->normalize($target_entity, $format, $context);
|
||||
$link = $embedded['_links']['self'];
|
||||
// If the field is translatable, add the langcode to the link relation
|
||||
// object. This does not indicate the language of the target entity.
|
||||
if ($langcode) {
|
||||
$embedded['lang'] = $link['lang'] = $langcode;
|
||||
}
|
||||
|
||||
// The returned structure will be recursively merged into the normalized
|
||||
// entity so that the items are properly added to the _links and _embedded
|
||||
// objects.
|
||||
$field_name = $field_item->getParent()->getName();
|
||||
$entity = $field_item->getEntity();
|
||||
$field_uri = $this->linkManager->getRelationUri($entity->getEntityTypeId(), $entity->bundle(), $field_name, $context);
|
||||
return array(
|
||||
'_links' => array(
|
||||
$field_uri => array($link),
|
||||
),
|
||||
'_embedded' => array(
|
||||
$field_uri => array($embedded),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
protected function constructValue($data, $context) {
|
||||
$field_item = $context['target_instance'];
|
||||
$field_definition = $field_item->getFieldDefinition();
|
||||
$target_type = $field_definition->getSetting('target_type');
|
||||
$id = $this->entityResolver->resolve($this, $data, $target_type);
|
||||
if (isset($id)) {
|
||||
return array('target_id' => $id);
|
||||
}
|
||||
return NULL;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function getUuid($data) {
|
||||
if (isset($data['uuid'])) {
|
||||
$uuid = $data['uuid'];
|
||||
// The value may be a nested array like $uuid[0]['value'].
|
||||
if (is_array($uuid) && isset($uuid[0]['value'])) {
|
||||
$uuid = $uuid[0]['value'];
|
||||
}
|
||||
return $uuid;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
111
web/core/modules/hal/src/Normalizer/FieldItemNormalizer.php
Normal file
111
web/core/modules/hal/src/Normalizer/FieldItemNormalizer.php
Normal file
|
@ -0,0 +1,111 @@
|
|||
<?php
|
||||
|
||||
namespace Drupal\hal\Normalizer;
|
||||
|
||||
use Drupal\Core\Field\FieldItemInterface;
|
||||
use Symfony\Component\Serializer\Exception\InvalidArgumentException;
|
||||
|
||||
/**
|
||||
* Converts the Drupal field item object structure to HAL array structure.
|
||||
*/
|
||||
class FieldItemNormalizer extends NormalizerBase {
|
||||
|
||||
/**
|
||||
* The interface or class that this Normalizer supports.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
protected $supportedInterfaceOrClass = 'Drupal\Core\Field\FieldItemInterface';
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function normalize($field_item, $format = NULL, array $context = array()) {
|
||||
$values = $field_item->toArray();
|
||||
if (isset($context['langcode'])) {
|
||||
$values['lang'] = $context['langcode'];
|
||||
}
|
||||
|
||||
// The values are wrapped in an array, and then wrapped in another array
|
||||
// keyed by field name so that field items can be merged by the
|
||||
// FieldNormalizer. This is necessary for the EntityReferenceItemNormalizer
|
||||
// to be able to place values in the '_links' array.
|
||||
$field = $field_item->getParent();
|
||||
return array(
|
||||
$field->getName() => array($values),
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function denormalize($data, $class, $format = NULL, array $context = array()) {
|
||||
if (!isset($context['target_instance'])) {
|
||||
throw new InvalidArgumentException('$context[\'target_instance\'] must be set to denormalize with the FieldItemNormalizer');
|
||||
}
|
||||
if ($context['target_instance']->getParent() == NULL) {
|
||||
throw new InvalidArgumentException('The field item passed in via $context[\'target_instance\'] must have a parent set.');
|
||||
}
|
||||
|
||||
$field_item = $context['target_instance'];
|
||||
|
||||
// If this field is translatable, we need to create a translated instance.
|
||||
if (isset($data['lang'])) {
|
||||
$langcode = $data['lang'];
|
||||
unset($data['lang']);
|
||||
$field_definition = $field_item->getFieldDefinition();
|
||||
if ($field_definition->isTranslatable()) {
|
||||
$field_item = $this->createTranslatedInstance($field_item, $langcode);
|
||||
}
|
||||
}
|
||||
|
||||
$field_item->setValue($this->constructValue($data, $context));
|
||||
return $field_item;
|
||||
}
|
||||
|
||||
/**
|
||||
* Build the field item value using the incoming data.
|
||||
*
|
||||
* @param $data
|
||||
* The incoming data for this field item.
|
||||
* @param $context
|
||||
* The context passed into the Normalizer.
|
||||
*
|
||||
* @return mixed
|
||||
* The value to use in Entity::setValue().
|
||||
*/
|
||||
protected function constructValue($data, $context) {
|
||||
return $data;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get a translated version of the field item instance.
|
||||
*
|
||||
* To indicate that a field item applies to one translation of an entity and
|
||||
* not another, the property path must originate with a translation of the
|
||||
* entity. This is the reason for using target_instances, from which the
|
||||
* property path can be traversed up to the root.
|
||||
*
|
||||
* @param \Drupal\Core\Field\FieldItemInterface $field_item
|
||||
* The untranslated field item instance.
|
||||
* @param $langcode
|
||||
* The langcode.
|
||||
*
|
||||
* @return \Drupal\Core\Field\FieldItemInterface
|
||||
* The translated field item instance.
|
||||
*/
|
||||
protected function createTranslatedInstance(FieldItemInterface $item, $langcode) {
|
||||
// Remove the untranslated item that was created for the default language
|
||||
// by FieldNormalizer::denormalize().
|
||||
$items = $item->getParent();
|
||||
$delta = $item->getName();
|
||||
unset($items[$delta]);
|
||||
|
||||
// Instead, create a new item for the entity in the requested language.
|
||||
$entity = $item->getEntity();
|
||||
$entity_translation = $entity->hasTranslation($langcode) ? $entity->getTranslation($langcode) : $entity->addTranslation($langcode);
|
||||
$field_name = $item->getFieldDefinition()->getName();
|
||||
return $entity_translation->get($field_name)->appendItem();
|
||||
}
|
||||
|
||||
}
|
104
web/core/modules/hal/src/Normalizer/FieldNormalizer.php
Normal file
104
web/core/modules/hal/src/Normalizer/FieldNormalizer.php
Normal file
|
@ -0,0 +1,104 @@
|
|||
<?php
|
||||
|
||||
namespace Drupal\hal\Normalizer;
|
||||
|
||||
use Drupal\Component\Utility\NestedArray;
|
||||
use Symfony\Component\Serializer\Exception\InvalidArgumentException;
|
||||
|
||||
/**
|
||||
* Converts the Drupal field structure to HAL array structure.
|
||||
*/
|
||||
class FieldNormalizer extends NormalizerBase {
|
||||
|
||||
/**
|
||||
* The interface or class that this Normalizer supports.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
protected $supportedInterfaceOrClass = 'Drupal\Core\Field\FieldItemListInterface';
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function normalize($field, $format = NULL, array $context = array()) {
|
||||
$normalized_field_items = array();
|
||||
|
||||
// Get the field definition.
|
||||
$entity = $field->getEntity();
|
||||
$field_name = $field->getName();
|
||||
$field_definition = $field->getFieldDefinition();
|
||||
|
||||
// If this field is not translatable, it can simply be normalized without
|
||||
// separating it into different translations.
|
||||
if (!$field_definition->isTranslatable()) {
|
||||
$normalized_field_items = $this->normalizeFieldItems($field, $format, $context);
|
||||
}
|
||||
// Otherwise, the languages have to be extracted from the entity and passed
|
||||
// in to the field item normalizer in the context. The langcode is appended
|
||||
// to the field item values.
|
||||
else {
|
||||
foreach ($entity->getTranslationLanguages() as $language) {
|
||||
$context['langcode'] = $language->getId();
|
||||
$translation = $entity->getTranslation($language->getId());
|
||||
$translated_field = $translation->get($field_name);
|
||||
$normalized_field_items = array_merge($normalized_field_items, $this->normalizeFieldItems($translated_field, $format, $context));
|
||||
}
|
||||
}
|
||||
|
||||
// Merge deep so that links set in entity reference normalizers are merged
|
||||
// into the links property.
|
||||
$normalized = NestedArray::mergeDeepArray($normalized_field_items);
|
||||
return $normalized;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function denormalize($data, $class, $format = NULL, array $context = array()) {
|
||||
if (!isset($context['target_instance'])) {
|
||||
throw new InvalidArgumentException('$context[\'target_instance\'] must be set to denormalize with the FieldNormalizer');
|
||||
}
|
||||
if ($context['target_instance']->getParent() == NULL) {
|
||||
throw new InvalidArgumentException('The field passed in via $context[\'target_instance\'] must have a parent set.');
|
||||
}
|
||||
|
||||
$items = $context['target_instance'];
|
||||
$item_class = $items->getItemDefinition()->getClass();
|
||||
foreach ($data as $item_data) {
|
||||
// Create a new item and pass it as the target for the unserialization of
|
||||
// $item_data. Note: if $item_data is about a different language than the
|
||||
// default, FieldItemNormalizer::denormalize() will dismiss this item and
|
||||
// create a new one for the right language.
|
||||
$context['target_instance'] = $items->appendItem();
|
||||
$this->serializer->denormalize($item_data, $item_class, $format, $context);
|
||||
}
|
||||
|
||||
return $items;
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Helper function to normalize field items.
|
||||
*
|
||||
* @param \Drupal\Core\Field\FieldItemListInterface $field
|
||||
* The field object.
|
||||
* @param string $format
|
||||
* The format.
|
||||
* @param array $context
|
||||
* The context array.
|
||||
*
|
||||
* @return array
|
||||
* The array of normalized field items.
|
||||
*/
|
||||
protected function normalizeFieldItems($field, $format, $context) {
|
||||
$normalized_field_items = array();
|
||||
if (!$field->isEmpty()) {
|
||||
foreach ($field as $field_item) {
|
||||
$normalized_field_items[] = $this->serializer->normalize($field_item, $format, $context);
|
||||
}
|
||||
}
|
||||
return $normalized_field_items;
|
||||
}
|
||||
|
||||
}
|
70
web/core/modules/hal/src/Normalizer/FileEntityNormalizer.php
Normal file
70
web/core/modules/hal/src/Normalizer/FileEntityNormalizer.php
Normal file
|
@ -0,0 +1,70 @@
|
|||
<?php
|
||||
|
||||
namespace Drupal\hal\Normalizer;
|
||||
|
||||
use Drupal\Core\Entity\EntityManagerInterface;
|
||||
use Drupal\Core\Extension\ModuleHandlerInterface;
|
||||
use Drupal\rest\LinkManager\LinkManagerInterface;
|
||||
use GuzzleHttp\ClientInterface;
|
||||
|
||||
/**
|
||||
* Converts the Drupal entity object structure to a HAL array structure.
|
||||
*/
|
||||
class FileEntityNormalizer extends ContentEntityNormalizer {
|
||||
|
||||
/**
|
||||
* The interface or class that this Normalizer supports.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
protected $supportedInterfaceOrClass = 'Drupal\file\FileInterface';
|
||||
|
||||
/**
|
||||
* The HTTP client.
|
||||
*
|
||||
* @var \GuzzleHttp\ClientInterface
|
||||
*/
|
||||
protected $httpClient;
|
||||
|
||||
/**
|
||||
* Constructs a FileEntityNormalizer object.
|
||||
*
|
||||
* @param \Drupal\Core\Entity\EntityManagerInterface $entity_manager
|
||||
* The entity manager.
|
||||
* @param \GuzzleHttp\ClientInterface $http_client
|
||||
* The HTTP Client.
|
||||
* @param \Drupal\rest\LinkManager\LinkManagerInterface $link_manager
|
||||
* The hypermedia link manager.
|
||||
* @param \Drupal\Core\Extension\ModuleHandlerInterface $module_handler
|
||||
* The module handler.
|
||||
*/
|
||||
public function __construct(EntityManagerInterface $entity_manager, ClientInterface $http_client, LinkManagerInterface $link_manager, ModuleHandlerInterface $module_handler) {
|
||||
parent::__construct($link_manager, $entity_manager, $module_handler);
|
||||
|
||||
$this->httpClient = $http_client;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function normalize($entity, $format = NULL, array $context = array()) {
|
||||
$data = parent::normalize($entity, $format, $context);
|
||||
// Replace the file url with a full url for the file.
|
||||
$data['uri'][0]['value'] = $this->getEntityUri($entity);
|
||||
|
||||
return $data;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function denormalize($data, $class, $format = NULL, array $context = array()) {
|
||||
$file_data = (string) $this->httpClient->get($data['uri'][0]['value'])->getBody();
|
||||
|
||||
$path = 'temporary://' . drupal_basename($data['uri'][0]['value']);
|
||||
$data['uri'] = file_unmanaged_save_data($file_data, $path);
|
||||
|
||||
return $this->entityManager->getStorage('file')->create($data);
|
||||
}
|
||||
|
||||
}
|
45
web/core/modules/hal/src/Normalizer/NormalizerBase.php
Normal file
45
web/core/modules/hal/src/Normalizer/NormalizerBase.php
Normal file
|
@ -0,0 +1,45 @@
|
|||
<?php
|
||||
|
||||
namespace Drupal\hal\Normalizer;
|
||||
|
||||
use Drupal\serialization\Normalizer\NormalizerBase as SerializationNormalizerBase;
|
||||
use Symfony\Component\Serializer\Normalizer\DenormalizerInterface;
|
||||
|
||||
/**
|
||||
* Base class for Normalizers.
|
||||
*/
|
||||
abstract class NormalizerBase extends SerializationNormalizerBase implements DenormalizerInterface {
|
||||
|
||||
/**
|
||||
* The formats that the Normalizer can handle.
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
protected $formats = array('hal_json');
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function supportsNormalization($data, $format = NULL) {
|
||||
return in_array($format, $this->formats) && parent::supportsNormalization($data, $format);
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function supportsDenormalization($data, $type, $format = NULL) {
|
||||
if (in_array($format, $this->formats) && (class_exists($this->supportedInterfaceOrClass) || interface_exists($this->supportedInterfaceOrClass))) {
|
||||
$target = new \ReflectionClass($type);
|
||||
$supported = new \ReflectionClass($this->supportedInterfaceOrClass);
|
||||
if ($supported->isInterface()) {
|
||||
return $target->implementsInterface($this->supportedInterfaceOrClass);
|
||||
}
|
||||
else {
|
||||
return ($target->getName() == $this->supportedInterfaceOrClass || $target->isSubclassOf($this->supportedInterfaceOrClass));
|
||||
}
|
||||
}
|
||||
|
||||
return FALSE;
|
||||
}
|
||||
|
||||
}
|
75
web/core/modules/hal/src/Tests/FileDenormalizeTest.php
Normal file
75
web/core/modules/hal/src/Tests/FileDenormalizeTest.php
Normal file
|
@ -0,0 +1,75 @@
|
|||
<?php
|
||||
|
||||
namespace Drupal\hal\Tests;
|
||||
|
||||
use Drupal\file\Entity\File;
|
||||
use Drupal\simpletest\WebTestBase;
|
||||
|
||||
/**
|
||||
* Tests that file entities can be denormalized in HAL.
|
||||
*
|
||||
* @group hal
|
||||
* @see \Drupal\hal\Normalizer\FileEntityNormalizer
|
||||
*/
|
||||
class FileDenormalizeTest extends WebTestBase {
|
||||
|
||||
/**
|
||||
* Modules to enable.
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
public static $modules = array('hal', 'file', 'node');
|
||||
|
||||
/**
|
||||
* Tests file entity denormalization.
|
||||
*/
|
||||
public function testFileDenormalize() {
|
||||
$file_params = array(
|
||||
'filename' => 'test_1.txt',
|
||||
'uri' => 'public://test_1.txt',
|
||||
'filemime' => 'text/plain',
|
||||
'status' => FILE_STATUS_PERMANENT,
|
||||
);
|
||||
// Create a new file entity.
|
||||
$file = File::create($file_params);
|
||||
file_put_contents($file->getFileUri(), 'hello world');
|
||||
$file->save();
|
||||
|
||||
$serializer = \Drupal::service('serializer');
|
||||
$normalized_data = $serializer->normalize($file, 'hal_json');
|
||||
$denormalized = $serializer->denormalize($normalized_data, 'Drupal\file\Entity\File', 'hal_json');
|
||||
|
||||
$this->assertTrue($denormalized instanceof File, 'A File instance was created.');
|
||||
|
||||
$this->assertIdentical('temporary://' . $file->getFilename(), $denormalized->getFileUri(), 'The expected file URI was found.');
|
||||
$this->assertTrue(file_exists($denormalized->getFileUri()), 'The temporary file was found.');
|
||||
|
||||
$this->assertIdentical($file->uuid(), $denormalized->uuid(), 'The expected UUID was found');
|
||||
$this->assertIdentical($file->getMimeType(), $denormalized->getMimeType(), 'The expected MIME type was found.');
|
||||
$this->assertIdentical($file->getFilename(), $denormalized->getFilename(), 'The expected filename was found.');
|
||||
$this->assertTrue($denormalized->isPermanent(), 'The file has a permanent status.');
|
||||
|
||||
// Try to denormalize with the file uri only.
|
||||
$file_name = 'test_2.txt';
|
||||
$file_path = 'public://' . $file_name;
|
||||
|
||||
file_put_contents($file_path, 'hello world');
|
||||
$file_uri = file_create_url($file_path);
|
||||
|
||||
$data = array(
|
||||
'uri' => array(
|
||||
array('value' => $file_uri),
|
||||
),
|
||||
);
|
||||
|
||||
$denormalized = $serializer->denormalize($data, 'Drupal\file\Entity\File', 'hal_json');
|
||||
|
||||
$this->assertIdentical('temporary://' . $file_name, $denormalized->getFileUri(), 'The expected file URI was found.');
|
||||
$this->assertTrue(file_exists($denormalized->getFileUri()), 'The temporary file was found.');
|
||||
|
||||
$this->assertIdentical('text/plain', $denormalized->getMimeType(), 'The expected MIME type was found.');
|
||||
$this->assertIdentical($file_name, $denormalized->getFilename(), 'The expected filename was found.');
|
||||
$this->assertFalse($denormalized->isPermanent(), 'The file has a permanent status.');
|
||||
}
|
||||
|
||||
}
|
Reference in a new issue