first commit
This commit is contained in:
@@ -0,0 +1,21 @@
|
||||
<?php
|
||||
|
||||
namespace Drupal\hal\Encoder;
|
||||
|
||||
use Drupal\serialization\Encoder\JsonEncoder as SerializationJsonEncoder;
|
||||
|
||||
/**
|
||||
* Encodes HAL data in JSON.
|
||||
*
|
||||
* Simply respond to hal_json format requests using the JSON encoder.
|
||||
*/
|
||||
class JsonEncoder extends SerializationJsonEncoder {
|
||||
|
||||
/**
|
||||
* The formats that this Encoder supports.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
protected static $format = ['hal_json'];
|
||||
|
||||
}
|
||||
@@ -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']]);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
<?php
|
||||
|
||||
namespace Drupal\hal\LinkManager;
|
||||
|
||||
/**
|
||||
* Defines an interface for a link manager with a configurable domain.
|
||||
*/
|
||||
interface ConfigurableLinkManagerInterface {
|
||||
|
||||
/**
|
||||
* Sets the link domain used in constructing link URIs.
|
||||
*
|
||||
* @param string $domain
|
||||
* The link domain to use for constructing link URIs.
|
||||
*
|
||||
* @return $this
|
||||
*/
|
||||
public function setLinkDomain($domain);
|
||||
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
<?php
|
||||
|
||||
namespace Drupal\hal\LinkManager;
|
||||
|
||||
class LinkManager implements LinkManagerInterface {
|
||||
|
||||
/**
|
||||
* The type link manager.
|
||||
*
|
||||
* @var \Drupal\hal\LinkManager\TypeLinkManagerInterface
|
||||
*/
|
||||
protected $typeLinkManager;
|
||||
|
||||
/**
|
||||
* The relation link manager.
|
||||
*
|
||||
* @var \Drupal\hal\LinkManager\RelationLinkManagerInterface
|
||||
*/
|
||||
protected $relationLinkManager;
|
||||
|
||||
/**
|
||||
* Constructor.
|
||||
*
|
||||
* @param \Drupal\hal\LinkManager\TypeLinkManagerInterface $type_link_manager
|
||||
* Manager for handling bundle URIs.
|
||||
* @param \Drupal\hal\LinkManager\RelationLinkManagerInterface $relation_link_manager
|
||||
* Manager for handling bundle URIs.
|
||||
*/
|
||||
public function __construct(TypeLinkManagerInterface $type_link_manager, RelationLinkManagerInterface $relation_link_manager) {
|
||||
$this->typeLinkManager = $type_link_manager;
|
||||
$this->relationLinkManager = $relation_link_manager;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function getTypeUri($entity_type, $bundle, $context = []) {
|
||||
return $this->typeLinkManager->getTypeUri($entity_type, $bundle, $context);
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function getTypeInternalIds($type_uri, $context = []) {
|
||||
return $this->typeLinkManager->getTypeInternalIds($type_uri, $context);
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function getRelationUri($entity_type, $bundle, $field_name, $context = []) {
|
||||
return $this->relationLinkManager->getRelationUri($entity_type, $bundle, $field_name, $context);
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function getRelationInternalIds($relation_uri) {
|
||||
return $this->relationLinkManager->getRelationInternalIds($relation_uri);
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function setLinkDomain($domain) {
|
||||
$this->relationLinkManager->setLinkDomain($domain);
|
||||
$this->typeLinkManager->setLinkDomain($domain);
|
||||
return $this;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
<?php
|
||||
|
||||
namespace Drupal\hal\LinkManager;
|
||||
|
||||
use Drupal\serialization\Normalizer\CacheableNormalizerInterface;
|
||||
|
||||
/**
|
||||
* Defines an abstract base-class for HAL link manager objects.
|
||||
*/
|
||||
abstract class LinkManagerBase {
|
||||
|
||||
/**
|
||||
* Link domain used for type links URIs.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
protected $linkDomain;
|
||||
|
||||
/**
|
||||
* Config factory service.
|
||||
*
|
||||
* @var \Drupal\Core\Config\ConfigFactoryInterface
|
||||
*/
|
||||
protected $configFactory;
|
||||
|
||||
/**
|
||||
* The request stack.
|
||||
*
|
||||
* @var \Symfony\Component\HttpFoundation\RequestStack
|
||||
*/
|
||||
protected $requestStack;
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function setLinkDomain($domain) {
|
||||
$this->linkDomain = rtrim($domain, '/');
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the link domain.
|
||||
*
|
||||
* @param array $context
|
||||
* Normalization/serialization context.
|
||||
*
|
||||
* @return string
|
||||
* The link domain.
|
||||
*
|
||||
* @see \Symfony\Component\Serializer\Normalizer\NormalizerInterface::normalize()
|
||||
* @see \Symfony\Component\Serializer\SerializerInterface::serialize()
|
||||
* @see \Drupal\serialization\Normalizer\CacheableNormalizerInterface::SERIALIZATION_CONTEXT_CACHEABILITY
|
||||
*/
|
||||
protected function getLinkDomain(array $context = []) {
|
||||
if (empty($this->linkDomain)) {
|
||||
if ($domain = $this->configFactory->get('hal.settings')->get('link_domain')) {
|
||||
// Bubble the appropriate cacheability metadata whenever possible.
|
||||
if (isset($context[CacheableNormalizerInterface::SERIALIZATION_CONTEXT_CACHEABILITY])) {
|
||||
$context[CacheableNormalizerInterface::SERIALIZATION_CONTEXT_CACHEABILITY]->addCacheableDependency($this->configFactory->get('hal.settings'));
|
||||
}
|
||||
return rtrim($domain, '/');
|
||||
}
|
||||
else {
|
||||
// Bubble the relevant cacheability metadata whenever possible.
|
||||
if (isset($context[CacheableNormalizerInterface::SERIALIZATION_CONTEXT_CACHEABILITY])) {
|
||||
$context[CacheableNormalizerInterface::SERIALIZATION_CONTEXT_CACHEABILITY]->addCacheContexts(['url.site']);
|
||||
}
|
||||
$request = $this->requestStack->getCurrentRequest();
|
||||
return $request->getSchemeAndHttpHost() . $request->getBasePath();
|
||||
}
|
||||
}
|
||||
return $this->linkDomain;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
<?php
|
||||
|
||||
namespace Drupal\hal\LinkManager;
|
||||
|
||||
/**
|
||||
* Interface implemented by link managers.
|
||||
*
|
||||
* There are no explicit methods on the manager interface. Instead link managers
|
||||
* broker the interactions of the different components, and therefore must
|
||||
* implement each component interface, which is enforced by this interface
|
||||
* extending all of the component ones.
|
||||
*
|
||||
* While a link manager may directly implement these interface methods with
|
||||
* custom logic, it is expected to be more common for plugin managers to proxy
|
||||
* the method invocations to the respective components.
|
||||
*/
|
||||
interface LinkManagerInterface extends TypeLinkManagerInterface, RelationLinkManagerInterface {
|
||||
}
|
||||
@@ -0,0 +1,205 @@
|
||||
<?php
|
||||
|
||||
namespace Drupal\hal\LinkManager;
|
||||
|
||||
use Drupal\Core\Cache\Cache;
|
||||
use Drupal\Core\Cache\CacheBackendInterface;
|
||||
use Drupal\Core\Config\ConfigFactoryInterface;
|
||||
use Drupal\Core\DependencyInjection\DeprecatedServicePropertyTrait;
|
||||
use Drupal\Core\Entity\ContentEntityTypeInterface;
|
||||
use Drupal\Core\Entity\EntityFieldManagerInterface;
|
||||
use Drupal\Core\Entity\EntityTypeBundleInfoInterface;
|
||||
use Drupal\Core\Entity\EntityTypeManagerInterface;
|
||||
use Drupal\Core\Extension\ModuleHandlerInterface;
|
||||
use Symfony\Component\HttpFoundation\RequestStack;
|
||||
|
||||
class RelationLinkManager extends LinkManagerBase implements RelationLinkManagerInterface {
|
||||
use DeprecatedServicePropertyTrait;
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
protected $deprecatedProperties = ['entityManager' => 'entity.manager'];
|
||||
|
||||
/**
|
||||
* @var \Drupal\Core\Cache\CacheBackendInterface
|
||||
*/
|
||||
protected $cache;
|
||||
|
||||
/**
|
||||
* The entity field manager.
|
||||
*
|
||||
* @var \Drupal\Core\Entity\EntityFieldManagerInterface
|
||||
*/
|
||||
protected $entityFieldManager;
|
||||
|
||||
/**
|
||||
* The entity bundle info.
|
||||
*
|
||||
* @var \Drupal\Core\Entity\EntityTypeBundleInfoInterface
|
||||
*/
|
||||
protected $entityTypeBundleInfo;
|
||||
|
||||
/**
|
||||
* The entity type manager.
|
||||
*
|
||||
* @var \Drupal\Core\Entity\EntityTypeManagerInterface
|
||||
*/
|
||||
protected $entityTypeManager;
|
||||
|
||||
/**
|
||||
* Module handler service.
|
||||
*
|
||||
* @var \Drupal\Core\Extension\ModuleHandlerInterface
|
||||
*/
|
||||
protected $moduleHandler;
|
||||
|
||||
/**
|
||||
* Constructor.
|
||||
*
|
||||
* @param \Drupal\Core\Cache\CacheBackendInterface $cache
|
||||
* The cache of relation URIs and their associated Typed Data IDs.
|
||||
* @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
|
||||
* The entity type manager.
|
||||
* @param \Drupal\Core\Extension\ModuleHandlerInterface $module_handler
|
||||
* The module handler service.
|
||||
* @param \Drupal\Core\Config\ConfigFactoryInterface $config_factory
|
||||
* The config factory service.
|
||||
* @param \Symfony\Component\HttpFoundation\RequestStack $request_stack
|
||||
* The request stack.
|
||||
* @param \Drupal\Core\Entity\EntityTypeBundleInfoInterface $entity_type_bundle_info
|
||||
* The entity type bundle info.
|
||||
* @param \Drupal\Core\Entity\EntityFieldManagerInterface $entity_field_manager
|
||||
* The entity field manager.
|
||||
*/
|
||||
public function __construct(CacheBackendInterface $cache, EntityTypeManagerInterface $entity_type_manager, ModuleHandlerInterface $module_handler, ConfigFactoryInterface $config_factory, RequestStack $request_stack, EntityTypeBundleInfoInterface $entity_type_bundle_info = NULL, EntityFieldManagerInterface $entity_field_manager = NULL) {
|
||||
$this->cache = $cache;
|
||||
$this->entityTypeManager = $entity_type_manager;
|
||||
if (!$entity_type_bundle_info) {
|
||||
@trigger_error('The entity_type.bundle.info service must be passed to RelationLinkManager::__construct(), it is required before Drupal 9.0.0. See https://www.drupal.org/node/2549139.', E_USER_DEPRECATED);
|
||||
$entity_type_bundle_info = \Drupal::service('entity_type.bundle.info');
|
||||
}
|
||||
$this->entityTypeBundleInfo = $entity_type_bundle_info;
|
||||
if (!$entity_field_manager) {
|
||||
@trigger_error('The entity_field.manager service must be passed to RelationLinkManager::__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;
|
||||
$this->configFactory = $config_factory;
|
||||
$this->moduleHandler = $module_handler;
|
||||
$this->requestStack = $request_stack;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function getRelationUri($entity_type, $bundle, $field_name, $context = []) {
|
||||
// Per the interface documentation of this method, the returned URI may
|
||||
// optionally also serve as the URL of a documentation page about this
|
||||
// field. However, Drupal does not currently implement such a documentation
|
||||
// page. Therefore, we return a URI assembled relative to the site's base
|
||||
// URL, which is sufficient to uniquely identify the site's entity type +
|
||||
// bundle + field for use in hypermedia formats, but we do not take into
|
||||
// account unclean URLs, language prefixing, or anything else that would be
|
||||
// required for Drupal to be able to respond with content at this URL. If a
|
||||
// module is installed that adds such content, but requires this URL to be
|
||||
// different (e.g., include a language prefix), then the module must also
|
||||
// override the RelationLinkManager class/service to return the desired URL.
|
||||
$uri = $this->getLinkDomain($context) . "/rest/relation/$entity_type/$bundle/$field_name";
|
||||
$this->moduleHandler->alter('hal_relation_uri', $uri, $context);
|
||||
$this->moduleHandler->alterDeprecated('This hook is deprecated in Drupal 8.3.x and will be removed before Drupal 9.0.0. Implement hook_hal_relation_uri_alter() instead.', 'rest_relation_uri', $uri, $context);
|
||||
return $uri;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function getRelationInternalIds($relation_uri, $context = []) {
|
||||
$relations = $this->getRelations($context);
|
||||
if (isset($relations[$relation_uri])) {
|
||||
return $relations[$relation_uri];
|
||||
}
|
||||
return FALSE;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the array of relation links.
|
||||
*
|
||||
* Any field can be handled as a relation simply by changing how it is
|
||||
* normalized. Therefore, there is no prior knowledge that can be used here
|
||||
* to determine which fields to assign relation URIs. Instead, each field,
|
||||
* even primitives, are given a relation URI. It is up to the caller to
|
||||
* determine which URIs to use.
|
||||
*
|
||||
* @param array $context
|
||||
* Context from the normalizer/serializer operation.
|
||||
*
|
||||
* @return array
|
||||
* An array of typed data IDs keyed by corresponding relation URI. The keys
|
||||
* are:
|
||||
* - 'entity_type_id'
|
||||
* - 'bundle'
|
||||
* - 'field_name'
|
||||
* - 'entity_type' (deprecated)
|
||||
* The values for 'entity_type_id', 'bundle' and 'field_name' are strings.
|
||||
* The 'entity_type' key exists for backwards compatibility and its value is
|
||||
* the full entity type object. The 'entity_type' key will be removed before
|
||||
* Drupal 9.0.
|
||||
*
|
||||
* @see https://www.drupal.org/node/2877608
|
||||
*/
|
||||
protected function getRelations($context = []) {
|
||||
$cid = 'hal:links:relations';
|
||||
$cache = $this->cache->get($cid);
|
||||
if (!$cache) {
|
||||
$data = $this->writeCache($context);
|
||||
}
|
||||
else {
|
||||
$data = $cache->data;
|
||||
}
|
||||
|
||||
// @todo https://www.drupal.org/node/2716163 Remove this in Drupal 9.0.
|
||||
foreach ($data as $relation_uri => $ids) {
|
||||
$data[$relation_uri]['entity_type'] = $this->entityTypeManager->getDefinition($ids['entity_type_id']);
|
||||
}
|
||||
return $data;
|
||||
}
|
||||
|
||||
/**
|
||||
* Writes the cache of relation links.
|
||||
*
|
||||
* @param array $context
|
||||
* Context from the normalizer/serializer operation.
|
||||
*
|
||||
* @return array
|
||||
* An array of typed data IDs keyed by corresponding relation URI. The keys
|
||||
* are:
|
||||
* - 'entity_type_id'
|
||||
* - 'bundle'
|
||||
* - 'field_name'
|
||||
* The values for 'entity_type_id', 'bundle' and 'field_name' are strings.
|
||||
*/
|
||||
protected function writeCache($context = []) {
|
||||
$data = [];
|
||||
|
||||
foreach ($this->entityTypeManager->getDefinitions() as $entity_type) {
|
||||
if ($entity_type instanceof ContentEntityTypeInterface) {
|
||||
foreach ($this->entityTypeBundleInfo->getBundleInfo($entity_type->id()) as $bundle => $bundle_info) {
|
||||
foreach ($this->entityFieldManager->getFieldDefinitions($entity_type->id(), $bundle) as $field_definition) {
|
||||
$relation_uri = $this->getRelationUri($entity_type->id(), $bundle, $field_definition->getName(), $context);
|
||||
$data[$relation_uri] = [
|
||||
'entity_type_id' => $entity_type->id(),
|
||||
'bundle' => $bundle,
|
||||
'field_name' => $field_definition->getName(),
|
||||
];
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
// These URIs only change when field info changes, so cache it permanently
|
||||
// and only clear it when the fields cache is cleared.
|
||||
$this->cache->set('hal:links:relations', $data, Cache::PERMANENT, ['entity_field_info']);
|
||||
return $data;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
<?php
|
||||
|
||||
namespace Drupal\hal\LinkManager;
|
||||
|
||||
interface RelationLinkManagerInterface extends ConfigurableLinkManagerInterface {
|
||||
|
||||
/**
|
||||
* Gets the URI that corresponds to a field.
|
||||
*
|
||||
* When using hypermedia formats, this URI can be used to indicate which
|
||||
* field the data represents. Documentation about this field can also be
|
||||
* provided at this URI.
|
||||
*
|
||||
* @param string $entity_type
|
||||
* The bundle's entity type.
|
||||
* @param string $bundle
|
||||
* The bundle name.
|
||||
* @param string $field_name
|
||||
* The field name.
|
||||
* @param array $context
|
||||
* (optional) Optional serializer/normalizer context.
|
||||
*
|
||||
* @return string
|
||||
* The corresponding URI (or IANA link relation type) for the field.
|
||||
*/
|
||||
public function getRelationUri($entity_type, $bundle, $field_name, $context = []);
|
||||
|
||||
/**
|
||||
* Translates a REST URI into internal IDs.
|
||||
*
|
||||
* @param string $relation_uri
|
||||
* Relation URI (or IANA link relation type) to transform into internal IDs.
|
||||
*
|
||||
* @return array
|
||||
* Array with keys 'entity_type_id', 'bundle' and 'field_name'. For
|
||||
* backwards compatibility, the entity_type key returns the full entity type
|
||||
* object, this will be removed before Drupal 9.0.
|
||||
*/
|
||||
public function getRelationInternalIds($relation_uri);
|
||||
|
||||
}
|
||||
@@ -0,0 +1,172 @@
|
||||
<?php
|
||||
|
||||
namespace Drupal\hal\LinkManager;
|
||||
|
||||
use Drupal\Core\Cache\Cache;
|
||||
use Drupal\Core\Cache\CacheBackendInterface;
|
||||
use Drupal\Core\Config\ConfigFactoryInterface;
|
||||
use Drupal\Core\Config\Entity\ConfigEntityInterface;
|
||||
use Drupal\Core\DependencyInjection\DeprecatedServicePropertyTrait;
|
||||
use Drupal\Core\Entity\EntityTypeBundleInfoInterface;
|
||||
use Drupal\Core\Entity\EntityTypeManagerInterface;
|
||||
use Drupal\Core\Extension\ModuleHandlerInterface;
|
||||
use Symfony\Component\HttpFoundation\RequestStack;
|
||||
|
||||
class TypeLinkManager extends LinkManagerBase implements TypeLinkManagerInterface {
|
||||
use DeprecatedServicePropertyTrait;
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
protected $deprecatedProperties = ['entityManager' => 'entity.manager'];
|
||||
|
||||
/**
|
||||
* Injected cache backend.
|
||||
*
|
||||
* @var \Drupal\Core\Cache\CacheBackendInterface
|
||||
*/
|
||||
protected $cache;
|
||||
|
||||
/**
|
||||
* Module handler service.
|
||||
*
|
||||
* @var \Drupal\Core\Extension\ModuleHandlerInterface
|
||||
*/
|
||||
protected $moduleHandler;
|
||||
|
||||
/**
|
||||
* The bundle info service.
|
||||
*
|
||||
* @var \Drupal\Core\Entity\EntityTypeBundleInfoInterface
|
||||
*/
|
||||
protected $bundleInfoService;
|
||||
|
||||
/**
|
||||
* The entity type manager.
|
||||
*
|
||||
* @var \Drupal\Core\Entity\EntityTypeManagerInterface
|
||||
*/
|
||||
protected $entityTypeManager;
|
||||
|
||||
/**
|
||||
* Constructor.
|
||||
*
|
||||
* @param \Drupal\Core\Cache\CacheBackendInterface $cache
|
||||
* The injected cache backend for caching type URIs.
|
||||
* @param \Drupal\Core\Extension\ModuleHandlerInterface $module_handler
|
||||
* The module handler service.
|
||||
* @param \Drupal\Core\Config\ConfigFactoryInterface $config_factory
|
||||
* The config factory service.
|
||||
* @param \Symfony\Component\HttpFoundation\RequestStack $request_stack
|
||||
* The request stack.
|
||||
* @param \Drupal\Core\Entity\EntityTypeBundleInfoInterface $bundle_info_service
|
||||
* The bundle info service.
|
||||
* @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
|
||||
* The entity type manager.
|
||||
*/
|
||||
public function __construct(CacheBackendInterface $cache, ModuleHandlerInterface $module_handler, ConfigFactoryInterface $config_factory, RequestStack $request_stack, EntityTypeBundleInfoInterface $bundle_info_service, EntityTypeManagerInterface $entity_type_manager = NULL) {
|
||||
$this->cache = $cache;
|
||||
$this->configFactory = $config_factory;
|
||||
$this->moduleHandler = $module_handler;
|
||||
$this->requestStack = $request_stack;
|
||||
$this->bundleInfoService = $bundle_info_service;
|
||||
|
||||
if (!$entity_type_manager) {
|
||||
@trigger_error('The entity_type.manager service must be passed to TypeLinkManager::__construct(), it is required before Drupal 9.0.0. See https://www.drupal.org/node/2549139.', E_USER_DEPRECATED);
|
||||
$entity_type_manager = \Drupal::service('entity_type.manager.manager');
|
||||
}
|
||||
$this->entityTypeManager = $entity_type_manager;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function getTypeUri($entity_type, $bundle, $context = []) {
|
||||
// Per the interface documentation of this method, the returned URI may
|
||||
// optionally also serve as the URL of a documentation page about this
|
||||
// bundle. However, Drupal does not currently implement such a documentation
|
||||
// page. Therefore, we return a URI assembled relative to the site's base
|
||||
// URL, which is sufficient to uniquely identify the site's entity type and
|
||||
// bundle for use in hypermedia formats, but we do not take into account
|
||||
// unclean URLs, language prefixing, or anything else that would be required
|
||||
// for Drupal to be able to respond with content at this URL. If a module is
|
||||
// installed that adds such content, but requires this URL to be different
|
||||
// (e.g., include a language prefix), then the module must also override the
|
||||
// TypeLinkManager class/service to return the desired URL.
|
||||
$uri = $this->getLinkDomain($context) . "/rest/type/$entity_type/$bundle";
|
||||
$this->moduleHandler->alter('hal_type_uri', $uri, $context);
|
||||
$this->moduleHandler->alterDeprecated('This hook is deprecated in Drupal 8.3.x and will be removed before Drupal 9.0.0. Implement hook_hal_type_uri_alter() instead.', 'rest_type_uri', $uri, $context);
|
||||
return $uri;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function getTypeInternalIds($type_uri, $context = []) {
|
||||
$types = $this->getTypes($context);
|
||||
if (isset($types[$type_uri])) {
|
||||
return $types[$type_uri];
|
||||
}
|
||||
return FALSE;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the array of type links.
|
||||
*
|
||||
* @param array $context
|
||||
* Context from the normalizer/serializer operation.
|
||||
*
|
||||
* @return array
|
||||
* An array of typed data ids (entity_type and bundle) keyed by
|
||||
* corresponding type URI.
|
||||
*/
|
||||
protected function getTypes($context = []) {
|
||||
$cid = 'hal:links:types';
|
||||
$cache = $this->cache->get($cid);
|
||||
if (!$cache) {
|
||||
$data = $this->writeCache($context);
|
||||
}
|
||||
else {
|
||||
$data = $cache->data;
|
||||
}
|
||||
return $data;
|
||||
}
|
||||
|
||||
/**
|
||||
* Writes the cache of type links.
|
||||
*
|
||||
* @param array $context
|
||||
* Context from the normalizer/serializer operation.
|
||||
*
|
||||
* @return array
|
||||
* An array of typed data ids (entity_type and bundle) keyed by
|
||||
* corresponding type URI.
|
||||
*/
|
||||
protected function writeCache($context = []) {
|
||||
$data = [];
|
||||
|
||||
// Type URIs correspond to bundles. Iterate through the bundles to get the
|
||||
// URI and data for them.
|
||||
$entity_types = $this->entityTypeManager->getDefinitions();
|
||||
foreach ($this->bundleInfoService->getAllBundleInfo() as $entity_type_id => $bundles) {
|
||||
// Only content entities are supported currently.
|
||||
// @todo Consider supporting config entities.
|
||||
if ($entity_types[$entity_type_id]->entityClassImplements(ConfigEntityInterface::class)) {
|
||||
continue;
|
||||
}
|
||||
foreach ($bundles as $bundle => $bundle_info) {
|
||||
// Get a type URI for the bundle.
|
||||
$bundle_uri = $this->getTypeUri($entity_type_id, $bundle, $context);
|
||||
$data[$bundle_uri] = [
|
||||
'entity_type' => $entity_type_id,
|
||||
'bundle' => $bundle,
|
||||
];
|
||||
}
|
||||
}
|
||||
// These URIs only change when entity info changes, so cache it permanently
|
||||
// and only clear it when entity_info is cleared.
|
||||
$this->cache->set('hal:links:types', $data, Cache::PERMANENT, ['entity_types']);
|
||||
return $data;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
<?php
|
||||
|
||||
namespace Drupal\hal\LinkManager;
|
||||
|
||||
interface TypeLinkManagerInterface extends ConfigurableLinkManagerInterface {
|
||||
|
||||
/**
|
||||
* Gets the URI that corresponds to a bundle.
|
||||
*
|
||||
* When using hypermedia formats, this URI can be used to indicate which
|
||||
* bundle the data represents. Documentation about required and optional
|
||||
* fields can also be provided at this URI.
|
||||
*
|
||||
* @param $entity_type
|
||||
* The bundle's entity type.
|
||||
* @param $bundle
|
||||
* The bundle name.
|
||||
* @param array $context
|
||||
* (optional) Optional serializer/normalizer context.
|
||||
*
|
||||
* @return string
|
||||
* The corresponding URI for the bundle.
|
||||
*/
|
||||
public function getTypeUri($entity_type, $bundle, $context = []);
|
||||
|
||||
/**
|
||||
* Get a bundle's Typed Data IDs based on a URI.
|
||||
*
|
||||
* @param string $type_uri
|
||||
* The type URI.
|
||||
* @param array $context
|
||||
* Context from the normalizer/serializer operation.
|
||||
*
|
||||
* @return array|bool
|
||||
* If the URI matches a bundle, returns an array containing entity_type and
|
||||
* bundle. Otherwise, returns false.
|
||||
*/
|
||||
public function getTypeInternalIds($type_uri, $context = []);
|
||||
|
||||
}
|
||||
@@ -0,0 +1,287 @@
|
||||
<?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;
|
||||
|
||||
/**
|
||||
* Converts the Drupal entity object structure to a HAL array structure.
|
||||
*/
|
||||
class ContentEntityNormalizer extends NormalizerBase {
|
||||
use FieldableEntityNormalizerTrait;
|
||||
use DeprecatedServicePropertyTrait;
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
protected $deprecatedProperties = ['entityManager' => 'entity.manager'];
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
protected $supportedInterfaceOrClass = ContentEntityInterface::class;
|
||||
|
||||
/**
|
||||
* The hypermedia link manager.
|
||||
*
|
||||
* @var \Drupal\hal\LinkManager\LinkManagerInterface
|
||||
*/
|
||||
protected $linkManager;
|
||||
|
||||
/**
|
||||
* The module handler.
|
||||
*
|
||||
* @var \Drupal\Core\Extension\ModuleHandlerInterface
|
||||
*/
|
||||
protected $moduleHandler;
|
||||
|
||||
/**
|
||||
* Constructs an ContentEntityNormalizer object.
|
||||
*
|
||||
* @param \Drupal\hal\LinkManager\LinkManagerInterface $link_manager
|
||||
* The hypermedia link manager.
|
||||
* @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.
|
||||
*/
|
||||
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;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function normalize($entity, $format = NULL, array $context = []) {
|
||||
$context += [
|
||||
'account' => NULL,
|
||||
'included_fields' => NULL,
|
||||
];
|
||||
|
||||
// Create the array of normalized fields, starting with the URI.
|
||||
/** @var $entity \Drupal\Core\Entity\ContentEntityInterface */
|
||||
$normalized = [
|
||||
'_links' => [
|
||||
'self' => [
|
||||
'href' => $this->getEntityUri($entity),
|
||||
],
|
||||
'type' => [
|
||||
'href' => $this->linkManager->getTypeUri($entity->getEntityTypeId(), $entity->bundle(), $context),
|
||||
],
|
||||
],
|
||||
];
|
||||
|
||||
$field_items = TypedDataInternalPropertiesHelper::getNonInternalProperties($entity->getTypedData());
|
||||
// If the fields to use were specified, only output those field values.
|
||||
if (isset($context['included_fields'])) {
|
||||
$field_items = array_intersect_key($field_items, array_flip($context['included_fields']));
|
||||
}
|
||||
foreach ($field_items 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 parameter.
|
||||
* @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);
|
||||
|
||||
// Pass the names of the fields whose values can be merged.
|
||||
// @todo https://www.drupal.org/node/2456257 remove this.
|
||||
$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()) {
|
||||
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();
|
||||
}
|
||||
|
||||
/**
|
||||
* 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;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,187 @@
|
||||
<?php
|
||||
|
||||
namespace Drupal\hal\Normalizer;
|
||||
|
||||
use Drupal\Core\Entity\EntityTypeManagerInterface;
|
||||
use Drupal\Core\Entity\FieldableEntityInterface;
|
||||
use Drupal\Core\Field\FieldItemInterface;
|
||||
use Drupal\Core\Field\Plugin\Field\FieldType\EntityReferenceItem;
|
||||
use Drupal\hal\LinkManager\LinkManagerInterface;
|
||||
use Drupal\serialization\EntityResolver\EntityResolverInterface;
|
||||
use Drupal\serialization\EntityResolver\UuidReferenceInterface;
|
||||
use Drupal\serialization\Normalizer\EntityReferenceFieldItemNormalizerTrait;
|
||||
|
||||
/**
|
||||
* Converts the Drupal entity reference item object to HAL array structure.
|
||||
*/
|
||||
class EntityReferenceItemNormalizer extends FieldItemNormalizer implements UuidReferenceInterface {
|
||||
|
||||
use EntityReferenceFieldItemNormalizerTrait;
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
protected $supportedInterfaceOrClass = EntityReferenceItem::class;
|
||||
|
||||
/**
|
||||
* The hypermedia link manager.
|
||||
*
|
||||
* @var \Drupal\hal\LinkManager\LinkManagerInterface
|
||||
*/
|
||||
protected $linkManager;
|
||||
|
||||
/**
|
||||
* The entity resolver.
|
||||
*
|
||||
* @var \Drupal\serialization\EntityResolver\EntityResolverInterface
|
||||
*/
|
||||
protected $entityResolver;
|
||||
|
||||
/**
|
||||
* The entity type manager.
|
||||
*
|
||||
* @var \Drupal\Core\Entity\EntityTypeManagerInterface
|
||||
*/
|
||||
protected $entityTypeManager;
|
||||
|
||||
/**
|
||||
* Constructs an EntityReferenceItemNormalizer object.
|
||||
*
|
||||
* @param \Drupal\hal\LinkManager\LinkManagerInterface $link_manager
|
||||
* The hypermedia link manager.
|
||||
* @param \Drupal\serialization\EntityResolver\EntityResolverInterface $entity_Resolver
|
||||
* The entity resolver.
|
||||
* @param \Drupal\Core\Entity\EntityTypeManagerInterface|null $entity_type_manager
|
||||
* The entity type manager.
|
||||
*/
|
||||
public function __construct(LinkManagerInterface $link_manager, EntityResolverInterface $entity_Resolver, EntityTypeManagerInterface $entity_type_manager = NULL) {
|
||||
$this->linkManager = $link_manager;
|
||||
$this->entityResolver = $entity_Resolver;
|
||||
$this->entityTypeManager = $entity_type_manager ?: \Drupal::service('entity_type.manager');
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function normalize($field_item, $format = NULL, array $context = []) {
|
||||
// If this is not a fieldable entity, let the parent implementation handle
|
||||
// it, only fieldable entities are supported as embedded resources.
|
||||
if (!$this->targetEntityIsFieldable($field_item)) {
|
||||
return parent::normalize($field_item, $format, $context);
|
||||
}
|
||||
|
||||
/** @var $field_item \Drupal\Core\Field\FieldItemInterface */
|
||||
$target_entity = $field_item->get('entity')->getValue();
|
||||
|
||||
// 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'] = ['uuid'];
|
||||
|
||||
// Normalize the target entity.
|
||||
$embedded = $this->serializer->normalize($target_entity, $format, $context);
|
||||
// @todo https://www.drupal.org/project/drupal/issues/3110815 $embedded will
|
||||
// be NULL if the target entity does not exist. Use null coalescence
|
||||
// operator to preserve behavior in PHP 7.4.
|
||||
$link = $embedded['_links']['self'] ?? NULL;
|
||||
// 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 [
|
||||
'_links' => [
|
||||
$field_uri => [$link],
|
||||
],
|
||||
'_embedded' => [
|
||||
$field_uri => [$embedded],
|
||||
],
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks whether the referenced entity is of a fieldable entity type.
|
||||
*
|
||||
* @param \Drupal\Core\Field\Plugin\Field\FieldType\EntityReferenceItem $item
|
||||
* The reference field item whose target entity needs to be checked.
|
||||
*
|
||||
* @return bool
|
||||
* TRUE when the referenced entity is of a fieldable entity type.
|
||||
*/
|
||||
protected function targetEntityIsFieldable(EntityReferenceItem $item) {
|
||||
$target_entity = $item->get('entity')->getValue();
|
||||
|
||||
if ($target_entity !== NULL) {
|
||||
return $target_entity instanceof FieldableEntityInterface;
|
||||
}
|
||||
|
||||
$referencing_entity = $item->getEntity();
|
||||
$target_entity_type_id = $item->getFieldDefinition()->getSetting('target_type');
|
||||
|
||||
// If the entity type is the same as the parent, we can check that. This is
|
||||
// just a shortcut to avoid getting the entity type definition and checking
|
||||
// the class.
|
||||
if ($target_entity_type_id === $referencing_entity->getEntityTypeId()) {
|
||||
return $referencing_entity instanceof FieldableEntityInterface;
|
||||
}
|
||||
|
||||
// Otherwise, we need to get the class for the type.
|
||||
$target_entity_type = $this->entityTypeManager->getDefinition($target_entity_type_id);
|
||||
$target_entity_type_class = $target_entity_type->getClass();
|
||||
|
||||
return is_a($target_entity_type_class, FieldableEntityInterface::class, TRUE);
|
||||
}
|
||||
|
||||
/**
|
||||
* {@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 ['target_id' => $id] + array_intersect_key($data, $field_item->getProperties());
|
||||
}
|
||||
return NULL;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
protected function normalizedFieldValues(FieldItemInterface $field_item, $format, array $context) {
|
||||
// Normalize root reference values here so we don't need to deal with hal's
|
||||
// nested data structure for field items. This will be called from
|
||||
// \Drupal\hal\Normalizer\FieldItemNormalizer::normalize. Which will only
|
||||
// be called from this class for entities that are not fieldable.
|
||||
$normalized = parent::normalizedFieldValues($field_item, $format, $context);
|
||||
|
||||
$this->normalizeRootReferenceValue($normalized, $field_item);
|
||||
|
||||
return $normalized;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@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;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,128 @@
|
||||
<?php
|
||||
|
||||
namespace Drupal\hal\Normalizer;
|
||||
|
||||
use Drupal\Core\Field\FieldItemInterface;
|
||||
use Drupal\Core\TypedData\TypedDataInternalPropertiesHelper;
|
||||
use Drupal\serialization\Normalizer\FieldableEntityNormalizerTrait;
|
||||
use Drupal\serialization\Normalizer\SerializedColumnNormalizerTrait;
|
||||
use Symfony\Component\Serializer\Exception\InvalidArgumentException;
|
||||
|
||||
/**
|
||||
* Converts the Drupal field item object structure to HAL array structure.
|
||||
*/
|
||||
class FieldItemNormalizer extends NormalizerBase {
|
||||
|
||||
use FieldableEntityNormalizerTrait;
|
||||
use SerializedColumnNormalizerTrait;
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
protected $supportedInterfaceOrClass = FieldItemInterface::class;
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function normalize($field_item, $format = NULL, array $context = []) {
|
||||
// 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 [
|
||||
$field->getName() => [$this->normalizedFieldValues($field_item, $format, $context)],
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function denormalize($data, $class, $format = NULL, array $context = []) {
|
||||
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'];
|
||||
$this->checkForSerializedStrings($data, $class, $field_item);
|
||||
|
||||
// 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;
|
||||
}
|
||||
|
||||
/**
|
||||
* Normalizes field values for an item.
|
||||
*
|
||||
* @param \Drupal\Core\Field\FieldItemInterface $field_item
|
||||
* The field item instance.
|
||||
* @param string|null $format
|
||||
* The normalization format.
|
||||
* @param array $context
|
||||
* The context passed into the normalizer.
|
||||
*
|
||||
* @return array
|
||||
* An array of field item values, keyed by property name.
|
||||
*/
|
||||
protected function normalizedFieldValues(FieldItemInterface $field_item, $format, array $context) {
|
||||
$normalized = [];
|
||||
// We normalize each individual property, so each can do their own casting,
|
||||
// if needed.
|
||||
/** @var \Drupal\Core\TypedData\TypedDataInterface $property */
|
||||
$field_properties = !empty($field_item->getProperties(TRUE))
|
||||
? TypedDataInternalPropertiesHelper::getNonInternalProperties($field_item)
|
||||
: $field_item->getValue();
|
||||
foreach ($field_properties as $property_name => $property) {
|
||||
$normalized[$property_name] = $this->serializer->normalize($property, $format, $context);
|
||||
}
|
||||
|
||||
if (isset($context['langcode'])) {
|
||||
$normalized['lang'] = $context['langcode'];
|
||||
}
|
||||
|
||||
return $normalized;
|
||||
}
|
||||
|
||||
/**
|
||||
* 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 $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();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
<?php
|
||||
|
||||
namespace Drupal\hal\Normalizer;
|
||||
|
||||
use Drupal\Component\Utility\NestedArray;
|
||||
use Drupal\serialization\Normalizer\FieldNormalizer as SerializationFieldNormalizer;
|
||||
|
||||
/**
|
||||
* Converts the Drupal field structure to HAL array structure.
|
||||
*/
|
||||
class FieldNormalizer extends SerializationFieldNormalizer {
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
protected $format = ['hal_json'];
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function normalize($field_items, $format = NULL, array $context = []) {
|
||||
$normalized_field_items = [];
|
||||
|
||||
// Get the field definition.
|
||||
$entity = $field_items->getEntity();
|
||||
$field_name = $field_items->getName();
|
||||
$field_definition = $field_items->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_items, $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_items = $translation->get($field_name);
|
||||
$normalized_field_items = array_merge($normalized_field_items, $this->normalizeFieldItems($translated_field_items, $format, $context));
|
||||
}
|
||||
}
|
||||
|
||||
// Merge deep so that links set in entity reference normalizers are merged
|
||||
// into the links property.
|
||||
return NestedArray::mergeDeepArray($normalized_field_items);
|
||||
}
|
||||
|
||||
/**
|
||||
* Helper function to normalize field items.
|
||||
*
|
||||
* @param \Drupal\Core\Field\FieldItemListInterface $field_items
|
||||
* The field item list object.
|
||||
* @param string $format
|
||||
* The format.
|
||||
* @param array $context
|
||||
* The context array.
|
||||
*
|
||||
* @return array
|
||||
* The array of normalized field items.
|
||||
*/
|
||||
protected function normalizeFieldItems($field_items, $format, $context) {
|
||||
$normalized_field_items = [];
|
||||
if (!$field_items->isEmpty()) {
|
||||
foreach ($field_items as $field_item) {
|
||||
$normalized_field_items[] = $this->serializer->normalize($field_item, $format, $context);
|
||||
}
|
||||
}
|
||||
return $normalized_field_items;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
<?php
|
||||
|
||||
namespace Drupal\hal\Normalizer;
|
||||
|
||||
use Drupal\Core\Config\ConfigFactoryInterface;
|
||||
use Drupal\Core\Entity\EntityInterface;
|
||||
use Drupal\Core\Entity\EntityFieldManagerInterface;
|
||||
use Drupal\Core\Entity\EntityTypeManagerInterface;
|
||||
use Drupal\Core\Entity\EntityTypeRepositoryInterface;
|
||||
use Drupal\Core\Extension\ModuleHandlerInterface;
|
||||
use Drupal\file\FileInterface;
|
||||
use Drupal\hal\LinkManager\LinkManagerInterface;
|
||||
|
||||
/**
|
||||
* Converts the Drupal entity object structure to a HAL array structure.
|
||||
*
|
||||
* @internal
|
||||
*/
|
||||
class FileEntityNormalizer extends ContentEntityNormalizer {
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
protected $supportedInterfaceOrClass = FileInterface::class;
|
||||
|
||||
/**
|
||||
* The HTTP client.
|
||||
*
|
||||
* @var \GuzzleHttp\ClientInterface
|
||||
*/
|
||||
protected $httpClient;
|
||||
|
||||
/**
|
||||
* The HAL settings config.
|
||||
*
|
||||
* @var \Drupal\Core\Config\ImmutableConfig
|
||||
*/
|
||||
protected $halSettings;
|
||||
|
||||
/**
|
||||
* Constructs a FileEntityNormalizer object.
|
||||
*
|
||||
* @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
|
||||
* The entity type manager service.
|
||||
* @param \Drupal\hal\LinkManager\LinkManagerInterface $link_manager
|
||||
* The hypermedia link manager.
|
||||
* @param \Drupal\Core\Extension\ModuleHandlerInterface $module_handler
|
||||
* The module handler.
|
||||
* @param \Drupal\Core\Config\ConfigFactoryInterface $config_factory
|
||||
* The config factory.
|
||||
* @param \Drupal\Core\Entity\EntityTypeRepositoryInterface $entity_type_repository
|
||||
* The entity type repository.
|
||||
* @param \Drupal\Core\Entity\EntityFieldManagerInterface $entity_field_manager
|
||||
* The entity field manager.
|
||||
*/
|
||||
public function __construct(EntityTypeManagerInterface $entity_type_manager, LinkManagerInterface $link_manager, ModuleHandlerInterface $module_handler, ConfigFactoryInterface $config_factory, EntityTypeRepositoryInterface $entity_type_repository = NULL, EntityFieldManagerInterface $entity_field_manager = NULL) {
|
||||
parent::__construct($link_manager, $entity_type_manager, $module_handler, $entity_type_repository, $entity_field_manager);
|
||||
|
||||
$this->halSettings = $config_factory->get('hal.settings');
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*
|
||||
* @deprecated in drupal:8.5.0 and is removed from drupal:9.0.0.
|
||||
*/
|
||||
public function normalize($entity, $format = NULL, array $context = []) {
|
||||
$data = parent::normalize($entity, $format, $context);
|
||||
|
||||
$this->addCacheableDependency($context, $this->halSettings);
|
||||
|
||||
if ($this->halSettings->get('bc_file_uri_as_url_normalizer')) {
|
||||
// Replace the file url with a full url for the file.
|
||||
$data['uri'][0]['value'] = $this->getEntityUri($entity);
|
||||
@trigger_error("Replacing the file uri with the URL is deprecated in drupal:8.8.0 and is removed from drupal:9.0.0. Use the provided url property instead and disable hal.settings:bc_file_uri_as_url_normalizer. See https://www.drupal.org/node/2925783", E_USER_DEPRECATED);
|
||||
}
|
||||
|
||||
return $data;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
protected function getEntityUri(EntityInterface $entity, array $context = []) {
|
||||
assert($entity instanceof FileInterface);
|
||||
// https://www.drupal.org/project/drupal/issues/2277705 introduced a hack
|
||||
// in \Drupal\file\Entity\File::url(), but EntityInterface::url() was
|
||||
// deprecated in favor of ::toUrl(). The parent implementation now calls
|
||||
// ::toUrl(), but this normalizer (for File entities) needs to override that
|
||||
// back to the old behavior because it relies on said hack, not just to
|
||||
// generate the value for the 'uri' field of a file (see ::normalize()), but
|
||||
// also for the HAL normalization's '_links' value.
|
||||
return $entity->createFileUrl(FALSE);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
<?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 {
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
protected $format = ['hal_json'];
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
protected function checkFormat($format = NULL) {
|
||||
if (isset($this->formats)) {
|
||||
@trigger_error('::formats is deprecated in Drupal 8.4.0 and will be removed before Drupal 9.0.0. Use ::$format instead. See https://www.drupal.org/node/2868275', E_USER_DEPRECATED);
|
||||
|
||||
$this->format = $this->formats;
|
||||
}
|
||||
|
||||
return parent::checkFormat($format);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
<?php
|
||||
|
||||
namespace Drupal\hal\Normalizer;
|
||||
|
||||
use Drupal\Core\Field\FieldItemInterface;
|
||||
use Drupal\Core\Field\Plugin\Field\FieldType\TimestampItem;
|
||||
use Drupal\Core\TypedData\Plugin\DataType\Timestamp;
|
||||
|
||||
/**
|
||||
* Converts values for TimestampItem to and from common formats for hal.
|
||||
*
|
||||
* Overrides FieldItemNormalizer to
|
||||
* - during normalization, add the 'format' key to assist consumers
|
||||
* - during denormalization, use
|
||||
* \Drupal\serialization\Normalizer\TimestampNormalizer
|
||||
*/
|
||||
class TimestampItemNormalizer extends FieldItemNormalizer {
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
protected $supportedInterfaceOrClass = TimestampItem::class;
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
protected function normalizedFieldValues(FieldItemInterface $field_item, $format, array $context) {
|
||||
return parent::normalizedFieldValues($field_item, $format, $context) + [
|
||||
// 'format' is not a property on Timestamp objects. This is present to
|
||||
// assist consumers of this data.
|
||||
'format' => \DateTime::RFC3339,
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
protected function constructValue($data, $context) {
|
||||
if (!empty($data['format'])) {
|
||||
$context['datetime_allowed_formats'] = [$data['format']];
|
||||
}
|
||||
return ['value' => $this->serializer->denormalize($data['value'], Timestamp::class, NULL, $context)];
|
||||
}
|
||||
|
||||
}
|
||||
Reference in New Issue
Block a user