You are here

final class LinkProviderManager in JSON:API Hypermedia 8

Manages discovery and instantiation of resourceFieldEnhancer plugins.

@internal

Hierarchy

Expanded class hierarchy of LinkProviderManager

1 string reference to 'LinkProviderManager'
jsonapi_hypermedia.services.yml in ./jsonapi_hypermedia.services.yml
jsonapi_hypermedia.services.yml
1 service uses LinkProviderManager
jsonapi_hypermedia_provider.manager in ./jsonapi_hypermedia.services.yml
Drupal\jsonapi_hypermedia\Plugin\LinkProviderManager

File

src/Plugin/LinkProviderManager.php, line 31

Namespace

Drupal\jsonapi_hypermedia\Plugin
View source
final class LinkProviderManager extends DefaultPluginManager implements LinkProviderManagerInterface {

  /**
   * A map of plugin definition context types to class and interface names.
   *
   * @var array
   */
  protected static $contextTypes = [
    'top_level_object' => JsonApiDocumentTopLevel::class,
    'resource_object' => ResourceObject::class,
    'relationship_object' => Relationship::class,
  ];

  /**
   * The renderer service.
   *
   * @var \Drupal\Core\Render\Renderer
   */
  protected $renderer;

  /**
   * The current route match.
   *
   * @var \Drupal\Core\Routing\RouteMatchInterface
   */
  protected $currentRouteMatch;

  /**
   * The link relation type manager.
   *
   * @var \Drupal\Core\Http\LinkRelationTypeManager
   */
  protected $linkRelationTypeManager;

  /**
   * Constructs a new HypermediaProviderManager.
   *
   * @param \Traversable $namespaces
   *   An object that implements \Traversable which contains the root paths
   *   keyed by the corresponding namespace to look for plugin implementations.
   * @param \Drupal\Core\Cache\CacheBackendInterface $cache_backend
   *   Cache backend instance to use.
   * @param \Drupal\Core\Extension\ModuleHandlerInterface $module_handler
   *   The module handler to invoke the alter hook with.
   */
  public function __construct(\Traversable $namespaces, CacheBackendInterface $cache_backend, ModuleHandlerInterface $module_handler) {
    parent::__construct('Plugin/jsonapi_hypermedia/LinkProvider', $namespaces, $module_handler, LinkProviderInterface::class, JsonapiHypermediaLinkProvider::class);
    $this
      ->alterInfo('jsonapi_hypermedia_provider_info');
    $this
      ->setCacheBackend($cache_backend, 'jsonapi_hypermedia_provider_plugins');
  }

  /**
   * Set the current route match.
   *
   * @param \Drupal\Core\Routing\RouteMatchInterface $route_match
   *   The current route match.
   */
  public function setCurrentRouteMatch(RouteMatchInterface $route_match) {
    $this->currentRouteMatch = $route_match;
  }

  /**
   * Set the link relation type manager.
   *
   * @param \Drupal\Core\Http\LinkRelationTypeManager $link_relation_type_manager
   *   The link relation type manager.
   */
  public function setLinkRelationTypeManager(LinkRelationTypeManager $link_relation_type_manager) {
    $this->linkRelationTypeManager = $link_relation_type_manager;
  }

  /**
   * {@inheritdoc}
   */
  public function getLinkCollection($context) {
    $definitions = $this
      ->getApplicableDefinitions($context);
    $providers = array_map(function ($plugin_id) use ($definitions) {
      return $this
        ->createInstance($plugin_id, $definitions[$plugin_id]['default_configuration'] ?? []);
    }, array_keys($definitions));
    $cacheability = NULL;
    $link_collection = array_reduce($providers, function (LinkCollection $link_collection, LinkProviderInterface $provider) use ($context, &$cacheability) {
      $link = $this
        ->ensureAccess($cacheability, $provider
        ->getLink($context));
      return $link ? $link_collection
        ->withLink($provider
        ->getLinkKey(), $this
        ->getValidatedLink($link)) : $link_collection;
    }, new LinkCollection([]));
    $this
      ->bubbleAccessCacheability($cacheability);
    return $link_collection
      ->withContext($context);
  }

