Update core 8.3.0

This commit is contained in:
Rob Davies 2017-04-13 15:53:35 +01:00
parent da7a7918f8
commit cd7a898e66
6144 changed files with 132297 additions and 87747 deletions

View file

@ -0,0 +1,3 @@
# Set the domain for HAL type and relation links.
# If left blank, the site's domain will be used.
link_domain: ~

View file

@ -0,0 +1,8 @@
# Schema for the configuration files of the HAL module.
hal.settings:
type: config_object
label: 'HAL settings'
mapping:
link_domain:
type: string
label: 'Domain of the relation'

View file

@ -0,0 +1,62 @@
<?php
/**
* @file
* Describes hooks provided by the HAL module.
*/
/**
* @addtogroup hooks
* @{
*/
/**
* Alter the HAL type URI.
*
* Modules may wish to alter the type URI generated for a resource based on the
* context of the serializer/normalizer operation.
*
* @param string $uri
* The URI to alter.
* @param array $context
* The context from the serializer/normalizer operation.
*
* @see \Symfony\Component\Serializer\SerializerInterface::serialize()
* @see \Symfony\Component\Serializer\SerializerInterface::deserialize()
* @see \Symfony\Component\Serializer\NormalizerInterface::normalize()
* @see \Symfony\Component\Serializer\DenormalizerInterface::denormalize()
*/
function hook_hal_type_uri_alter(&$uri, $context = []) {
if ($context['mymodule'] == TRUE) {
$base = \Drupal::config('hal.settings')->get('link_domain');
$uri = str_replace($base, 'http://mymodule.domain', $uri);
}
}
/**
* Alter the HAL relation URI.
*
* Modules may wish to alter the relation URI generated for a resource based on
* the context of the serializer/normalizer operation.
*
* @param string $uri
* The URI to alter.
* @param array $context
* The context from the serializer/normalizer operation.
*
* @see \Symfony\Component\Serializer\SerializerInterface::serialize()
* @see \Symfony\Component\Serializer\SerializerInterface::deserialize()
* @see \Symfony\Component\Serializer\NormalizerInterface::normalize()
* @see \Symfony\Component\Serializer\DenormalizerInterface::denormalize()
*/
function hook_hal_relation_uri_alter(&$uri, $context = []) {
if ($context['mymodule'] == TRUE) {
$base = \Drupal::config('hal.settings')->get('link_domain');
$uri = str_replace($base, 'http://mymodule.domain', $uri);
}
}
/**
* @} End of "addtogroup hooks".
*/

View file

@ -5,5 +5,4 @@ package: Web services
version: VERSION
core: 8.x
dependencies:
- rest
- serialization

View file

@ -0,0 +1,33 @@
<?php
/**
* @file
* Update functions for the HAL module.
*/
/**
* Move 'link_domain' from 'rest.settings' to 'hal.settings'.
*/
function hal_update_8301() {
$config_factory = \Drupal::configFactory();
// The default value for the 'link_domain' key is `~`, which is the YAML
// equivalent of PHP's `NULL`. If the REST module is not installed, this is
// the value we will store in 'hal.settings'.
$link_domain = NULL;
// But if the REST module was installed, we migrate its 'link_domain' setting,
// because we are actually moving that setting from 'rest.settings' to
// 'hal.settings'.
$rest_settings = $config_factory->getEditable('rest.settings');
if ($rest_settings->getRawData() !== []) {
$link_domain = $rest_settings->get('link_domain');
// Remove the 'link_domain' setting from 'rest.settings'.
$rest_settings->clear('link_domain')
->save();
}
$hal_settings = $config_factory->getEditable('hal.settings');
$hal_settings->set('link_domain', $link_domain);
$hal_settings->save(TRUE);
}

View file

@ -15,9 +15,9 @@ function hal_help($route_name, RouteMatchInterface $route_match) {
case 'help.page.hal':
$output = '';
$output .= '<h3>' . t('About') . '</h3>';
$output .= '<p>' . t('<a href=":hal_spec">Hypertext Application Language (HAL)</a> is a format that supports the linking required for hypermedia APIs.', array(':hal_spec' => 'http://stateless.co/hal_specification.html')) . '</p>';
$output .= '<p>' . t('<a href=":hal_spec">Hypertext Application Language (HAL)</a> is a format that supports the linking required for hypermedia APIs.', [':hal_spec' => 'http://stateless.co/hal_specification.html']) . '</p>';
$output .= '<p>' . t('Hypermedia APIs are a style of Web API that uses URIs to identify resources and the <a href="http://wikipedia.org/wiki/Link_relation">link relations</a> between them, enabling API consumers to follow links to discover API functionality.') . '</p>';
$output .= '<p>' . t('This module adds support for serializing entities (such as content items, taxonomy terms, etc.) to the JSON version of HAL. For more information, see the <a href=":hal_do">online documentation for the HAL module</a>.', array(':hal_do' => 'https://www.drupal.org/documentation/modules/hal')) . '</p>';
$output .= '<p>' . t('This module adds support for serializing entities (such as content items, taxonomy terms, etc.) to the JSON version of HAL. For more information, see the <a href=":hal_do">online documentation for the HAL module</a>.', [':hal_do' => 'https://www.drupal.org/documentation/modules/hal']) . '</p>';
return $output;
}
}

View file

@ -1,7 +1,7 @@
services:
serializer.normalizer.entity_reference_item.hal:
class: Drupal\hal\Normalizer\EntityReferenceItemNormalizer
arguments: ['@rest.link_manager', '@serializer.entity_resolver']
arguments: ['@hal.link_manager', '@serializer.entity_resolver']
tags:
- { name: normalizer, priority: 10 }
serializer.normalizer.field_item.hal:
@ -16,17 +16,24 @@ services:
class: Drupal\hal\Normalizer\FileEntityNormalizer
tags:
- { name: normalizer, priority: 20 }
arguments: ['@entity.manager', '@http_client', '@rest.link_manager', '@module_handler']
arguments: ['@entity.manager', '@http_client', '@hal.link_manager', '@module_handler']
serializer.normalizer.entity.hal:
class: Drupal\hal\Normalizer\ContentEntityNormalizer
arguments: ['@rest.link_manager', '@entity.manager', '@module_handler']
arguments: ['@hal.link_manager', '@entity.manager', '@module_handler']
tags:
- { name: normalizer, priority: 10 }
serializer.encoder.hal:
class: Drupal\hal\Encoder\JsonEncoder
tags:
- { name: encoder, priority: 10, format: hal_json }
exception.default_json:
class: Drupal\hal\EventSubscriber\ExceptionHalJsonSubscriber
tags:
- { name: event_subscriber }
# Link managers.
hal.link_manager:
class: Drupal\hal\LinkManager\LinkManager
arguments: ['@hal.link_manager.type', '@hal.link_manager.relation']
hal.link_manager.type:
class: Drupal\hal\LinkManager\TypeLinkManager
arguments: ['@cache.default', '@module_handler', '@config.factory', '@request_stack', '@entity_type.bundle.info']
hal.link_manager.relation:
class: Drupal\hal\LinkManager\RelationLinkManager
arguments: ['@cache.default', '@entity.manager', '@module_handler', '@config.factory', '@request_stack']

View file

