You are here

class LayoutPluginManager in Drupal 8

Same name and namespace in other branches
  1. 9 core/lib/Drupal/Core/Layout/LayoutPluginManager.php \Drupal\Core\Layout\LayoutPluginManager

Provides a plugin manager for layouts.

Hierarchy

Expanded class hierarchy of LayoutPluginManager

1 file declares its use of LayoutPluginManager
LayoutPluginManagerTest.php in core/tests/Drupal/Tests/Core/Layout/LayoutPluginManagerTest.php
1 string reference to 'LayoutPluginManager'
layout_discovery.services.yml in core/modules/layout_discovery/layout_discovery.services.yml
core/modules/layout_discovery/layout_discovery.services.yml
1 service uses LayoutPluginManager
plugin.manager.core.layout in core/modules/layout_discovery/layout_discovery.services.yml
Drupal\Core\Layout\LayoutPluginManager

File

core/lib/Drupal/Core/Layout/LayoutPluginManager.php, line 21

Namespace

Drupal\Core\Layout
View source
class LayoutPluginManager extends DefaultPluginManager implements LayoutPluginManagerInterface {
  use FilteredPluginManagerTrait;

  /**
   * The theme handler.
   *
   * @var \Drupal\Core\Extension\ThemeHandlerInterface
   */
  protected $themeHandler;

  /**
   * LayoutPluginManager constructor.
   *
   * @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.
   * @param \Drupal\Core\Extension\ThemeHandlerInterface $theme_handler
   *   The theme handler to invoke the alter hook with.
   */
  public function __construct(\Traversable $namespaces, CacheBackendInterface $cache_backend, ModuleHandlerInterface $module_handler, ThemeHandlerInterface $theme_handler) {
    parent::__construct('Plugin/Layout', $namespaces, $module_handler, LayoutInterface::class, Layout::class);
    $this->themeHandler = $theme_handler;
    $type = $this
      ->getType();
    $this
      ->setCacheBackend($cache_backend, $type);
    $this
      ->alterInfo($type);
  }

  /**
   * {@inheritdoc}
   */
  protected function getType() {
    return 'layout';
  }

  /**
   * {@inheritdoc}
   */
  protected function providerExists($provider) {
    return $this->moduleHandler
      ->moduleExists($provider) || $this->themeHandler
      ->themeExists($provider);
  }

  /**
   * {@inheritdoc}
   */
  protected function getDiscovery() {
    if (!$this->discovery) {
      $discovery = new AnnotatedClassDiscovery($this->subdir, $this->namespaces, $this->pluginDefinitionAnnotationName, $this->additionalAnnotationNamespaces);
      $discovery = new YamlDiscoveryDecorator($discovery, 'layouts', $this->moduleHandler
        ->getModuleDirectories() + $this->themeHandler
        ->getThemeDirectories());
      $discovery
        ->addTranslatableProperty('label')
        ->addTranslatableProperty('description')
        ->addTranslatableProperty('category');
      $discovery = new AnnotationBridgeDecorator($discovery, $this->pluginDefinitionAnnotationName);
      $discovery = new ContainerDerivativeDiscoveryDecorator($discovery);
      $this->discovery = $discovery;
    }
    return $this->discovery;
  }

  /**
   * {@inheritdoc}
   */
  public function processDefinition(&$definition, $plugin_id) {
    parent::processDefinition($definition, $plugin_id);
    if (!$definition instanceof LayoutDefinition) {
      throw new InvalidPluginDefinitionException($plugin_id, sprintf('The "%s" layout definition must extend %s', $plugin_id, LayoutDefinition::class));
    }

    // Add the module or theme path to the 'path'.
    $provider = $definition
      ->getProvider();
    if ($this->moduleHandler
      ->moduleExists($provider)) {
      $base_path = $this->moduleHandler
        ->getModule($provider)
        ->getPath();
    }
    elseif ($this->themeHandler
      ->themeExists($provider)) {
      $base_path = $this->themeHandler
        ->getTheme($provider)
        ->getPath();
    }
    else {
      $base_path = '';
    }
    $path = $definition
      ->getPath();
    $path = !empty($path) ? $base_path . '/' . $path : $base_path;
    $definition
      ->setPath($path);

    // Add the base path to the icon path.
    if ($icon_path = $definition
      ->getIconPath()) {
      $definition
        ->setIconPath($path . '/' . $icon_path);
    }

    // Add a dependency on the provider of the library.
    if ($library = $definition
      ->getLibrary()) {
      $config_dependencies = $definition
        ->getConfigDependencies();
      list($library_provider) = explode('/', $library, 2);
      if ($this->moduleHandler
        ->moduleExists($library_provider)) {
        $config_dependencies['module'][] = $library_provider;
      }
      elseif ($this->themeHandler
        ->themeExists($library_provider)) {
        $config_dependencies['theme'][] = $library_provider;
      }
      $definition
        ->setConfigDependencies($config_dependencies);
    }

    // If 'template' is set, then we'll derive 'template_path' and 'theme_hook'.
    $template = $definition
      ->getTemplate();
    if (!empty($template)) {
      $template_parts = explode('/', $template);
      $template = array_pop($template_parts);
      $template_path = $path;
      if (count($template_parts) > 0) {
        $template_path .= '/' . implode('/', $template_parts);
      }
      $definition
        ->setTemplate($template);
      $definition
        ->setThemeHook(strtr($template, '-', '_'));
      $definition
        ->setTemplatePath($template_path);
    }
    if (!$definition
      ->getDefaultRegion()) {
      $definition
        ->setDefaultRegion(key($definition
        ->getRegions()));
    }

    // Makes sure region names are translatable.
    $regions = array_map(function ($region) {
      if (!$region['label'] instanceof TranslatableMarkup) {

        // Region labels from YAML discovery needs translation.
        $region['label'] = new TranslatableMarkup($region['label'], [], [
          'context' => 'layout_region',
        ]);
      }
      return $region;
    }, $definition
      ->getRegions());
    $definition
      ->setRegions($regions);
  }