  /**
   * Ensures that access cacheability is captured.
   *
   * @param \Drupal\Core\Cache\CacheableMetadata|null $cacheability
   *   The access related cacheability to be captured or NULL if there is none.
   * @param \Drupal\jsonapi_hypermedia\AccessRestrictedLink $link
   *   The link for which to ensure access cacheability is captured.
   *
   * @return \Drupal\jsonapi\JsonApiResource\Link|null
   *   A JSON:API link or NULL if the given link is not accessible.
   */
  protected function ensureAccess(&$cacheability, AccessRestrictedLink $link) {
    if (!$cacheability) {
      $cacheability = new CacheableMetadata();
    }
    $cacheability
      ->addCacheableDependency($link);
    if (!$link
      ->isAllowed()) {
      return NULL;
    }
    return $link
      ->getInnerLink();
  }

  /**
   * Gets a new, validated link.
   *
   * @param \Drupal\jsonapi\JsonApiResource\Link $link
   *   The link to validate.
   *
   * @return \Drupal\jsonapi\JsonApiResource\Link
   *   A new, validated link.
   *
   * @throws \Drupal\Component\Plugin\Exception\InvalidPluginDefinitionException
   *   Thrown if a link relation type plugin is improperly defined.
   * @throws \Drupal\Component\Plugin\Exception\PluginException
   *   Thrown if a link relation type plugin could not be found.
   */
  protected function getValidatedLink(Link $link) {
    $link_relation_type = $link
      ->getLinkRelationType();
    $link_relation = $this->linkRelationTypeManager
      ->createInstance($link_relation_type);
    assert($link_relation instanceof LinkRelationTypeInterface);
    $link_relation_type_name = $link_relation
      ->isExtension() ? $link_relation
      ->getExtensionUri() : $link_relation
      ->getRegisteredName();
    if (!$link_relation_type_name) {
      throw new InvalidPluginDefinitionException($link_relation_type);
    }
    return new Link(CacheableMetadata::createFromObject($link), $link
      ->getUri(), $link_relation_type_name, $link
      ->getTargetAttributes());
  }

  /**
   * Bubbles access-related cacheability of the link.
   *
   * @param \Drupal\Core\Cache\CacheableMetadata|null $cacheability
   *   The access related cacheability to be captured or NULL if there is none.
   *
   * @todo: removes this once https://www.drupal.org/project/drupal/issues/3055889 lands.
   */
  protected function bubbleAccessCacheability($cacheability) {
    assert(is_null($cacheability) || $cacheability instanceof CacheableMetadata);
    if (is_null($cacheability)) {
      return;
    }
    $request = \Drupal::requestStack()
      ->getCurrentRequest();
    $renderer = \Drupal::service('renderer');
    if ($request
      ->isMethodCacheable() && $renderer
      ->hasRenderContext()) {
      $build = [];
      $cacheability
        ->applyTo($build);
      $renderer
        ->render($build);
    }
  }

  /**
   * Gets the context type.
   *
   * @param \Drupal\jsonapi\JsonApiResource\JsonApiDocumentTopLevel|\Drupal\jsonapi\JsonApiResource\ResourceObject|\Drupal\jsonapi\JsonApiResource\Relationship $context
   *   The context object from which links should be generated.
   *
   * @return string
   *   The context type.
   */
  protected static function getContextType($context) {
    foreach (static::$contextTypes as $type => $class) {
      if ($context instanceof $class) {
        $context_type = $type;
      }
    }
    assert(isset($context_type));
    return $context_type;
  }

