PageRenderTime 40ms CodeModel.GetById 13ms RepoModel.GetById 0ms app.codeStats 0ms

/core/modules/rest/src/Plugin/ResourceBase.php

http://github.com/drupal/drupal
PHP | 237 lines | 108 code | 22 blank | 107 comment | 6 complexity | b9096b2a1899f6e725527bcb8354f109 MD5 | raw file
Possible License(s): GPL-2.0, LGPL-2.1
  1. <?php
  2. namespace Drupal\rest\Plugin;
  3. use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
  4. use Drupal\Core\Plugin\PluginBase;
  5. use Drupal\Core\Routing\BcRoute;
  6. use Psr\Log\LoggerInterface;
  7. use Symfony\Component\DependencyInjection\ContainerInterface;
  8. use Symfony\Component\Routing\Route;
  9. use Symfony\Component\Routing\RouteCollection;
  10. /**
  11. * Common base class for resource plugins.
  12. *
  13. * Note that this base class' implementation of the permissions() method
  14. * generates a permission for every method for a resource. If your resource
  15. * already has its own access control mechanism, you should opt out from this
  16. * default permissions() method by overriding it.
  17. *
  18. * @see \Drupal\rest\Annotation\RestResource
  19. * @see \Drupal\rest\Plugin\Type\ResourcePluginManager
  20. * @see \Drupal\rest\Plugin\ResourceInterface
  21. * @see plugin_api
  22. *
  23. * @ingroup third_party
  24. */
  25. abstract class ResourceBase extends PluginBase implements ContainerFactoryPluginInterface, ResourceInterface {
  26. /**
  27. * The available serialization formats.
  28. *
  29. * @var array
  30. */
  31. protected $serializerFormats = [];
  32. /**
  33. * A logger instance.
  34. *
  35. * @var \Psr\Log\LoggerInterface
  36. */
  37. protected $logger;
  38. /**
  39. * Constructs a Drupal\rest\Plugin\ResourceBase object.
  40. *
  41. * @param array $configuration
  42. * A configuration array containing information about the plugin instance.
  43. * @param string $plugin_id
  44. * The plugin_id for the plugin instance.
  45. * @param mixed $plugin_definition
  46. * The plugin implementation definition.
  47. * @param array $serializer_formats
  48. * The available serialization formats.
  49. * @param \Psr\Log\LoggerInterface $logger
  50. * A logger instance.
  51. */
  52. public function __construct(array $configuration, $plugin_id, $plugin_definition, array $serializer_formats, LoggerInterface $logger) {
  53. parent::__construct($configuration, $plugin_id, $plugin_definition);
  54. $this->serializerFormats = $serializer_formats;
  55. $this->logger = $logger;
  56. }
  57. /**
  58. * {@inheritdoc}
  59. */
  60. public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
  61. return new static(
  62. $configuration,
  63. $plugin_id,
  64. $plugin_definition,
  65. $container->getParameter('serializer.formats'),
  66. $container->get('logger.factory')->get('rest')
  67. );
  68. }
  69. /**
  70. * Implements ResourceInterface::permissions().
  71. *
  72. * Every plugin operation method gets its own user permission. Example:
  73. * "restful delete entity:node" with the title "Access DELETE on Node
  74. * resource".
  75. */
  76. public function permissions() {
  77. $permissions = [];
  78. $definition = $this->getPluginDefinition();
  79. foreach ($this->availableMethods() as $method) {
  80. $lowered_method = strtolower($method);
  81. $permissions["restful $lowered_method $this->pluginId"] = [
  82. 'title' => $this->t('Access @method on %label resource', ['@method' => $method, '%label' => $definition['label']]),
  83. ];
  84. }
  85. return $permissions;
  86. }
  87. /**
  88. * {@inheritdoc}
  89. */
  90. public function routes() {
  91. $collection = new RouteCollection();
  92. $definition = $this->getPluginDefinition();
  93. $canonical_path = isset($definition['uri_paths']['canonical']) ? $definition['uri_paths']['canonical'] : '/' . strtr($this->pluginId, ':', '/') . '/{id}';
  94. $create_path = isset($definition['uri_paths']['create']) ? $definition['uri_paths']['create'] : '/' . strtr($this->pluginId, ':', '/');
  95. // BC: the REST module originally created the POST URL for a resource by
  96. // reading the 'https://www.drupal.org/link-relations/create' URI path from
  97. // the plugin annotation. For consistency with entity type definitions, that
  98. // then changed to reading the 'create' URI path. For any REST Resource
  99. // plugins that were using the old mechanism, we continue to support that.
  100. if (!isset($definition['uri_paths']['create']) && isset($definition['uri_paths']['https://www.drupal.org/link-relations/create'])) {
  101. @trigger_error('The "https://www.drupal.org/link-relations/create" string as a RestResource plugin annotation URI path key is deprecated in Drupal 8.4.0, now a valid link relation type name must be specified, so "create" must be specified instead before Drupal 9.0.0. See https://www.drupal.org/node/2737401.', E_USER_DEPRECATED);
  102. $create_path = $definition['uri_paths']['https://www.drupal.org/link-relations/create'];
  103. }
  104. $route_name = strtr($this->pluginId, ':', '.');
  105. $methods = $this->availableMethods();
  106. foreach ($methods as $method) {
  107. $path = $method === 'POST'
  108. ? $create_path
  109. : $canonical_path;
  110. $route = $this->getBaseRoute($path, $method);
  111. // Note that '_format' and '_content_type_format' route requirements are
  112. // added in ResourceRoutes::getRoutesForResourceConfig().
  113. $collection->add("$route_name.$method", $route);
  114. // BC: the REST module originally created per-format GET routes, instead
  115. // of a single route. To minimize the surface of this BC layer, this uses
  116. // route definitions that are as empty as possible, plus an outbound route
  117. // processor.
  118. // @see \Drupal\rest\RouteProcessor\RestResourceGetRouteProcessorBC
  119. if ($method === 'GET' || $method === 'HEAD') {
  120. foreach ($this->serializerFormats as $format_name) {
  121. $collection->add("$route_name.$method.$format_name", (new BcRoute())->setRequirement('_format', $format_name));
  122. }
  123. }
  124. }
  125. return $collection;
  126. }
  127. /**
  128. * Provides predefined HTTP request methods.
  129. *
  130. * Plugins can override this method to provide additional custom request
  131. * methods.
  132. *
  133. * @return array
  134. * The list of allowed HTTP request method strings.
  135. */
  136. protected function requestMethods() {
  137. return [
  138. 'HEAD',
  139. 'GET',
  140. 'POST',
  141. 'PUT',
  142. 'DELETE',
  143. 'TRACE',
  144. 'OPTIONS',
  145. 'CONNECT',
  146. 'PATCH',
  147. ];
  148. }
  149. /**
  150. * {@inheritdoc}
  151. */
  152. public function availableMethods() {
  153. $methods = $this->requestMethods();
  154. $available = [];
  155. foreach ($methods as $method) {
  156. // Only expose methods where the HTTP request method exists on the plugin.
  157. if (method_exists($this, strtolower($method))) {
  158. $available[] = $method;
  159. }
  160. }
  161. return $available;
  162. }
  163. /**
  164. * Gets the base route for a particular method.
  165. *
  166. * @param string $canonical_path
  167. * The canonical path for the resource.
  168. * @param string $method
  169. * The HTTP method to be used for the route.
  170. *
  171. * @return \Symfony\Component\Routing\Route
  172. * The created base route.
  173. */
  174. protected function getBaseRoute($canonical_path, $method) {
  175. return new Route($canonical_path, [
  176. '_controller' => 'Drupal\rest\RequestHandler::handle',
  177. ],
  178. $this->getBaseRouteRequirements($method),
  179. [],
  180. '',
  181. [],
  182. // The HTTP method is a requirement for this route.
  183. [$method]
  184. );
  185. }
  186. /**
  187. * Gets the base route requirements for a particular method.
  188. *
  189. * @param $method
  190. * The HTTP method to be used for the route.
  191. *
  192. * @return array
  193. * An array of requirements for parameters.
  194. */
  195. protected function getBaseRouteRequirements($method) {
  196. $lower_method = strtolower($method);
  197. // Every route MUST have requirements that result in the access manager
  198. // having access checks to check. If it does not, the route is made
  199. // inaccessible. So, we default to granting access to everyone. If a
  200. // permission exists, then we add that below. The access manager requires
  201. // that ALL access checks must grant access, so this still results in
  202. // correct behavior.
  203. $requirements = [
  204. '_access' => 'TRUE',
  205. ];
  206. // Only specify route requirements if the default permission exists. For any
  207. // more advanced route definition, resource plugins extending this base
  208. // class must override this method.
  209. $permission = "restful $lower_method $this->pluginId";
  210. if (isset($this->permissions()[$permission])) {
  211. $requirements['_permission'] = $permission;
  212. }
  213. return $requirements;
  214. }
  215. }