updated core and modules

This commit is contained in:
Bachir Soussi Chiadmi
2017-09-09 16:27:51 +02:00
parent 027aa99b32
commit 41863f872c
7810 changed files with 318922 additions and 83631 deletions
@@ -23,14 +23,14 @@ use \Drupal\Component\Annotation\Plugin;
class RestResource extends Plugin {
/**
* The resource plugin ID.
* The REST resource plugin ID.
*
* @var string
*/
public $id;
/**
* The human-readable name of the resource plugin.
* The human-readable name of the REST resource plugin.
*
* @ingroup plugin_translatable
*
@@ -38,4 +38,25 @@ class RestResource extends Plugin {
*/
public $label;
/**
* The serialization class to deserialize serialized data into.
*
* @see \Symfony\Component\Serializer\SerializerInterface's "type" parameter.
*
* @var string (optional)
*/
public $serialization_class;
/**
* The URI paths that this REST resource plugin provides.
*
* Key-value pairs, with link relation type plugin IDs as keys, and URL
* templates as values.
*
* @see core/core.link_relation_types.yml
*
* @var string[]
*/
public $uri_paths = [];
}
@@ -0,0 +1,271 @@
<?php
namespace Drupal\rest\Entity;
use Drupal\Core\DependencyInjection\ContainerInjectionInterface;
use Drupal\rest\RestResourceConfigInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
/**
* Calculates rest resource config dependencies.
*
* @internal
*/
class ConfigDependencies implements ContainerInjectionInterface {
/**
* The serialization format providers, keyed by format.
*
* @var string[]
*/
protected $formatProviders;
/**
* The authentication providers, keyed by ID.
*
* @var string[]
*/
protected $authProviders;
/**
* Creates a new ConfigDependencies instance.
*
* @param string[] $format_providers
* The serialization format providers, keyed by format.
* @param string[] $auth_providers
* The authentication providers, keyed by ID.
*/
public function __construct(array $format_providers, array $auth_providers) {
$this->formatProviders = $format_providers;
$this->authProviders = $auth_providers;
}
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container) {
return new static(
$container->getParameter('serializer.format_providers'),
$container->getParameter('authentication_providers')
);
}
/**
* Calculates dependencies of a specific rest resource configuration.
*
* This function returns dependencies in a non-sorted, non-unique manner. It
* is therefore the caller's responsibility to sort and remove duplicates
* from the result prior to saving it with the configuration or otherwise
* using it in a way that requires that. For example,
* \Drupal\rest\Entity\RestResourceConfig::calculateDependencies() does this
* via its \Drupal\Core\Entity\DependencyTrait::addDependency() method.
*
* @param \Drupal\rest\RestResourceConfigInterface $rest_config
* The rest configuration.
*
* @return string[][]
* Dependencies keyed by dependency type.
*
* @see \Drupal\rest\Entity\RestResourceConfig::calculateDependencies()
*/
public function calculateDependencies(RestResourceConfigInterface $rest_config) {
$granularity = $rest_config->get('granularity');
// Dependency calculation is the same for either granularity, the most
// notable difference is that for the 'resource' granularity, the same
// authentication providers and formats are supported for every method.
switch ($granularity) {
case RestResourceConfigInterface::METHOD_GRANULARITY:
$methods = $rest_config->getMethods();
break;
case RestResourceConfigInterface::RESOURCE_GRANULARITY:
$methods = array_slice($rest_config->getMethods(), 0, 1);
break;
default:
throw new \InvalidArgumentException('Invalid granularity specified.');
}
// The dependency lists for authentication providers and formats
// generated on container build.
$dependencies = [];
foreach ($methods as $request_method) {
// Add dependencies based on the supported authentication providers.
foreach ($rest_config->getAuthenticationProviders($request_method) as $auth) {
if (isset($this->authProviders[$auth])) {
$module_name = $this->authProviders[$auth];
$dependencies['module'][] = $module_name;
}
}
// Add dependencies based on the supported authentication formats.
foreach ($rest_config->getFormats($request_method) as $format) {
if (isset($this->formatProviders[$format])) {
$module_name = $this->formatProviders[$format];
$dependencies['module'][] = $module_name;
}
}
}
return $dependencies;
}
/**
* Informs the entity that entities it depends on will be deleted.
*
* @param \Drupal\rest\RestResourceConfigInterface $rest_config
* The rest configuration.
* @param array $dependencies
* An array of dependencies that will be deleted keyed by dependency type.
* Dependency types are, for example, entity, module and theme.
*
* @return bool
* TRUE if the entity has been changed as a result, FALSE if not.
*
* @see \Drupal\Core\Config\Entity\ConfigEntityInterface::onDependencyRemoval()
*/
public function onDependencyRemoval(RestResourceConfigInterface $rest_config, array $dependencies) {
$granularity = $rest_config->get('granularity');
switch ($granularity) {
case RestResourceConfigInterface::METHOD_GRANULARITY:
return $this->onDependencyRemovalForMethodGranularity($rest_config, $dependencies);
case RestResourceConfigInterface::RESOURCE_GRANULARITY:
return $this->onDependencyRemovalForResourceGranularity($rest_config, $dependencies);
default:
throw new \InvalidArgumentException('Invalid granularity specified.');
}
}
/**
* Informs the entity that entities it depends on will be deleted.
*
* @param \Drupal\rest\RestResourceConfigInterface $rest_config
* The rest configuration.
* @param array $dependencies
* An array of dependencies that will be deleted keyed by dependency type.
* Dependency types are, for example, entity, module and theme.
*
* @return bool
* TRUE if the entity has been changed as a result, FALSE if not.
*/
protected function onDependencyRemovalForMethodGranularity(RestResourceConfigInterface $rest_config, array $dependencies) {
$changed = FALSE;
// Only module-related dependencies can be fixed. All other types of
// dependencies cannot, because they were not generated based on supported
// authentication providers or formats.
if (isset($dependencies['module'])) {
// Try to fix dependencies.
$removed_auth = array_keys(array_intersect($this->authProviders, $dependencies['module']));
$removed_formats = array_keys(array_intersect($this->formatProviders, $dependencies['module']));
$configuration_before = $configuration = $rest_config->get('configuration');
if (!empty($removed_auth) || !empty($removed_formats)) {
// Try to fix dependency problems by removing affected
// authentication providers and formats.
foreach (array_keys($rest_config->get('configuration')) as $request_method) {
foreach ($removed_formats as $format) {
if (in_array($format, $rest_config->getFormats($request_method), TRUE)) {
$configuration[$request_method]['supported_formats'] = array_diff($configuration[$request_method]['supported_formats'], $removed_formats);
}
}
foreach ($removed_auth as $auth) {
if (in_array($auth, $rest_config->getAuthenticationProviders($request_method), TRUE)) {
$configuration[$request_method]['supported_auth'] = array_diff($configuration[$request_method]['supported_auth'], $removed_auth);
}
}
if (empty($configuration[$request_method]['supported_auth'])) {
// Remove the key if there are no more authentication providers
// supported by this request method.
unset($configuration[$request_method]['supported_auth']);
}
if (empty($configuration[$request_method]['supported_formats'])) {
// Remove the key if there are no more formats supported by this
// request method.
unset($configuration[$request_method]['supported_formats']);
}
if (empty($configuration[$request_method])) {
// Remove the request method altogether if it no longer has any
// supported authentication providers or formats.
unset($configuration[$request_method]);
}
}
}
if ($configuration_before != $configuration && !empty($configuration)) {
$rest_config->set('configuration', $configuration);
// Only mark the dependencies problems as fixed if there is any
// configuration left.
$changed = TRUE;
}
}
// If the dependency problems are not marked as fixed at this point they
// should be related to the resource plugin and the config entity should
// be deleted.
return $changed;
}
/**
* Informs the entity that entities it depends on will be deleted.
*
* @param \Drupal\rest\RestResourceConfigInterface $rest_config
* The rest configuration.
* @param array $dependencies
* An array of dependencies that will be deleted keyed by dependency type.
* Dependency types are, for example, entity, module and theme.
*
* @return bool
* TRUE if the entity has been changed as a result, FALSE if not.
*/
protected function onDependencyRemovalForResourceGranularity(RestResourceConfigInterface $rest_config, array $dependencies) {
$changed = FALSE;
// Only module-related dependencies can be fixed. All other types of
// dependencies cannot, because they were not generated based on supported
// authentication providers or formats.
if (isset($dependencies['module'])) {
// Try to fix dependencies.
$removed_auth = array_keys(array_intersect($this->authProviders, $dependencies['module']));
$removed_formats = array_keys(array_intersect($this->formatProviders, $dependencies['module']));
$configuration_before = $configuration = $rest_config->get('configuration');
if (!empty($removed_auth) || !empty($removed_formats)) {
// All methods support the same formats and authentication providers, so
// get those for whichever the first listed method is.
$first_method = $rest_config->getMethods()[0];
// Try to fix dependency problems by removing affected
// authentication providers and formats.
foreach ($removed_formats as $format) {
if (in_array($format, $rest_config->getFormats($first_method), TRUE)) {
$configuration['formats'] = array_diff($configuration['formats'], $removed_formats);
}
}
foreach ($removed_auth as $auth) {
if (in_array($auth, $rest_config->getAuthenticationProviders($first_method), TRUE)) {
$configuration['authentication'] = array_diff($configuration['authentication'], $removed_auth);
}
}
if (empty($configuration['authentication'])) {
// Remove the key if there are no more authentication providers
// supported.
unset($configuration['authentication']);
}
if (empty($configuration['formats'])) {
// Remove the key if there are no more formats supported.
unset($configuration['formats']);
}
if (empty($configuration['authentication']) || empty($configuration['formats'])) {
// If there no longer are any supported authentication providers or
// formats, this REST resource can no longer function, and so we
// cannot fix this config entity to keep it working.
$configuration = [];
}
}
if ($configuration_before != $configuration && !empty($configuration)) {
$rest_config->set('configuration', $configuration);
// Only mark the dependencies problems as fixed if there is any
// configuration left.
$changed = TRUE;
}
}
// If the dependency problems are not marked as fixed at this point they
// should be related to the resource plugin and the config entity should
// be deleted.
return $changed;
}
}
@@ -0,0 +1,277 @@
<?php
namespace Drupal\rest\Entity;
use Drupal\Core\Config\Entity\ConfigEntityBase;
use Drupal\Core\Entity\EntityStorageInterface;
use Drupal\Core\Plugin\DefaultSingleLazyPluginCollection;
use Drupal\rest\RestResourceConfigInterface;
/**
* Defines a RestResourceConfig configuration entity class.
*
* @ConfigEntityType(
* id = "rest_resource_config",
* label = @Translation("REST resource configuration"),
* config_prefix = "resource",
* admin_permission = "administer rest resources",
* label_callback = "getLabelFromPlugin",
* entity_keys = {
* "id" = "id"
* },
* config_export = {
* "id",
* "plugin_id",
* "granularity",
* "configuration"
* }
* )
*/
class RestResourceConfig extends ConfigEntityBase implements RestResourceConfigInterface {
/**
* The REST resource config id.
*
* @var string
*/
protected $id;
/**
* The REST resource plugin id.
*
* @var string
*/
protected $plugin_id;
/**
* The REST resource configuration granularity.
*
* Currently either:
* - \Drupal\rest\RestResourceConfigInterface::METHOD_GRANULARITY
* - \Drupal\rest\RestResourceConfigInterface::RESOURCE_GRANULARITY
*
* @var string
*/
protected $granularity;
/**
* The REST resource configuration.
*
* @var array
*/
protected $configuration;
/**
* The rest resource plugin manager.
*
* @var \Drupal\Component\Plugin\PluginManagerInterface
*/
protected $pluginManager;
/**
* {@inheritdoc}
*/
public function __construct(array $values, $entity_type) {
parent::__construct($values, $entity_type);
// The config entity id looks like the plugin id but uses __ instead of :
// because : is not valid for config entities.
if (!isset($this->plugin_id) && isset($this->id)) {
// Generate plugin_id on first entity creation.
$this->plugin_id = str_replace('.', ':', $this->id);
}
}
/**
* The label callback for this configuration entity.
*
* @return string The label.
*/
protected function getLabelFromPlugin() {
$plugin_definition = $this->getResourcePluginManager()
->getDefinition(['id' => $this->plugin_id]);
return $plugin_definition['label'];
}
/**
* Returns the resource plugin manager.
*
* @return \Drupal\Component\Plugin\PluginManagerInterface
*/
protected function getResourcePluginManager() {
if (!isset($this->pluginManager)) {
$this->pluginManager = \Drupal::service('plugin.manager.rest');
}
return $this->pluginManager;
}
/**
* {@inheritdoc}
*/
public function getResourcePlugin() {
return $this->getPluginCollections()['resource']->get($this->plugin_id);
}
/**
* {@inheritdoc}
*/
public function getMethods() {
switch ($this->granularity) {
case RestResourceConfigInterface::METHOD_GRANULARITY:
return $this->getMethodsForMethodGranularity();
case RestResourceConfigInterface::RESOURCE_GRANULARITY:
return $this->configuration['methods'];
default:
throw new \InvalidArgumentException('Invalid granularity specified.');
}
}
/**
* Retrieves a list of supported HTTP methods for this resource.
*
* @return string[]
* A list of supported HTTP methods.
*/
protected function getMethodsForMethodGranularity() {
$methods = array_keys($this->configuration);
return array_map([$this, 'normalizeRestMethod'], $methods);
}
/**
* {@inheritdoc}
*/
public function getAuthenticationProviders($method) {
switch ($this->granularity) {
case RestResourceConfigInterface::METHOD_GRANULARITY:
return $this->getAuthenticationProvidersForMethodGranularity($method);
case RestResourceConfigInterface::RESOURCE_GRANULARITY:
return $this->configuration['authentication'];
default:
throw new \InvalidArgumentException('Invalid granularity specified.');
}
}
/**
* Retrieves a list of supported authentication providers.
*
* @param string $method
* The request method e.g GET or POST.
*
* @return string[]
* A list of supported authentication provider IDs.
*/
public function getAuthenticationProvidersForMethodGranularity($method) {
$method = $this->normalizeRestMethod($method);
if (in_array($method, $this->getMethods()) && isset($this->configuration[$method]['supported_auth'])) {
return $this->configuration[$method]['supported_auth'];
}
return [];
}
/**
* {@inheritdoc}
*/
public function getFormats($method) {
switch ($this->granularity) {
case RestResourceConfigInterface::METHOD_GRANULARITY:
return $this->getFormatsForMethodGranularity($method);
case RestResourceConfigInterface::RESOURCE_GRANULARITY:
return $this->configuration['formats'];
default:
throw new \InvalidArgumentException('Invalid granularity specified.');
}
}
/**
* Retrieves a list of supported response formats.
*
* @param string $method
* The request method e.g GET or POST.
*
* @return string[]
* A list of supported format IDs.
*/
protected function getFormatsForMethodGranularity($method) {
$method = $this->normalizeRestMethod($method);
if (in_array($method, $this->getMethods()) && isset($this->configuration[$method]['supported_formats'])) {
return $this->configuration[$method]['supported_formats'];
}
return [];
}
/**
* {@inheritdoc}
*/
public function getPluginCollections() {
return [
'resource' => new DefaultSingleLazyPluginCollection($this->getResourcePluginManager(), $this->plugin_id, [])
];
}
/**
* (@inheritdoc)
*/
public function calculateDependencies() {
parent::calculateDependencies();
foreach ($this->getRestResourceDependencies()->calculateDependencies($this) as $type => $dependencies) {
foreach ($dependencies as $dependency) {
$this->addDependency($type, $dependency);
}
}
return $this;
}
/**
* {@inheritdoc}
*/
public function onDependencyRemoval(array $dependencies) {
$parent = parent::onDependencyRemoval($dependencies);
// If the dependency problems are not marked as fixed at this point they
// should be related to the resource plugin and the config entity should
// be deleted.
$changed = $this->getRestResourceDependencies()->onDependencyRemoval($this, $dependencies);
return $parent || $changed;
}
/**
* Returns the REST resource dependencies.
*
* @return \Drupal\rest\Entity\ConfigDependencies
*/
protected function getRestResourceDependencies() {
return \Drupal::service('class_resolver')->getInstanceFromDefinition(ConfigDependencies::class);
}
/**
* Normalizes the method.
*
* @param string $method
* The request method.
*
* @return string
* The normalized request method.
*/
protected function normalizeRestMethod($method) {
return strtoupper($method);
}
/**
* {@inheritdoc}
*/
public function postSave(EntityStorageInterface $storage, $update = TRUE) {
parent::postSave($storage, $update);
\Drupal::service('router.builder')->setRebuildNeeded();
}
/**
* {@inheritdoc}
*/
public static function postDelete(EntityStorageInterface $storage, array $entities) {
parent::postDelete($storage, $entities);
\Drupal::service('router.builder')->setRebuildNeeded();
}
}
@@ -0,0 +1,204 @@
<?php
namespace Drupal\rest\EventSubscriber;
use Drupal\Core\Cache\CacheableResponse;
use Drupal\Core\Cache\CacheableResponseInterface;
use Drupal\Core\Render\RenderContext;
use Drupal\Core\Render\RendererInterface;
use Drupal\Core\Routing\RouteMatchInterface;
use Drupal\rest\ResourceResponseInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Event\FilterResponseEvent;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\Serializer\SerializerInterface;
/**
* Response subscriber that serializes and removes ResourceResponses' data.
*/
class ResourceResponseSubscriber implements EventSubscriberInterface {
/**
* The serializer.
*
* @var \Symfony\Component\Serializer\SerializerInterface
*/
protected $serializer;
/**
* The renderer.
*
* @var \Drupal\Core\Render\RendererInterface
*/
protected $renderer;
/**
* The current route match.
*
* @var \Drupal\Core\Routing\RouteMatchInterface
*/
protected $routeMatch;
/**
* Constructs a ResourceResponseSubscriber object.
*
* @param \Symfony\Component\Serializer\SerializerInterface $serializer
* The serializer.
* @param \Drupal\Core\Render\RendererInterface $renderer
* The renderer.
* @param \Drupal\Core\Routing\RouteMatchInterface $route_match
* The current route match.
*/
public function __construct(SerializerInterface $serializer, RendererInterface $renderer, RouteMatchInterface $route_match) {
$this->serializer = $serializer;
$this->renderer = $renderer;
$this->routeMatch = $route_match;
}
/**
* Serializes ResourceResponse responses' data, and removes that data.
*
* @param \Symfony\Component\HttpKernel\Event\FilterResponseEvent $event
* The event to process.
*/
public function onResponse(FilterResponseEvent $event) {
$response = $event->getResponse();
if (!$response instanceof ResourceResponseInterface) {
return;
}
$request = $event->getRequest();
$format = $this->getResponseFormat($this->routeMatch, $request);
$this->renderResponseBody($request, $response, $this->serializer, $format);
$event->setResponse($this->flattenResponse($response));
}
/**
* Determines the format to respond in.
*
* Respects the requested format if one is specified. However, it is common to
* forget to specify a request format in case of a POST or PATCH. Rather than
* simply throwing an error, we apply the robustness principle: when POSTing
* or PATCHing using a certain format, you probably expect a response in that
* same format.
*
* @param \Drupal\Core\Routing\RouteMatchInterface $route_match
* The current route match.
* @param \Symfony\Component\HttpFoundation\Request $request
* The current request.
*
* @return string
* The response format.
*/
public function getResponseFormat(RouteMatchInterface $route_match, Request $request) {
$route = $route_match->getRouteObject();
$acceptable_request_formats = $route->hasRequirement('_format') ? explode('|', $route->getRequirement('_format')) : [];
$acceptable_content_type_formats = $route->hasRequirement('_content_type_format') ? explode('|', $route->getRequirement('_content_type_format')) : [];
$acceptable_formats = $request->isMethodSafe() ? $acceptable_request_formats : $acceptable_content_type_formats;
$requested_format = $request->getRequestFormat();
$content_type_format = $request->getContentType();
// If an acceptable format is requested, then use that. Otherwise, including
// and particularly when the client forgot to specify a format, then use
// heuristics to select the format that is most likely expected.
if (in_array($requested_format, $acceptable_formats)) {
return $requested_format;
}
// If a request body is present, then use the format corresponding to the
// request body's Content-Type for the response, if it's an acceptable
// format for the request.
elseif (!empty($request->getContent()) && in_array($content_type_format, $acceptable_content_type_formats)) {
return $content_type_format;
}
// Otherwise, use the first acceptable format.
elseif (!empty($acceptable_formats)) {
return $acceptable_formats[0];
}
// Sometimes, there are no acceptable formats, e.g. DELETE routes.
else {
return NULL;
}
}
/**
* Renders a resource response body.
*
* Serialization can invoke rendering (e.g., generating URLs), but the
* serialization API does not provide a mechanism to collect the
* bubbleable metadata associated with that (e.g., language and other
* contexts), so instead, allow those to "leak" and collect them here in
* a render context.
*
* @param \Symfony\Component\HttpFoundation\Request $request
* The request object.
* @param \Drupal\rest\ResourceResponseInterface $response
* The response from the REST resource.
* @param \Symfony\Component\Serializer\SerializerInterface $serializer
* The serializer to use.
* @param string|null $format
* The response format, or NULL in case the response does not need a format,
* for example for the response to a DELETE request.
*
* @todo Add test coverage for language negotiation contexts in
* https://www.drupal.org/node/2135829.
*/
protected function renderResponseBody(Request $request, ResourceResponseInterface $response, SerializerInterface $serializer, $format) {
$data = $response->getResponseData();
// If there is data to send, serialize and set it as the response body.
if ($data !== NULL) {
$context = new RenderContext();
$output = $this->renderer
->executeInRenderContext($context, function () use ($serializer, $data, $format) {
return $serializer->serialize($data, $format);
});
if ($response instanceof CacheableResponseInterface && !$context->isEmpty()) {
$response->addCacheableDependency($context->pop());
}
$response->setContent($output);
$response->headers->set('Content-Type', $request->getMimeType($format));
}
}
/**
* Flattens a fully rendered resource response.
*
* Ensures that complex data structures in ResourceResponse::getResponseData()
* are not serialized. Not doing this means that caching this response object
* requires unserializing the PHP data when reading this response object from
* cache, which can be very costly, and is unnecessary.
*
* @param \Drupal\rest\ResourceResponseInterface $response
* A fully rendered resource response.
*
* @return \Drupal\Core\Cache\CacheableResponse|\Symfony\Component\HttpFoundation\Response
* The flattened response.
*/
protected function flattenResponse(ResourceResponseInterface $response) {
$final_response = ($response instanceof CacheableResponseInterface) ? new CacheableResponse() : new Response();
$final_response->setContent($response->getContent());
$final_response->setStatusCode($response->getStatusCode());
$final_response->setProtocolVersion($response->getProtocolVersion());
$final_response->setCharset($response->getCharset());
$final_response->headers = clone $response->headers;
if ($final_response instanceof CacheableResponseInterface) {
$final_response->addCacheableDependency($response->getCacheableMetadata());
}
return $final_response;
}
/**
* {@inheritdoc}
*/
public static function getSubscribedEvents() {
// Run shortly before \Drupal\Core\EventSubscriber\FinishResponseSubscriber.
$events[KernelEvents::RESPONSE][] = ['onResponse', 5];
return $events;
}
}
@@ -0,0 +1,53 @@
<?php
namespace Drupal\rest\EventSubscriber;
use Drupal\Core\Config\ConfigCrudEvent;
use Drupal\Core\Config\ConfigEvents;
use Drupal\Core\Routing\RouteBuilderInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
/**
* A subscriber triggering a route rebuild when certain configuration changes.
*/
class RestConfigSubscriber implements EventSubscriberInterface {
/**
* The router builder.
*
* @var \Drupal\Core\Routing\RouteBuilderInterface
*/
protected $routerBuilder;
/**
* Constructs the RestConfigSubscriber.
*
* @param \Drupal\Core\Routing\RouteBuilderInterface $route_builder
* The router builder service.
*/
public function __construct(RouteBuilderInterface $router_builder) {
$this->routerBuilder = $router_builder;
}
/**
* Informs the router builder a rebuild is needed when necessary.
*
* @param \Drupal\Core\Config\ConfigCrudEvent $event
* The Event to process.
*/
public function onSave(ConfigCrudEvent $event) {
$saved_config = $event->getConfig();
if ($saved_config->getName() === 'rest.settings' && $event->isChanged('bc_entity_resource_permissions')) {
$this->routerBuilder->setRebuildNeeded();
}
}
/**
* {@inheritdoc}
*/
public static function getSubscribedEvents() {
$events[ConfigEvents::SAVE][] = ['onSave'];
return $events;
}
}
@@ -2,19 +2,12 @@
namespace Drupal\rest\LinkManager;
use Drupal\hal\LinkManager\ConfigurableLinkManagerInterface as MovedConfigurableLinkManagerInterface;
/**
* Defines an interface for a link manager with a configurable domain.
* @deprecated in Drupal 8.3.x and will be removed before Drupal 9.0.0. This has
* been moved to the hal module. This exists solely for BC.
*
* @see https://www.drupal.org/node/2830467
*/
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);
}
interface ConfigurableLinkManagerInterface extends MovedConfigurableLinkManagerInterface {}
@@ -2,70 +2,12 @@
namespace Drupal\rest\LinkManager;
class LinkManager implements LinkManagerInterface {
use Drupal\hal\LinkManager\LinkManager as MovedLinkManager;
/**
* The type link manager.
*
* @var \Drupal\rest\LinkManager\TypeLinkManagerInterface
*/
protected $typeLinkManager;
/**
* The relation link manager.
*
* @var \Drupal\rest\LinkManager\RelationLinkManagerInterface
*/
protected $relationLinkManager;
/**
* Constructor.
*
* @param \Drupal\rest\LinkManager\TypeLinkManagerInterface $type_link_manager
* Manager for handling bundle URIs.
* @param \Drupal\rest\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 = array()) {
return $this->typeLinkManager->getTypeUri($entity_type, $bundle, $context);
}
/**
* {@inheritdoc}
*/
public function getTypeInternalIds($type_uri, $context = array()) {
return $this->typeLinkManager->getTypeInternalIds($type_uri, $context);
}
/**
* {@inheritdoc}
*/
public function getRelationUri($entity_type, $bundle, $field_name, $context = array()) {
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;
}
}
/**
* @deprecated in Drupal 8.3.x and will be removed before Drupal 9.0.0. This has
* been moved to the hal module. This exists solely for BC.
*
* @see https://www.drupal.org/node/2830467
*/
class LinkManager extends MovedLinkManager implements LinkManagerInterface {}
@@ -2,57 +2,12 @@
namespace Drupal\rest\LinkManager;
use Drupal\hal\LinkManager\LinkManagerBase as MovedLinkManagerBase;
/**
* Defines an abstract base-class for REST link manager objects.
* @deprecated in Drupal 8.3.x and will be removed before Drupal 9.0.0. This has
* been moved to the hal module. This exists solely for BC.
*
* @see https://www.drupal.org/node/2830467
*/
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('rest.settings')->get('link_domain')) {
$this->linkDomain = rtrim($domain, '/');
}
else {
$request = $this->requestStack->getCurrentRequest();
$this->linkDomain = $request->getSchemeAndHttpHost() . $request->getBasePath();
}
}
return $this->linkDomain;
}
}
abstract class LinkManagerBase extends MovedLinkManagerBase {}
@@ -2,17 +2,12 @@
namespace Drupal\rest\LinkManager;
use Drupal\hal\LinkManager\LinkManagerInterface as MovedLinkManagerInterface;
/**
* Interface implemented by link managers.
* @deprecated in Drupal 8.3.x and will be removed before Drupal 9.0.0. This has
* been moved to the hal module. This exists solely for BC.
*
* 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.
* @see https://www.drupal.org/node/2830467
*/
interface LinkManagerInterface extends TypeLinkManagerInterface, RelationLinkManagerInterface {
}
interface LinkManagerInterface extends MovedLinkManagerInterface {}
@@ -2,141 +2,12 @@
namespace Drupal\rest\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;
use Drupal\hal\LinkManager\RelationLinkManager as MovedLinkRelationManager;
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 = array()) {
// Per the interface documention of this method, the returned URI may
// optionally also serve as the URL of a documentation page about this
// field. However, the REST module 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('rest_relation_uri', $uri, $context);
return $uri;
}
/**
* {@inheritdoc}
*/
public function getRelationInternalIds($relation_uri, $context = array()) {
$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 = array()) {
$cid = 'rest: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 = array()) {
$data = array();
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] = array(
'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('rest:links:relations', $data, Cache::PERMANENT, array('entity_field_info'));
}
}
/**
* @deprecated in Drupal 8.3.x and will be removed before Drupal 9.0.0. This has
* been moved to the hal module. This exists solely for BC.
*
* @see https://www.drupal.org/node/2830467
*/
class RelationLinkManager extends MovedLinkRelationManager implements RelationLinkManagerInterface {}
@@ -2,38 +2,12 @@
namespace Drupal\rest\LinkManager;
interface RelationLinkManagerInterface extends ConfigurableLinkManagerInterface {
use Drupal\hal\LinkManager\RelationLinkManagerInterface as MovedRelationLinkManagerInterface;
/**
* 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 = array());
/**
* 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);
}
/**
* @deprecated in Drupal 8.3.x and will be removed before Drupal 9.0.0. This has
* been moved to the hal module. This exists solely for BC.
*
* @see https://www.drupal.org/node/2830467
*/
interface RelationLinkManagerInterface extends MovedRelationLinkManagerInterface {}
@@ -2,129 +2,12 @@
namespace Drupal\rest\LinkManager;
use Drupal\Core\Cache\Cache;
use Drupal\Core\Cache\CacheBackendInterface;
use Drupal\Core\Config\ConfigFactoryInterface;
use Drupal\Core\Extension\ModuleHandlerInterface;
use Symfony\Component\HttpFoundation\RequestStack;
use Drupal\hal\LinkManager\TypeLinkManager as MovedTypeLinkManager;
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;
/**
* 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.
*/
public function __construct(CacheBackendInterface $cache, ModuleHandlerInterface $module_handler, ConfigFactoryInterface $config_factory, RequestStack $request_stack) {
$this->cache = $cache;
$this->configFactory = $config_factory;
$this->moduleHandler = $module_handler;
$this->requestStack = $request_stack;
}
/**
* {@inheritdoc}
*/
public function getTypeUri($entity_type, $bundle, $context = array()) {
// Per the interface documention of this method, the returned URI may
// optionally also serve as the URL of a documentation page about this
// bundle. However, the REST module 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('rest_type_uri', $uri, $context);
return $uri;
}
/**
* {@inheritdoc}
*/
public function getTypeInternalIds($type_uri, $context = array()) {
$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 = array()) {
$cid = 'rest:links:types';
$cache = $this->cache->get($cid);
if (!$cache) {
$this->writeCache($context);
$cache = $this->cache->get($cid);
}
return $cache->data;
}
/**
* Writes the cache of type links.
*
* @param array $context
* Context from the normalizer/serializer operation.
*/
protected function writeCache($context = array()) {
$data = array();
// Type URIs correspond to bundles. Iterate through the bundles to get the
// URI and data for them.
$entity_types = \Drupal::entityManager()->getDefinitions();
foreach (entity_get_bundles() as $entity_type_id => $bundles) {
// Only content entities are supported currently.
// @todo Consider supporting config entities.
if ($entity_types[$entity_type_id]->isSubclassOf('\Drupal\Core\Config\Entity\ConfigEntityInterface')) {
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] = array(
'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('rest:links:types', $data, Cache::PERMANENT, array('entity_types'));
}
}
/**
* @deprecated in Drupal 8.3.x and will be removed before Drupal 9.0.0. This has
* been moved to the hal module. This exists solely for BC.
*
* @see https://www.drupal.org/node/2830467
*/
class TypeLinkManager extends MovedTypeLinkManager implements TypeLinkManagerInterface {}
@@ -2,39 +2,12 @@
namespace Drupal\rest\LinkManager;
interface TypeLinkManagerInterface extends ConfigurableLinkManagerInterface {
use Drupal\hal\LinkManager\TypeLinkManagerInterface as MovedTypeLinkManagerInterface;
/**
* 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 = array());
/**
* 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 = array());
}
/**
* @deprecated in Drupal 8.3.x and will be removed before Drupal 9.0.0. This has
* been moved to the hal module. This exists solely for BC.
*
* @see https://www.drupal.org/node/2830467
*/
interface TypeLinkManagerInterface extends MovedTypeLinkManagerInterface {}
@@ -0,0 +1,34 @@
<?php
namespace Drupal\rest;
use Symfony\Component\HttpFoundation\Response;
/**
* A response that does not contain cacheability metadata.
*
* Used when resources are modified by a request: responses to unsafe requests
* (POST/PATCH/DELETE) can never be cached.
*
* @see \Drupal\rest\ResourceResponse
*/
class ModifiedResourceResponse extends Response implements ResourceResponseInterface {
use ResourceResponseTrait;
/**
* Constructor for ModifiedResourceResponse objects.
*
* @param mixed $data
* Response data that should be serialized.
* @param int $status
* The response status code.
* @param array $headers
* An array of response headers.
*/
public function __construct($data = NULL, $status = 200, $headers = []) {
$this->responseData = $data;
parent::__construct('', $status, $headers);
}
}
@@ -65,17 +65,17 @@ class EntityDeriver implements ContainerDeriverInterface {
if (!isset($this->derivatives)) {
// Add in the default plugin configuration and the resource type.
foreach ($this->entityManager->getDefinitions() as $entity_type_id => $entity_type) {
$this->derivatives[$entity_type_id] = array(
$this->derivatives[$entity_type_id] = [
'id' => 'entity:' . $entity_type_id,
'entity_type' => $entity_type_id,
'serialization_class' => $entity_type->getClass(),
'label' => $entity_type->getLabel(),
);
];
$default_uris = array(
$default_uris = [
'canonical' => "/entity/$entity_type_id/" . '{' . $entity_type_id . '}',
'https://www.drupal.org/link-relations/create' => "/entity/$entity_type_id",
);
];
foreach ($default_uris as $link_relation => $default_uri) {
// Check if there are link templates defined for the entity type and
+53 -32
View File
@@ -12,6 +12,11 @@ use Symfony\Component\Routing\RouteCollection;
/**
* Common base class for resource plugins.
*
* Note that this base class' implementation of the permissions() method
* generates a permission for every method for a resource. If your resource
* already has its own access control mechanism, you should opt out from this
* default permissions() method by overriding it.
*
* @see \Drupal\rest\Annotation\RestResource
* @see \Drupal\rest\Plugin\Type\ResourcePluginManager
* @see \Drupal\rest\Plugin\ResourceInterface
@@ -26,7 +31,7 @@ abstract class ResourceBase extends PluginBase implements ContainerFactoryPlugin
*
* @var array
*/
protected $serializerFormats = array();
protected $serializerFormats = [];
/**
* A logger instance.
@@ -76,13 +81,13 @@ abstract class ResourceBase extends PluginBase implements ContainerFactoryPlugin
* resource".
*/
public function permissions() {
$permissions = array();
$permissions = [];
$definition = $this->getPluginDefinition();
foreach ($this->availableMethods() as $method) {
$lowered_method = strtolower($method);
$permissions["restful $lowered_method $this->pluginId"] = array(
'title' => $this->t('Access @method on %label resource', array('@method' => $method, '%label' => $definition['label'])),
);
$permissions["restful $lowered_method $this->pluginId"] = [
'title' => $this->t('Access @method on %label resource', ['@method' => $method, '%label' => $definition['label']]),
];
}
return $permissions;
}
@@ -106,16 +111,6 @@ abstract class ResourceBase extends PluginBase implements ContainerFactoryPlugin
switch ($method) {
case 'POST':
$route->setPath($create_path);
// Restrict the incoming HTTP Content-type header to the known
// serialization formats.
$route->addRequirements(array('_content_type_format' => implode('|', $this->serializerFormats)));
$collection->add("$route_name.$method", $route);
break;
case 'PATCH':
// Restrict the incoming HTTP Content-type header to the known
// serialization formats.
$route->addRequirements(array('_content_type_format' => implode('|', $this->serializerFormats)));
$collection->add("$route_name.$method", $route);
break;
@@ -126,7 +121,7 @@ abstract class ResourceBase extends PluginBase implements ContainerFactoryPlugin
foreach ($this->serializerFormats as $format_name) {
// Expose one route per available format.
$format_route = clone $route;
$format_route->addRequirements(array('_format' => $format_name));
$format_route->addRequirements(['_format' => $format_name]);
$collection->add("$route_name.$method.$format_name", $format_route);
}
break;
@@ -150,7 +145,7 @@ abstract class ResourceBase extends PluginBase implements ContainerFactoryPlugin
* The list of allowed HTTP request method strings.
*/
protected function requestMethods() {
return array(
return [
'HEAD',
'GET',
'POST',
@@ -160,7 +155,7 @@ abstract class ResourceBase extends PluginBase implements ContainerFactoryPlugin
'OPTIONS',
'CONNECT',
'PATCH',
);
];
}
/**
@@ -168,7 +163,7 @@ abstract class ResourceBase extends PluginBase implements ContainerFactoryPlugin
*/
public function availableMethods() {
$methods = $this->requestMethods();
$available = array();
$available = [];
foreach ($methods as $method) {
// Only expose methods where the HTTP request method exists on the plugin.
if (method_exists($this, strtolower($method))) {
@@ -179,7 +174,7 @@ abstract class ResourceBase extends PluginBase implements ContainerFactoryPlugin
}
/**
* Setups the base route for all HTTP methods.
* Gets the base route for a particular method.
*
* @param string $canonical_path
* The canonical path for the resource.
@@ -190,22 +185,48 @@ abstract class ResourceBase extends PluginBase implements ContainerFactoryPlugin
* The created base route.
*/
protected function getBaseRoute($canonical_path, $method) {
$lower_method = strtolower($method);
$route = new Route($canonical_path, array(
return new Route($canonical_path, [
'_controller' => 'Drupal\rest\RequestHandler::handle',
// Pass the resource plugin ID along as default property.
'_plugin' => $this->pluginId,
), array(
'_permission' => "restful $lower_method $this->pluginId",
),
array(),
],
$this->getBaseRouteRequirements($method),
[],
'',
array(),
[],
// The HTTP method is a requirement for this route.
array($method)
[$method]
);
return $route;
}
/**
* Gets the base route requirements for a particular method.
*
* @param $method
* The HTTP method to be used for the route.
*
* @return array
* An array of requirements for parameters.
*/
protected function getBaseRouteRequirements($method) {
$lower_method = strtolower($method);
// Every route MUST have requirements that result in the access manager
// having access checks to check. If it does not, the route is made
// inaccessible. So, we default to granting access to everyone. If a
// permission exists, then we add that below. The access manager requires
// that ALL access checks must grant access, so this still results in
// correct behavior.
$requirements = [
'_access' => 'TRUE',
];
// Only specify route requirements if the default permission exists. For any
// more advanced route definition, resource plugins extending this base
// class must override this method.
$permission = "restful $lower_method $this->pluginId";
if (isset($this->permissions()[$permission])) {
$requirements['_permission'] = $permission;
}
return $requirements;
}
}
@@ -33,6 +33,10 @@ interface ResourceInterface extends PluginInspectionInterface {
* A resource plugin can define a set of user permissions that are used on the
* routes for this resource or for other purposes.
*
* It is not required for a resource plugin to specify permissions: if they
* have their own access control mechanism, they can use that, and return the
* empty array.
*
* @return array
* The permission array.
*/
@@ -36,6 +36,12 @@ class ResourcePluginManager extends DefaultPluginManager {
/**
* {@inheritdoc}
*
* @deprecated in Drupal 8.2.0.
* Use Drupal\rest\Plugin\Type\ResourcePluginManager::createInstance()
* instead.
*
* @see https://www.drupal.org/node/2874934
*/
public function getInstance(array $options){
if (isset($options['id'])) {
@@ -2,10 +2,23 @@
namespace Drupal\rest\Plugin\rest\resource;
use Drupal\Component\Plugin\DependentPluginInterface;
use Drupal\Component\Plugin\PluginManagerInterface;
use Drupal\Core\Cache\CacheableResponseInterface;
use Drupal\Core\Config\Entity\ConfigEntityType;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Entity\FieldableEntityInterface;
use Drupal\Core\Config\ConfigFactoryInterface;
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Entity\EntityStorageException;
use Drupal\Core\Field\FieldItemListInterface;
use Drupal\Core\TypedData\PrimitiveInterface;
use Drupal\rest\Plugin\ResourceBase;
use Drupal\rest\ResourceResponse;
use Psr\Log\LoggerInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Drupal\rest\ModifiedResourceResponse;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
use Symfony\Component\HttpKernel\Exception\HttpException;
@@ -26,7 +39,74 @@ use Symfony\Component\HttpKernel\Exception\HttpException;
* }
* )
*/
class EntityResource extends ResourceBase {
class EntityResource extends ResourceBase implements DependentPluginInterface {
use EntityResourceValidationTrait;
use EntityResourceAccessTrait;
/**
* The entity type targeted by this resource.
*
* @var \Drupal\Core\Entity\EntityTypeInterface
*/
protected $entityType;
/**
* The config factory.
*
* @var \Drupal\Core\Config\ConfigFactoryInterface
*/
protected $configFactory;
/**
* The link relation type manager used to create HTTP header links.
*
* @var \Drupal\Component\Plugin\PluginManagerInterface
*/
protected $linkRelationTypeManager;
/**
* Constructs a Drupal\rest\Plugin\rest\resource\EntityResource object.
*
* @param array $configuration
* A configuration array containing information about the plugin instance.
* @param string $plugin_id
* The plugin_id for the plugin instance.
* @param mixed $plugin_definition
* The plugin implementation definition.
* @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
* The entity type manager
* @param array $serializer_formats
* The available serialization formats.
* @param \Psr\Log\LoggerInterface $logger
* A logger instance.
* @param \Drupal\Core\Config\ConfigFactoryInterface $config_factory
* The config factory.
* @param \Drupal\Component\Plugin\PluginManagerInterface $link_relation_type_manager
* The link relation type manager.
*/
public function __construct(array $configuration, $plugin_id, $plugin_definition, EntityTypeManagerInterface $entity_type_manager, $serializer_formats, LoggerInterface $logger, ConfigFactoryInterface $config_factory, PluginManagerInterface $link_relation_type_manager) {
parent::__construct($configuration, $plugin_id, $plugin_definition, $serializer_formats, $logger);
$this->entityType = $entity_type_manager->getDefinition($plugin_definition['entity_type']);
$this->configFactory = $config_factory;
$this->linkRelationTypeManager = $link_relation_type_manager;
}
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
return new static(
$configuration,
$plugin_id,
$plugin_definition,
$container->get('entity_type.manager'),
$container->getParameter('serializer.formats'),
$container->get('logger.factory')->get('rest'),
$container->get('config.factory'),
$container->get('plugin.manager.link_relation_type')
);
}
/**
* Responds to entity GET requests.
@@ -42,22 +122,27 @@ class EntityResource extends ResourceBase {
public function get(EntityInterface $entity) {
$entity_access = $entity->access('view', NULL, TRUE);
if (!$entity_access->isAllowed()) {
throw new AccessDeniedHttpException();
throw new AccessDeniedHttpException($entity_access->getReason() ?: $this->generateFallbackAccessDeniedMessage($entity, 'view'));
}
$response = new ResourceResponse($entity, 200);
$response->addCacheableDependency($entity);
$response->addCacheableDependency($entity_access);
foreach ($entity as $field_name => $field) {
/** @var \Drupal\Core\Field\FieldItemListInterface $field */
$field_access = $field->access('view', NULL, TRUE);
$response->addCacheableDependency($field_access);
if (!$field_access->isAllowed()) {
$entity->set($field_name, NULL);
if ($entity instanceof FieldableEntityInterface) {
foreach ($entity as $field_name => $field) {
/** @var \Drupal\Core\Field\FieldItemListInterface $field */
$field_access = $field->access('view', NULL, TRUE);
$response->addCacheableDependency($field_access);
if (!$field_access->isAllowed()) {
$entity->set($field_name, NULL);
}
}
}
$this->addLinkHeaders($entity, $response);
return $response;
}
@@ -67,7 +152,7 @@ class EntityResource extends ResourceBase {
* @param \Drupal\Core\Entity\EntityInterface $entity
* The entity.
*
* @return \Drupal\rest\ResourceResponse
* @return \Drupal\rest\ModifiedResourceResponse
* The HTTP response object.
*
* @throws \Symfony\Component\HttpKernel\Exception\HttpException
@@ -77,8 +162,9 @@ class EntityResource extends ResourceBase {
throw new BadRequestHttpException('No entity content received.');
}
if (!$entity->access('create')) {
throw new AccessDeniedHttpException();
$entity_access = $entity->access('create', NULL, TRUE);
if (!$entity_access->isAllowed()) {
throw new AccessDeniedHttpException($entity_access->getReason() ?: $this->generateFallbackAccessDeniedMessage($entity, 'create'));
}
$definition = $this->getPluginDefinition();
// Verify that the deserialized entity is of the type that we expect to
@@ -92,34 +178,64 @@ class EntityResource extends ResourceBase {
throw new BadRequestHttpException('Only new entities can be created');
}
// Only check 'edit' permissions for fields that were actually
// submitted by the user. Field access makes no difference between 'create'
// and 'update', so the 'edit' operation is used here.
foreach ($entity->_restSubmittedFields as $key => $field_name) {
if (!$entity->get($field_name)->access('edit')) {
throw new AccessDeniedHttpException("Access denied on creating field '$field_name'");
}
}
$this->checkEditFieldAccess($entity);
// Validate the received data before saving.
$this->validate($entity);
try {
$entity->save();
$this->logger->notice('Created entity %type with ID %id.', array('%type' => $entity->getEntityTypeId(), '%id' => $entity->id()));
$this->logger->notice('Created entity %type with ID %id.', ['%type' => $entity->getEntityTypeId(), '%id' => $entity->id()]);
// 201 Created responses return the newly created entity in the response
// body.
$url = $entity->urlInfo('canonical', ['absolute' => TRUE])->toString(TRUE);
$response = new ResourceResponse($entity, 201, ['Location' => $url->getGeneratedUrl()]);
// Responses after creating an entity are not cacheable, so we add no
// cacheability metadata here.
return $response;
// body. These responses are not cacheable, so we add no cacheability
// metadata here.
$headers = [];
if (in_array('canonical', $entity->uriRelationships(), TRUE)) {
$url = $entity->urlInfo('canonical', ['absolute' => TRUE])->toString(TRUE);
$headers['Location'] = $url->getGeneratedUrl();
}
return new ModifiedResourceResponse($entity, 201, $headers);
}
catch (EntityStorageException $e) {
throw new HttpException(500, 'Internal Server Error', $e);
}
}
/**
* Gets the values from the field item list casted to the correct type.
*
* Values are casted to the correct type so we can determine whether or not
* something has changed. REST formats such as JSON support typed data but
* Drupal's database API will return values as strings. Currently, only
* primitive data types know how to cast their values to the correct type.
*
* @param \Drupal\Core\Field\FieldItemListInterface $field_item_list
* The field item list to retrieve its data from.
*
* @return mixed[][]
* The values from the field item list casted to the correct type. The array
* of values returned is a multidimensional array keyed by delta and the
* property name.
*/
protected function getCastedValueFromFieldItemList(FieldItemListInterface $field_item_list) {
$value = $field_item_list->getValue();
foreach ($value as $delta => $field_item_value) {
/** @var \Drupal\Core\Field\FieldItemInterface $field_item */
$field_item = $field_item_list->get($delta);
$properties = $field_item->getProperties(TRUE);
// Foreach field value we check whether we know the underlying property.
// If we exists we try to cast the value.
foreach ($field_item_value as $property_name => $property_value) {
if (isset($properties[$property_name]) && ($property = $field_item->get($property_name)) && $property instanceof PrimitiveInterface) {
$value[$delta][$property_name] = $property->getCastedValue();
}
}
}
return $value;
}
/**
* Responds to entity PATCH requests.
*
@@ -128,7 +244,7 @@ class EntityResource extends ResourceBase {
* @param \Drupal\Core\Entity\EntityInterface $entity
* The entity.
*
* @return \Drupal\rest\ResourceResponse
* @return \Drupal\rest\ModifiedResourceResponse
* The HTTP response object.
*
* @throws \Symfony\Component\HttpKernel\Exception\HttpException
@@ -141,8 +257,9 @@ class EntityResource extends ResourceBase {
if ($entity->getEntityTypeId() != $definition['entity_type']) {
throw new BadRequestHttpException('Invalid entity type');
}
if (!$original_entity->access('update')) {
throw new AccessDeniedHttpException();
$entity_access = $original_entity->access('update', NULL, TRUE);
if (!$entity_access->isAllowed()) {
throw new AccessDeniedHttpException($entity_access->getReason() ?: $this->generateFallbackAccessDeniedMessage($entity, 'update'));
}
// Overwrite the received properties.
@@ -155,8 +272,15 @@ class EntityResource extends ResourceBase {
// them. However, rather than throwing an error, we just ignore them as
// long as their specified values match their current values.
if (in_array($field_name, $entity_keys, TRUE)) {
// @todo Work around the wrong assumption that entity keys need special
// treatment, when only read-only fields need it.
// This will be fixed in https://www.drupal.org/node/2824851.
if ($entity->getEntityTypeId() == 'comment' && $field_name == 'status' && !$original_entity->get($field_name)->access('edit')) {
throw new AccessDeniedHttpException("Access denied on updating field '$field_name'.");
}
// Unchanged values for entity keys don't need access checking.
if ($original_entity->get($field_name)->getValue() === $entity->get($field_name)->getValue()) {
if ($this->getCastedValueFromFieldItemList($original_entity->get($field_name)) === $this->getCastedValueFromFieldItemList($entity->get($field_name))) {
continue;
}
// It is not possible to set the language to NULL as it is automatically
@@ -176,10 +300,10 @@ class EntityResource extends ResourceBase {
$this->validate($original_entity);
try {
$original_entity->save();
$this->logger->notice('Updated entity %type with ID %id.', array('%type' => $original_entity->getEntityTypeId(), '%id' => $original_entity->id()));
$this->logger->notice('Updated entity %type with ID %id.', ['%type' => $original_entity->getEntityTypeId(), '%id' => $original_entity->id()]);
// Update responses have an empty body.
return new ResourceResponse(NULL, 204);
// Return the updated entity in the response body.
return new ModifiedResourceResponse($original_entity, 200);
}
catch (EntityStorageException $e) {
throw new HttpException(500, 'Internal Server Error', $e);
@@ -192,21 +316,22 @@ class EntityResource extends ResourceBase {
* @param \Drupal\Core\Entity\EntityInterface $entity
* The entity object.
*
* @return \Drupal\rest\ResourceResponse
* @return \Drupal\rest\ModifiedResourceResponse
* The HTTP response object.
*
* @throws \Symfony\Component\HttpKernel\Exception\HttpException
*/
public function delete(EntityInterface $entity) {
if (!$entity->access('delete')) {
throw new AccessDeniedHttpException();
$entity_access = $entity->access('delete', NULL, TRUE);
if (!$entity_access->isAllowed()) {
throw new AccessDeniedHttpException($entity_access->getReason() ?: $this->generateFallbackAccessDeniedMessage($entity, 'delete'));
}
try {
$entity->delete();
$this->logger->notice('Deleted entity %type with ID %id.', array('%type' => $entity->getEntityTypeId(), '%id' => $entity->id()));
$this->logger->notice('Deleted entity %type with ID %id.', ['%type' => $entity->getEntityTypeId(), '%id' => $entity->id()]);
// Delete responses have an empty body.
return new ResourceResponse(NULL, 204);
// DELETE responses have an empty body.
return new ModifiedResourceResponse(NULL, 204);
}
catch (EntityStorageException $e) {
throw new HttpException(500, 'Internal Server Error', $e);
@@ -214,31 +339,37 @@ class EntityResource extends ResourceBase {
}
/**
* Verifies that the whole entity does not violate any validation constraints.
* Generates a fallback access denied message, when no specific reason is set.
*
* @param \Drupal\Core\Entity\EntityInterface $entity
* The entity object.
* @param string $operation
* The disallowed entity operation.
*
* @throws \Symfony\Component\HttpKernel\Exception\HttpException
* If validation errors are found.
* @return string
* The proper message to display in the AccessDeniedHttpException.
*/
protected function validate(EntityInterface $entity) {
$violations = $entity->validate();
protected function generateFallbackAccessDeniedMessage(EntityInterface $entity, $operation) {
$message = "You are not authorized to {$operation} this {$entity->getEntityTypeId()} entity";
// Remove violations of inaccessible fields as they cannot stem from our
// changes.
$violations->filterByFieldAccess();
if ($entity->bundle() !== $entity->getEntityTypeId()) {
$message .= " of bundle {$entity->bundle()}";
}
return "{$message}.";
}
if (count($violations) > 0) {
$message = "Unprocessable Entity: validation failed.\n";
foreach ($violations as $violation) {
$message .= $violation->getPropertyPath() . ': ' . $violation->getMessage() . "\n";
}
// Instead of returning a generic 400 response we use the more specific
// 422 Unprocessable Entity code from RFC 4918. That way clients can
// distinguish between general syntax errors in bad serializations (code
// 400) and semantic errors in well-formed requests (code 422).
throw new HttpException(422, $message);
/**
* {@inheritdoc}
*/
public function permissions() {
// @see https://www.drupal.org/node/2664780
if ($this->configFactory->get('rest.settings')->get('bc_entity_resource_permissions')) {
// The default Drupal 8.0.x and 8.1.x behavior.
return parent::permissions();
}
else {
// The default Drupal 8.2.x behavior.
return [];
}
}
@@ -249,11 +380,75 @@ class EntityResource extends ResourceBase {
$route = parent::getBaseRoute($canonical_path, $method);
$definition = $this->getPluginDefinition();
$parameters = $route->getOption('parameters') ?: array();
$parameters = $route->getOption('parameters') ?: [];
$parameters[$definition['entity_type']]['type'] = 'entity:' . $definition['entity_type'];
$route->setOption('parameters', $parameters);
return $route;
}
/**
* {@inheritdoc}
*/
public function availableMethods() {
$methods = parent::availableMethods();
if ($this->isConfigEntityResource()) {
// Currently only GET is supported for Config Entities.
// @todo Remove when supported https://www.drupal.org/node/2300677
$unsupported_methods = ['POST', 'PUT', 'DELETE', 'PATCH'];
$methods = array_diff($methods, $unsupported_methods);
}
return $methods;
}
/**
* Checks if this resource is for a Config Entity.
*
* @return bool
* TRUE if the entity is a Config Entity, FALSE otherwise.
*/
protected function isConfigEntityResource() {
return $this->entityType instanceof ConfigEntityType;
}
/**
* {@inheritdoc}
*/
public function calculateDependencies() {
if (isset($this->entityType)) {
return ['module' => [$this->entityType->getProvider()]];
}
}
/**
* Adds link headers to a response.
*
* @param \Drupal\Core\Entity\EntityInterface $entity
* The entity.
* @param \Symfony\Component\HttpFoundation\Response $response
* The response.
*
* @see https://tools.ietf.org/html/rfc5988#section-5
*/
protected function addLinkHeaders(EntityInterface $entity, Response $response) {
foreach ($entity->getEntityType()->getLinkTemplates() as $relation_name => $link_template) {
if ($definition = $this->linkRelationTypeManager->getDefinition($relation_name, FALSE)) {
$generator_url = $entity->toUrl($relation_name)
->setAbsolute(TRUE)
->toString(TRUE);
if ($response instanceof CacheableResponseInterface) {
$response->addCacheableDependency($generator_url);
}
$uri = $generator_url->getGeneratedUrl();
$relationship = $relation_name;
if (!empty($definition['uri'])) {
$relationship = $definition['uri'];
}
$link_header = '<' . $uri . '>; rel="' . $relationship . '"';
$response->headers->set('Link', $link_header, FALSE);
}
}
}
}
@@ -0,0 +1,35 @@
<?php
namespace Drupal\rest\Plugin\rest\resource;
use Drupal\Core\Entity\EntityInterface;
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
/**
* @internal
* @todo Consider making public in https://www.drupal.org/node/2300677
*/
trait EntityResourceAccessTrait {
/**
* Performs edit access checks for fields.
*
* @param \Drupal\Core\Entity\EntityInterface $entity
* The entity whose fields edit access should be checked for.
*
* @throws \Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException
* Throws access denied when the user does not have permissions to edit a
* field.
*/
protected function checkEditFieldAccess(EntityInterface $entity) {
// Only check 'edit' permissions for fields that were actually submitted by
// the user. Field access makes no difference between 'create' and 'update',
// so the 'edit' operation is used here.
foreach ($entity->_restSubmittedFields as $key => $field_name) {
if (!$entity->get($field_name)->access('edit')) {
throw new AccessDeniedHttpException("Access denied on creating field '$field_name'.");
}
}
}
}
@@ -0,0 +1,47 @@
<?php
namespace Drupal\rest\Plugin\rest\resource;
use Drupal\Component\Render\PlainTextOutput;
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Entity\FieldableEntityInterface;
use Symfony\Component\HttpKernel\Exception\UnprocessableEntityHttpException;
/**
* @internal
* @todo Consider making public in https://www.drupal.org/node/2300677
*/
trait EntityResourceValidationTrait {
/**
* Verifies that the whole entity does not violate any validation constraints.
*
* @param \Drupal\Core\Entity\EntityInterface $entity
* The entity to validate.
*
* @throws \Symfony\Component\HttpKernel\Exception\UnprocessableEntityHttpException
* If validation errors are found.
*/
protected function validate(EntityInterface $entity) {
// @todo Remove when https://www.drupal.org/node/2164373 is committed.
if (!$entity instanceof FieldableEntityInterface) {
return;
}
$violations = $entity->validate();
// Remove violations of inaccessible fields as they cannot stem from our
// changes.
$violations->filterByFieldAccess();
if ($violations->count() > 0) {
$message = "Unprocessable Entity: validation failed.\n";
foreach ($violations as $violation) {
// We strip every HTML from the error message to have a nicer to read
// message on REST responses.
$message .= $violation->getPropertyPath() . ': ' . PlainTextOutput::renderFromHtml($violation->getMessage()) . "\n";
}
throw new UnprocessableEntityHttpException($message);
}
}
}
@@ -4,6 +4,7 @@ namespace Drupal\rest\Plugin\views\display;
use Drupal\Core\Cache\CacheableMetadata;
use Drupal\Core\Cache\CacheableResponse;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Render\RenderContext;
use Drupal\Core\Render\RendererInterface;
use Drupal\Core\Routing\RouteProviderInterface;
@@ -13,6 +14,7 @@ use Drupal\views\Render\ViewsRenderPipelineMarkup;
use Drupal\views\ViewExecutable;
use Drupal\views\Plugin\views\display\PathPluginBase;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\Routing\Route;
use Symfony\Component\Routing\RouteCollection;
/**
@@ -77,6 +79,20 @@ class RestExport extends PathPluginBase implements ResponseDisplayPluginInterfac
*/
protected $renderer;
/**
* The collector of authentication providers.
*
* @var \Drupal\Core\Authentication\AuthenticationCollectorInterface
*/
protected $authenticationCollector;
/**
* The authentication providers, keyed by ID.
*
* @var string[]
*/
protected $authenticationProviders;
/**
* Constructs a RestExport object.
*
@@ -92,11 +108,14 @@ class RestExport extends PathPluginBase implements ResponseDisplayPluginInterfac
* The state key value store.
* @param \Drupal\Core\Render\RendererInterface $renderer
* The renderer.
* @param string[] $authentication_providers
* The authentication providers, keyed by ID.
*/
public function __construct(array $configuration, $plugin_id, $plugin_definition, RouteProviderInterface $route_provider, StateInterface $state, RendererInterface $renderer) {
public function __construct(array $configuration, $plugin_id, $plugin_definition, RouteProviderInterface $route_provider, StateInterface $state, RendererInterface $renderer, array $authentication_providers) {
parent::__construct($configuration, $plugin_id, $plugin_definition, $route_provider, $state);
$this->renderer = $renderer;
$this->authenticationProviders = $authentication_providers;
}
/**
@@ -109,7 +128,9 @@ class RestExport extends PathPluginBase implements ResponseDisplayPluginInterfac
$plugin_definition,
$container->get('router.route_provider'),
$container->get('state'),
$container->get('renderer')
$container->get('renderer'),
$container->getParameter('authentication_providers')
);
}
/**
@@ -199,12 +220,25 @@ class RestExport extends PathPluginBase implements ResponseDisplayPluginInterfac
return $this->contentType;
}
/**
* Gets the auth options available.
*
* @return string[]
* An array to use as value for "#options" in the form element.
*/
public function getAuthOptions() {
return array_combine($this->authenticationProviders, $this->authenticationProviders);
}
/**
* {@inheritdoc}
*/
protected function defineOptions() {
$options = parent::defineOptions();
// Options for REST authentication.
$options['auth'] = ['default' => []];
// Set the default style plugin to 'json'.
$options['style']['contains']['type']['default'] = 'serializer';
$options['row']['contains']['type']['default'] = 'data_entity';
@@ -225,20 +259,28 @@ class RestExport extends PathPluginBase implements ResponseDisplayPluginInterfac
public function optionsSummary(&$categories, &$options) {
parent::optionsSummary($categories, $options);
// Authentication.
$auth = $this->getOption('auth') ? implode(', ', $this->getOption('auth')) : $this->t('No authentication is set');
unset($categories['page'], $categories['exposed']);
// Hide some settings, as they aren't useful for pure data output.
unset($options['show_admin_links'], $options['analyze-theme']);
$categories['path'] = array(
$categories['path'] = [
'title' => $this->t('Path settings'),
'column' => 'second',
'build' => array(
'build' => [
'#weight' => -10,
),
);
],
];
$options['path']['category'] = 'path';
$options['path']['title'] = $this->t('Path');
$options['auth'] = [
'category' => 'path',
'title' => $this->t('Authentication'),
'value' => views_ui_truncate($auth, 24),
];
// Remove css/exposed form settings, as they are not used for the data
// display.
@@ -247,6 +289,34 @@ class RestExport extends PathPluginBase implements ResponseDisplayPluginInterfac
unset($options['css_class']);
}
/**
* {@inheritdoc}
*/
public function buildOptionsForm(&$form, FormStateInterface $form_state) {
parent::buildOptionsForm($form, $form_state);
if ($form_state->get('section') === 'auth') {
$form['#title'] .= $this->t('The supported authentication methods for this view');
$form['auth'] = [
'#type' => 'checkboxes',
'#title' => $this->t('Authentication methods'),
'#description' => $this->t('These are the supported authentication providers for this view. When this view is requested, the client will be forced to authenticate with one of the selected providers. Make sure you set the appropriate requirements at the <em>Access</em> section since the Authentication System will fallback to the anonymous user if it fails to authenticate. For example: require Access: Role | Authenticated User.'),
'#options' => $this->getAuthOptions(),
'#default_value' => $this->getOption('auth'),
];
}
}
/**
* {@inheritdoc}
*/
public function submitOptionsForm(&$form, FormStateInterface $form_state) {
parent::submitOptionsForm($form, $form_state);
if ($form_state->get('section') == 'auth') {
$this->setOption('auth', array_keys(array_filter($form_state->getValue('auth'))));
}
}
/**
* {@inheritdoc}
*/
@@ -268,21 +338,53 @@ class RestExport extends PathPluginBase implements ResponseDisplayPluginInterfac
// anyway.
$route->setRequirement('_format', implode('|', $formats + ['html']));
}
// Add authentication to the route if it was set. If no authentication was
// set, the default authentication will be used, which is cookie based by
// default.
$auth = $this->getOption('auth');
if (!empty($auth)) {
$route->setOption('_auth', $auth);
}
}
}
/**
* Determines whether the view overrides the given route.
*
* @param string $view_path
* The path of the view.
* @param \Symfony\Component\Routing\Route $view_route
* The route of the view.
* @param \Symfony\Component\Routing\Route $route
* The route itself.
*
* @return bool
* TRUE, when the view should override the given route.
*/
protected function overrideApplies($view_path, Route $view_route, Route $route) {
$route_formats = explode('|', $route->getRequirement('_format'));
$view_route_formats = explode('|', $view_route->getRequirement('_format'));
return $this->overrideAppliesPathAndMethod($view_path, $view_route, $route)
&& (!$route->hasRequirement('_format') || array_intersect($route_formats, $view_route_formats) != []);
}
/**
* {@inheritdoc}
*/
public static function buildResponse($view_id, $display_id, array $args = []) {
$build = static::buildBasicRenderable($view_id, $display_id, $args);
// Setup an empty response so headers can be added as needed during views
// rendering and processing.
$response = new CacheableResponse('', 200);
$build['#response'] = $response;
/** @var \Drupal\Core\Render\RendererInterface $renderer */
$renderer = \Drupal::service('renderer');
$output = $renderer->renderRoot($build);
$output = (string) $renderer->renderRoot($build);
$response = new CacheableResponse($output, 200);
$response->setContent($output);
$cache_metadata = CacheableMetadata::createFromRenderArray($build);
$response->addCacheableDependency($cache_metadata);
@@ -304,7 +406,7 @@ class RestExport extends PathPluginBase implements ResponseDisplayPluginInterfac
* {@inheritdoc}
*/
public function render() {
$build = array();
$build = [];
$build['#markup'] = $this->renderer->executeInRenderContext(new RenderContext(), function() {
return $this->view->style_plugin->render();
});
@@ -348,4 +450,19 @@ class RestExport extends PathPluginBase implements ResponseDisplayPluginInterfac
return $this->view->render();
}
/**
* {@inheritdoc}
*/
public function calculateDependencies() {
$dependencies = parent::calculateDependencies();
$dependencies += ['module' => []];
$modules = array_map(function ($authentication_provider) {
return $this->authenticationProviders[$authentication_provider];
}, $this->getOption('auth'));
$dependencies['module'] = array_merge($dependencies['module'], $modules);
return $dependencies;
}
}
@@ -31,14 +31,14 @@ class DataFieldRow extends RowPluginBase {
*
* @var array
*/
protected $replacementAliases = array();
protected $replacementAliases = [];
/**
* Stores an array of options to determine if the raw field output is used.
*
* @var array
*/
protected $rawOutputOptions = array();
protected $rawOutputOptions = [];
/**
* {@inheritdoc}
@@ -61,7 +61,7 @@ class DataFieldRow extends RowPluginBase {
*/
protected function defineOptions() {
$options = parent::defineOptions();
$options['field_options'] = array('default' => array());
$options['field_options'] = ['default' => []];
return $options;
}
@@ -72,12 +72,12 @@ class DataFieldRow extends RowPluginBase {
public function buildOptionsForm(&$form, FormStateInterface $form_state) {
parent::buildOptionsForm($form, $form_state);
$form['field_options'] = array(
$form['field_options'] = [
'#type' => 'table',
'#header' => array($this->t('Field'), $this->t('Alias'), $this->t('Raw output')),
'#header' => [$this->t('Field'), $this->t('Alias'), $this->t('Raw output')],
'#empty' => $this->t('You have no fields. Add some to your view.'),
'#tree' => TRUE,
);
];
$options = $this->options['field_options'];
@@ -87,22 +87,22 @@ class DataFieldRow extends RowPluginBase {
if (!empty($field['exclude'])) {
continue;
}
$form['field_options'][$id]['field'] = array(
$form['field_options'][$id]['field'] = [
'#markup' => $id,
);
$form['field_options'][$id]['alias'] = array(
'#title' => $this->t('Alias for @id', array('@id' => $id)),
];
$form['field_options'][$id]['alias'] = [
'#title' => $this->t('Alias for @id', ['@id' => $id]),
'#title_display' => 'invisible',
'#type' => 'textfield',
'#default_value' => isset($options[$id]['alias']) ? $options[$id]['alias'] : '',
'#element_validate' => array(array($this, 'validateAliasName')),
);
$form['field_options'][$id]['raw_output'] = array(
'#title' => $this->t('Raw output for @id', array('@id' => $id)),
'#element_validate' => [[$this, 'validateAliasName']],
];
$form['field_options'][$id]['raw_output'] = [
'#title' => $this->t('Raw output for @id', ['@id' => $id]),
'#title_display' => 'invisible',
'#type' => 'checkbox',
'#default_value' => isset($options[$id]['raw_output']) ? $options[$id]['raw_output'] : '',
);
];
}
}
}
@@ -121,7 +121,7 @@ class DataFieldRow extends RowPluginBase {
*/
public function validateOptionsForm(&$form, FormStateInterface $form_state) {
// Collect an array of aliases to validate.
$aliases = static::extractFromOptionsArray('alias', $form_state->getValue(array('row_options', 'field_options')));
$aliases = static::extractFromOptionsArray('alias', $form_state->getValue(['row_options', 'field_options']));
// If array filter returns empty, no values have been entered. Unique keys
// should only be validated if we have some.
@@ -134,13 +134,9 @@ class DataFieldRow extends RowPluginBase {
* {@inheritdoc}
*/
public function render($row) {
$output = array();
$output = [];
foreach ($this->view->field as $id => $field) {
// Don't render anything if this field is excluded.
if (!empty($field->options['exclude'])) {
continue;
}
// If the raw output option has been set, just get the raw value.
if (!empty($this->rawOutputOptions[$id])) {
$value = $field->getValue($row);
@@ -150,7 +146,10 @@ class DataFieldRow extends RowPluginBase {
$value = $field->advancedRender($row);
}
$output[$this->getFieldKeyAlias($id)] = $value;
// Omit excluded fields from the rendered output.
if (empty($field->options['exclude'])) {
$output[$this->getFieldKeyAlias($id)] = $value;
}
}
return $output;
@@ -45,7 +45,14 @@ class Serializer extends StylePluginBase implements CacheableDependencyInterface
*
* @var array
*/
protected $formats = array();
protected $formats = [];
/**
* The serialization format providers, keyed by format.
*
* @var string[]
*/
protected $formatProviders;
/**
* {@inheritdoc}
@@ -56,19 +63,21 @@ class Serializer extends StylePluginBase implements CacheableDependencyInterface
$plugin_id,
$plugin_definition,
$container->get('serializer'),
$container->getParameter('serializer.formats')
$container->getParameter('serializer.formats'),
$container->getParameter('serializer.format_providers')
);
}
/**
* Constructs a Plugin object.
*/
public function __construct(array $configuration, $plugin_id, $plugin_definition, SerializerInterface $serializer, array $serializer_formats) {
public function __construct(array $configuration, $plugin_id, $plugin_definition, SerializerInterface $serializer, array $serializer_formats, array $serializer_format_providers) {
parent::__construct($configuration, $plugin_id, $plugin_definition);
$this->definition = $plugin_definition + $configuration;
$this->serializer = $serializer;
$this->formats = $serializer_formats;
$this->formatProviders = $serializer_format_providers;
}
/**
@@ -76,7 +85,7 @@ class Serializer extends StylePluginBase implements CacheableDependencyInterface
*/
protected function defineOptions() {
$options = parent::defineOptions();
$options['formats'] = array('default' => array());
$options['formats'] = ['default' => []];
return $options;
}
@@ -87,13 +96,13 @@ class Serializer extends StylePluginBase implements CacheableDependencyInterface
public function buildOptionsForm(&$form, FormStateInterface $form_state) {
parent::buildOptionsForm($form, $form_state);
$form['formats'] = array(
$form['formats'] = [
'#type' => 'checkboxes',
'#title' => $this->t('Accepted request formats'),
'#description' => $this->t('Request formats that will be allowed in responses. If none are selected all formats will be allowed.'),
'#options' => array_combine($this->formats, $this->formats),
'#options' => $this->getFormatOptions(),
'#default_value' => $this->options['formats'],
);
];
}
/**
@@ -102,15 +111,15 @@ class Serializer extends StylePluginBase implements CacheableDependencyInterface
public function submitOptionsForm(&$form, FormStateInterface $form_state) {
parent::submitOptionsForm($form, $form_state);
$formats = $form_state->getValue(array('style_options', 'formats'));
$form_state->setValue(array('style_options', 'formats'), array_filter($formats));
$formats = $form_state->getValue(['style_options', 'formats']);
$form_state->setValue(['style_options', 'formats'], array_filter($formats));
}
/**
* {@inheritdoc}
*/
public function render() {
$rows = array();
$rows = [];
// If the Data Entity row plugin is used, this will be an array of entities
// which will pass through Serializer to one of the registered Normalizers,
// which will transform it to arrays/scalars. If the Data field row plugin
@@ -167,4 +176,30 @@ class Serializer extends StylePluginBase implements CacheableDependencyInterface
return [];
}
/**
* {@inheritdoc}
*/
public function calculateDependencies() {
$dependencies = parent::calculateDependencies();
$formats = $this->getFormats();
$providers = array_intersect_key($this->formatProviders, array_flip($formats));
// The plugin always uses services from the serialization module.
$providers[] = 'serialization';
$dependencies += ['module' => []];
$dependencies['module'] = array_merge($dependencies['module'], $providers);
return $dependencies;
}
/**
* Returns an array of format options
*
* @return string[]
* An array of format options. Both key and value are the same.
*/
protected function getFormatOptions() {
$formats = array_keys($this->formatProviders);
return array_combine($formats, $formats);
}
}
+53 -74
View File
@@ -2,23 +2,50 @@
namespace Drupal\rest;
use Drupal\Core\Render\RenderContext;
use Drupal\Core\Cache\CacheableResponseInterface;
use Drupal\Core\DependencyInjection\ContainerInjectionInterface;
use Drupal\Core\Entity\EntityStorageInterface;
use Drupal\Core\Routing\RouteMatchInterface;
use Symfony\Component\DependencyInjection\ContainerAwareInterface;
use Symfony\Component\DependencyInjection\ContainerAwareTrait;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Exception\HttpException;
use Symfony\Component\HttpKernel\Exception\UnsupportedMediaTypeHttpException;
use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
use Symfony\Component\Serializer\Exception\UnexpectedValueException;
/**
* Acts as intermediate request forwarder for resource plugins.
*
* @see \Drupal\rest\EventSubscriber\ResourceResponseSubscriber
*/
class RequestHandler implements ContainerAwareInterface {
class RequestHandler implements ContainerAwareInterface, ContainerInjectionInterface {
use ContainerAwareTrait;
/**
* The resource configuration storage.
*
* @var \Drupal\Core\Entity\EntityStorageInterface
*/
protected $resourceStorage;
/**
* Creates a new RequestHandler instance.
*
* @param \Drupal\Core\Entity\EntityStorageInterface $entity_storage
* The resource configuration storage.
*/
public function __construct(EntityStorageInterface $entity_storage) {
$this->resourceStorage = $entity_storage;
}
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container) {
return new static($container->get('entity_type.manager')->getStorage('rest_resource_config'));
}
/**
* Handles a web API request.
*
@@ -31,8 +58,6 @@ class RequestHandler implements ContainerAwareInterface {
* The response object.
*/
public function handle(RouteMatchInterface $route_match, Request $request) {
$plugin = $route_match->getRouteObject()->getDefault('_plugin');
$method = strtolower($request->getMethod());
// Symfony is built to transparently map HEAD requests to a GET request. In
@@ -50,44 +75,39 @@ class RequestHandler implements ContainerAwareInterface {
$method = 'get';
}
$resource = $this->container
->get('plugin.manager.rest')
->getInstance(array('id' => $plugin));
$resource_config_id = $route_match->getRouteObject()->getDefault('_rest_resource_config');
/** @var \Drupal\rest\RestResourceConfigInterface $resource_config */
$resource_config = $this->resourceStorage->load($resource_config_id);
$resource = $resource_config->getResourcePlugin();
// Deserialize incoming data if available.
/** @var \Symfony\Component\Serializer\SerializerInterface $serializer */
$serializer = $this->container->get('serializer');
$received = $request->getContent();
$unserialized = NULL;
if (!empty($received)) {
$format = $request->getContentType();
// Only allow serialization formats that are explicitly configured. If no
// formats are configured allow all and hope that the serializer knows the
// format. If the serializer cannot handle it an exception will be thrown
// that bubbles up to the client.
$config = $this->container->get('config.factory')->get('rest.settings')->get('resources');
$method_settings = $config[$plugin][$request->getMethod()];
if (empty($method_settings['supported_formats']) || in_array($format, $method_settings['supported_formats'])) {
$definition = $resource->getPluginDefinition();
$class = $definition['serialization_class'];
try {
$unserialized = $serializer->deserialize($received, $class, $format, array('request_method' => $method));
$definition = $resource->getPluginDefinition();
try {
if (!empty($definition['serialization_class'])) {
$unserialized = $serializer->deserialize($received, $definition['serialization_class'], $format, ['request_method' => $method]);
}
catch (UnexpectedValueException $e) {
$error['error'] = $e->getMessage();
$content = $serializer->serialize($error, $format);
return new Response($content, 400, array('Content-Type' => $request->getMimeType($format)));
// If the plugin does not specify a serialization class just decode
// the received data.
else {
$unserialized = $serializer->decode($received, $format, ['request_method' => $method]);
}
}
else {
throw new UnsupportedMediaTypeHttpException();
catch (UnexpectedValueException $e) {
throw new BadRequestHttpException($e->getMessage());
}
}
// Determine the request parameters that should be passed to the resource
// plugin.
$route_parameters = $route_match->getParameters();
$parameters = array();
$parameters = [];
// Filter out all internal parameters starting with "_".
foreach ($route_parameters as $key => $parameter) {
if ($key{0} !== '_') {
@@ -96,55 +116,14 @@ class RequestHandler implements ContainerAwareInterface {
}
// Invoke the operation on the resource plugin.
// All REST routes are restricted to exactly one format, so instead of
// parsing it out of the Accept headers again, we can simply retrieve the
// format requirement. If there is no format associated, just pick JSON.
$format = $route_match->getRouteObject()->getRequirement('_format') ?: 'json';
try {
$response = call_user_func_array(array($resource, $method), array_merge($parameters, array($unserialized, $request)));
}
catch (HttpException $e) {
$error['error'] = $e->getMessage();
$content = $serializer->serialize($error, $format);
// Add the default content type, but only if the headers from the
// exception have not specified it already.
$headers = $e->getHeaders() + array('Content-Type' => $request->getMimeType($format));
return new Response($content, $e->getStatusCode(), $headers);
$response = call_user_func_array([$resource, $method], array_merge($parameters, [$unserialized, $request]));
if ($response instanceof CacheableResponseInterface) {
// Add rest config's cache tags.
$response->addCacheableDependency($resource_config);
}
if ($response instanceof ResourceResponse) {
$data = $response->getResponseData();
// Serialization can invoke rendering (e.g., generating URLs), but the
// serialization API does not provide a mechanism to collect the
// bubbleable metadata associated with that (e.g., language and other
// contexts), so instead, allow those to "leak" and collect them here in
// a render context.
// @todo Add test coverage for language negotiation contexts in
// https://www.drupal.org/node/2135829.
$context = new RenderContext();
$output = $this->container->get('renderer')->executeInRenderContext($context, function() use ($serializer, $data, $format) {
return $serializer->serialize($data, $format);
});
$response->setContent($output);
if (!$context->isEmpty()) {
$response->addCacheableDependency($context->pop());
}
$response->headers->set('Content-Type', $request->getMimeType($format));
// Add rest settings config's cache tags.
$response->addCacheableDependency($this->container->get('config.factory')->get('rest.settings'));
}
return $response;
}
/**
* Generates a CSRF protecting session token.
*
* @return \Symfony\Component\HttpFoundation\Response
* The response object.
*/
public function csrfToken() {
return new Response(\Drupal::csrfToken()->get('rest'), 200, array('Content-Type' => 'text/plain'));
}
}
+5 -19
View File
@@ -13,17 +13,13 @@ use Symfony\Component\HttpFoundation\Response;
* our response data. $content implies that the provided data must either be a
* string or an object with a __toString() method, which is not a requirement
* for data used here.
*
* @see \Drupal\rest\ModifiedResourceResponse
*/
class ResourceResponse extends Response implements CacheableResponseInterface {
class ResourceResponse extends Response implements CacheableResponseInterface, ResourceResponseInterface {
use CacheableResponseTrait;
/**
* Response data that should be serialized.
*
* @var mixed
*/
protected $responseData;
use ResourceResponseTrait;
/**
* Constructor for ResourceResponse objects.
@@ -35,19 +31,9 @@ class ResourceResponse extends Response implements CacheableResponseInterface {
* @param array $headers
* An array of response headers.
*/
public function __construct($data = NULL, $status = 200, $headers = array()) {
public function __construct($data = NULL, $status = 200, $headers = []) {
$this->responseData = $data;
parent::__construct('', $status, $headers);
}
/**
* Returns response data that should be serialized.
*
* @return mixed
* Response data that should be serialized.
*/
public function getResponseData() {
return $this->responseData;
}
}
@@ -0,0 +1,18 @@
<?php
namespace Drupal\rest;
/**
* Defines a common interface for resource responses.
*/
interface ResourceResponseInterface {
/**
* Returns response data that should be serialized.
*
* @return mixed
* Response data that should be serialized.
*/
public function getResponseData();
}
@@ -0,0 +1,25 @@
<?php
namespace Drupal\rest;
trait ResourceResponseTrait {
/**
* Response data that should be serialized.
*
* @var mixed
*/
protected $responseData;
/**
* Returns response data that should be serialized.
*
* @return mixed
* Response data that should be serialized.
*/
public function getResponseData() {
return $this->responseData;
}
}
+14 -15
View File
@@ -2,8 +2,8 @@
namespace Drupal\rest;
use Drupal\Core\Config\ConfigFactoryInterface;
use Drupal\Core\DependencyInjection\ContainerInjectionInterface;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\rest\Plugin\Type\ResourcePluginManager;
use Symfony\Component\DependencyInjection\ContainerInterface;
@@ -20,30 +20,30 @@ class RestPermissions implements ContainerInjectionInterface {
protected $restPluginManager;
/**
* The config factory.
* The REST resource config storage.
*
* @var \Drupal\Core\Config\ConfigFactoryInterface
* @var \Drupal\Core\Entity\EntityManagerInterface
*/
protected $configFactory;
protected $resourceConfigStorage;
/**
* Constructs a new RestPermissions instance.
*
* @param \Drupal\rest\Plugin\Type\ResourcePluginManager $rest_plugin_manager
* The rest resource plugin manager.
* @param \Drupal\Core\Config\ConfigFactoryInterface $config_factory
* The config factory.
* @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
* The entity type manager.
*/
public function __construct(ResourcePluginManager $rest_plugin_manager, ConfigFactoryInterface $config_factory) {
public function __construct(ResourcePluginManager $rest_plugin_manager, EntityTypeManagerInterface $entity_type_manager) {
$this->restPluginManager = $rest_plugin_manager;
$this->configFactory = $config_factory;
$this->resourceConfigStorage = $entity_type_manager->getStorage('rest_resource_config');
}
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container) {
return new static($container->get('plugin.manager.rest'), $container->get('config.factory'));
return new static($container->get('plugin.manager.rest'), $container->get('entity_type.manager'));
}
/**
@@ -53,12 +53,11 @@ class RestPermissions implements ContainerInjectionInterface {
*/
public function permissions() {
$permissions = [];
$resources = $this->configFactory->get('rest.settings')->get('resources');
if ($resources && $enabled = array_intersect_key($this->restPluginManager->getDefinitions(), $resources)) {
foreach ($enabled as $key => $resource) {
$plugin = $this->restPluginManager->getInstance(['id' => $key]);
$permissions = array_merge($permissions, $plugin->permissions());
}
/** @var \Drupal\rest\RestResourceConfigInterface[] $resource_configs */
$resource_configs = $this->resourceConfigStorage->loadMultiple();
foreach ($resource_configs as $resource_config) {
$plugin = $resource_config->getResourcePlugin();
$permissions = array_merge($permissions, $plugin->permissions());
}
return $permissions;
}
@@ -0,0 +1,61 @@
<?php
namespace Drupal\rest;
use Drupal\Core\Config\Entity\ConfigEntityInterface;
use Drupal\Core\Entity\EntityWithPluginCollectionInterface;
/**
* Defines a configuration entity to store enabled REST resources.
*/
interface RestResourceConfigInterface extends ConfigEntityInterface, EntityWithPluginCollectionInterface {
/**
* Granularity value for per-method configuration.
*/
const METHOD_GRANULARITY = 'method';
/**
* Granularity value for per-resource configuration.
*/
const RESOURCE_GRANULARITY = 'resource';
/**
* Retrieves the REST resource plugin.
*
* @return \Drupal\rest\Plugin\ResourceInterface
* The resource plugin
*/
public function getResourcePlugin();
/**
* Retrieves a list of supported HTTP methods.
*
* @return string[]
* A list of supported HTTP methods.
*/
public function getMethods();
/**
* Retrieves a list of supported authentication providers.
*
* @param string $method
* The request method e.g GET or POST.
*
* @return string[]
* A list of supported authentication provider IDs.
*/
public function getAuthenticationProviders($method);
/**
* Retrieves a list of supported response formats.
*
* @param string $method
* The request method e.g GET or POST.
*
* @return string[]
* A list of supported format IDs.
*/
public function getFormats($method);
}
@@ -0,0 +1,51 @@
<?php
namespace Drupal\rest;
use Drupal\Core\DependencyInjection\ContainerBuilder;
use Drupal\Core\DependencyInjection\ServiceProviderInterface;
use Drupal\rest\LinkManager\LinkManager;
use Drupal\rest\LinkManager\RelationLinkManager;
use Drupal\rest\LinkManager\TypeLinkManager;
use Symfony\Component\DependencyInjection\DefinitionDecorator;
use Symfony\Component\DependencyInjection\Reference;
/**
* Provides BC services.
*
* These services are not added via rest.services.yml because the service
* classes extend classes from the HAL module. They also have no use without
* that module.
*/
class RestServiceProvider implements ServiceProviderInterface {
/**
* {@inheritdoc}
*/
public function register(ContainerBuilder $container) {
$modules = $container->getParameter(('container.modules'));
if (isset($modules['hal'])) {
// @deprecated in Drupal 8.3.x and will be removed before Drupal 9.0.0.
// Use hal.link_manager instead.
// @see https://www.drupal.org/node/2830467
$service_definition = new DefinitionDecorator(new Reference('hal.link_manager'));
$service_definition->setClass(LinkManager::class);
$container->setDefinition('rest.link_manager', $service_definition);
// @deprecated in Drupal 8.3.x and will be removed before Drupal 9.0.0.
// Use hal.link_manager.type instead.
// @see https://www.drupal.org/node/2830467
$service_definition = new DefinitionDecorator(new Reference('hal.link_manager.type'));
$service_definition->setClass(TypeLinkManager::class);
$container->setDefinition('rest.link_manager.type', $service_definition);
// @deprecated in Drupal 8.3.x and will be removed before Drupal 9.0.0.
// Use hal.link_manager.relation instead.
// @see https://www.drupal.org/node/2830467
$service_definition = new DefinitionDecorator(new Reference('hal.link_manager.relation'));
$service_definition->setClass(RelationLinkManager::class);
$container->setDefinition('rest.link_manager.relation', $service_definition);
}
}
}
@@ -2,9 +2,10 @@
namespace Drupal\rest\Routing;
use Drupal\Core\Config\ConfigFactoryInterface;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Routing\RouteSubscriberBase;
use Drupal\rest\Plugin\Type\ResourcePluginManager;
use Drupal\rest\RestResourceConfigInterface;
use Psr\Log\LoggerInterface;
use Symfony\Component\Routing\RouteCollection;
@@ -21,11 +22,11 @@ class ResourceRoutes extends RouteSubscriberBase {
protected $manager;
/**
* The Drupal configuration factory.
* The REST resource config storage.
*
* @var \Drupal\Core\Config\ConfigFactoryInterface
* @var \Drupal\Core\Entity\EntityManagerInterface
*/
protected $config;
protected $resourceConfigStorage;
/**
* A logger instance.
@@ -39,14 +40,14 @@ class ResourceRoutes extends RouteSubscriberBase {
*
* @param \Drupal\rest\Plugin\Type\ResourcePluginManager $manager
* The resource plugin manager.
* @param \Drupal\Core\Config\ConfigFactoryInterface $config
* The configuration factory holding resource settings.
* @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
* The entity type manager
* @param \Psr\Log\LoggerInterface $logger
* A logger instance.
*/
public function __construct(ResourcePluginManager $manager, ConfigFactoryInterface $config, LoggerInterface $logger) {
public function __construct(ResourcePluginManager $manager, EntityTypeManagerInterface $entity_type_manager, LoggerInterface $logger) {
$this->manager = $manager;
$this->config = $config;
$this->resourceConfigStorage = $entity_type_manager->getStorage('rest_resource_config');
$this->logger = $logger;
}
@@ -58,57 +59,76 @@ class ResourceRoutes extends RouteSubscriberBase {
* @return array
*/
protected function alterRoutes(RouteCollection $collection) {
$routes = array();
// Silently ignore resources that are in the settings but are not defined on
// the plugin manager currently. That avoids exceptions when REST module is
// enabled before another module that provides the resource plugin specified
// in the settings.
// @todo Remove in https://www.drupal.org/node/2308745
$resources = $this->config->get('rest.settings')->get('resources') ?: array();
$enabled_resources = array_intersect_key($resources, $this->manager->getDefinitions());
if (count($resources) != count($enabled_resources)) {
trigger_error('rest.settings lists resources relying on the following missing plugins: ' . implode(', ', array_keys(array_diff_key($resources, $enabled_resources))));
}
// Iterate over all enabled resource plugins.
foreach ($enabled_resources as $id => $enabled_methods) {
$plugin = $this->manager->getInstance(array('id' => $id));
foreach ($plugin->routes() as $name => $route) {
// @todo: Are multiple methods possible here?
$methods = $route->getMethods();
// Only expose routes where the method is enabled in the configuration.
if ($methods && ($method = $methods[0]) && $method && isset($enabled_methods[$method])) {
$route->setRequirement('_access_rest_csrf', 'TRUE');
// Check that authentication providers are defined.
if (empty($enabled_methods[$method]['supported_auth']) || !is_array($enabled_methods[$method]['supported_auth'])) {
$this->logger->error('At least one authentication provider must be defined for resource @id', array(':id' => $id));
continue;
}
// Check that formats are defined.
if (empty($enabled_methods[$method]['supported_formats']) || !is_array($enabled_methods[$method]['supported_formats'])) {
$this->logger->error('At least one format must be defined for resource @id', array(':id' => $id));
continue;
}
// If the route has a format requirement, then verify that the
// resource has it.
$format_requirement = $route->getRequirement('_format');
if ($format_requirement && !in_array($format_requirement, $enabled_methods[$method]['supported_formats'])) {
continue;
}
// The configuration seems legit at this point, so we set the
// authentication provider and add the route.
$route->setOption('_auth', $enabled_methods[$method]['supported_auth']);
$routes["rest.$name"] = $route;
$collection->add("rest.$name", $route);
}
// Iterate over all enabled REST resource config entities.
/** @var \Drupal\rest\RestResourceConfigInterface[] $resource_configs */
$resource_configs = $this->resourceConfigStorage->loadMultiple();
foreach ($resource_configs as $resource_config) {
if ($resource_config->status()) {
$resource_routes = $this->getRoutesForResourceConfig($resource_config);
$collection->addCollection($resource_routes);
}
}
}
/**
* Provides all routes for a given REST resource config.
*
* This method determines where a resource is reachable, what path
* replacements are used, the required HTTP method for the operation etc.
*
* @param \Drupal\rest\RestResourceConfigInterface $rest_resource_config
* The rest resource config.
*
* @return \Symfony\Component\Routing\RouteCollection
* The route collection.
*/
protected function getRoutesForResourceConfig(RestResourceConfigInterface $rest_resource_config) {
$plugin = $rest_resource_config->getResourcePlugin();
$collection = new RouteCollection();
foreach ($plugin->routes() as $name => $route) {
/** @var \Symfony\Component\Routing\Route $route */
// @todo: Are multiple methods possible here?
$methods = $route->getMethods();
// Only expose routes where the method is enabled in the configuration.
if ($methods && ($method = $methods[0]) && $supported_formats = $rest_resource_config->getFormats($method)) {
$route->setRequirement('_csrf_request_header_token', 'TRUE');
// Check that authentication providers are defined.
if (empty($rest_resource_config->getAuthenticationProviders($method))) {
$this->logger->error('At least one authentication provider must be defined for resource @id', [':id' => $rest_resource_config->id()]);
continue;
}
// Check that formats are defined.
if (empty($rest_resource_config->getFormats($method))) {
$this->logger->error('At least one format must be defined for resource @id', [':id' => $rest_resource_config->id()]);
continue;
}
// If the route has a format requirement, then verify that the
// resource has it.
$format_requirement = $route->getRequirement('_format');
if ($format_requirement && !in_array($format_requirement, $rest_resource_config->getFormats($method))) {
continue;
}
// The configuration has been validated, so we update the route to:
// - set the allowed request body content types/formats for methods that
// allow request bodies to be sent
// - set the allowed authentication providers
if (in_array($method, ['POST', 'PATCH', 'PUT'], TRUE)) {
// Restrict the incoming HTTP Content-type header to the allowed
// formats.
$route->addRequirements(['_content_type_format' => implode('|', $rest_resource_config->getFormats($method))]);
}
$route->setOption('_auth', $rest_resource_config->getAuthenticationProviders($method));
$route->setDefault('_rest_resource_config', $rest_resource_config->id());
$collection->add("rest.$name", $route);
}
}
return $collection;
}
}
+299 -109
View File
@@ -2,14 +2,28 @@
namespace Drupal\rest\Tests;
use Drupal\Component\Utility\NestedArray;
use Drupal\Core\Config\Entity\ConfigEntityType;
use Drupal\node\NodeInterface;
use Drupal\rest\RestResourceConfigInterface;
use Drupal\simpletest\WebTestBase;
use GuzzleHttp\Cookie\FileCookieJar;
use GuzzleHttp\Cookie\SetCookie;
/**
* Test helper class that provides a REST client method to send HTTP requests.
*
* @deprecated in Drupal 8.3.x-dev and will be removed before Drupal 9.0.0. Use \Drupal\Tests\rest\Functional\ResourceTestBase and \Drupal\Tests\rest\Functional\EntityResource\EntityResourceTestBase instead. Only retained for contributed module tests that may be using this base class.
*/
abstract class RESTTestBase extends WebTestBase {
/**
* The REST resource config storage.
*
* @var \Drupal\Core\Entity\EntityStorageInterface
*/
protected $resourceConfigStorage;
/**
* The default serialization format to use for testing REST operations.
*
@@ -51,15 +65,57 @@ abstract class RESTTestBase extends WebTestBase {
*
* @var array
*/
public static $modules = array('rest', 'entity_test', 'node');
public static $modules = ['rest', 'entity_test'];
/**
* The last response.
*
* @var \Psr\Http\Message\ResponseInterface
*/
protected $response;
protected function setUp() {
parent::setUp();
$this->defaultFormat = 'hal_json';
$this->defaultMimeType = 'application/hal+json';
$this->defaultAuth = array('cookie');
$this->defaultAuth = ['cookie'];
$this->resourceConfigStorage = $this->container->get('entity_type.manager')->getStorage('rest_resource_config');
// Create a test content type for node testing.
$this->drupalCreateContentType(array('name' => 'resttest', 'type' => 'resttest'));
if (in_array('node', static::$modules)) {
$this->drupalCreateContentType(['name' => 'resttest', 'type' => 'resttest']);
}
$this->cookieFile = $this->publicFilesDirectory . '/cookie.jar';
}
/**
* Calculates cookies used by guzzle later.
*
* @return \GuzzleHttp\Cookie\CookieJarInterface
* The used CURL options in guzzle.
*/
protected function cookies() {
$cookies = [];
foreach ($this->cookies as $key => $cookie) {
$cookies[$key][] = $cookie['value'];
}
$request = \Drupal::request();
$cookies = NestedArray::mergeDeep($cookies, $this->extractCookiesFromRequest($request));
$cookie_jar = new FileCookieJar($this->cookieFile);
foreach ($cookies as $key => $cookie_values) {
foreach ($cookie_values as $cookie_value) {
// setcookie() sets the value of a cookie to be deleted, when its gonna
// be removed.
if ($cookie_value !== 'deleted') {
$cookie_jar->setCookie(new SetCookie(['Name' => $key, 'Value' => $cookie_value, 'Domain' => $request->getHost()]));
}
}
}
return $cookie_jar;
}
/**
@@ -73,112 +129,150 @@ abstract class RESTTestBase extends WebTestBase {
* The body for POST and PUT.
* @param string $mime_type
* The MIME type of the transmitted content.
* @param bool $csrf_token
* If NULL, a CSRF token will be retrieved and used. If FALSE, omit the
* X-CSRF-Token request header (to simulate developer error). Otherwise, the
* passed in value will be used as the value for the X-CSRF-Token request
* header (to simulate developer error, by sending an invalid CSRF token).
*
* @return string
* The content returned from the request.
*/
protected function httpRequest($url, $method, $body = NULL, $mime_type = NULL) {
protected function httpRequest($url, $method, $body = NULL, $mime_type = NULL, $csrf_token = NULL) {
if (!isset($mime_type)) {
$mime_type = $this->defaultMimeType;
}
if (!in_array($method, array('GET', 'HEAD', 'OPTIONS', 'TRACE'))) {
if (!in_array($method, ['GET', 'HEAD', 'OPTIONS', 'TRACE'])) {
// GET the CSRF token first for writing requests.
$token = $this->drupalGet('rest/session/token');
$requested_token = $this->drupalGet('session/token');
}
$client = \Drupal::httpClient();
$url = $this->buildUrl($url);
$curl_options = array();
$options = [
'http_errors' => FALSE,
'cookies' => $this->cookies(),
'curl' => [
CURLOPT_HEADERFUNCTION => [&$this, 'curlHeaderCallback'],
],
];
switch ($method) {
case 'GET':
// Set query if there are additional GET parameters.
$curl_options = array(
CURLOPT_HTTPGET => TRUE,
CURLOPT_CUSTOMREQUEST => 'GET',
CURLOPT_URL => $url,
CURLOPT_NOBODY => FALSE,
CURLOPT_HTTPHEADER => array('Accept: ' . $mime_type),
);
$options += [
'headers' => [
'Accept' => $mime_type,
],
];
$response = $client->get($url, $options);
break;
case 'HEAD':
$curl_options = array(
CURLOPT_HTTPGET => FALSE,
CURLOPT_CUSTOMREQUEST => 'HEAD',
CURLOPT_URL => $url,
CURLOPT_NOBODY => TRUE,
CURLOPT_HTTPHEADER => array('Accept: ' . $mime_type),
);
break;
case 'HEAD':
$response = $client->head($url, $options);
break;
case 'POST':
$curl_options = array(
CURLOPT_HTTPGET => FALSE,
CURLOPT_POST => TRUE,
CURLOPT_POSTFIELDS => $body,
CURLOPT_URL => $url,
CURLOPT_NOBODY => FALSE,
CURLOPT_HTTPHEADER => array(
'Content-Type: ' . $mime_type,
'X-CSRF-Token: ' . $token,
),
);
$options += [
'headers' => $csrf_token !== FALSE ? [
'Content-Type' => $mime_type,
'X-CSRF-Token' => ($csrf_token === NULL ? $requested_token : $csrf_token),
] : [
'Content-Type' => $mime_type,
],
'body' => $body,
];
$response = $client->post($url, $options);
break;
case 'PUT':
$curl_options = array(
CURLOPT_HTTPGET => FALSE,
CURLOPT_CUSTOMREQUEST => 'PUT',
CURLOPT_POSTFIELDS => $body,
CURLOPT_URL => $url,
CURLOPT_NOBODY => FALSE,
CURLOPT_HTTPHEADER => array(
'Content-Type: ' . $mime_type,
'X-CSRF-Token: ' . $token,
),
);
$options += [
'headers' => $csrf_token !== FALSE ? [
'Content-Type' => $mime_type,
'X-CSRF-Token' => ($csrf_token === NULL ? $requested_token : $csrf_token),
] : [
'Content-Type' => $mime_type,
],
'body' => $body,
];
$response = $client->put($url, $options);
break;
case 'PATCH':
$curl_options = array(
CURLOPT_HTTPGET => FALSE,
CURLOPT_CUSTOMREQUEST => 'PATCH',
CURLOPT_POSTFIELDS => $body,
CURLOPT_URL => $url,
CURLOPT_NOBODY => FALSE,
CURLOPT_HTTPHEADER => array(
'Content-Type: ' . $mime_type,
'X-CSRF-Token: ' . $token,
),
);
$options += [
'headers' => $csrf_token !== FALSE ? [
'Content-Type' => $mime_type,
'X-CSRF-Token' => ($csrf_token === NULL ? $requested_token : $csrf_token),
] : [
'Content-Type' => $mime_type,
],
'body' => $body,
];
$response = $client->patch($url, $options);
break;
case 'DELETE':
$curl_options = array(
CURLOPT_HTTPGET => FALSE,
CURLOPT_CUSTOMREQUEST => 'DELETE',
CURLOPT_URL => $url,
CURLOPT_NOBODY => FALSE,
CURLOPT_HTTPHEADER => array('X-CSRF-Token: ' . $token),
);
$options += [
'headers' => $csrf_token !== FALSE ? [
'Content-Type' => $mime_type,
'X-CSRF-Token' => ($csrf_token === NULL ? $requested_token : $csrf_token),
] : [],
];
$response = $client->delete($url, $options);
break;
}
$this->responseBody = $this->curlExec($curl_options);
$this->response = $response;
$this->responseBody = (string) $response->getBody();
$this->setRawContent($this->responseBody);
// Ensure that any changes to variables in the other thread are picked up.
$this->refreshVariables();
$headers = $this->drupalGetHeaders();
$this->verbose($method . ' request to: ' . $url .
'<hr />Code: ' . curl_getinfo($this->curlHandle, CURLINFO_HTTP_CODE) .
'<hr />Response headers: ' . nl2br(print_r($headers, TRUE)) .
'<hr />Code: ' . $this->response->getStatusCode() .
(isset($options['headers']) ? '<hr />Request headers: ' . nl2br(print_r($options['headers'], TRUE)) : '') .
(isset($options['body']) ? '<hr />Request body: ' . nl2br(print_r($options['body'], TRUE)) : '') .
'<hr />Response headers: ' . nl2br(print_r($response->getHeaders(), TRUE)) .
'<hr />Response body: ' . $this->responseBody);
return $this->responseBody;
}
/**
* {@inheritdoc}
*/
protected function assertResponse($code, $message = '', $group = 'Browser') {
if (!isset($this->response)) {
return parent::assertResponse($code, $message, $group);
}
return $this->assertEqual($code, $this->response->getStatusCode(), $message ? $message : "HTTP response expected $code, actual {$this->response->getStatusCode()}", $group);
}
/**
* {@inheritdoc}
*/
protected function drupalGetHeaders($all_requests = FALSE) {
if (!isset($this->response)) {
return parent::drupalGetHeaders($all_requests);
}
$lowercased_keys = array_map('strtolower', array_keys($this->response->getHeaders()));
return array_map(function (array $header) {
return implode(', ', $header);
}, array_combine($lowercased_keys, array_values($this->response->getHeaders())));
}
/**
* {@inheritdoc}
*/
protected function drupalGetHeader($name, $all_requests = FALSE) {
if (!isset($this->response)) {
return parent::drupalGetHeader($name, $all_requests);
}
if ($header = $this->response->getHeader($name)) {
return implode(', ', $header);
}
}
/**
* Creates entity objects based on their types.
*
@@ -200,32 +294,37 @@ abstract class RESTTestBase extends WebTestBase {
* Required properties differ from entity type to entity type, so we keep a
* minimum mapping here.
*
* @param string $entity_type
* The type of the entity that should be created.
* @param string $entity_type_id
* The ID of the type of entity that should be created.
*
* @return array
* An array of values keyed by property name.
*/
protected function entityValues($entity_type) {
switch ($entity_type) {
protected function entityValues($entity_type_id) {
switch ($entity_type_id) {
case 'entity_test':
return array(
return [
'name' => $this->randomMachineName(),
'user_id' => 1,
'field_test_text' => array(0 => array(
'field_test_text' => [0 => [
'value' => $this->randomString(),
'format' => 'plain_text',
)),
);
]],
];
case 'config_test':
return [
'id' => $this->randomMachineName(),
'label' => 'Test label',
];
case 'node':
return array('title' => $this->randomString(), 'type' => 'resttest');
return ['title' => $this->randomString(), 'type' => 'resttest'];
case 'node_type':
return array(
return [
'type' => 'article',
'name' => $this->randomMachineName(),
);
];
case 'user':
return array('name' => $this->randomMachineName());
return ['name' => $this->randomMachineName()];
case 'comment':
return [
@@ -236,16 +335,32 @@ abstract class RESTTestBase extends WebTestBase {
'entity_id' => 'invalid',
'field_name' => 'comment',
];
case 'taxonomy_vocabulary':
return [
'vid' => 'tags',
'name' => $this->randomMachineName(),
];
case 'block':
// Block placements depend on themes, ensure Bartik is installed.
$this->container->get('theme_installer')->install(['bartik']);
return [
'id' => strtolower($this->randomMachineName(8)),
'plugin' => 'system_powered_by_block',
'theme' => 'bartik',
'region' => 'header',
];
default:
return array();
if ($this->isConfigEntity($entity_type_id)) {
return $this->configEntityValues($entity_type_id);
}
return [];
}
}
/**
* Enables the REST service interface for a specific entity type.
*
* @param string|FALSE $resource_type
* @param string|false $resource_type
* The resource type that should get REST API enabled or FALSE to disable all
* resource types.
* @param string $method
@@ -255,29 +370,49 @@ abstract class RESTTestBase extends WebTestBase {
* @param array $auth
* (Optional) The list of valid authentication methods.
*/
protected function enableService($resource_type, $method = 'GET', $format = NULL, $auth = NULL) {
// Enable REST API for this entity type.
$config = $this->config('rest.settings');
$settings = array();
protected function enableService($resource_type, $method = 'GET', $format = NULL, array $auth = []) {
if ($resource_type) {
// Enable REST API for this entity type.
$resource_config_id = str_replace(':', '.', $resource_type);
// get entity by id
/** @var \Drupal\rest\RestResourceConfigInterface $resource_config */
$resource_config = $this->resourceConfigStorage->load($resource_config_id);
if (!$resource_config) {
$resource_config = $this->resourceConfigStorage->create([
'id' => $resource_config_id,
'granularity' => RestResourceConfigInterface::METHOD_GRANULARITY,
'configuration' => []
]);
}
$configuration = $resource_config->get('configuration');
if (is_array($format)) {
$settings[$resource_type][$method]['supported_formats'] = $format;
for ($i = 0; $i < count($format); $i++) {
$configuration[$method]['supported_formats'][] = $format[$i];
}
}
else {
if ($format == NULL) {
$format = $this->defaultFormat;
}
$settings[$resource_type][$method]['supported_formats'][] = $format;
$configuration[$method]['supported_formats'][] = $format;
}
if ($auth == NULL) {
if (!is_array($auth) || empty($auth)) {
$auth = $this->defaultAuth;
}
$settings[$resource_type][$method]['supported_auth'] = $auth;
foreach ($auth as $auth_provider) {
$configuration[$method]['supported_auth'][] = $auth_provider;
}
$resource_config->set('configuration', $configuration);
$resource_config->save();
}
else {
foreach ($this->resourceConfigStorage->loadMultiple() as $resource_config) {
$resource_config->delete();
}
}
$config->set('resources', $settings);
$config->save();
$this->rebuildCache();
}
@@ -285,8 +420,7 @@ abstract class RESTTestBase extends WebTestBase {
* Rebuilds routing caches.
*/
protected function rebuildCache() {
// Rebuild routing cache, so that the REST API paths are available.
$this->container->get('router.builder')->rebuild();
$this->container->get('router.builder')->rebuildIfNeeded();
}
/**
@@ -297,6 +431,8 @@ abstract class RESTTestBase extends WebTestBase {
* override it every time it is omitted.
*/
protected function curlExec($curl_options, $redirect = FALSE) {
unset($this->response);
if (!isset($curl_options[CURLOPT_CUSTOMREQUEST])) {
if (!empty($curl_options[CURLOPT_HTTPGET])) {
$curl_options[CURLOPT_CUSTOMREQUEST] = 'GET';
@@ -311,7 +447,7 @@ abstract class RESTTestBase extends WebTestBase {
/**
* Provides the necessary user permissions for entity operations.
*
* @param string $entity_type
* @param string $entity_type_id
* The entity type.
* @param string $operation
* The operation, one of 'view', 'create', 'update' or 'delete'.
@@ -319,27 +455,27 @@ abstract class RESTTestBase extends WebTestBase {
* @return array
* The set of user permission strings.
*/
protected function entityPermissions($entity_type, $operation) {
switch ($entity_type) {
protected function entityPermissions($entity_type_id, $operation) {
switch ($entity_type_id) {
case 'entity_test':
switch ($operation) {
case 'view':
return array('view test entity');
return ['view test entity'];
case 'create':
case 'update':
case 'delete':
return array('administer entity_test content');
return ['administer entity_test content'];
}
case 'node':
switch ($operation) {
case 'view':
return array('access content');
return ['access content'];
case 'create':
return array('create resttest content');
return ['create resttest content'];
case 'update':
return array('edit any resttest content');
return ['edit any resttest content'];
case 'delete':
return array('delete any resttest content');
return ['delete any resttest content'];
}
case 'comment':
@@ -365,9 +501,17 @@ abstract class RESTTestBase extends WebTestBase {
default:
return ['administer users'];
}
default:
if ($this->isConfigEntity($entity_type_id)) {
$entity_type = \Drupal::entityTypeManager()->getDefinition($entity_type_id);
if ($admin_permission = $entity_type->getAdminPermission()) {
return [$admin_permission];
}
}
}
return [];
}
/**
@@ -376,13 +520,14 @@ abstract class RESTTestBase extends WebTestBase {
* @param string $location_url
* The URL returned in the Location header.
*
* @return \Drupal\Core\Entity\Entity|FALSE.
* @return \Drupal\Core\Entity\Entity|false
* The entity or FALSE if there is no matching entity.
*/
protected function loadEntityFromLocationHeader($location_url) {
$url_parts = explode('/', $location_url);
$id = end($url_parts);
return entity_load($this->testEntityType, $id);
return $this->container->get('entity_type.manager')
->getStorage($this->testEntityType)->load($id);
}
/**
@@ -428,7 +573,52 @@ abstract class RESTTestBase extends WebTestBase {
* TRUE if the assertion succeeded, FALSE otherwise.
*/
protected function assertResponseBody($expected, $message = '', $group = 'REST Response') {
return $this->assertIdentical($expected, $this->responseBody, $message ? $message : strtr('Response body @expected (expected) is equal to @response (actual).', array('@expected' => var_export($expected, TRUE), '@response' => var_export($this->responseBody, TRUE))), $group);
return $this->assertIdentical($expected, $this->responseBody, $message ? $message : strtr('Response body @expected (expected) is equal to @response (actual).', ['@expected' => var_export($expected, TRUE), '@response' => var_export($this->responseBody, TRUE)]), $group);
}
/**
* Checks if an entity type id is for a Config Entity.
*
* @param string $entity_type_id
* The entity type ID to check.
*
* @return bool
* TRUE if the entity is a Config Entity, FALSE otherwise.
*/
protected function isConfigEntity($entity_type_id) {
return \Drupal::entityTypeManager()->getDefinition($entity_type_id) instanceof ConfigEntityType;
}
/**
* Provides an array of suitable property values for a config entity type.
*
* Config entities have some common keys that need to be created. Required
* properties differ among config entity types, so we keep a minimum mapping
* here.
*
* @param string $entity_type_id
* The ID of the type of entity that should be created.
*
* @return array
* An array of values keyed by property name.
*/
protected function configEntityValues($entity_type_id) {
$entity_type = \Drupal::entityTypeManager()->getDefinition($entity_type_id);
$keys = $entity_type->getKeys();
$values = [];
// Fill out known key values that are shared across entity types.
foreach ($keys as $key) {
if ($key === 'id' || $key === 'label') {
$values[$key] = $this->randomMachineName();
}
}
// Add extra values for particular entity types.
switch ($entity_type_id) {
case 'block':
$values['plugin'] = 'system_powered_by_block';
break;
}
return $values;
}
}
+40 -57
View File
@@ -2,9 +2,10 @@
namespace Drupal\rest\Tests;
use Drupal\Component\Plugin\Exception\PluginNotFoundException;
use Drupal\Core\Session\AccountInterface;
use Drupal\rest\RestResourceConfigInterface;
use Drupal\user\Entity\Role;
use Drupal\user\RoleInterface;
/**
* Tests the structure of a REST resource.
@@ -18,7 +19,7 @@ class ResourceTest extends RESTTestBase {
*
* @var array
*/
public static $modules = array('hal', 'rest', 'entity_test');
public static $modules = ['hal', 'rest', 'entity_test', 'rest_test'];
/**
* The entity.
@@ -32,9 +33,7 @@ class ResourceTest extends RESTTestBase {
*/
protected function setUp() {
parent::setUp();
$this->config = $this->config('rest.settings');
// Create an entity programmatically.
// Create an entity programmatic.
$this->entity = $this->entityCreate('entity_test');
$this->entity->save();
@@ -47,20 +46,17 @@ class ResourceTest extends RESTTestBase {
* Tests that a resource without formats cannot be enabled.
*/
public function testFormats() {
$settings = array(
'entity:entity_test' => array(
'GET' => array(
'supported_auth' => array(
$this->resourceConfigStorage->create([
'id' => 'entity.entity_test',
'granularity' => RestResourceConfigInterface::METHOD_GRANULARITY,
'configuration' => [
'GET' => [
'supported_auth' => [
'basic_auth',
),
),
),
);
// Attempt to enable the resource.
$this->config->set('resources', $settings);
$this->config->save();
$this->rebuildCache();
],
],
],
])->save();
// Verify that accessing the resource returns 406.
$response = $this->httpRequest($this->entity->urlInfo()->setRouteParameter('_format', $this->defaultFormat), 'GET');
@@ -77,20 +73,17 @@ class ResourceTest extends RESTTestBase {
* Tests that a resource without authentication cannot be enabled.
*/
public function testAuthentication() {
$settings = array(
'entity:entity_test' => array(
'GET' => array(
'supported_formats' => array(
$this->resourceConfigStorage->create([
'id' => 'entity.entity_test',
'granularity' => RestResourceConfigInterface::METHOD_GRANULARITY,
'configuration' => [
'GET' => [
'supported_formats' => [
'hal_json',
),
),
),
);
// Attempt to enable the resource.
$this->config->set('resources', $settings);
$this->config->save();
$this->rebuildCache();
],
],
],
])->save();
// Verify that accessing the resource returns 401.
$response = $this->httpRequest($this->entity->urlInfo()->setRouteParameter('_format', $this->defaultFormat), 'GET');
@@ -103,6 +96,22 @@ class ResourceTest extends RESTTestBase {
$this->curlClose();
}
/**
* Tests that serialization_class is optional.
*/
public function testSerializationClassIsOptional() {
$this->enableService('serialization_test', 'POST', 'json');
Role::load(RoleInterface::ANONYMOUS_ID)
->grantPermission('restful post serialization_test')
->save();
$serialized = $this->container->get('serializer')->serialize(['foo', 'bar'], 'json');
$this->httpRequest('serialization_test', 'POST', $serialized, 'application/json');
$this->assertResponse(200);
$this->assertResponseBody('["foo","bar"]');
}
/**
* Tests that resource URI paths are formatted properly.
*/
@@ -118,30 +127,4 @@ class ResourceTest extends RESTTestBase {
}
}
/**
* Tests that a resource with a missing plugin does not cause an exception.
*/
public function testMissingPlugin() {
$settings = array(
'entity:nonexisting' => array(
'GET' => array(
'supported_formats' => array(
'hal_json',
),
),
),
);
try {
// Attempt to enable the resource.
$this->config->set('resources', $settings);
$this->config->save();
$this->rebuildCache();
$this->pass('rest.settings referencing a missing REST resource plugin does not cause an exception.');
}
catch (PluginNotFoundException $e) {
$this->fail('rest.settings referencing a missing REST resource plugin caused an exception.');
}
}
}
@@ -0,0 +1,56 @@
<?php
namespace Drupal\rest\Tests\Update;
use Drupal\system\Tests\Update\UpdatePathTestBase;
/**
* Tests that existing sites continue to use permissions for EntityResource.
*
* @see https://www.drupal.org/node/2664780
*
* @group rest
*/
class EntityResourcePermissionsUpdateTest extends UpdatePathTestBase {
/**
* {@inheritdoc}
*/
protected static $modules = ['rest', 'serialization'];
/**
* {@inheritdoc}
*/
public function setDatabaseDumpFiles() {
$this->databaseDumpFiles = [
__DIR__ . '/../../../../system/tests/fixtures/update/drupal-8.bare.standard.php.gz',
__DIR__ . '/../../../../rest/tests/fixtures/update/drupal-8.rest-rest_update_8203.php',
];
}
/**
* Tests rest_update_8203().
*/
public function testBcEntityResourcePermissionSettingAdded() {
$permission_handler = $this->container->get('user.permissions');
$is_rest_resource_permission = function ($permission) {
return $permission['provider'] === 'rest' && (string) $permission['title'] !== 'Administer REST resource configuration';
};
// Make sure we have the expected values before the update.
$rest_settings = $this->config('rest.settings');
$this->assertFalse(array_key_exists('bc_entity_resource_permissions', $rest_settings->getRawData()));
$this->assertEqual([], array_filter($permission_handler->getPermissions(), $is_rest_resource_permission));
$this->runUpdates();
// Make sure we have the expected values after the update.
$rest_settings = $this->config('rest.settings');
$this->assertTrue(array_key_exists('bc_entity_resource_permissions', $rest_settings->getRawData()));
$this->assertTrue($rest_settings->get('bc_entity_resource_permissions'));
$rest_permissions = array_keys(array_filter($permission_handler->getPermissions(), $is_rest_resource_permission));
$this->assertEqual(['restful delete entity:node', 'restful get entity:node', 'restful patch entity:node', 'restful post entity:node'], $rest_permissions);
}
}
@@ -0,0 +1,71 @@
<?php
namespace Drupal\rest\Tests\Update;
use Drupal\system\Tests\Update\UpdatePathTestBase;
/**
* Tests method-granularity REST config is simplified to resource-granularity.
*
* @see https://www.drupal.org/node/2721595
* @see rest_post_update_resource_granularity()
*
* @group rest
*/
class ResourceGranularityUpdateTest extends UpdatePathTestBase {
/**
* {@inheritdoc}
*/
protected static $modules = ['rest', 'serialization'];
/**
* {@inheritdoc}
*/
public function setDatabaseDumpFiles() {
$this->databaseDumpFiles = [
__DIR__ . '/../../../../system/tests/fixtures/update/drupal-8.bare.standard.php.gz',
__DIR__ . '/../../../../rest/tests/fixtures/update/drupal-8.rest-rest_post_update_resource_granularity.php',
];
}
/**
* Tests rest_post_update_simplify_resource_granularity().
*/
public function testMethodGranularityConvertedToResourceGranularity() {
/** @var \Drupal\Core\Entity\EntityStorageInterface $resource_config_storage */
$resource_config_storage = $this->container->get('entity_type.manager')->getStorage('rest_resource_config');
// Make sure we have the expected values before the update.
$resource_config_entities = $resource_config_storage->loadMultiple();
$this->assertIdentical(['entity.comment', 'entity.node', 'entity.user'], array_keys($resource_config_entities));
$this->assertIdentical('method', $resource_config_entities['entity.node']->get('granularity'));
$this->assertIdentical('method', $resource_config_entities['entity.comment']->get('granularity'));
$this->assertIdentical('method', $resource_config_entities['entity.user']->get('granularity'));
// Read the existing 'entity:comment' and 'entity:user' resource
// configuration so we can verify it after the update.
$comment_resource_configuration = $resource_config_entities['entity.comment']->get('configuration');
$user_resource_configuration = $resource_config_entities['entity.user']->get('configuration');
$this->runUpdates();
// Make sure we have the expected values after the update.
$resource_config_entities = $resource_config_storage->loadMultiple();
$this->assertIdentical(['entity.comment', 'entity.node', 'entity.user'], array_keys($resource_config_entities));
// 'entity:node' should be updated.
$this->assertIdentical('resource', $resource_config_entities['entity.node']->get('granularity'));
$this->assertidentical($resource_config_entities['entity.node']->get('configuration'), [
'methods' => ['GET', 'POST', 'PATCH', 'DELETE'],
'formats' => ['hal_json'],
'authentication' => ['basic_auth'],
]);
// 'entity:comment' should be unchanged.
$this->assertIdentical('method', $resource_config_entities['entity.comment']->get('granularity'));
$this->assertIdentical($comment_resource_configuration, $resource_config_entities['entity.comment']->get('configuration'));
// 'entity:user' should be unchanged.
$this->assertIdentical('method', $resource_config_entities['entity.user']->get('granularity'));
$this->assertIdentical($user_resource_configuration, $resource_config_entities['entity.user']->get('configuration'));
}
}
@@ -0,0 +1,65 @@
<?php
namespace Drupal\rest\Tests\Update;
use Drupal\rest\RestResourceConfigInterface;
use Drupal\system\Tests\Update\UpdatePathTestBase;
/**
* Tests that rest.settings is converted to rest_resource_config entities.
*
* @see https://www.drupal.org/node/2308745
* @see rest_update_8201()
* @see rest_post_update_create_rest_resource_config_entities()
*
* @group rest
*/
class RestConfigurationEntitiesUpdateTest extends UpdatePathTestBase {
/**
* {@inheritdoc}
*/
protected static $modules = ['rest', 'serialization'];
/**
* {@inheritdoc}
*/
public function setDatabaseDumpFiles() {
$this->databaseDumpFiles = [
__DIR__ . '/../../../../system/tests/fixtures/update/drupal-8.bare.standard.php.gz',
__DIR__ . '/../../../../rest/tests/fixtures/update/drupal-8.rest-rest_update_8201.php',
];
}
/**
* Tests rest_update_8201().
*/
public function testResourcesConvertedToConfigEntities() {
/** @var \Drupal\Core\Entity\EntityStorageInterface $resource_config_storage */
$resource_config_storage = $this->container->get('entity_type.manager')->getStorage('rest_resource_config');
// Make sure we have the expected values before the update.
$rest_settings = $this->config('rest.settings');
$this->assertTrue(array_key_exists('resources', $rest_settings->getRawData()));
$this->assertTrue(array_key_exists('entity:node', $rest_settings->getRawData()['resources']));
$resource_config_entities = $resource_config_storage->loadMultiple();
$this->assertIdentical([], array_keys($resource_config_entities));
$this->runUpdates();
// Make sure we have the expected values after the update.
$rest_settings = $this->config('rest.settings');
$this->assertFalse(array_key_exists('resources', $rest_settings->getRawData()));
$resource_config_entities = $resource_config_storage->loadMultiple();
$this->assertIdentical(['entity.node'], array_keys($resource_config_entities));
$node_resource_config_entity = $resource_config_entities['entity.node'];
$this->assertIdentical(RestResourceConfigInterface::RESOURCE_GRANULARITY, $node_resource_config_entity->get('granularity'));
$this->assertIdentical([
'methods' => ['GET'],
'formats' => ['json'],
'authentication' => ['basic_auth'],
], $node_resource_config_entity->get('configuration'));
$this->assertIdentical(['module' => ['basic_auth', 'node', 'serialization']], $node_resource_config_entity->getDependencies());
}
}
@@ -0,0 +1,36 @@
<?php
namespace Drupal\rest\Tests\Update;
use Drupal\system\Tests\Update\UpdatePathTestBase;
/**
* Ensures that update hook is run properly for REST Export config.
*
* @group Update
*/
class RestExportAuthUpdateTest extends UpdatePathTestBase {
/**
* {@inheritdoc}
*/
protected function setDatabaseDumpFiles() {
$this->databaseDumpFiles = [
__DIR__ . '/../../../../system/tests/fixtures/update/drupal-8.bare.standard.php.gz',
__DIR__ . '/../../../tests/fixtures/update/rest-export-with-authentication.php',
];
}
/**
* Ensures that update hook is run for rest module.
*/
public function testUpdate() {
$this->runUpdates();
// Get particular view.
$view = \Drupal::entityTypeManager()->getStorage('view')->load('rest_export_with_authorization');
$displays = $view->get('display');
$this->assertIdentical($displays['rest_export_1']['display_options']['auth']['basic_auth'], 'basic_auth', 'Basic authentication is set as authentication method.');
}
}
@@ -0,0 +1,87 @@
<?php
namespace Drupal\rest\Tests\Views;
use Drupal\node\Entity\Node;
use Drupal\views\Tests\ViewTestBase;
use Drupal\views\Tests\ViewTestData;
use Drupal\views\Views;
/**
* Tests the display of an excluded field that is used as a token.
*
* @group rest
* @see \Drupal\rest\Plugin\views\display\RestExport
* @see \Drupal\rest\Plugin\views\row\DataFieldRow
*/
class ExcludedFieldTokenTest extends ViewTestBase {
/**
* @var \Drupal\views\ViewExecutable
*/
protected $view;
/**
* The views that are used by this test.
*
* @var array
*/
public static $testViews = ['test_excluded_field_token_display'];
/**
* The modules that need to be installed for this test.
*
* @var array
*/
public static $modules = [
'entity_test',
'rest_test_views',
'node',
'field',
];
/**
* {@inheritdoc}
*/
protected function setUp() {
parent::setUp();
ViewTestData::createTestViews(get_class($this), ['rest_test_views']);
// Create some test content.
for ($i = 1; $i <= 10; $i++) {
Node::create([
'type' => 'article',
'title' => 'Article test ' . $i,
])->save();
}
$this->enableViewsTestModule();
$this->view = Views::getView('test_excluded_field_token_display');
$this->view->setDisplay('rest_export_1');
}
/**
* Tests the display of an excluded title field when used as a token.
*/
public function testExcludedTitleTokenDisplay() {
$actual_json = $this->drupalGetWithFormat($this->view->getPath(), 'json');
$this->assertResponse(200);
$expected = [
['nothing' => 'Article test 10'],
['nothing' => 'Article test 9'],
['nothing' => 'Article test 8'],
['nothing' => 'Article test 7'],
['nothing' => 'Article test 6'],
['nothing' => 'Article test 5'],
['nothing' => 'Article test 4'],
['nothing' => 'Article test 3'],
['nothing' => 'Article test 2'],
['nothing' => 'Article test 1'],
];
$this->assertIdentical($actual_json, json_encode($expected));
}
}
@@ -3,6 +3,7 @@
namespace Drupal\rest\Tests\Views;
use Drupal\Core\Cache\Cache;
use Drupal\Core\EventSubscriber\MainContentViewSubscriber;
use Drupal\Core\Field\FieldStorageDefinitionInterface;
use Drupal\entity_test\Entity\EntityTest;
use Drupal\field\Entity\FieldConfig;
@@ -39,14 +40,14 @@ class StyleSerializerTest extends PluginTestBase {
*
* @var array
*/
public static $modules = array('views_ui', 'entity_test', 'hal', 'rest_test_views', 'node', 'text', 'field', 'language');
public static $modules = ['views_ui', 'entity_test', 'hal', 'rest_test_views', 'node', 'text', 'field', 'language', 'basic_auth'];
/**
* Views used by this test.
*
* @var array
*/
public static $testViews = array('test_serializer_display_field', 'test_serializer_display_entity', 'test_serializer_display_entity_translated', 'test_serializer_node_display_field', 'test_serializer_node_exposed_filter');
public static $testViews = ['test_serializer_display_field', 'test_serializer_display_entity', 'test_serializer_display_entity_translated', 'test_serializer_node_display_field', 'test_serializer_node_exposed_filter'];
/**
* A user with administrative privileges to look at test entity and configure views.
@@ -56,18 +57,51 @@ class StyleSerializerTest extends PluginTestBase {
protected function setUp() {
parent::setUp();
ViewTestData::createTestViews(get_class($this), array('rest_test_views'));
ViewTestData::createTestViews(get_class($this), ['rest_test_views']);
$this->adminUser = $this->drupalCreateUser(array('administer views', 'administer entity_test content', 'access user profiles', 'view test entity'));
$this->adminUser = $this->drupalCreateUser(['administer views', 'administer entity_test content', 'access user profiles', 'view test entity']);
// Save some entity_test entities.
for ($i = 1; $i <= 10; $i++) {
EntityTest::create(array('name' => 'test_' . $i, 'user_id' => $this->adminUser->id()))->save();
EntityTest::create(['name' => 'test_' . $i, 'user_id' => $this->adminUser->id()])->save();
}
$this->enableViewsTestModule();
}
/**
* Checks that the auth options restricts access to a REST views display.
*/
public function testRestViewsAuthentication() {
// Assume the view is hidden behind a permission.
$this->drupalGetWithFormat('test/serialize/auth_with_perm', 'json');
$this->assertResponse(401);
// Not even logging in would make it possible to see the view, because then
// we are denied based on authentication method (cookie).
$this->drupalLogin($this->adminUser);
$this->drupalGetWithFormat('test/serialize/auth_with_perm', 'json');
$this->assertResponse(403);
$this->drupalLogout();
// But if we use the basic auth authentication strategy, we should be able
// to see the page.
$url = $this->buildUrl('test/serialize/auth_with_perm');
$response = \Drupal::httpClient()->get($url, [
'auth' => [$this->adminUser->getUsername(), $this->adminUser->pass_raw],
]);
// Ensure that any changes to variables in the other thread are picked up.
$this->refreshVariables();
$headers = $response->getHeaders();
$this->verbose('GET request to: ' . $url .
'<hr />Code: ' . curl_getinfo($this->curlHandle, CURLINFO_HTTP_CODE) .
'<hr />Response headers: ' . nl2br(print_r($headers, TRUE)) .
'<hr />Response body: ' . (string) $response->getBody());
$this->assertResponse(200);
}
/**
* Checks the behavior of the Serializer callback paths and row plugins.
*/
@@ -88,9 +122,9 @@ class StyleSerializerTest extends PluginTestBase {
$headers = $this->drupalGetHeaders();
$this->assertEqual($headers['content-type'], 'application/json', 'The header Content-type is correct.');
$expected = array();
$expected = [];
foreach ($view->result as $row) {
$expected_row = array();
$expected_row = [];
foreach ($view->field as $id => $field) {
$expected_row[$id] = $field->render($row);
}
@@ -120,7 +154,7 @@ class StyleSerializerTest extends PluginTestBase {
// Get the serializer service.
$serializer = $this->container->get('serializer');
$entities = array();
$entities = [];
foreach ($view->result as $row) {
$entities[] = $row->_entity;
}
@@ -146,15 +180,15 @@ class StyleSerializerTest extends PluginTestBase {
// Change the default format to xml.
$view->setDisplay('rest_export_1');
$view->getDisplay()->setOption('style', array(
$view->getDisplay()->setOption('style', [
'type' => 'serializer',
'options' => array(
'options' => [
'uses_fields' => FALSE,
'formats' => array(
'formats' => [
'xml' => 'xml',
),
),
));
],
],
]);
$view->save();
$expected = $serializer->serialize($entities, 'xml');
$actual_xml = $this->drupalGet('test/serialize/entity');
@@ -163,16 +197,16 @@ class StyleSerializerTest extends PluginTestBase {
// Allow multiple formats.
$view->setDisplay('rest_export_1');
$view->getDisplay()->setOption('style', array(
$view->getDisplay()->setOption('style', [
'type' => 'serializer',
'options' => array(
'options' => [
'uses_fields' => FALSE,
'formats' => array(
'formats' => [
'xml' => 'xml',
'json' => 'json',
),
),
));
],
],
]);
$view->save();
$expected = $serializer->serialize($entities, 'json');
$actual_json = $this->drupalGetWithFormat('test/serialize/entity', 'json');
@@ -185,7 +219,7 @@ class StyleSerializerTest extends PluginTestBase {
/**
* Verifies site maintenance mode functionality.
*/
protected function testSiteMaintenance() {
public function testSiteMaintenance() {
$view = Views::getView('test_serializer_display_field');
$view->initDisplay();
$this->executeView($view);
@@ -312,21 +346,21 @@ class StyleSerializerTest extends PluginTestBase {
$style_options = 'admin/structure/views/nojs/display/test_serializer_display_field/rest_export_1/style_options';
// Select only 'xml' as an accepted format.
$this->drupalPostForm($style_options, array('style_options[formats][xml]' => 'xml'), t('Apply'));
$this->drupalPostForm(NULL, array(), t('Save'));
$this->drupalPostForm($style_options, ['style_options[formats][xml]' => 'xml'], t('Apply'));
$this->drupalPostForm(NULL, [], t('Save'));
// Should return a 406.
$this->drupalGetWithFormat('test/serialize/field', 'json');
$this->assertHeader('content-type', 'application/json');
$this->assertResponse(406, 'A 406 response was returned when JSON was requested.');
// Should return a 200.
// Should return a 200.
$this->drupalGetWithFormat('test/serialize/field', 'xml');
$this->assertHeader('content-type', 'text/xml; charset=UTF-8');
$this->assertResponse(200, 'A 200 response was returned when XML was requested.');
// Add 'json' as an accepted format, so we have multiple.
$this->drupalPostForm($style_options, array('style_options[formats][json]' => 'json'), t('Apply'));
$this->drupalPostForm(NULL, array(), t('Save'));
$this->drupalPostForm($style_options, ['style_options[formats][json]' => 'json'], t('Apply'));
$this->drupalPostForm(NULL, [], t('Save'));
// Should return a 200.
// @todo This should be fixed when we have better content negotiation.
@@ -335,7 +369,7 @@ class StyleSerializerTest extends PluginTestBase {
$this->assertResponse(200, 'A 200 response was returned when any format was requested.');
// Should return a 200. Emulates a sample Firefox header.
$this->drupalGet('test/serialize/field', array(), array('Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8'));
$this->drupalGet('test/serialize/field', [], ['Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8']);
$this->assertHeader('content-type', 'application/json');
$this->assertResponse(200, 'A 200 response was returned when a browser accept header was requested.');
@@ -359,7 +393,7 @@ class StyleSerializerTest extends PluginTestBase {
$this->assertResponse(200, 'A 200 response was returned when HTML was requested.');
// Now configure now format, so all of them should be allowed.
$this->drupalPostForm($style_options, array('style_options[formats][json]' => '0', 'style_options[formats][xml]' => '0'), t('Apply'));
$this->drupalPostForm($style_options, ['style_options[formats][json]' => '0', 'style_options[formats][xml]' => '0'], t('Apply'));
// Should return a 200.
$this->drupalGetWithFormat('test/serialize/field', 'json');
@@ -390,16 +424,16 @@ class StyleSerializerTest extends PluginTestBase {
// Test an empty string for an alias, this should not be used. This also
// tests that the form can be submitted with no aliases.
$this->drupalPostForm($row_options, array('row_options[field_options][name][alias]' => ''), t('Apply'));
$this->drupalPostForm(NULL, array(), t('Save'));
$this->drupalPostForm($row_options, ['row_options[field_options][name][alias]' => ''], t('Apply'));
$this->drupalPostForm(NULL, [], t('Save'));
$view = Views::getView('test_serializer_display_field');
$view->setDisplay('rest_export_1');
$this->executeView($view);
$expected = array();
$expected = [];
foreach ($view->result as $row) {
$expected_row = array();
$expected_row = [];
foreach ($view->field as $id => $field) {
$expected_row[$id] = $field->render($row);
}
@@ -409,32 +443,32 @@ class StyleSerializerTest extends PluginTestBase {
$this->assertIdentical($this->drupalGetJSON('test/serialize/field'), $this->castSafeStrings($expected));
// Test a random aliases for fields, they should be replaced.
$alias_map = array(
$alias_map = [
'name' => $this->randomMachineName(),
// Use # to produce an invalid character for the validation.
'nothing' => '#' . $this->randomMachineName(),
'created' => 'created',
);
];
$edit = array('row_options[field_options][name][alias]' => $alias_map['name'], 'row_options[field_options][nothing][alias]' => $alias_map['nothing']);
$edit = ['row_options[field_options][name][alias]' => $alias_map['name'], 'row_options[field_options][nothing][alias]' => $alias_map['nothing']];
$this->drupalPostForm($row_options, $edit, t('Apply'));
$this->assertText(t('The machine-readable name must contain only letters, numbers, dashes and underscores.'));
// Change the map alias value to a valid one.
$alias_map['nothing'] = $this->randomMachineName();
$edit = array('row_options[field_options][name][alias]' => $alias_map['name'], 'row_options[field_options][nothing][alias]' => $alias_map['nothing']);
$edit = ['row_options[field_options][name][alias]' => $alias_map['name'], 'row_options[field_options][nothing][alias]' => $alias_map['nothing']];
$this->drupalPostForm($row_options, $edit, t('Apply'));
$this->drupalPostForm(NULL, array(), t('Save'));
$this->drupalPostForm(NULL, [], t('Save'));
$view = Views::getView('test_serializer_display_field');
$view->setDisplay('rest_export_1');
$this->executeView($view);
$expected = array();
$expected = [];
foreach ($view->result as $row) {
$expected_row = array();
$expected_row = [];
foreach ($view->field as $id => $field) {
$expected_row[$alias_map[$id]] = $field->render($row);
}
@@ -457,12 +491,12 @@ class StyleSerializerTest extends PluginTestBase {
// Test an empty string for an alias, this should not be used. This also
// tests that the form can be submitted with no aliases.
$values = array(
$values = [
'row_options[field_options][created][raw_output]' => '1',
'row_options[field_options][name][raw_output]' => '1',
);
];
$this->drupalPostForm($row_options, $values, t('Apply'));
$this->drupalPostForm(NULL, array(), t('Save'));
$this->drupalPostForm(NULL, [], t('Save'));
$view = Views::getView('test_serializer_display_field');
$view->setDisplay('rest_export_1');
@@ -516,9 +550,8 @@ class StyleSerializerTest extends PluginTestBase {
public function testLivePreview() {
// We set up a request so it looks like an request in the live preview.
$request = new Request();
$request->setFormat('drupal_ajax', 'application/vnd.drupal-ajax');
$request->headers->set('Accept', 'application/vnd.drupal-ajax');
/** @var \Symfony\Component\HttpFoundation\RequestStack $request_stack */
$request->query->add([MainContentViewSubscriber::WRAPPER_FORMAT => 'drupal_ajax']);
/** @var \Symfony\Component\HttpFoundation\RequestStack $request_stack */
$request_stack = \Drupal::service('request_stack');
$request_stack->push($request);
@@ -529,7 +562,7 @@ class StyleSerializerTest extends PluginTestBase {
// Get the serializer service.
$serializer = $this->container->get('serializer');
$entities = array();
$entities = [];
foreach ($view->result as $row) {
$entities[] = $row->_entity;
}
@@ -547,15 +580,15 @@ class StyleSerializerTest extends PluginTestBase {
// Change the request format to xml.
$view->setDisplay('rest_export_1');
$view->getDisplay()->setOption('style', array(
$view->getDisplay()->setOption('style', [
'type' => 'serializer',
'options' => array(
'options' => [
'uses_fields' => FALSE,
'formats' => array(
'formats' => [
'xml' => 'xml',
),
),
));
],
],
]);
$this->executeView($view);
$build = $view->preview();
@@ -569,7 +602,7 @@ class StyleSerializerTest extends PluginTestBase {
public function testSerializerViewsUI() {
$this->drupalLogin($this->adminUser);
// Click the "Update preview button".
$this->drupalPostForm('admin/structure/views/view/test_serializer_display_field/edit/rest_export_1', $edit = array(), t('Update preview'));
$this->drupalPostForm('admin/structure/views/view/test_serializer_display_field/edit/rest_export_1', $edit = [], t('Update preview'));
$this->assertResponse(200);
// Check if we receive the expected result.
$result = $this->xpath('//div[@id="views-live-preview"]/pre');
@@ -580,7 +613,7 @@ class StyleSerializerTest extends PluginTestBase {
* Tests the field row style using fieldapi fields.
*/
public function testFieldapiField() {
$this->drupalCreateContentType(array('type' => 'page'));
$this->drupalCreateContentType(['type' => 'page']);
$node = $this->drupalCreateNode();
$result = $this->drupalGetJSON('test/serialize/node-field');
@@ -716,44 +749,44 @@ class StyleSerializerTest extends PluginTestBase {
* the value provided.
*/
public function testRestViewExposedFilter() {
$this->drupalCreateContentType(array('type' => 'page'));
$node0 = $this->drupalCreateNode(array('title' => 'Node 1'));
$node1 = $this->drupalCreateNode(array('title' => 'Node 11'));
$node2 = $this->drupalCreateNode(array('title' => 'Node 111'));
$this->drupalCreateContentType(['type' => 'page']);
$node0 = $this->drupalCreateNode(['title' => 'Node 1']);
$node1 = $this->drupalCreateNode(['title' => 'Node 11']);
$node2 = $this->drupalCreateNode(['title' => 'Node 111']);
// Test that no filter brings back all three nodes.
$result = $this->drupalGetJSON('test/serialize/node-exposed-filter');
$expected = array(
0 => array(
$expected = [
0 => [
'nid' => $node0->id(),
'body' => $node0->body->processed,
),
1 => array(
],
1 => [
'nid' => $node1->id(),
'body' => $node1->body->processed,
),
2 => array(
],
2 => [
'nid' => $node2->id(),
'body' => $node2->body->processed,
),
);
],
];
$this->assertEqual($result, $expected, 'Querying a view with no exposed filter returns all nodes.');
// Test that title starts with 'Node 11' query finds 2 of the 3 nodes.
$result = $this->drupalGetJSON('test/serialize/node-exposed-filter', ['query' => ['title' => 'Node 11']]);
$expected = array(
0 => array(
$expected = [
0 => [
'nid' => $node1->id(),
'body' => $node1->body->processed,
),
1 => array(
],
1 => [
'nid' => $node2->id(),
'body' => $node2->body->processed,
),
);
],
];
$cache_contexts = [
'languages:language_content',