  /**
   * Gets the link provider definitions applicable to the given context object.
   *
   * @param \Drupal\jsonapi\JsonApiResource\JsonApiDocumentTopLevel|\Drupal\jsonapi\JsonApiResource\ResourceObject $context
   *   The link context object.
   *
   * @return array
   *   An array of the application provider definitions.
   *
   * @see \Drupal\Component\Plugin\PluginManagerInterface::getDefinitions()
   */
  protected function getApplicableDefinitions($context) {
    $context_type = static::getContextType($context);
    $definitions = $this
      ->getDefinitions();
    return array_filter($definitions, function ($plugin_definition) use ($context_type, $context) {
      if (!empty($plugin_definition['link_context']['relationship_object'])) {
        $plugin_definition['link_context']['top_level_object'] = 'relationship_object';
      }
      if (empty($plugin_definition['link_context'][$context_type])) {
        return FALSE;
      }
      if ($plugin_definition['link_context'][$context_type] === TRUE) {
        return TRUE;
      }
      switch ($context_type) {
        case 'top_level_object':
          assert($context instanceof JsonApiDocumentTopLevel);
          $data = $context
            ->getData();
          $is_error_document = $data instanceof ErrorCollection;
          $is_entrypoint = $this->currentRouteMatch
            ->getRouteName() === 'jsonapi.resource_list';
          $is_relationship_document = $data instanceof RelationshipData;
          switch ($plugin_definition['link_context'][$context_type]) {
            case 'entrypoint':
              return !$is_error_document && $is_entrypoint;
            case 'success':
              return !$is_error_document;
            case 'error':
              return $is_error_document;
            case 'individual':
              return !$is_error_document && !$is_entrypoint && $data instanceof ResourceObjectData && $data
                ->getCardinality() === 1;
            case 'collection':
              return !$is_error_document && !$is_entrypoint && $data instanceof ResourceObjectData && $data
                ->getCardinality() !== 1;
            case 'relationship':
              return !$is_error_document && !$is_entrypoint && $is_relationship_document;
            case 'relationship_object':
              if ($is_error_document || $is_entrypoint || !$is_relationship_document) {
                return FALSE;
              }
              if (is_bool($plugin_definition['link_context']['relationship_object'])) {
                return $plugin_definition['link_context']['relationship_object'];
              }
              $route = $this->currentRouteMatch
                ->getRouteObject();
              list($resource_type_name, $relationship_field_name) = $plugin_definition['link_context']['relationship_object'];
              return $route
                ->getDefault(Routes::RESOURCE_TYPE_KEY) === $resource_type_name && $route
                ->getDefault('related') === $relationship_field_name;
            default:
              return FALSE;
          }
        case 'resource_object':
          assert($context instanceof ResourceObject);
          return $context
            ->getResourceType()
            ->getTypeName() === $plugin_definition['link_context'][$context_type];
        case 'relationship_object':
          assert($context instanceof Relationship);
          list($resource_type_name, $relationship_field_name) = $plugin_definition['link_context'][$context_type];
          return $context
            ->getContext()
            ->getResourceType()
            ->getTypeName() === $resource_type_name && $context
            ->getFieldName() === $relationship_field_name;
        default:
          return FALSE;
      }
    });
  }

}

Members