@ -2,34 +2,20 @@
namespace Drupal\hal\Encoder;
use Symfony\Component\Serializer\Encoder\JsonEncoder as SymfonyJsonEncoder;
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 SymfonyJsonEncoder {
class JsonEncoder extends SerializationJsonEncoder {
/**
* 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;
}
protected static $format = ['hal_json'];
}

View file

@ -1,19 +0,0 @@
<?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'];
}
}

View file

@ -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);
}

View file

@ -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;
}
}

View file

@ -0,0 +1,58 @@
<?php
namespace Drupal\hal\LinkManager;
/**
* 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.
*
* @return string
* The link domain.
*/
protected function getLinkDomain() {
if (empty($this->linkDomain)) {
if ($domain = $this->configFactory->get('hal.settings')->get('link_domain')) {
$this->linkDomain = rtrim($domain, '/');
}
else {
$request = $this->requestStack->getCurrentRequest();
$this->linkDomain = $request->getSchemeAndHttpHost() . $request->getBasePath();
}
}
return $this->linkDomain;
}
}

View file

@ -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 {
}

View file

@ -0,0 +1,144 @@
<?php
namespace Drupal\hal\LinkManager;
use Drupal\Core\Cache\Cache;
use Drupal\Core\Cache\CacheBackendInterface;
use Drupal\Core\Config\ConfigFactoryInterface;
use Drupal\Core\Entity\ContentEntityTypeInterface;
use Drupal\Core\Entity\EntityManagerInterface;
use Drupal\Core\Extension\ModuleHandlerInterface;
use Symfony\Component\HttpFoundation\RequestStack;
class RelationLinkManager extends LinkManagerBase implements RelationLinkManagerInterface {
/**
* @var \Drupal\Core\Cache\CacheBackendInterface;
*/
protected $cache;
/**
* Entity manager.
*
* @var \Drupal\Core\Entity\EntityManagerInterface
*/
protected $entityManager;
/**
* 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\EntityManagerInterface $entity_manager
* The entity 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.
*/
public function __construct(CacheBackendInterface $cache, EntityManagerInterface $entity_manager, ModuleHandlerInterface $module_handler, ConfigFactoryInterface $config_factory, RequestStack $request_stack) {
$this->cache = $cache;
$this->entityManager = $entity_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() . "/rest/relation/$entity_type/$bundle/$field_name";
$this->moduleHandler->alter('hal_relation_uri', $uri, $context);
// @deprecated in Drupal 8.3.x and will be removed before Drupal 9.0.0. This
// hook is invoked to maintain backwards compatibility
$this->moduleHandler->alter('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 (entity_type, bundle, and field name) keyed
* by corresponding relation URI.
*/
protected function getRelations($context = []) {
$cid = 'hal:links:relations';
$cache = $this->cache->get($cid);
if (!$cache) {
$this->writeCache($context);
$cache = $this->cache->get($cid);
}
return $cache->data;
}
/**
* Writes the cache of relation links.
*
* @param array $context
* Context from the normalizer/serializer operation.
*/
protected function writeCache($context = []) {
$data = [];
foreach ($this->entityManager->getDefinitions() as $entity_type) {
if ($entity_type instanceof ContentEntityTypeInterface) {
foreach ($this->entityManager->getBundleInfo($entity_type->id()) as $bundle => $bundle_info) {
foreach ($this->entityManager->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' => $entity_type,
'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']);
}
}

View file

@ -0,0 +1,39 @@
<?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 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 to transform into internal IDs
*
* @return array
* Array with keys 'entity_type', 'bundle' and 'field_name'.
*/
public function getRelationInternalIds($relation_uri);
}

View file

@ -0,0 +1,150 @@
<?php
namespace Drupal\hal\LinkManager;
use Drupal\Core\Cache\Cache;
use Drupal\Core\Cache\CacheBackendInterface;
use Drupal\Core\Config\ConfigFactoryInterface;
use Drupal\Core\Entity\EntityTypeBundleInfoInterface;
use Drupal\Core\Extension\ModuleHandlerInterface;
use Symfony\Component\HttpFoundation\RequestStack;
class TypeLinkManager extends LinkManagerBase implements TypeLinkManagerInterface {
/**
* 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;
/**
* 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.
*/
public function __construct(CacheBackendInterface $cache, ModuleHandlerInterface $module_handler, ConfigFactoryInterface $config_factory, RequestStack $request_stack, EntityTypeBundleInfoInterface $bundle_info_service) {
$this->cache = $cache;
$this->configFactory = $config_factory;
$this->moduleHandler = $module_handler;
$this->requestStack = $request_stack;
$this->bundleInfoService = $bundle_info_service;
}
/**
* {@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() . "/rest/type/$entity_type/$bundle";
$this->moduleHandler->alter('hal_type_uri', $uri, $context);
// @deprecated in Drupal 8.3.x and will be removed before Drupal 9.0.0. This
// hook is invoked to maintain backwards compatibility
$this->moduleHandler->alter('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 = \Drupal::entityManager()->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;
}
}

View file

@ -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 | boolean
* If the URI matches a bundle, returns an array containing entity_type and
* bundle. Otherwise, returns false.
*/
public function getTypeInternalIds($type_uri, $context = []);
}

View file

@ -6,7 +6,8 @@ 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 Drupal\hal\LinkManager\LinkManagerInterface;
use Drupal\serialization\Normalizer\FieldableEntityNormalizerTrait;
use Symfony\Component\Serializer\Exception\UnexpectedValueException;
/**
@ -14,6 +15,8 @@ use Symfony\Component\Serializer\Exception\UnexpectedValueException;
*/
class ContentEntityNormalizer extends NormalizerBase {
use FieldableEntityNormalizerTrait;
/**
* The interface or class that this Normalizer supports.
*
@ -24,17 +27,10 @@ class ContentEntityNormalizer extends NormalizerBase {
/**
* The hypermedia link manager.
*
* @var \Drupal\rest\LinkManager\LinkManagerInterface
* @var \Drupal\hal\LinkManager\LinkManagerInterface
*/
protected $linkManager;
/**
* The entity manager.
*
* @var \Drupal\Core\Entity\EntityManagerInterface
*/
protected $entityManager;
/**
* The module handler.
*
@ -42,11 +38,10 @@ class ContentEntityNormalizer extends NormalizerBase {
*/
protected $moduleHandler;
/**
* Constructs an ContentEntityNormalizer object.
*
* @param \Drupal\rest\LinkManager\LinkManagerInterface $link_manager
* @param \Drupal\hal\LinkManager\LinkManagerInterface $link_manager
* The hypermedia link manager.
*/
public function __construct(LinkManagerInterface $link_manager, EntityManagerInterface $entity_manager, ModuleHandlerInterface $module_handler) {
@ -58,28 +53,28 @@ class ContentEntityNormalizer extends NormalizerBase {
/**
* {@inheritdoc}
*/
public function normalize($entity, $format = NULL, array $context = array()) {
$context += array(
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 = array(
'_links' => array(
'self' => array(
$normalized = [
'_links' => [
'self' => [
'href' => $this->getEntityUri($entity),
),
'type' => array(
],
'type' => [
'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();
$fields = [];
foreach ($context['included_fields'] as $field_name) {
$fields[] = $entity->get($field_name);
}
@ -120,7 +115,7 @@ class ContentEntityNormalizer extends NormalizerBase {
*
* @throws \Symfony\Component\Serializer\Exception\UnexpectedValueException
*/
public function denormalize($data, $class, $format = NULL, array $context = array()) {
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.');
@ -128,10 +123,10 @@ class ContentEntityNormalizer extends NormalizerBase {
// Create the entity.
$typed_data_ids = $this->getTypedDataIds($data['_links']['type'], $context);
$entity_type = $this->entityManager->getDefinition($typed_data_ids['entity_type']);
$entity_type = $this->getEntityTypeDefinition($typed_data_ids['entity_type']);
$default_langcode_key = $entity_type->getKey('default_langcode');
$langcode_key = $entity_type->getKey('langcode');
$values = array();
$values = [];
// Figure out the language to use.
if (isset($data[$default_langcode_key])) {
@ -159,7 +154,7 @@ class ContentEntityNormalizer extends NormalizerBase {
// Remove links from data array.
unset($data['_links']);
// Get embedded resources and remove from data array.
$embedded = array();
$embedded = [];
if (isset($data['_embedded'])) {
$embedded = $data['_embedded'];
unset($data['_embedded']);
@ -174,23 +169,11 @@ class ContentEntityNormalizer extends NormalizerBase {
}
}
// Pass the names of the fields whose values can be merged.
$entity->_restSubmittedFields = array_keys($data);
$this->denormalizeFieldData($data, $entity, $format, $context);
// 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);
}
}
// 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;
}
@ -224,12 +207,12 @@ class ContentEntityNormalizer extends NormalizerBase {
* @return array
* The typed data IDs.
*/
protected function getTypedDataIds($types, $context = array()) {
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 = array($types);
$types = [$types];
}
if (empty($types)) {

View file

@ -3,7 +3,7 @@
namespace Drupal\hal\Normalizer;
use Drupal\Core\Entity\FieldableEntityInterface;
use Drupal\rest\LinkManager\LinkManagerInterface;
use Drupal\hal\LinkManager\LinkManagerInterface;
use Drupal\serialization\EntityResolver\EntityResolverInterface;
use Drupal\serialization\EntityResolver\UuidReferenceInterface;
@ -22,7 +22,7 @@ class EntityReferenceItemNormalizer extends FieldItemNormalizer implements UuidR
/**
* The hypermedia link manager.
*
* @var \Drupal\rest\LinkManager\LinkManagerInterface
* @var \Drupal\hal\LinkManager\LinkManagerInterface
*/
protected $linkManager;
@ -36,7 +36,7 @@ class EntityReferenceItemNormalizer extends FieldItemNormalizer implements UuidR
/**
* Constructs an EntityReferenceItemNormalizer object.
*
* @param \Drupal\rest\LinkManager\LinkManagerInterface $link_manager
* @param \Drupal\hal\LinkManager\LinkManagerInterface $link_manager
* The hypermedia link manager.
* @param \Drupal\serialization\EntityResolver\EntityResolverInterface $entity_Resolver
* The entity resolver.
@ -49,7 +49,7 @@ class EntityReferenceItemNormalizer extends FieldItemNormalizer implements UuidR
/**
* {@inheritdoc}
*/
public function normalize($field_item, $format = NULL, array $context = array()) {
public function normalize($field_item, $format = NULL, array $context = []) {
/** @var $field_item \Drupal\Core\Field\FieldItemInterface */
$target_entity = $field_item->get('entity')->getValue();
@ -64,7 +64,7 @@ class EntityReferenceItemNormalizer extends FieldItemNormalizer implements UuidR
// will include the langcode.
$langcode = isset($context['langcode']) ? $context['langcode'] : NULL;
unset($context['langcode']);
$context['included_fields'] = array('uuid');
$context['included_fields'] = ['uuid'];
// Normalize the target entity.
$embedded = $this->serializer->normalize($target_entity, $format, $context);
@ -81,14 +81,14 @@ class EntityReferenceItemNormalizer extends FieldItemNormalizer implements UuidR
$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),
),
);
return [
'_links' => [
$field_uri => [$link],
],
'_embedded' => [
$field_uri => [$embedded],
],
];
}
/**
@ -100,7 +100,7 @@ class EntityReferenceItemNormalizer extends FieldItemNormalizer implements UuidR
$target_type = $field_definition->getSetting('target_type');
$id = $this->entityResolver->resolve($this, $data, $target_type);
if (isset($id)) {
return array('target_id' => $id);
return ['target_id' => $id];
}
return NULL;
}

View file

@ -20,8 +20,15 @@ class FieldItemNormalizer extends NormalizerBase {
/**
* {@inheritdoc}
*/
public function normalize($field_item, $format = NULL, array $context = array()) {
$values = $field_item->toArray();
public function normalize($field_item, $format = NULL, array $context = []) {
$values = [];
// We normalize each individual property, so each can do their own casting,
// if needed.
/** @var \Drupal\Core\TypedData\TypedDataInterface $property */
foreach ($field_item as $property_name => $property) {
$values[$property_name] = $this->serializer->normalize($property, $format, $context);
}
if (isset($context['langcode'])) {
$values['lang'] = $context['langcode'];
}
@ -31,15 +38,15 @@ class FieldItemNormalizer extends NormalizerBase {
// 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),
);
return [
$field->getName() => [$values],
];
}
/**
* {@inheritdoc}
*/
public function denormalize($data, $class, $format = NULL, array $context = array()) {
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');
}

View file

@ -3,25 +3,25 @@
namespace Drupal\hal\Normalizer;
use Drupal\Component\Utility\NestedArray;
use Symfony\Component\Serializer\Exception\InvalidArgumentException;
use Drupal\serialization\Normalizer\FieldNormalizer as SerializationFieldNormalizer;
/**
* Converts the Drupal field structure to HAL array structure.
*/
class FieldNormalizer extends NormalizerBase {
class FieldNormalizer extends SerializationFieldNormalizer {
/**
* The interface or class that this Normalizer supports.
* The formats that the Normalizer can handle.
*
* @var string
* @var array
*/
protected $supportedInterfaceOrClass = 'Drupal\Core\Field\FieldItemListInterface';
protected $format = ['hal_json'];
/**
* {@inheritdoc}
*/
public function normalize($field, $format = NULL, array $context = array()) {
$normalized_field_items = array();
public function normalize($field, $format = NULL, array $context = []) {
$normalized_field_items = [];
// Get the field definition.
$entity = $field->getEntity();
@ -51,33 +51,6 @@ class FieldNormalizer extends NormalizerBase {
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.
*
@ -92,7 +65,7 @@ class FieldNormalizer extends NormalizerBase {
* The array of normalized field items.
*/
protected function normalizeFieldItems($field, $format, $context) {
$normalized_field_items = array();
$normalized_field_items = [];
if (!$field->isEmpty()) {
foreach ($field as $field_item) {
$normalized_field_items[] = $this->serializer->normalize($field_item, $format, $context);

View file

@ -4,7 +4,7 @@ namespace Drupal\hal\Normalizer;
use Drupal\Core\Entity\EntityManagerInterface;
use Drupal\Core\Extension\ModuleHandlerInterface;
use Drupal\rest\LinkManager\LinkManagerInterface;
use Drupal\hal\LinkManager\LinkManagerInterface;
use GuzzleHttp\ClientInterface;
/**
@ -33,7 +33,7 @@ class FileEntityNormalizer extends ContentEntityNormalizer {
* The entity manager.
* @param \GuzzleHttp\ClientInterface $http_client
* The HTTP Client.
* @param \Drupal\rest\LinkManager\LinkManagerInterface $link_manager
* @param \Drupal\hal\LinkManager\LinkManagerInterface $link_manager
* The hypermedia link manager.
* @param \Drupal\Core\Extension\ModuleHandlerInterface $module_handler
* The module handler.
@ -47,7 +47,7 @@ class FileEntityNormalizer extends ContentEntityNormalizer {
/**
* {@inheritdoc}
*/
public function normalize($entity, $format = NULL, array $context = array()) {
public function normalize($entity, $format = NULL, array $context = []) {
$data = parent::normalize($entity, $format, $context);
// Replace the file url with a full url for the file.
$data['uri'][0]['value'] = $this->getEntityUri($entity);
@ -58,7 +58,7 @@ class FileEntityNormalizer extends ContentEntityNormalizer {
/**
* {@inheritdoc}
*/
public function denormalize($data, $class, $format = NULL, array $context = array()) {
public function denormalize($data, $class, $format = NULL, array $context = []) {
$file_data = (string) $this->httpClient->get($data['uri'][0]['value'])->getBody();
$path = 'temporary://' . drupal_basename($data['uri'][0]['value']);

View file

@ -15,7 +15,7 @@ abstract class NormalizerBase extends SerializationNormalizerBase implements Den
*
* @var array
*/
protected $formats = array('hal_json');
protected $formats = ['hal_json'];
/**
* {@inheritdoc}

View file

@ -0,0 +1,43 @@
<?php
/**
* @file
* Contains database additions to drupal-8.bare.standard.php.gz for testing the
* upgrade path of hal_update_8301().
*/
use Drupal\Core\Database\Database;
$connection = Database::getConnection();
// Set the schema version.
$connection->insert('key_value')
->fields([
'collection' => 'system.schema',
'name' => 'hal',
'value' => 'i:8000;',
])
->fields([
'collection' => 'system.schema',
'name' => 'serialization',
'value' => 'i:8000;',
])
->execute();
// Update core.extension.
$extensions = $connection->select('config')
->fields('config', ['data'])
->condition('collection', '')
->condition('name', 'core.extension')
->execute()
->fetchField();
$extensions = unserialize($extensions);
$extensions['module']['hal'] = 0;
$extensions['module']['serialization'] = 0;
$connection->update('config')
->fields([
'data' => serialize($extensions),
])
->condition('collection', '')
->condition('name', 'core.extension')
->execute();

View file

@ -0,0 +1,6 @@
name: HAL test module
type: module
description: "Support module for HAL tests."
package: Testing
version: VERSION
core: 8.x

View file

@ -0,0 +1,46 @@
<?php
/**
* @file
* Contains hook implementations for testing HAL module.
*/
/**
* Implements hook_hal_type_uri_alter().
*/
function hal_test_hal_type_uri_alter(&$uri, $context = []) {
if (!empty($context['hal_test'])) {
$uri = 'hal_test_type';
}
}
/**
* Implements hook_hal_relation_uri_alter().
*/
function hal_test_hal_relation_uri_alter(&$uri, $context = []) {
if (!empty($context['hal_test'])) {
$uri = 'hal_test_relation';
}
}
/**
* Implements hook_rest_type_uri_alter().
*
* @deprecated Kept only for BC test coverage, see \Drupal\Tests\hal\Kernel\HalLinkManagerTest::testGetTypeUri().
*/
function hal_test_rest_type_uri_alter(&$uri, $context = []) {
if (!empty($context['rest_test'])) {
$uri = 'rest_test_type';
}
}
/**
* Implements hook_rest_relation_uri_alter().
*
* @deprecated Kept only for BC test coverage, see \Drupal\Tests\hal\Kernel\HalLinkManagerTest::testGetRelationUri().
*/
function hal_test_rest_relation_uri_alter(&$uri, $context = []) {
if (!empty($context['rest_test'])) {
$uri = 'rest_test_relation';
}
}

View file

@ -0,0 +1,30 @@
<?php
namespace Drupal\Tests\hal\Functional\EntityResource\Action;
use Drupal\Tests\rest\Functional\AnonResourceTestTrait;
use Drupal\Tests\rest\Functional\EntityResource\Action\ActionResourceTestBase;
/**
* @group hal
*/
class ActionHalJsonAnonTest extends ActionResourceTestBase {
use AnonResourceTestTrait;
/**
* {@inheritdoc}
*/
public static $modules = ['hal'];
/**
* {@inheritdoc}
*/
protected static $format = 'hal_json';
/**
* {@inheritdoc}
*/
protected static $mimeType = 'application/hal+json';
}

View file

@ -0,0 +1,35 @@
<?php
namespace Drupal\Tests\hal\Functional\EntityResource\Action;
use Drupal\Tests\rest\Functional\BasicAuthResourceTestTrait;
use Drupal\Tests\rest\Functional\EntityResource\Action\ActionResourceTestBase;
/**
* @group hal
*/
class ActionHalJsonBasicAuthTest extends ActionResourceTestBase {
use BasicAuthResourceTestTrait;
/**
* {@inheritdoc}
*/
public static $modules = ['hal', 'basic_auth'];
/**
* {@inheritdoc}
*/
protected static $format = 'hal_json';
/**
* {@inheritdoc}
*/
protected static $mimeType = 'application/hal+json';
/**
* {@inheritdoc}
*/
protected static $auth = 'basic_auth';
}

View file

@ -0,0 +1,35 @@
<?php
namespace Drupal\Tests\hal\Functional\EntityResource\Action;
use Drupal\Tests\rest\Functional\CookieResourceTestTrait;
use Drupal\Tests\rest\Functional\EntityResource\Action\ActionResourceTestBase;
/**
* @group hal
*/
class ActionHalJsonCookieTest extends ActionResourceTestBase {
use CookieResourceTestTrait;
/**
* {@inheritdoc}
*/
public static $modules = ['hal'];
/**
* {@inheritdoc}
*/
protected static $format = 'hal_json';
/**
* {@inheritdoc}
*/
protected static $mimeType = 'application/hal+json';
/**
* {@inheritdoc}
*/
protected static $auth = 'cookie';
}

View file

@ -27,9 +27,4 @@ class BlockHalJsonAnonTest extends BlockResourceTestBase {
*/
protected static $mimeType = 'application/hal+json';
/**
* {@inheritdoc}
*/
protected static $expectedErrorMimeType = 'application/json';
}

View file

@ -2,7 +2,6 @@
namespace Drupal\Tests\hal\Functional\EntityResource\Block;
use Drupal\Tests\hal\Functional\HalJsonBasicAuthWorkaroundFor2805281Trait;
use Drupal\Tests\rest\Functional\BasicAuthResourceTestTrait;
use Drupal\Tests\rest\Functional\EntityResource\Block\BlockResourceTestBase;
@ -28,19 +27,9 @@ class BlockHalJsonBasicAuthTest extends BlockResourceTestBase {
*/
protected static $mimeType = 'application/hal+json';
/**
* {@inheritdoc}
*/
protected static $expectedErrorMimeType = 'application/json';
/**
* {@inheritdoc}
*/
protected static $auth = 'basic_auth';
// @todo Fix in https://www.drupal.org/node/2805281: remove this trait usage.
use HalJsonBasicAuthWorkaroundFor2805281Trait {
HalJsonBasicAuthWorkaroundFor2805281Trait::assertResponseWhenMissingAuthentication insteadof BasicAuthResourceTestTrait;
}
}

View file

@ -27,11 +27,6 @@ class BlockHalJsonCookieTest extends BlockResourceTestBase {
*/
protected static $mimeType = 'application/hal+json';
/**
* {@inheritdoc}
*/
protected static $expectedErrorMimeType = 'application/json';
/**
* {@inheritdoc}
*/

View file

@ -2,7 +2,6 @@
namespace Drupal\Tests\hal\Functional\EntityResource\Comment;
use Drupal\Tests\hal\Functional\HalJsonBasicAuthWorkaroundFor2805281Trait;
use Drupal\Tests\rest\Functional\BasicAuthResourceTestTrait;
/**
@ -22,9 +21,4 @@ class CommentHalJsonBasicAuthTest extends CommentHalJsonTestBase {
*/
protected static $auth = 'basic_auth';
// @todo Fix in https://www.drupal.org/node/2805281: remove this trait usage.
use HalJsonBasicAuthWorkaroundFor2805281Trait {
HalJsonBasicAuthWorkaroundFor2805281Trait::assertResponseWhenMissingAuthentication insteadof BasicAuthResourceTestTrait;
}
}

View file

@ -2,7 +2,6 @@
namespace Drupal\Tests\hal\Functional\EntityResource\Comment;
use Drupal\Core\Cache\Cache;
use Drupal\entity_test\Entity\EntityTest;
use Drupal\Tests\hal\Functional\EntityResource\HalEntityNormalizationTrait;
use Drupal\Tests\rest\Functional\EntityResource\Comment\CommentResourceTestBase;
@ -27,11 +26,6 @@ abstract class CommentHalJsonTestBase extends CommentResourceTestBase {
*/
protected static $mimeType = 'application/hal+json';
/**
* {@inheritdoc}
*/
protected static $expectedErrorMimeType = 'application/json';
/**
* {@inheritdoc}
*
@ -42,9 +36,9 @@ abstract class CommentHalJsonTestBase extends CommentResourceTestBase {
* @todo fix in https://www.drupal.org/node/2824271
*/
protected static $patchProtectedFieldNames = [
'status',
'created',
'changed',
'status',
'thread',
'entity_type',
'field_name',
@ -133,12 +127,4 @@ abstract class CommentHalJsonTestBase extends CommentResourceTestBase {
];
}
/**
* {@inheritdoc}
*/
protected function getExpectedCacheContexts() {
// The 'url.site' cache context is added for '_links' in the response.
return Cache::mergeTags(parent::getExpectedCacheContexts(), ['url.site']);
}
}

View file

@ -0,0 +1,30 @@
<?php
namespace Drupal\Tests\hal\Functional\EntityResource\CommentType;
use Drupal\Tests\rest\Functional\AnonResourceTestTrait;
use Drupal\Tests\rest\Functional\EntityResource\CommentType\CommentTypeResourceTestBase;
/**
* @group hal
*/
class CommentTypeHalJsonAnonTest extends CommentTypeResourceTestBase {
use AnonResourceTestTrait;
/**
* {@inheritdoc}
*/
public static $modules = ['hal'];
/**
* {@inheritdoc}
*/
protected static $format = 'hal_json';
/**
* {@inheritdoc}
*/
protected static $mimeType = 'application/hal+json';
}

View file

@ -0,0 +1,35 @@
<?php
namespace Drupal\Tests\hal\Functional\EntityResource\CommentType;
use Drupal\Tests\rest\Functional\BasicAuthResourceTestTrait;
use Drupal\Tests\rest\Functional\EntityResource\CommentType\CommentTypeResourceTestBase;
/**
* @group hal
*/
class CommentTypeHalJsonBasicAuthTest extends CommentTypeResourceTestBase {
use BasicAuthResourceTestTrait;
/**
* {@inheritdoc}
*/
public static $modules = ['hal', 'basic_auth'];
/**
* {@inheritdoc}
*/
protected static $format = 'hal_json';
/**
* {@inheritdoc}
*/
protected static $mimeType = 'application/hal+json';
/**
* {@inheritdoc}
*/
protected static $auth = 'basic_auth';
}

View file

@ -0,0 +1,35 @@
<?php
namespace Drupal\Tests\hal\Functional\EntityResource\CommentType;
use Drupal\Tests\rest\Functional\CookieResourceTestTrait;
use Drupal\Tests\rest\Functional\EntityResource\CommentType\CommentTypeResourceTestBase;
/**
* @group hal
*/
class CommentTypeHalJsonCookieTest extends CommentTypeResourceTestBase {
use CookieResourceTestTrait;
/**
* {@inheritdoc}
*/
public static $modules = ['hal'];
/**
* {@inheritdoc}
*/
protected static $format = 'hal_json';
/**
* {@inheritdoc}
*/
protected static $mimeType = 'application/hal+json';
/**
* {@inheritdoc}
*/
protected static $auth = 'cookie';
}

View file

@ -27,9 +27,4 @@ class ConfigTestHalJsonAnonTest extends ConfigTestResourceTestBase {
*/
protected static $mimeType = 'application/hal+json';
/**
* {@inheritdoc}
*/
protected static $expectedErrorMimeType = 'application/json';
}

View file

@ -2,7 +2,6 @@
namespace Drupal\Tests\hal\Functional\EntityResource\ConfigTest;
use Drupal\Tests\hal\Functional\HalJsonBasicAuthWorkaroundFor2805281Trait;
use Drupal\Tests\rest\Functional\BasicAuthResourceTestTrait;
use Drupal\Tests\rest\Functional\EntityResource\ConfigTest\ConfigTestResourceTestBase;
@ -28,19 +27,9 @@ class ConfigTestHalJsonBasicAuthTest extends ConfigTestResourceTestBase {
*/
protected static $mimeType = 'application/hal+json';
/**
* {@inheritdoc}
*/
protected static $expectedErrorMimeType = 'application/json';
/**
* {@inheritdoc}
*/
protected static $auth = 'basic_auth';
// @todo Fix in https://www.drupal.org/node/2805281: remove this trait usage.
use HalJsonBasicAuthWorkaroundFor2805281Trait {
HalJsonBasicAuthWorkaroundFor2805281Trait::assertResponseWhenMissingAuthentication insteadof BasicAuthResourceTestTrait;
}
}

View file

@ -27,11 +27,6 @@ class ConfigTestHalJsonCookieTest extends ConfigTestResourceTestBase {
*/
protected static $mimeType = 'application/hal+json';
/**
* {@inheritdoc}
*/
protected static $expectedErrorMimeType = 'application/json';
/**
* {@inheritdoc}
*/

View file

@ -0,0 +1,30 @@
<?php
namespace Drupal\Tests\hal\Functional\EntityResource\ConfigurableLanguage;
use Drupal\Tests\rest\Functional\AnonResourceTestTrait;
use Drupal\Tests\rest\Functional\EntityResource\ConfigurableLanguage\ConfigurableLanguageResourceTestBase;
/**
* @group hal
*/
class ConfigurableLanguageHalJsonAnonTest extends ConfigurableLanguageResourceTestBase {
use AnonResourceTestTrait;
/**
* {@inheritdoc}
*/
public static $modules = ['hal'];
/**
* {@inheritdoc}
*/
protected static $format = 'hal_json';
/**
* {@inheritdoc}
*/
protected static $mimeType = 'application/hal+json';
}

View file

@ -0,0 +1,35 @@
<?php
namespace Drupal\Tests\hal\Functional\EntityResource\ConfigurableLanguage;
use Drupal\Tests\rest\Functional\BasicAuthResourceTestTrait;
use Drupal\Tests\rest\Functional\EntityResource\ConfigurableLanguage\ConfigurableLanguageResourceTestBase;
/**
* @group hal
*/
class ConfigurableLanguageHalJsonBasicAuthTest extends ConfigurableLanguageResourceTestBase {
use BasicAuthResourceTestTrait;
/**
* {@inheritdoc}
*/
public static $modules = ['hal', 'basic_auth'];
/**
* {@inheritdoc}
*/
protected static $format = 'hal_json';
/**
* {@inheritdoc}
*/
protected static $mimeType = 'application/hal+json';
/**
* {@inheritdoc}
*/
protected static $auth = 'basic_auth';
}

View file

@ -0,0 +1,35 @@
<?php
namespace Drupal\Tests\hal\Functional\EntityResource\ConfigurableLanguage;
use Drupal\Tests\rest\Functional\CookieResourceTestTrait;
use Drupal\Tests\rest\Functional\EntityResource\ConfigurableLanguage\ConfigurableLanguageResourceTestBase;
/**
* @group hal
*/
class ConfigurableLanguageHalJsonCookieTest extends ConfigurableLanguageResourceTestBase {
use CookieResourceTestTrait;
/**
* {@inheritdoc}
*/
public static $modules = ['hal'];
/**
* {@inheritdoc}
*/
protected static $format = 'hal_json';
/**
* {@inheritdoc}
*/
protected static $mimeType = 'application/hal+json';
/**
* {@inheritdoc}
*/
protected static $auth = 'cookie';
}

View file

@ -2,7 +2,6 @@
namespace Drupal\Tests\hal\Functional\EntityResource\EntityTest;
use Drupal\Core\Cache\Cache;
use Drupal\Tests\hal\Functional\EntityResource\HalEntityNormalizationTrait;
use Drupal\Tests\rest\Functional\AnonResourceTestTrait;
use Drupal\Tests\rest\Functional\EntityResource\EntityTest\EntityTestResourceTestBase;
@ -31,11 +30,6 @@ class EntityTestHalJsonAnonTest extends EntityTestResourceTestBase {
*/
protected static $mimeType = 'application/hal+json';
/**
* {@inheritdoc}
*/
protected static $expectedErrorMimeType = 'application/json';
/**
* {@inheritdoc}
*/
@ -94,12 +88,4 @@ class EntityTestHalJsonAnonTest extends EntityTestResourceTestBase {
];
}
/**
* {@inheritdoc}
*/
protected function getExpectedCacheContexts() {
// The 'url.site' cache context is added for '_links' in the response.
return Cache::mergeTags(parent::getExpectedCacheContexts(), ['url.site']);
}
}

View file

@ -2,7 +2,6 @@
namespace Drupal\Tests\hal\Functional\EntityResource\EntityTest;
use Drupal\Tests\hal\Functional\HalJsonBasicAuthWorkaroundFor2805281Trait;
use Drupal\Tests\rest\Functional\BasicAuthResourceTestTrait;
/**
@ -22,9 +21,4 @@ class EntityTestHalJsonBasicAuthTest extends EntityTestHalJsonAnonTest {
*/
protected static $auth = 'basic_auth';
// @todo Fix in https://www.drupal.org/node/2805281: remove this trait usage.
use HalJsonBasicAuthWorkaroundFor2805281Trait {
HalJsonBasicAuthWorkaroundFor2805281Trait::assertResponseWhenMissingAuthentication insteadof BasicAuthResourceTestTrait;
}
}

View file

@ -0,0 +1,103 @@
<?php
namespace Drupal\Tests\hal\Functional\EntityResource\EntityTestLabel;
use Drupal\Tests\hal\Functional\EntityResource\HalEntityNormalizationTrait;
use Drupal\Tests\rest\Functional\AnonResourceTestTrait;
use Drupal\Tests\rest\Functional\EntityResource\EntityTestLabel\EntityTestLabelResourceTestBase;
use Drupal\user\Entity\User;
/**
* @group hal
*/
class EntityTestLabelHalJsonAnonTest extends EntityTestLabelResourceTestBase {
use HalEntityNormalizationTrait;
use AnonResourceTestTrait;
/**
* {@inheritdoc}
*/
public static $modules = ['hal'];
/**
* {@inheritdoc}
*/
protected static $format = 'hal_json';
/**
* {@inheritdoc}
*/
protected static $mimeType = 'application/hal+json';
/**
* {@inheritdoc}
*/
protected function getExpectedNormalizedEntity() {
$default_normalization = parent::getExpectedNormalizedEntity();
$normalization = $this->applyHalFieldNormalization($default_normalization);
$author = User::load(0);
return $normalization + [
'_links' => [
'self' => [
'href' => '',
],
'type' => [
'href' => $this->baseUrl . '/rest/type/entity_test_label/entity_test_label',
],
$this->baseUrl . '/rest/relation/entity_test_label/entity_test_label/user_id' => [
[
'href' => $this->baseUrl . '/user/0?_format=hal_json',
'lang' => 'en',
],
],
],
'_embedded' => [
$this->baseUrl . '/rest/relation/entity_test_label/entity_test_label/user_id' => [
[
'_links' => [
'self' => [
'href' => $this->baseUrl . '/user/0?_format=hal_json',
],
'type' => [
'href' => $this->baseUrl . '/rest/type/user/user',
],
],
'uuid' => [
[
'value' => $author->uuid(),
],
],
'lang' => 'en',
],
],
],
];
}
/**
* {@inheritdoc}
*/
protected function getNormalizedPostEntity() {
return parent::getNormalizedPostEntity() + [
'_links' => [
'type' => [
'href' => $this->baseUrl . '/rest/type/entity_test_label/entity_test_label',
],
],
];
}
/**
* {@inheritdoc}
*/
protected function getExpectedCacheContexts() {
return [
'url.site',
'user.permissions',
];
}
}

View file

@ -0,0 +1,24 @@
<?php
namespace Drupal\Tests\hal\Functional\EntityResource\EntityTestLabel;
use Drupal\Tests\rest\Functional\BasicAuthResourceTestTrait;
/**
* @group hal
*/
class EntityTestLabelHalJsonBasicAuthTest extends EntityTestLabelHalJsonAnonTest {
use BasicAuthResourceTestTrait;
/**
* {@inheritdoc}
*/
public static $modules = ['basic_auth'];
/**
* {@inheritdoc}
*/
protected static $auth = 'basic_auth';
}

View file

@ -0,0 +1,19 @@
<?php
namespace Drupal\Tests\hal\Functional\EntityResource\EntityTestLabel;
use Drupal\Tests\rest\Functional\CookieResourceTestTrait;
/**
* @group hal
*/
class EntityTestLabelHalJsonCookieTest extends EntityTestLabelHalJsonAnonTest {
use CookieResourceTestTrait;
/**
* {@inheritdoc}
*/
protected static $auth = 'cookie';
}

View file

@ -0,0 +1,30 @@
<?php
namespace Drupal\Tests\hal\Functional\EntityResource\FilterFormat;
use Drupal\Tests\rest\Functional\AnonResourceTestTrait;
use Drupal\Tests\rest\Functional\EntityResource\FilterFormat\FilterFormatResourceTestBase;
/**
* @group hal
*/
class FilterFormatHalJsonAnonTest extends FilterFormatResourceTestBase {
use AnonResourceTestTrait;
/**
* {@inheritdoc}
*/
public static $modules = ['hal'];
/**
* {@inheritdoc}
*/
protected static $format = 'hal_json';
/**
* {@inheritdoc}
*/
protected static $mimeType = 'application/hal+json';
}

View file

@ -0,0 +1,35 @@
<?php
namespace Drupal\Tests\hal\Functional\EntityResource\FilterFormat;
use Drupal\Tests\rest\Functional\BasicAuthResourceTestTrait;
use Drupal\Tests\rest\Functional\EntityResource\FilterFormat\FilterFormatResourceTestBase;
/**
* @group hal
*/
class FilterFormatHalJsonBasicAuthTest extends FilterFormatResourceTestBase {
use BasicAuthResourceTestTrait;
/**
* {@inheritdoc}
*/
public static $modules = ['hal', 'basic_auth'];
/**
* {@inheritdoc}
*/
protected static $format = 'hal_json';
/**
* {@inheritdoc}
*/
protected static $mimeType = 'application/hal+json';
/**
* {@inheritdoc}
*/
protected static $auth = 'basic_auth';
}

View file

@ -0,0 +1,35 @@
<?php
namespace Drupal\Tests\hal\Functional\EntityResource\FilterFormat;
use Drupal\Tests\rest\Functional\CookieResourceTestTrait;
use Drupal\Tests\rest\Functional\EntityResource\FilterFormat\FilterFormatResourceTestBase;
/**
* @group hal
*/
class FilterFormatHalJsonCookieTest extends FilterFormatResourceTestBase {
use CookieResourceTestTrait;
/**
* {@inheritdoc}
*/
public static $modules = ['hal'];
/**
* {@inheritdoc}
*/
protected static $format = 'hal_json';
/**
* {@inheritdoc}
*/
protected static $mimeType = 'application/hal+json';
/**
* {@inheritdoc}
*/
protected static $auth = 'cookie';
}

View file

@ -92,7 +92,7 @@ trait HalEntityNormalizationTrait {
* {@inheritdoc}
*/
protected function assertNormalizationEdgeCases($method, Url $url, array $request_options) {
// \Drupal\serialization\Normalizer\EntityNormalizer::denormalize(): entity
// \Drupal\hal\Normalizer\EntityNormalizer::denormalize(): entity
// types with bundles MUST send their bundle field to be denormalizable.
if ($this->entity->getEntityType()->hasKey('bundle')) {
$normalization = $this->getNormalizedPostEntity();
@ -103,11 +103,7 @@ trait HalEntityNormalizationTrait {
// DX: 400 when incorrect entity type bundle is specified.
$response = $this->request($method, $url, $request_options);
// @todo Uncomment, remove next 3 in https://www.drupal.org/node/2813853.
// $this->assertResourceErrorResponse(400, 'No entity type(s) specified', $response);
$this->assertSame(400, $response->getStatusCode());
$this->assertSame([static::$mimeType], $response->getHeader('Content-Type'));
$this->assertSame($this->serializer->encode(['error' => 'No entity type(s) specified'], static::$format), (string) $response->getBody());
$this->assertResourceErrorResponse(400, 'No entity type(s) specified', $response);
unset($normalization['_links']['type']);
@ -116,11 +112,7 @@ trait HalEntityNormalizationTrait {
// DX: 400 when no entity type bundle is specified.
$response = $this->request($method, $url, $request_options);
// @todo Uncomment, remove next 3 in https://www.drupal.org/node/2813853.
// $this->assertResourceErrorResponse(400, 'The type link relation must be specified.', $response);
$this->assertSame(400, $response->getStatusCode());
$this->assertSame([static::$mimeType], $response->getHeader('Content-Type'));
$this->assertSame($this->serializer->encode(['error' => 'The type link relation must be specified.'], static::$format), (string) $response->getBody());
$this->assertResourceErrorResponse(400, 'The type link relation must be specified.', $response);
}
}

View file

@ -0,0 +1,30 @@
<?php
namespace Drupal\Tests\hal\Functional\EntityResource\ImageStyle;
use Drupal\Tests\rest\Functional\AnonResourceTestTrait;
use Drupal\Tests\rest\Functional\EntityResource\ImageStyle\ImageStyleResourceTestBase;
/**
* @group rest
*/
class ImageStyleHalJsonAnonTest extends ImageStyleResourceTestBase {
use AnonResourceTestTrait;
/**
* {@inheritdoc}
*/
public static $modules = ['hal'];
/**
* {@inheritdoc}
*/
protected static $format = 'hal_json';
/**
* {@inheritdoc}
*/
protected static $mimeType = 'application/hal+json';
}

View file

@ -0,0 +1,35 @@
<?php
namespace Drupal\Tests\hal\Functional\EntityResource\ImageStyle;
use Drupal\Tests\rest\Functional\BasicAuthResourceTestTrait;
use Drupal\Tests\rest\Functional\EntityResource\ImageStyle\ImageStyleResourceTestBase;
/**
* @group rest
*/
class ImageStyleHalJsonBasicAuthTest extends ImageStyleResourceTestBase {
use BasicAuthResourceTestTrait;
/**
* {@inheritdoc}
*/
public static $modules = ['hal', 'basic_auth'];
/**
* {@inheritdoc}
*/
protected static $format = 'hal_json';
/**
* {@inheritdoc}
*/
protected static $mimeType = 'application/hal+json';
/**
* {@inheritdoc}
*/
protected static $auth = 'basic_auth';
}

View file

@ -0,0 +1,35 @@
<?php
namespace Drupal\Tests\hal\Functional\EntityResource\ImageStyle;
use Drupal\Tests\rest\Functional\CookieResourceTestTrait;
use Drupal\Tests\rest\Functional\EntityResource\ImageStyle\ImageStyleResourceTestBase;
/**
* @group rest
*/
class ImageStyleHalJsonCookieTest extends ImageStyleResourceTestBase {
use CookieResourceTestTrait;
/**
* {@inheritdoc}
*/
public static $modules = ['hal'];
/**
* {@inheritdoc}
*/
protected static $format = 'hal_json';
/**
* {@inheritdoc}
*/
protected static $mimeType = 'application/hal+json';
/**
* {@inheritdoc}
*/
protected static $auth = 'cookie';
}

View file

@ -0,0 +1,29 @@
<?php
namespace Drupal\Tests\hal\Functional\EntityResource\Item;
use Drupal\Tests\rest\Functional\AnonResourceTestTrait;
/**
* @group hal
*/
class ItemHalJsonAnonTest extends ItemHalJsonTestBase {
use AnonResourceTestTrait;
/**
* {@inheritdoc}
*/
public static $modules = ['hal'];
/**
* {@inheritdoc}
*/
protected static $format = 'hal_json';
/**
* {@inheritdoc}
*/
protected static $mimeType = 'application/hal+json';
}

View file

@ -0,0 +1,34 @@
<?php
namespace Drupal\Tests\hal\Functional\EntityResource\Item;
use Drupal\Tests\rest\Functional\BasicAuthResourceTestTrait;
/**
* @group hal
*/
class ItemHalJsonBasicAuthTest extends ItemHalJsonTestBase {
use BasicAuthResourceTestTrait;
/**
* {@inheritdoc}
*/
public static $modules = ['hal', 'basic_auth'];
/**
* {@inheritdoc}
*/
protected static $format = 'hal_json';
/**
* {@inheritdoc}
*/
protected static $mimeType = 'application/hal+json';
/**
* {@inheritdoc}
*/
protected static $auth = 'basic_auth';
}

View file

@ -0,0 +1,34 @@
<?php
namespace Drupal\Tests\hal\Functional\EntityResource\Item;
use Drupal\Tests\rest\Functional\CookieResourceTestTrait;
/**
* @group hal
*/
class ItemHalJsonCookieTest extends ItemHalJsonTestBase {
use CookieResourceTestTrait;
/**
* {@inheritdoc}
*/
public static $modules = ['hal'];
/**
* {@inheritdoc}
*/
protected static $format = 'hal_json';
/**
* {@inheritdoc}
*/
protected static $mimeType = 'application/hal+json';
/**
* {@inheritdoc}
*/
protected static $auth = 'cookie';
}

View file

@ -0,0 +1,100 @@
<?php
namespace Drupal\Tests\hal\Functional\EntityResource\Item;
use Drupal\aggregator\Entity\Feed;
use Drupal\Tests\hal\Functional\EntityResource\HalEntityNormalizationTrait;
use Drupal\Tests\rest\Functional\AnonResourceTestTrait;
use Drupal\Tests\rest\Functional\EntityResource\Item\ItemResourceTestBase;
/**
* ResourceTestBase for Item entity.
*/
abstract class ItemHalJsonTestBase extends ItemResourceTestBase {
use HalEntityNormalizationTrait;
use AnonResourceTestTrait;
/**
* {@inheritdoc}
*/
public static $modules = ['hal'];
/**
* {@inheritdoc}
*/
protected static $format = 'hal_json';
/**
* {@inheritdoc}
*/
protected static $mimeType = 'application/hal+json';
/**
* {@inheritdoc}
*/
protected function getExpectedNormalizedEntity() {
$default_normalization = parent::getExpectedNormalizedEntity();
$normalization = $this->applyHalFieldNormalization($default_normalization);
$feed = Feed::load($this->entity->getFeedId());
return $normalization + [
'_embedded' => [
$this->baseUrl . '/rest/relation/aggregator_item/aggregator_item/fid' => [
[
'_links' => [
'self' => [
'href' => $this->baseUrl . '/aggregator/sources/1?_format=hal_json',
],
'type' => [
'href' => $this->baseUrl . '/rest/type/aggregator_feed/aggregator_feed',
],
],
'uuid' => [
[
'value' => $feed->uuid(),
],
],
],
],
],
'_links' => [
'self' => [
'href' => '',
],
'type' => [
'href' => $this->baseUrl . '/rest/type/aggregator_item/aggregator_item',
],
$this->baseUrl . '/rest/relation/aggregator_item/aggregator_item/fid' => [
[
'href' => $this->baseUrl . '/aggregator/sources/' . $feed->id() . '?_format=hal_json',
],
],
],
];
}
/**
* {@inheritdoc}
*/
protected function getNormalizedPostEntity() {
return parent::getNormalizedPostEntity() + [
'_links' => [
'type' => [
'href' => $this->baseUrl . '/rest/type/aggregator_item/aggregator_item',
],
],
];
}
/**
* {@inheritdoc}
*/
protected function getExpectedCacheContexts() {
return [
'url.site',
'user.permissions',
];
}
}

View file

@ -0,0 +1,74 @@
<?php
namespace Drupal\Tests\hal\Functional\EntityResource\MenuLinkContent;
use Drupal\Core\Cache\Cache;
use Drupal\Tests\hal\Functional\EntityResource\HalEntityNormalizationTrait;
use Drupal\Tests\rest\Functional\AnonResourceTestTrait;
use Drupal\Tests\rest\Functional\EntityResource\MenuLinkContent\MenuLinkContentResourceTestBase;
/**
* @group hal
*/
class MenuLinkContentHalJsonAnonTest extends MenuLinkContentResourceTestBase {
use HalEntityNormalizationTrait;
use AnonResourceTestTrait;
/**
* {@inheritdoc}
*/
public static $modules = ['hal'];
/**
* {@inheritdoc}
*/
protected static $format = 'hal_json';
/**
* {@inheritdoc}
*/
protected static $mimeType = 'application/hal+json';
/**
* {@inheritdoc}
*/
protected function getExpectedNormalizedEntity() {
$default_normalization = parent::getExpectedNormalizedEntity();
$normalization = $this->applyHalFieldNormalization($default_normalization);
return $normalization + [
'_links' => [
'self' => [
'href' => $this->baseUrl . '/admin/structure/menu/item/1/edit?_format=hal_json',
],
'type' => [
'href' => $this->baseUrl . '/rest/type/menu_link_content/menu_link_content',
],
],
];
}
/**
* {@inheritdoc}
*/
protected function getNormalizedPostEntity() {
return parent::getNormalizedPostEntity() + [
'_links' => [
'type' => [
'href' => $this->baseUrl . '/rest/type/menu_link_content/menu_link_content',
],
],
];
}
/**
* {@inheritdoc}
*/
protected function getExpectedCacheContexts() {
// The 'url.site' cache context is added for '_links' in the response.
return Cache::mergeTags(parent::getExpectedCacheContexts(), ['url.site']);
}
}

View file

@ -0,0 +1,24 @@
<?php
namespace Drupal\Tests\hal\Functional\EntityResource\MenuLinkContent;
use Drupal\Tests\rest\Functional\BasicAuthResourceTestTrait;
/**
* @group hal
*/
class MenuLinkContentHalJsonBasicAuthTest extends MenuLinkContentHalJsonAnonTest {
use BasicAuthResourceTestTrait;
/**
* {@inheritdoc}
*/
public static $modules = ['basic_auth'];
/**
* {@inheritdoc}
*/
protected static $auth = 'basic_auth';
}

View file

@ -0,0 +1,19 @@
<?php
namespace Drupal\Tests\hal\Functional\EntityResource\MenuLinkContent;
use Drupal\Tests\rest\Functional\CookieResourceTestTrait;
/**
* @group hal
*/
class MenuLinkContentHalJsonCookieTest extends MenuLinkContentHalJsonAnonTest {
use CookieResourceTestTrait;
/**
* {@inheritdoc}
*/
protected static $auth = 'cookie';
}

View file

@ -2,7 +2,6 @@
namespace Drupal\Tests\hal\Functional\EntityResource\Node;
use Drupal\Core\Cache\Cache;
use Drupal\Tests\hal\Functional\EntityResource\HalEntityNormalizationTrait;
use Drupal\Tests\rest\Functional\AnonResourceTestTrait;
use Drupal\Tests\rest\Functional\EntityResource\Node\NodeResourceTestBase;
@ -31,11 +30,6 @@ class NodeHalJsonAnonTest extends NodeResourceTestBase {
*/
protected static $mimeType = 'application/hal+json';
/**
* {@inheritdoc}
*/
protected static $expectedErrorMimeType = 'application/json';
/**
* {@inheritdoc}
*/
@ -126,12 +120,4 @@ class NodeHalJsonAnonTest extends NodeResourceTestBase {
];
}
/**
* {@inheritdoc}
*/
protected function getExpectedCacheContexts() {
// The 'url.site' cache context is added for '_links' in the response.
return Cache::mergeContexts(parent::getExpectedCacheContexts(), ['url.site']);
}
}

View file

@ -2,7 +2,6 @@
namespace Drupal\Tests\hal\Functional\EntityResource\Node;
use Drupal\Tests\hal\Functional\HalJsonBasicAuthWorkaroundFor2805281Trait;
use Drupal\Tests\rest\Functional\BasicAuthResourceTestTrait;
/**
@ -22,9 +21,4 @@ class NodeHalJsonBasicAuthTest extends NodeHalJsonAnonTest {
*/
protected static $auth = 'basic_auth';
// @todo Fix in https://www.drupal.org/node/2805281: remove this trait usage.
use HalJsonBasicAuthWorkaroundFor2805281Trait {
HalJsonBasicAuthWorkaroundFor2805281Trait::assertResponseWhenMissingAuthentication insteadof BasicAuthResourceTestTrait;
}
}

View file

@ -0,0 +1,30 @@
<?php
namespace Drupal\Tests\hal\Functional\EntityResource\NodeType;
use Drupal\Tests\rest\Functional\AnonResourceTestTrait;
use Drupal\Tests\rest\Functional\EntityResource\NodeType\NodeTypeResourceTestBase;
/**
* @group hal
*/
class NodeTypeHalJsonAnonTest extends NodeTypeResourceTestBase {
use AnonResourceTestTrait;
/**
* {@inheritdoc}
*/
public static $modules = ['hal'];
/**
* {@inheritdoc}
*/
protected static $format = 'hal_json';
/**
* {@inheritdoc}
*/
protected static $mimeType = 'application/hal+json';
}

View file

@ -0,0 +1,35 @@
<?php
namespace Drupal\Tests\hal\Functional\EntityResource\NodeType;
use Drupal\Tests\rest\Functional\BasicAuthResourceTestTrait;
use Drupal\Tests\rest\Functional\EntityResource\NodeType\NodeTypeResourceTestBase;
/**
* @group hal
*/
class NodeTypeHalJsonBasicAuthTest extends NodeTypeResourceTestBase {
use BasicAuthResourceTestTrait;
/**
* {@inheritdoc}
*/
public static $modules = ['hal', 'basic_auth'];
/**
* {@inheritdoc}
*/
protected static $format = 'hal_json';
/**
* {@inheritdoc}
*/
protected static $mimeType = 'application/hal+json';
/**
* {@inheritdoc}
*/
protected static $auth = 'basic_auth';
}

View file

@ -0,0 +1,35 @@
<?php
namespace Drupal\Tests\hal\Functional\EntityResource\NodeType;
use Drupal\Tests\rest\Functional\CookieResourceTestTrait;
use Drupal\Tests\rest\Functional\EntityResource\NodeType\NodeTypeResourceTestBase;
/**
* @group hal
*/
class NodeTypeHalJsonCookieTest extends NodeTypeResourceTestBase {
use CookieResourceTestTrait;
/**
* {@inheritdoc}
*/
public static $modules = ['hal'];
/**
* {@inheritdoc}
*/
protected static $format = 'hal_json';
/**
* {@inheritdoc}
*/
protected static $mimeType = 'application/hal+json';
/**
* {@inheritdoc}
*/
protected static $auth = 'cookie';
}

View file

@ -27,9 +27,4 @@ class RoleHalJsonAnonTest extends RoleResourceTestBase {
*/
protected static $mimeType = 'application/hal+json';
/**
* {@inheritdoc}
*/
protected static $expectedErrorMimeType = 'application/json';
}

View file

@ -2,7 +2,6 @@
namespace Drupal\Tests\hal\Functional\EntityResource\Role;
use Drupal\Tests\hal\Functional\HalJsonBasicAuthWorkaroundFor2805281Trait;
use Drupal\Tests\rest\Functional\BasicAuthResourceTestTrait;
use Drupal\Tests\rest\Functional\EntityResource\Role\RoleResourceTestBase;
@ -28,19 +27,9 @@ class RoleHalJsonBasicAuthTest extends RoleResourceTestBase {
*/
protected static $mimeType = 'application/hal+json';
/**
* {@inheritdoc}
*/
protected static $expectedErrorMimeType = 'application/json';
/**
* {@inheritdoc}
*/
protected static $auth = 'basic_auth';
// @todo Fix in https://www.drupal.org/node/2805281: remove this trait usage.
use HalJsonBasicAuthWorkaroundFor2805281Trait {
HalJsonBasicAuthWorkaroundFor2805281Trait::assertResponseWhenMissingAuthentication insteadof BasicAuthResourceTestTrait;
}
}

View file

@ -27,11 +27,6 @@ class RoleHalJsonCookieTest extends RoleResourceTestBase {
*/
protected static $mimeType = 'application/hal+json';
/**
* {@inheritdoc}
*/
protected static $expectedErrorMimeType = 'application/json';
/**
* {@inheritdoc}
*/

View file

@ -0,0 +1,30 @@
<?php
namespace Drupal\Tests\hal\Functional\EntityResource\SearchPage;
use Drupal\Tests\rest\Functional\AnonResourceTestTrait;
use Drupal\Tests\rest\Functional\EntityResource\SearchPage\SearchPageResourceTestBase;
/**
* @group hal
*/
class SearchPageHalJsonAnonTest extends SearchPageResourceTestBase {
use AnonResourceTestTrait;
/**
* {@inheritdoc}
*/
public static $modules = ['hal'];
/**
* {@inheritdoc}
*/
protected static $format = 'hal_json';
/**
* {@inheritdoc}
*/
protected static $mimeType = 'application/hal+json';
}

View file

@ -0,0 +1,35 @@
<?php
namespace Drupal\Tests\hal\Functional\EntityResource\SearchPage;
use Drupal\Tests\rest\Functional\BasicAuthResourceTestTrait;
use Drupal\Tests\rest\Functional\EntityResource\SearchPage\SearchPageResourceTestBase;
/**
* @group hal
*/
class SearchPageHalJsonBasicAuthTest extends SearchPageResourceTestBase {
use BasicAuthResourceTestTrait;
/**
* {@inheritdoc}
*/
public static $modules = ['hal', 'basic_auth'];
/**
* {@inheritdoc}
*/
protected static $format = 'hal_json';
/**
* {@inheritdoc}
*/
protected static $mimeType = 'application/hal+json';
/**
* {@inheritdoc}
*/
protected static $auth = 'basic_auth';
}

View file

@ -0,0 +1,35 @@
<?php
namespace Drupal\Tests\hal\Functional\EntityResource\SearchPage;
use Drupal\Tests\rest\Functional\CookieResourceTestTrait;
use Drupal\Tests\rest\Functional\EntityResource\SearchPage\SearchPageResourceTestBase;
/**
* @group hal
*/
class SearchPageHalJsonCookieTest extends SearchPageResourceTestBase {
use CookieResourceTestTrait;
/**
* {@inheritdoc}
*/
public static $modules = ['hal'];
/**
* {@inheritdoc}
*/
protected static $format = 'hal_json';
/**
* {@inheritdoc}
*/
protected static $mimeType = 'application/hal+json';
/**
* {@inheritdoc}
*/
protected static $auth = 'cookie';
}

View file

@ -0,0 +1,74 @@
<?php
namespace Drupal\Tests\hal\Functional\EntityResource\Shortcut;
use Drupal\Core\Cache\Cache;
use Drupal\Tests\hal\Functional\EntityResource\HalEntityNormalizationTrait;
use Drupal\Tests\rest\Functional\AnonResourceTestTrait;
use Drupal\Tests\rest\Functional\EntityResource\Shortcut\ShortcutResourceTestBase;
/**
* @group hal
*/
class ShortcutHalJsonAnonTest extends ShortcutResourceTestBase {
use HalEntityNormalizationTrait;
use AnonResourceTestTrait;
/**
* {@inheritdoc}
*/
public static $modules = ['hal'];
/**
* {@inheritdoc}
*/
protected static $format = 'hal_json';
/**
* {@inheritdoc}
*/
protected static $mimeType = 'application/hal+json';
/**
* {@inheritdoc}
*/
protected function getExpectedNormalizedEntity() {
$default_normalization = parent::getExpectedNormalizedEntity();
$normalization = $this->applyHalFieldNormalization($default_normalization);
return $normalization + [
'_links' => [
'self' => [
'href' => $this->baseUrl . '/admin/config/user-interface/shortcut/link/1?_format=hal_json',
],
'type' => [
'href' => $this->baseUrl . '/rest/type/shortcut/default',
],
],
];
}
/**
* {@inheritdoc}
*/
protected function getNormalizedPostEntity() {
return parent::getNormalizedPostEntity() + [
'_links' => [
'type' => [
'href' => $this->baseUrl . '/rest/type/shortcut/default',
],
],
];
}
/**
* {@inheritdoc}
*/
protected function getExpectedCacheContexts() {
// The 'url.site' cache context is added for '_links' in the response.
return Cache::mergeContexts(parent::getExpectedCacheContexts(), ['url.site']);
}
}

View file

@ -0,0 +1,24 @@
<?php
namespace Drupal\Tests\hal\Functional\EntityResource\Shortcut;
use Drupal\Tests\rest\Functional\BasicAuthResourceTestTrait;
/**
* @group hal
*/
class ShortcutHalJsonBasicAuthTest extends ShortcutHalJsonAnonTest {
use BasicAuthResourceTestTrait;
/**
* {@inheritdoc}
*/
public static $modules = ['basic_auth'];
/**
* {@inheritdoc}
*/
protected static $auth = 'basic_auth';
}

View file

@ -0,0 +1,18 @@
<?php
namespace Drupal\Tests\hal\Functional\EntityResource\Shortcut;
use Drupal\Tests\rest\Functional\CookieResourceTestTrait;
/**
* @group hal
*/
class ShortcutHalJsonCookieTest extends ShortcutHalJsonAnonTest {
use CookieResourceTestTrait;
/**
* {@inheritdoc}
*/
protected static $auth = 'cookie';
}

View file

@ -2,7 +2,6 @@
namespace Drupal\Tests\hal\Functional\EntityResource\Term;
use Drupal\Core\Cache\Cache;
use Drupal\Tests\hal\Functional\EntityResource\HalEntityNormalizationTrait;
use Drupal\Tests\rest\Functional\AnonResourceTestTrait;
use Drupal\Tests\rest\Functional\EntityResource\Term\TermResourceTestBase;
@ -30,11 +29,6 @@ class TermHalJsonAnonTest extends TermResourceTestBase {
*/
protected static $mimeType = 'application/hal+json';
/**
* {@inheritdoc}
*/
protected static $expectedErrorMimeType = 'application/json';
/**
* {@inheritdoc}
*/
@ -68,12 +62,4 @@ class TermHalJsonAnonTest extends TermResourceTestBase {
];
}
/**
* {@inheritdoc}
*/
protected function getExpectedCacheContexts() {
// The 'url.site' cache context is added for '_links' in the response.
return Cache::mergeContexts(parent::getExpectedCacheContexts(), ['url.site']);
}
}

View file

@ -2,7 +2,6 @@
namespace Drupal\Tests\hal\Functional\EntityResource\Term;
use Drupal\Tests\hal\Functional\HalJsonBasicAuthWorkaroundFor2805281Trait;
use Drupal\Tests\rest\Functional\BasicAuthResourceTestTrait;
/**
@ -22,9 +21,4 @@ class TermHalJsonBasicAuthTest extends TermHalJsonAnonTest {
*/
protected static $auth = 'basic_auth';
// @todo Fix in https://www.drupal.org/node/2805281: remove this trait usage.
use HalJsonBasicAuthWorkaroundFor2805281Trait {
HalJsonBasicAuthWorkaroundFor2805281Trait::assertResponseWhenMissingAuthentication insteadof BasicAuthResourceTestTrait;
}
}

View file

@ -2,7 +2,6 @@
namespace Drupal\Tests\hal\Functional\EntityResource\User;
use Drupal\Core\Cache\Cache;
use Drupal\Tests\hal\Functional\EntityResource\HalEntityNormalizationTrait;
use Drupal\Tests\rest\Functional\AnonResourceTestTrait;
use Drupal\Tests\rest\Functional\EntityResource\User\UserResourceTestBase;
@ -30,11 +29,6 @@ class UserHalJsonAnonTest extends UserResourceTestBase {
*/
protected static $mimeType = 'application/hal+json';
/**
* {@inheritdoc}
*/
protected static $expectedErrorMimeType = 'application/json';
/**
* {@inheritdoc}
*/
@ -68,12 +62,4 @@ class UserHalJsonAnonTest extends UserResourceTestBase {
];
}
/**
* {@inheritdoc}
*/
protected function getExpectedCacheContexts() {
// The 'url.site' cache context is added for '_links' in the response.
return Cache::mergeContexts(parent::getExpectedCacheContexts(), ['url.site']);
}
}

View file

@ -2,7 +2,6 @@
namespace Drupal\Tests\hal\Functional\EntityResource\User;
use Drupal\Tests\hal\Functional\HalJsonBasicAuthWorkaroundFor2805281Trait;
use Drupal\Tests\rest\Functional\BasicAuthResourceTestTrait;
/**
@ -22,9 +21,4 @@ class UserHalJsonBasicAuthTest extends UserHalJsonAnonTest {
*/
protected static $auth = 'basic_auth';
// @todo Fix in https://www.drupal.org/node/2805281: remove this trait usage.
use HalJsonBasicAuthWorkaroundFor2805281Trait {
HalJsonBasicAuthWorkaroundFor2805281Trait::assertResponseWhenMissingAuthentication insteadof BasicAuthResourceTestTrait;
}
}

View file

@ -27,11 +27,6 @@ class VocabularyHalJsonAnonTest extends VocabularyResourceTestBase {
*/
protected static $mimeType = 'application/hal+json';
/**
* {@inheritdoc}
*/
protected static $expectedErrorMimeType = 'application/json';
/**
* @todo Remove this override in https://www.drupal.org/node/2805281.
*/

View file

@ -2,7 +2,6 @@
namespace Drupal\Tests\hal\Functional\EntityResource\Vocabulary;
use Drupal\Tests\hal\Functional\HalJsonBasicAuthWorkaroundFor2805281Trait;
use Drupal\Tests\rest\Functional\BasicAuthResourceTestTrait;
use Drupal\Tests\rest\Functional\EntityResource\Vocabulary\VocabularyResourceTestBase;
@ -28,19 +27,9 @@ class VocabularyHalJsonBasicAuthTest extends VocabularyResourceTestBase {
*/
protected static $mimeType = 'application/hal+json';
/**
* {@inheritdoc}
*/
protected static $expectedErrorMimeType = 'application/json';
/**
* {@inheritdoc}
*/
protected static $auth = 'basic_auth';
// @todo Fix in https://www.drupal.org/node/2805281: remove this trait usage.
use HalJsonBasicAuthWorkaroundFor2805281Trait {
HalJsonBasicAuthWorkaroundFor2805281Trait::assertResponseWhenMissingAuthentication insteadof BasicAuthResourceTestTrait;
}
}

View file

@ -27,11 +27,6 @@ class VocabularyHalJsonCookieTest extends VocabularyResourceTestBase {
*/
protected static $mimeType = 'application/hal+json';
/**
* {@inheritdoc}
*/
protected static $expectedErrorMimeType = 'application/json';
/**
* {@inheritdoc}
*/

View file

@ -1,9 +1,9 @@
<?php
namespace Drupal\hal\Tests;
namespace Drupal\Tests\hal\Functional;
use Drupal\file\Entity\File;
use Drupal\simpletest\WebTestBase;
use Drupal\Tests\BrowserTestBase;
/**
* Tests that file entities can be denormalized in HAL.
@ -11,25 +11,25 @@ use Drupal\simpletest\WebTestBase;
* @group hal
* @see \Drupal\hal\Normalizer\FileEntityNormalizer
*/
class FileDenormalizeTest extends WebTestBase {
class FileDenormalizeTest extends BrowserTestBase {
/**
* Modules to enable.
*
* @var array
*/
public static $modules = array('hal', 'file', 'node');
public static $modules = ['hal', 'file', 'node'];
/**
* Tests file entity denormalization.
*/
public function testFileDenormalize() {
$file_params = array(
$file_params = [
'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');
@ -56,11 +56,11 @@ class FileDenormalizeTest extends WebTestBase {
file_put_contents($file_path, 'hello world');
$file_uri = file_create_url($file_path);
$data = array(
'uri' => array(
array('value' => $file_uri),
),
);
$data = [
'uri' => [
['value' => $file_uri],
],
];
$denormalized = $serializer->denormalize($data, 'Drupal\file\Entity\File', 'hal_json');

View file

@ -1,26 +0,0 @@
<?php
namespace Drupal\Tests\hal\Functional;
use Psr\Http\Message\ResponseInterface;
trait HalJsonBasicAuthWorkaroundFor2805281Trait {
/**
* {@inheritdoc}
*
* Note how the response claims it contains a application/hal+json body, but
* in reality it contains a text/plain body! Also, the correct error MIME type
* is application/json.
*
* @todo Fix in https://www.drupal.org/node/2805281: remove this trait.
*/
protected function assertResponseWhenMissingAuthentication(ResponseInterface $response) {
$this->assertSame(401, $response->getStatusCode());
// @todo this works fine locally, but on testbot it comes back with
// 'text/plain; charset=UTF-8'. WTF.
// $this->assertSame(['application/hal+json'], $response->getHeader('Content-Type'));
$this->assertSame('No authentication credentials provided.', (string) $response->getBody());
}
}

View file

@ -0,0 +1,42 @@
<?php
namespace Drupal\Tests\hal\Functional\Update;
use Drupal\system\Tests\Update\UpdatePathTestBase;
/**
* Tests that 'hal.settings' is created, to store 'link_domain'.
*
* @see https://www.drupal.org/node/2758897
*
* @group hal
*/
class CreateHalSettingsForLinkDomainUpdateTest extends UpdatePathTestBase {
/**
* {@inheritdoc}
*/
public function setDatabaseDumpFiles() {
$this->databaseDumpFiles = [
__DIR__ . '/../../../../../system/tests/fixtures/update/drupal-8.bare.standard.php.gz',
__DIR__ . '/../../../fixtures/update/drupal-8.hal-hal_update_8301.php',
];
}
/**
* Tests hal_update_8301().
*/
public function testHalSettingsCreated() {
// Make sure we have the expected values before the update.
$hal_settings = $this->config('hal.settings');
$this->assertIdentical([], $hal_settings->getRawData());
$this->runUpdates();
// Make sure we have the expected values after the update.
$hal_settings = \Drupal::configFactory()->get('hal.settings');
$this->assertTrue(array_key_exists('link_domain', $hal_settings->getRawData()));
$this->assertIdentical(NULL, $hal_settings->getRawData()['link_domain']);
}
}

View file

@ -0,0 +1,48 @@
<?php
namespace Drupal\Tests\hal\Functional\Update;
use Drupal\system\Tests\Update\UpdatePathTestBase;
/**
* 'link_domain' is migrated from 'rest.settings' to 'hal.settings'.
*
* @see https://www.drupal.org/node/2758897
*
* @group hal
*/
class MigrateLinkDomainSettingFromRestToHalUpdateTest extends UpdatePathTestBase {
/**
* {@inheritdoc}
*/
public function setDatabaseDumpFiles() {
$this->databaseDumpFiles = [
__DIR__ . '/../../../../../system/tests/fixtures/update/drupal-8.bare.standard.php.gz',
__DIR__ . '/../../../fixtures/update/drupal-8.hal-hal_update_8301.php',
__DIR__ . '/../../../fixtures/update/drupal-8.rest-hal_update_8301.php',
];
}
/**
* Tests hal_update_8301().
*/
public function testLinkDomainMigratedFromRestSettingsToHalSettings() {
// Make sure we have the expected values before the update.
$hal_settings = $this->config('hal.settings');
$this->assertIdentical([], $hal_settings->getRawData());
$rest_settings = $this->config('rest.settings');
$this->assertTrue(array_key_exists('link_domain', $rest_settings->getRawData()));
$this->assertIdentical('http://example.com', $rest_settings->getRawData()['link_domain']);
$this->runUpdates();
// Make sure we have the expected values after the update.
$hal_settings = \Drupal::configFactory()->get('hal.settings');
$this->assertTrue(array_key_exists('link_domain', $hal_settings->getRawData()));
$this->assertIdentical('http://example.com', $hal_settings->getRawData()['link_domain']);
$rest_settings = $this->config('rest.settings');
$this->assertFalse(array_key_exists('link_domain', $rest_settings->getRawData()));
}
}

View file

@ -18,40 +18,40 @@ class DenormalizeTest extends NormalizerTestBase {
*/
public function testTypeHandling() {
// Valid type.
$data_with_valid_type = array(
'_links' => array(
'type' => array(
'href' => Url::fromUri('base:rest/type/entity_test/entity_test', array('absolute' => TRUE))->toString(),
),
),
);
$data_with_valid_type = [
'_links' => [
'type' => [
'href' => Url::fromUri('base:rest/type/entity_test/entity_test', ['absolute' => TRUE])->toString(),
],
],
];
$denormalized = $this->serializer->denormalize($data_with_valid_type, $this->entityClass, $this->format);
$this->assertEqual(get_class($denormalized), $this->entityClass, 'Request with valid type results in creation of correct bundle.');
// Multiple types.
$data_with_multiple_types = array(
'_links' => array(
'type' => array(
array(
'href' => Url::fromUri('base:rest/types/foo', array('absolute' => TRUE))->toString(),
),
array(
'href' => Url::fromUri('base:rest/type/entity_test/entity_test', array('absolute' => TRUE))->toString(),
),
),
),
);
$data_with_multiple_types = [
'_links' => [
'type' => [
[
'href' => Url::fromUri('base:rest/types/foo', ['absolute' => TRUE])->toString(),
],
[
'href' => Url::fromUri('base:rest/type/entity_test/entity_test', ['absolute' => TRUE])->toString(),
],
],
],
];
$denormalized = $this->serializer->denormalize($data_with_multiple_types, $this->entityClass, $this->format);
$this->assertEqual(get_class($denormalized), $this->entityClass, 'Request with multiple types results in creation of correct bundle.');
// Invalid type.
$data_with_invalid_type = array(
'_links' => array(
'type' => array(
'href' => Url::fromUri('base:rest/types/foo', array('absolute' => TRUE))->toString(),
),
),
);
$data_with_invalid_type = [
'_links' => [
'type' => [
'href' => Url::fromUri('base:rest/types/foo', ['absolute' => TRUE])->toString(),
],
],
];
try {
$this->serializer->denormalize($data_with_invalid_type, $this->entityClass, $this->format);
$this->fail('Exception should be thrown when type is invalid.');
@ -61,10 +61,10 @@ class DenormalizeTest extends NormalizerTestBase {
}
// No type.
$data_with_no_type = array(
'_links' => array(
),
);
$data_with_no_type = [
'_links' => [
],
];
try {
$this->serializer->denormalize($data_with_no_type, $this->entityClass, $this->format);
$this->fail('Exception should be thrown when no type is provided.');
@ -78,13 +78,13 @@ class DenormalizeTest extends NormalizerTestBase {
* Tests link relation handling with an invalid type.
*/
public function testTypeHandlingWithInvalidType() {
$data_with_invalid_type = array(
'_links' => array(
'type' => array(
'href' => Url::fromUri('base:rest/type/entity_test/entity_test_invalid', array('absolute' => TRUE))->toString(),
),
),
);
$data_with_invalid_type = [
'_links' => [
'type' => [
'href' => Url::fromUri('base:rest/type/entity_test/entity_test_invalid', ['absolute' => TRUE])->toString(),
],
],
];
$this->setExpectedException(UnexpectedValueException::class);
$this->serializer->denormalize($data_with_invalid_type, $this->entityClass, $this->format);
@ -94,11 +94,11 @@ class DenormalizeTest extends NormalizerTestBase {
* Tests link relation handling with no types.
*/
public function testTypeHandlingWithNoTypes() {
$data_with_no_types = array(
'_links' => array(
'type' => array(),
),
);
$data_with_no_types = [
'_links' => [
'type' => [],
],
];
$this->setExpectedException(UnexpectedValueException::class);
$this->serializer->denormalize($data_with_no_types, $this->entityClass, $this->format);
@ -110,32 +110,32 @@ class DenormalizeTest extends NormalizerTestBase {
public function testMarkFieldForDeletion() {
// Add a default value for a field.
$field = FieldConfig::loadByName('entity_test', 'entity_test', 'field_test_text');
$field->setDefaultValue(array(array('value' => 'Llama')));
$field->setDefaultValue([['value' => 'Llama']]);
$field->save();
// Denormalize data that contains no entry for the field, and check that
// the default value is present in the resulting entity.
$data = array(
'_links' => array(
'type' => array(
'href' => Url::fromUri('base:rest/type/entity_test/entity_test', array('absolute' => TRUE))->toString(),
),
),
);
$data = [
'_links' => [
'type' => [
'href' => Url::fromUri('base:rest/type/entity_test/entity_test', ['absolute' => TRUE])->toString(),
],
],
];
$entity = $this->serializer->denormalize($data, $this->entityClass, $this->format);
$this->assertEqual($entity->field_test_text->count(), 1);
$this->assertEqual($entity->field_test_text->value, 'Llama');
// Denormalize data that contains an empty entry for the field, and check
// that the field is empty in the resulting entity.
$data = array(
'_links' => array(
'type' => array(
'href' => Url::fromUri('base:rest/type/entity_test/entity_test', array('absolute' => TRUE))->toString(),
),
),
'field_test_text' => array(),
);
$data = [
'_links' => [
'type' => [
'href' => Url::fromUri('base:rest/type/entity_test/entity_test', ['absolute' => TRUE])->toString(),
],
],
'field_test_text' => [],
];
$entity = $this->serializer->denormalize($data, get_class($entity), $this->format, [ 'target_instance' => $entity ]);
$this->assertEqual($entity->field_test_text->count(), 0);
}

View file

@ -3,6 +3,7 @@
namespace Drupal\Tests\hal\Kernel;
use Drupal\node\Entity\Node;
use Drupal\node\NodeInterface;
use Drupal\user\Entity\User;
use Drupal\node\Entity\NodeType;
@ -18,14 +19,14 @@ class EntityTranslationNormalizeTest extends NormalizerTestBase {
*
* @var array
*/
public static $modules = array('node', 'content_translation');
public static $modules = ['node', 'content_translation'];
/**
* {@inheritdoc}
*/
protected function setUp() {
parent::setUp();
$this->installSchema('system', array('sequences'));
$this->installSchema('system', ['sequences']);
$this->installConfig(['node', 'content_translation']);
}
@ -44,7 +45,7 @@ class EntityTranslationNormalizeTest extends NormalizerTestBase {
'title' => $this->randomMachineName(),
'uid' => $user->id(),
'type' => $node_type->id(),
'status' => NODE_PUBLISHED,
'status' => NodeInterface::PUBLISHED,
'langcode' => 'en',
'promote' => 1,
'sticky' => 0,

View file

@ -2,16 +2,7 @@
namespace Drupal\Tests\hal\Kernel;
use Drupal\Core\Cache\MemoryBackend;
use Drupal\file\Entity\File;
use Drupal\hal\Encoder\JsonEncoder;
use Drupal\hal\Normalizer\FieldItemNormalizer;
use Drupal\hal\Normalizer\FileEntityNormalizer;
use Drupal\rest\LinkManager\LinkManager;
use Drupal\rest\LinkManager\RelationLinkManager;
use Drupal\rest\LinkManager\TypeLinkManager;
use Symfony\Component\Serializer\Serializer;
/**
* Tests that file entities can be normalized in HAL.
@ -25,7 +16,7 @@ class FileNormalizeTest extends NormalizerTestBase {
*
* @var array
*/
public static $modules = array('file');
public static $modules = ['file'];
/**
* {@inheritdoc}
@ -33,20 +24,6 @@ class FileNormalizeTest extends NormalizerTestBase {
protected function setUp() {
parent::setUp();
$this->installEntitySchema('file');
$entity_manager = \Drupal::entityManager();
$link_manager = new LinkManager(new TypeLinkManager(new MemoryBackend('default'), \Drupal::moduleHandler(), \Drupal::service('config.factory'), \Drupal::service('request_stack'), \Drupal::service('entity_type.bundle.info')), new RelationLinkManager(new MemoryBackend('default'), $entity_manager, \Drupal::moduleHandler(), \Drupal::service('config.factory'), \Drupal::service('request_stack')));
// Set up the mock serializer.
$normalizers = array(
new FieldItemNormalizer(),
new FileEntityNormalizer($entity_manager, \Drupal::httpClient(), $link_manager, \Drupal::moduleHandler()),
);
$encoders = array(
new JsonEncoder(),
);
$this->serializer = new Serializer($normalizers, $encoders);
}
@ -54,23 +31,23 @@ class FileNormalizeTest extends NormalizerTestBase {
* Tests the normalize function.
*/
public function testNormalize() {
$file_params = array(
$file_params = [
'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();
$expected_array = array(
'uri' => array(
array(
'value' => file_create_url($file->getFileUri())),
),
);
$expected_array = [
'uri' => [
[
'value' => file_create_url($file->getFileUri())],
],
];
$normalized = $this->serializer->normalize($file, $this->format);
$this->assertEqual($normalized['uri'], $expected_array['uri'], 'URI is normalized.');

View file

@ -0,0 +1,74 @@
<?php
namespace Drupal\Tests\hal\Kernel;
use Drupal\Core\Url;
use Drupal\KernelTests\KernelTestBase;
/**
* @coversDefaultClass \Drupal\hal\LinkManager\LinkManager
* @group hal
*/
class HalLinkManagerTest extends KernelTestBase {
/**
* {@inheritdoc}
*/
public static $modules = ['hal', 'hal_test', 'serialization', 'system'];
/**
* {@inheritdoc}
*/
protected function setUp() {
parent::setUp();
\Drupal::service('router.builder')->rebuild();
}
/**
* @covers ::getTypeUri
*/
public function testGetTypeUri() {
/* @var \Drupal\rest\LinkManager\TypeLinkManagerInterface $type_manager */
$type_manager = \Drupal::service('hal.link_manager.type');
$base = Url::fromRoute('<front>', [], ['absolute' => TRUE])->toString();
$link = $type_manager->getTypeUri('node', 'page');
$this->assertSame($link, $base . 'rest/type/node/page');
// Now with optional context.
$link = $type_manager->getTypeUri('node', 'page', ['hal_test' => TRUE]);
$this->assertSame($link, 'hal_test_type');
// Test BC: hook_rest_type_uri_alter().
$link = $type_manager->getTypeUri('node', 'page', ['rest_test' => TRUE]);
$this->assertSame($link, 'rest_test_type');
}
/**
* @covers ::getRelationUri
*/
public function testGetRelationUri() {
/* @var \Drupal\rest\LinkManager\RelationLinkManagerInterface $relation_manager */
$relation_manager = \Drupal::service('hal.link_manager.relation');
$base = Url::fromRoute('<front>', [], ['absolute' => TRUE])->toString();
$link = $relation_manager->getRelationUri('node', 'page', 'field_ref');
$this->assertSame($link, $base . 'rest/relation/node/page/field_ref');
// Now with optional context.
$link = $relation_manager->getRelationUri('node', 'page', 'foobar', ['hal_test' => TRUE]);
$this->assertSame($link, 'hal_test_relation');
// Test BC: hook_rest_relation_uri_alter().
$link = $relation_manager->getRelationUri('node', 'page', 'foobar', ['rest_test' => TRUE]);
$this->assertSame($link, 'rest_test_relation');
}
/**
* @covers ::setLinkDomain
*/
public function testHalLinkManagersSetLinkDomain() {
/* @var \Drupal\rest\LinkManager\LinkManager $link_manager */
$link_manager = \Drupal::service('hal.link_manager');
$link_manager->setLinkDomain('http://example.com/');
$link = $link_manager->getTypeUri('node', 'page');
$this->assertEqual($link, 'http://example.com/rest/type/node/page');
$link = $link_manager->getRelationUri('node', 'page', 'field_ref');
$this->assertEqual($link, 'http://example.com/rest/relation/node/page/field_ref');
}
}

View file

@ -26,135 +26,135 @@ class NormalizeTest extends NormalizerTestBase {
* Tests the normalize function.
*/
public function testNormalize() {
$target_entity_de = EntityTest::create((array('langcode' => 'de', 'field_test_entity_reference' => NULL)));
$target_entity_de = EntityTest::create((['langcode' => 'de', 'field_test_entity_reference' => NULL]));
$target_entity_de->save();
$target_entity_en = EntityTest::create((array('langcode' => 'en', 'field_test_entity_reference' => NULL)));
$target_entity_en = EntityTest::create((['langcode' => 'en', 'field_test_entity_reference' => NULL]));
$target_entity_en->save();
// Create a German entity.
$values = array(
$values = [
'langcode' => 'de',
'name' => $this->randomMachineName(),
'field_test_text' => array(
'field_test_text' => [
'value' => $this->randomMachineName(),
'format' => 'full_html',
),
'field_test_entity_reference' => array(
],
'field_test_entity_reference' => [
'target_id' => $target_entity_de->id(),
),
);
],
];
// Array of translated values.
$translation_values = array(
$translation_values = [
'name' => $this->randomMachineName(),
'field_test_entity_reference' => array(
'field_test_entity_reference' => [
'target_id' => $target_entity_en->id(),
)
);
]
];
$entity = EntityTest::create($values);
$entity->save();
// Add an English value for name and entity reference properties.
$entity->addTranslation('en')->set('name', array(0 => array('value' => $translation_values['name'])));
$entity->getTranslation('en')->set('field_test_entity_reference', array(0 => $translation_values['field_test_entity_reference']));
$entity->addTranslation('en')->set('name', [0 => ['value' => $translation_values['name']]]);
$entity->getTranslation('en')->set('field_test_entity_reference', [0 => $translation_values['field_test_entity_reference']]);
$entity->save();
$type_uri = Url::fromUri('base:rest/type/entity_test/entity_test', array('absolute' => TRUE))->toString();
$relation_uri = Url::fromUri('base:rest/relation/entity_test/entity_test/field_test_entity_reference', array('absolute' => TRUE))->toString();
$type_uri = Url::fromUri('base:rest/type/entity_test/entity_test', ['absolute' => TRUE])->toString();
$relation_uri = Url::fromUri('base:rest/relation/entity_test/entity_test/field_test_entity_reference', ['absolute' => TRUE])->toString();
$expected_array = array(
'_links' => array(
'curies' => array(
array(
$expected_array = [
'_links' => [
'curies' => [
[
'href' => '/relations',
'name' => 'site',
'templated' => TRUE,
),
),
'self' => array(
],
],
'self' => [
'href' => $this->getEntityUri($entity),
),
'type' => array(
],
'type' => [
'href' => $type_uri,
),
$relation_uri => array(
array(
],
$relation_uri => [
[
'href' => $this->getEntityUri($target_entity_de),
'lang' => 'de',
),
array(
],
[
'href' => $this->getEntityUri($target_entity_en),
'lang' => 'en',
),
),
),
'_embedded' => array(
$relation_uri => array(
array(
'_links' => array(
'self' => array(
],
],
],
'_embedded' => [
$relation_uri => [
[
'_links' => [
'self' => [
'href' => $this->getEntityUri($target_entity_de),
),
'type' => array(
],
'type' => [
'href' => $type_uri,
),
),
'uuid' => array(
array(
],
],
'uuid' => [
[
'value' => $target_entity_de->uuid(),
),
),
],
],
'lang' => 'de',
),
array(
'_links' => array(
'self' => array(
],
[
'_links' => [
'self' => [
'href' => $this->getEntityUri($target_entity_en),
),
'type' => array(
],
'type' => [
'href' => $type_uri,
),
),
'uuid' => array(
array(
],
],
'uuid' => [
[
'value' => $target_entity_en->uuid(),
),
),
],
],
'lang' => 'en',
),
),
),
'id' => array(
array(
],
],
],
'id' => [
[
'value' => $entity->id(),
),
),
'uuid' => array(
array(
],
],
'uuid' => [
[
'value' => $entity->uuid(),
),
),
'langcode' => array(
array(
],
],
'langcode' => [
[
'value' => 'de',
),
),
'name' => array(
array(
],
],
'name' => [
[
'value' => $values['name'],
'lang' => 'de',
),
array(
],
[
'value' => $translation_values['name'],
'lang' => 'en',
),
),
'field_test_text' => array(
array(
],
],
'field_test_text' => [
[
'value' => $values['field_test_text']['value'],
'format' => $values['field_test_text']['format'],
),
),
);
],
],
];
$normalized = $this->serializer->normalize($entity, $this->format);
$this->assertEqual($normalized['_links']['self'], $expected_array['_links']['self'], 'self link placed correctly.');

View file

@ -2,22 +2,9 @@
namespace Drupal\Tests\hal\Kernel;
use Drupal\Core\Cache\MemoryBackend;
use Drupal\field\Entity\FieldConfig;
use Drupal\hal\Encoder\JsonEncoder;
use Drupal\hal\Normalizer\ContentEntityNormalizer;
use Drupal\hal\Normalizer\EntityReferenceItemNormalizer;
use Drupal\hal\Normalizer\FieldItemNormalizer;
use Drupal\hal\Normalizer\FieldNormalizer;
use Drupal\language\Entity\ConfigurableLanguage;
use Drupal\rest\LinkManager\LinkManager;
use Drupal\rest\LinkManager\RelationLinkManager;
use Drupal\rest\LinkManager\TypeLinkManager;
use Drupal\serialization\EntityResolver\ChainEntityResolver;
use Drupal\serialization\EntityResolver\TargetIdResolver;
use Drupal\serialization\EntityResolver\UuidResolver;
use Drupal\KernelTests\KernelTestBase;
use Symfony\Component\Serializer\Serializer;
use Drupal\field\Entity\FieldStorageConfig;
/**
@ -30,7 +17,7 @@ abstract class NormalizerTestBase extends KernelTestBase {
*
* @var array
*/
public static $modules = ['entity_test', 'field', 'hal', 'language', 'rest', 'serialization', 'system', 'text', 'user', 'filter'];
public static $modules = ['entity_test', 'field', 'hal', 'language', 'serialization', 'system', 'text', 'user', 'filter'];
/**
* The mock serializer.
@ -71,29 +58,29 @@ abstract class NormalizerTestBase extends KernelTestBase {
// Only check the modules, if the $modules property was not inherited.
$rp = new \ReflectionProperty($class, 'modules');
if ($rp->class == $class) {
foreach (array_intersect(array('node', 'comment'), $class::$modules) as $module) {
foreach (array_intersect(['node', 'comment'], $class::$modules) as $module) {
$this->installEntitySchema($module);
}
}
}
$class = get_parent_class($class);
}
$this->installConfig(array('field', 'language'));
$this->installConfig(['field', 'language']);
\Drupal::service('router.builder')->rebuild();
// Add German as a language.
ConfigurableLanguage::create(array(
ConfigurableLanguage::create([
'id' => 'de',
'label' => 'Deutsch',
'weight' => -1,
))->save();
])->save();
// Create the test text field.
FieldStorageConfig::create(array(
FieldStorageConfig::create([
'field_name' => 'field_test_text',
'entity_type' => 'entity_test',
'type' => 'text',
))->save();
])->save();
FieldConfig::create([
'entity_type' => 'entity_test',
'field_name' => 'field_test_text',
@ -102,11 +89,11 @@ abstract class NormalizerTestBase extends KernelTestBase {
])->save();
// Create the test translatable field.
FieldStorageConfig::create(array(
FieldStorageConfig::create([
'field_name' => 'field_test_translatable_text',
'entity_type' => 'entity_test',
'type' => 'text',
))->save();
])->save();
FieldConfig::create([
'entity_type' => 'entity_test',
'field_name' => 'field_test_translatable_text',
@ -115,14 +102,14 @@ abstract class NormalizerTestBase extends KernelTestBase {
])->save();
// Create the test entity reference field.
FieldStorageConfig::create(array(
FieldStorageConfig::create([
'field_name' => 'field_test_entity_reference',
'entity_type' => 'entity_test',
'type' => 'entity_reference',
'settings' => array(
'settings' => [
'target_type' => 'entity_test',
),
))->save();
],
])->save();
FieldConfig::create([
'entity_type' => 'entity_test',
'field_name' => 'field_test_entity_reference',
@ -130,23 +117,7 @@ abstract class NormalizerTestBase extends KernelTestBase {
'translatable' => TRUE,
])->save();
$entity_manager = \Drupal::entityManager();
$link_manager = new LinkManager(new TypeLinkManager(new MemoryBackend('default'), \Drupal::moduleHandler(), \Drupal::service('config.factory'), \Drupal::service('request_stack'), \Drupal::service('entity_type.bundle.info')), new RelationLinkManager(new MemoryBackend('default'), $entity_manager, \Drupal::moduleHandler(), \Drupal::service('config.factory'), \Drupal::service('request_stack')));
$chain_resolver = new ChainEntityResolver(array(new UuidResolver($entity_manager), new TargetIdResolver()));
// Set up the mock serializer.
$normalizers = array(
new ContentEntityNormalizer($link_manager, $entity_manager, \Drupal::moduleHandler()),
new EntityReferenceItemNormalizer($link_manager, $chain_resolver),
new FieldItemNormalizer(),
new FieldNormalizer(),
);
$encoders = array(
new JsonEncoder(),
);
$this->serializer = new Serializer($normalizers, $encoders);
$this->serializer = $this->container->get('serializer');
}
}

View file

@ -3,6 +3,7 @@
namespace Drupal\Tests\hal\Unit;
use Drupal\hal\Normalizer\FieldItemNormalizer;
use Symfony\Component\Serializer\Exception\InvalidArgumentException;
/**
* @coversDefaultClass \Drupal\hal\Normalizer\FieldItemNormalizer
@ -17,12 +18,12 @@ class FieldItemNormalizerDenormalizeExceptionsUnitTest extends NormalizerDenorma
* Context for FieldItemNormalizer::denormalize().
*
* @dataProvider providerNormalizerDenormalizeExceptions
* @expectedException \Symfony\Component\Serializer\Exception\InvalidArgumentException
*/
public function testFieldItemNormalizerDenormalizeExceptions($context) {
$field_item_normalizer = new FieldItemNormalizer();
$data = array();
$class = array();
$data = [];
$class = [];
$this->setExpectedException(InvalidArgumentException::class);
$field_item_normalizer->denormalize($data, $class, NULL, $context);
}

View file

@ -3,6 +3,7 @@
namespace Drupal\Tests\hal\Unit;
use Drupal\hal\Normalizer\FieldNormalizer;
use Symfony\Component\Serializer\Exception\InvalidArgumentException;
/**
* @coversDefaultClass \Drupal\hal\Normalizer\FieldNormalizer
@ -17,12 +18,12 @@ class FieldNormalizerDenormalizeExceptionsUnitTest extends NormalizerDenormalize
* Context for FieldNormalizer::denormalize().
*
* @dataProvider providerNormalizerDenormalizeExceptions
* @expectedException \Symfony\Component\Serializer\Exception\InvalidArgumentException
*/
public function testFieldNormalizerDenormalizeExceptions($context) {
$field_item_normalizer = new FieldNormalizer();
$data = array();
$class = array();
$data = [];
$class = [];
$this->setExpectedException(InvalidArgumentException::class);
$field_item_normalizer->denormalize($data, $class, NULL, $context);
}

View file

@ -18,14 +18,14 @@ abstract class NormalizerDenormalizeExceptionsUnitTestBase extends UnitTestCase
* @return array Test data.
*/
public function providerNormalizerDenormalizeExceptions() {
$mock = $this->getMock('\Drupal\Core\Field\Plugin\DataType\FieldItem', array('getParent'));
$mock = $this->getMock('\Drupal\Core\Field\Plugin\DataType\FieldItem', ['getParent']);
$mock->expects($this->any())
->method('getParent')
->will($this->returnValue(NULL));
return array(
array(array()),
array(array('target_instance' => $mock)),
);
return [
[[]],
[['target_instance' => $mock]],
];
}
}