  /**
   * {@inheritdoc}
   */
  public function getThemeImplementations() {
    $hooks = [];
    $hooks['layout'] = [
      'render element' => 'content',
    ];

    /** @var \Drupal\Core\Layout\LayoutDefinition[] $definitions */
    $definitions = $this
      ->getDefinitions();
    foreach ($definitions as $definition) {
      if ($template = $definition
        ->getTemplate()) {
        $hooks[$definition
          ->getThemeHook()] = [
          'render element' => 'content',
          'base hook' => 'layout',
          'template' => $template,
          'path' => $definition
            ->getTemplatePath(),
        ];
      }
    }
    return $hooks;
  }

  /**
   * {@inheritdoc}
   */
  public function getCategories() {

    // Fetch all categories from definitions and remove duplicates.
    $categories = array_unique(array_values(array_map(function (LayoutDefinition $definition) {
      return $definition
        ->getCategory();
    }, $this
      ->getDefinitions())));
    natcasesort($categories);
    return $categories;
  }

  /**
   * {@inheritdoc}
   *
   * @return \Drupal\Core\Layout\LayoutDefinition[]
   */
  public function getSortedDefinitions(array $definitions = NULL, $label_key = 'label') {

    // Sort the plugins first by category, then by label.
    $definitions = isset($definitions) ? $definitions : $this
      ->getDefinitions();

    // Suppress errors because PHPUnit will indirectly modify the contents,
    // triggering https://bugs.php.net/bug.php?id=50688.
    @uasort($definitions, function (LayoutDefinition $a, LayoutDefinition $b) {
      if ($a
        ->getCategory() != $b
        ->getCategory()) {
        return strnatcasecmp($a
          ->getCategory(), $b
          ->getCategory());
      }
      return strnatcasecmp($a
        ->getLabel(), $b
        ->getLabel());
    });
    return $definitions;
  }

  /**
   * {@inheritdoc}
   *
   * @return \Drupal\Core\Layout\LayoutDefinition[][]
   */
  public function getGroupedDefinitions(array $definitions = NULL, $label_key = 'label') {
    $definitions = $this
      ->getSortedDefinitions(isset($definitions) ? $definitions : $this
      ->getDefinitions(), $label_key);
    $grouped_definitions = [];
    foreach ($definitions as $id => $definition) {
      $grouped_definitions[(string) $definition
        ->getCategory()][$id] = $definition;
    }
    return $grouped_definitions;
  }

  /**
   * {@inheritdoc}
   */
  public function getLayoutOptions() {
    $layout_options = [];
    foreach ($this
      ->getGroupedDefinitions() as $category => $layout_definitions) {
      foreach ($layout_definitions as $name => $layout_definition) {
        $layout_options[$category][$name] = $layout_definition
          ->getLabel();
      }
    }
    return $layout_options;
  }

}

Members

Namesort descending Modifiers Type Description Overrides
ContextAwarePluginManagerTrait::contextHandler protected function Wraps the context handler. 1
ContextAwarePluginManagerTrait::getDefinitions abstract public function See \Drupal\Component\Plugin\Discovery\DiscoveryInterface::getDefinitions(). 1
ContextAwarePluginManagerTrait::getDefinitionsForContexts public function See \Drupal\Core\Plugin\Context\ContextAwarePluginManagerInterface::getDefinitionsForContexts().
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::getFactory protected function Gets the plugin factory. Overrides PluginManagerBase::getFactory
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
FilteredPluginManagerTrait::getFilteredDefinitions public function Implements \Drupal\Core\Plugin\FilteredPluginManagerInterface::getFilteredDefinitions().
FilteredPluginManagerTrait::moduleHandler protected function Wraps the module handler. 1
FilteredPluginManagerTrait::themeManager protected function Wraps the theme manager. 1
LayoutPluginManager::$themeHandler protected property The theme handler.
LayoutPluginManager::getCategories public function Gets the names of all categories. Overrides CategorizingPluginManagerInterface::getCategories
LayoutPluginManager::getDiscovery protected function Gets the plugin discovery. Overrides DefaultPluginManager::getDiscovery
LayoutPluginManager::getGroupedDefinitions public function Overrides LayoutPluginManagerInterface::getGroupedDefinitions
LayoutPluginManager::getLayoutOptions public function Returns an array of layout labels grouped by category. Overrides LayoutPluginManagerInterface::getLayoutOptions
LayoutPluginManager::getSortedDefinitions public function Overrides LayoutPluginManagerInterface::getSortedDefinitions
LayoutPluginManager::getThemeImplementations public function Gets theme implementations for layouts. Overrides LayoutPluginManagerInterface::getThemeImplementations
LayoutPluginManager::getType protected function A string identifying the plugin type. Overrides FilteredPluginManagerTrait::getType
LayoutPluginManager::processDefinition public function Performs extra processing on plugin definitions. Overrides DefaultPluginManager::processDefinition
LayoutPluginManager::providerExists protected function Determines if the provider of a definition exists. Overrides DefaultPluginManager::providerExists
LayoutPluginManager::__construct public function LayoutPluginManager constructor. 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.