Namesort descending Modifiers Type Description Overrides
DefaultPluginManager::$additionalAnnotationNamespaces protected property Additional namespaces the annotation discovery mechanism should scan for annotation definitions.
DefaultPluginManager::$alterHook protected property Name of the alter hook if one should be invoked.
DefaultPluginManager::$cacheKey protected property The cache key.
DefaultPluginManager::$cacheTags protected property An array of cache tags to use for the cached definitions.
DefaultPluginManager::$defaults protected property A set of defaults to be referenced by $this->processDefinition() if additional processing of plugins is necessary or helpful for development purposes. 9
DefaultPluginManager::$moduleHandler protected property The module handler to invoke the alter hook. 1
DefaultPluginManager::$namespaces protected property An object that implements \Traversable which contains the root paths keyed by the corresponding namespace to look for plugin implementations.
DefaultPluginManager::$pluginDefinitionAnnotationName protected property The name of the annotation that contains the plugin definition.
DefaultPluginManager::$pluginInterface protected property The interface each plugin should implement. 1
DefaultPluginManager::$subdir protected property The subdirectory within a namespace to look for plugins, or FALSE if the plugins are in the top level of the namespace.
DefaultPluginManager::alterDefinitions protected function Invokes the hook to alter the definitions if the alter hook is set. 1
DefaultPluginManager::alterInfo protected function Sets the alter hook name.
DefaultPluginManager::clearCachedDefinitions public function Clears static and persistent plugin definition caches. Overrides CachedDiscoveryInterface::clearCachedDefinitions 5
DefaultPluginManager::extractProviderFromDefinition protected function Extracts the provider from a plugin definition.
DefaultPluginManager::findDefinitions protected function Finds plugin definitions. 7
DefaultPluginManager::fixContextAwareDefinitions private function Fix the definitions of context-aware plugins.
DefaultPluginManager::getCacheContexts public function The cache contexts associated with this object. Overrides CacheableDependencyInterface::getCacheContexts
DefaultPluginManager::getCachedDefinitions protected function Returns the cached plugin definitions of the decorated discovery class.
DefaultPluginManager::getCacheMaxAge public function The maximum age for which this object may be cached. Overrides CacheableDependencyInterface::getCacheMaxAge
DefaultPluginManager::getCacheTags public function The cache tags associated with this object. Overrides CacheableDependencyInterface::getCacheTags
DefaultPluginManager::getDefinitions public function Gets the definition of all plugins for this type. Overrides DiscoveryTrait::getDefinitions 2
DefaultPluginManager::getDiscovery protected function Gets the plugin discovery. Overrides PluginManagerBase::getDiscovery 12
DefaultPluginManager::getFactory protected function Gets the plugin factory. Overrides PluginManagerBase::getFactory
DefaultPluginManager::processDefinition public function Performs extra processing on plugin definitions. 13
DefaultPluginManager::providerExists protected function Determines if the provider of a definition exists. 3
DefaultPluginManager::setCacheBackend public function Initialize the cache backend.
DefaultPluginManager::setCachedDefinitions protected function Sets a cache of plugin definitions for the decorated discovery class.
DefaultPluginManager::useCaches public function Disable the use of caches. Overrides CachedDiscoveryInterface::useCaches 1
DiscoveryCachedTrait::$definitions protected property Cached definitions array. 1
DiscoveryCachedTrait::getDefinition public function Overrides DiscoveryTrait::getDefinition 3
DiscoveryTrait::doGetDefinition protected function Gets a specific plugin definition.
DiscoveryTrait::hasDefinition public function
LinkProviderManager::$contextTypes protected static property A map of plugin definition context types to class and interface names.
LinkProviderManager::$currentRouteMatch protected property The current route match.
LinkProviderManager::$linkRelationTypeManager protected property The link relation type manager.
LinkProviderManager::$renderer protected property The renderer service.
LinkProviderManager::bubbleAccessCacheability protected function Bubbles access-related cacheability of the link.
LinkProviderManager::ensureAccess protected function Ensures that access cacheability is captured.
LinkProviderManager::getApplicableDefinitions protected function Gets the link provider definitions applicable to the given context object.
LinkProviderManager::getContextType protected static function Gets the context type.
LinkProviderManager::getLinkCollection public function Gets a LinkCollection of 3rd-party links for the given context object. Overrides LinkProviderManagerInterface::getLinkCollection
LinkProviderManager::getValidatedLink protected function Gets a new, validated link.
LinkProviderManager::setCurrentRouteMatch public function Set the current route match.
LinkProviderManager::setLinkRelationTypeManager public function Set the link relation type manager.
LinkProviderManager::__construct public function Constructs a new HypermediaProviderManager. Overrides DefaultPluginManager::__construct
PluginManagerBase::$discovery protected property The object that discovers plugins managed by this manager.
PluginManagerBase::$factory protected property The object that instantiates plugins managed by this manager.
PluginManagerBase::$mapper protected property The object that returns the preconfigured plugin instance appropriate for a particular runtime condition.
PluginManagerBase::createInstance public function Creates a pre-configured instance of a plugin. Overrides FactoryInterface::createInstance 12
PluginManagerBase::getInstance public function Gets a preconfigured instance of a plugin. Overrides MapperInterface::getInstance 7
PluginManagerBase::handlePluginNotFound protected function Allows plugin managers to specify custom behavior if a plugin is not found. 1
UseCacheBackendTrait::$cacheBackend protected property Cache backend instance.
UseCacheBackendTrait::$useCaches protected property Flag whether caches should be used or skipped.
UseCacheBackendTrait::cacheGet protected function Fetches from the cache backend, respecting the use caches flag. 1
UseCacheBackendTrait::cacheSet protected function Stores data in the persistent cache, respecting the use caches flag.