DefaultPluginManager.php 11 KB
Newer Older
1 2 3 4
<?php

namespace Drupal\Core\Plugin;

5
use Drupal\Component\Plugin\Definition\PluginDefinitionInterface;
6
use Drupal\Component\Plugin\Discovery\CachedDiscoveryInterface;
7
use Drupal\Core\Cache\CacheableDependencyInterface;
8 9
use Drupal\Core\Cache\CacheBackendInterface;
use Drupal\Core\Cache\UseCacheBackendTrait;
10
use Drupal\Component\Plugin\Discovery\DiscoveryCachedTrait;
11
use Drupal\Core\Plugin\Discovery\ContainerDerivativeDiscoveryDecorator;
12 13 14
use Drupal\Component\Plugin\PluginManagerBase;
use Drupal\Component\Plugin\PluginManagerInterface;
use Drupal\Component\Utility\NestedArray;
15
use Drupal\Core\Cache\Cache;
16 17 18 19 20 21
use Drupal\Core\Extension\ModuleHandlerInterface;
use Drupal\Core\Plugin\Discovery\AnnotatedClassDiscovery;
use Drupal\Core\Plugin\Factory\ContainerFactory;

/**
 * Base class for plugin managers.
22 23
 *
 * @ingroup plugin_api
24
 */
25
class DefaultPluginManager extends PluginManagerBase implements PluginManagerInterface, CachedDiscoveryInterface, CacheableDependencyInterface {
26

27
  use DiscoveryCachedTrait;
28
  use UseCacheBackendTrait;
29 30

  /**
31
   * The cache key.
32 33 34 35 36
   *
   * @var string
   */
  protected $cacheKey;

37 38 39 40 41
  /**
   * An array of cache tags to use for the cached definitions.
   *
   * @var array
   */
42
  protected $cacheTags = [];
43

44 45 46 47 48 49 50 51
  /**
   * Name of the alter hook if one should be invoked.
   *
   * @var string
   */
  protected $alterHook;

  /**
52 53
   * The subdirectory within a namespace to look for plugins, or FALSE if the
   * plugins are in the top level of the namespace.
54
   *
55
   * @var string|bool
56 57 58 59 60 61 62 63 64 65
   */
  protected $subdir;

  /**
   * The module handler to invoke the alter hook.
   *
   * @var \Drupal\Core\Extension\ModuleHandlerInterface
   */
  protected $moduleHandler;

66 67 68 69 70 71 72
  /**
   * A set of defaults to be referenced by $this->processDefinition() if
   * additional processing of plugins is necessary or helpful for development
   * purposes.
   *
   * @var array
   */
73
  protected $defaults = [];
74

75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96
  /**
   * The name of the annotation that contains the plugin definition.
   *
   * @var string
   */
  protected $pluginDefinitionAnnotationName;

  /**
   * The interface each plugin should implement.
   *
   * @var string|null
   */
  protected $pluginInterface;

  /**
   * An object that implements \Traversable which contains the root paths
   * keyed by the corresponding namespace to look for plugin implementations.
   *
   * @var \Traversable
   */
  protected $namespaces;

97 98 99 100 101 102 103 104
  /**
   * Additional namespaces the annotation discovery mechanism should scan for
   * annotation definitions.
   *
   * @var string[]
   */
  protected $additionalAnnotationNamespaces = [];

105 106 107
  /**
   * Creates the discovery object.
   *
108 109
   * @param string|bool $subdir
   *   The plugin's subdirectory, for example Plugin/views/filter.
110 111
   * @param \Traversable $namespaces
   *   An object that implements \Traversable which contains the root paths
112
   *   keyed by the corresponding namespace to look for plugin implementations.
113 114
   * @param \Drupal\Core\Extension\ModuleHandlerInterface $module_handler
   *   The module handler.
115 116
   * @param string|null $plugin_interface
   *   (optional) The interface each plugin should implement.
117 118 119
   * @param string $plugin_definition_annotation_name
   *   (optional) The name of the annotation that contains the plugin definition.
   *   Defaults to 'Drupal\Component\Annotation\Plugin'.
120 121
   * @param string[] $additional_annotation_namespaces
   *   (optional) Additional namespaces to scan for annotation definitions.
122
   */
123
  public function __construct($subdir, \Traversable $namespaces, ModuleHandlerInterface $module_handler, $plugin_interface = NULL, $plugin_definition_annotation_name = 'Drupal\Component\Annotation\Plugin', array $additional_annotation_namespaces = []) {
124
    $this->subdir = $subdir;
125 126 127
    $this->namespaces = $namespaces;
    $this->pluginDefinitionAnnotationName = $plugin_definition_annotation_name;
    $this->pluginInterface = $plugin_interface;
128
    $this->moduleHandler = $module_handler;
129
    $this->additionalAnnotationNamespaces = $additional_annotation_namespaces;
130 131 132 133 134
  }

  /**
   * Initialize the cache backend.
   *
135
   * Plugin definitions are cached using the provided cache backend.
136 137 138
   *
   * @param \Drupal\Core\Cache\CacheBackendInterface $cache_backend
   *   Cache backend instance to use.
139
   * @param string $cache_key
140
   *   Cache key prefix to use.
141
   * @param array $cache_tags
142 143 144 145 146 147 148
   *   (optional) When providing a list of cache tags, the cached plugin
   *   definitions are tagged with the provided cache tags. These cache tags can
   *   then be used to clear the corresponding cached plugin definitions. Note
   *   that this should be used with care! For clearing all cached plugin
   *   definitions of a plugin manager, call that plugin manager's
   *   clearCachedDefinitions() method. Only use cache tags when cached plugin
   *   definitions should be cleared along with other, related cache entries.
149
   */
150
  public function setCacheBackend(CacheBackendInterface $cache_backend, $cache_key, array $cache_tags = []) {
151
    assert('\Drupal\Component\Assertion\Inspector::assertAllStrings($cache_tags)', 'Cache Tags must be strings.');
152
    $this->cacheBackend = $cache_backend;
153
    $this->cacheKey = $cache_key;
154
    $this->cacheTags = $cache_tags;
155 156 157 158 159 160
  }

  /**
   * Initializes the alter hook.
   *
   * @param string $alter_hook
161 162
   *   Name of the alter hook; for example, to invoke
   *   hook_mymodule_data_alter() pass in "mymodule_data".
163
   */
164
  protected function alterInfo($alter_hook) {
165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184
    $this->alterHook = $alter_hook;
  }

  /**
   * {@inheritdoc}
   */
  public function getDefinitions() {
    $definitions = $this->getCachedDefinitions();
    if (!isset($definitions)) {
      $definitions = $this->findDefinitions();
      $this->setCachedDefinitions($definitions);
    }
    return $definitions;
  }

  /**
   * {@inheritdoc}
   */
  public function clearCachedDefinitions() {
    if ($this->cacheBackend) {
185 186
      if ($this->cacheTags) {
        // Use the cache tags to clear the cache.
187
        Cache::invalidateTags($this->cacheTags);
188
      }
189 190 191
      else {
        $this->cacheBackend->delete($this->cacheKey);
      }
192 193 194 195 196 197 198
    }
    $this->definitions = NULL;
  }

  /**
   * Returns the cached plugin definitions of the decorated discovery class.
   *
199
   * @return array|null
200 201 202 203 204 205
   *   On success this will return an array of plugin definitions. On failure
   *   this should return NULL, indicating to other methods that this has not
   *   yet been defined. Success with no values should return as an empty array
   *   and would actually be returned by the getDefinitions() method.
   */
  protected function getCachedDefinitions() {
206
    if (!isset($this->definitions) && $cache = $this->cacheGet($this->cacheKey)) {
207 208 209 210 211 212 213 214 215 216 217 218
      $this->definitions = $cache->data;
    }
    return $this->definitions;
  }

  /**
   * Sets a cache of plugin definitions for the decorated discovery class.
   *
   * @param array $definitions
   *   List of definitions to store in cache.
   */
  protected function setCachedDefinitions($definitions) {
219
    $this->cacheSet($this->cacheKey, $definitions, Cache::PERMANENT, $this->cacheTags);
220 221 222
    $this->definitions = $definitions;
  }

223 224 225 226 227 228 229 230 231 232
  /**
   * {@inheritdoc}
   */
  public function useCaches($use_caches = FALSE) {
    $this->useCaches = $use_caches;
    if (!$use_caches) {
      $this->definitions = NULL;
    }
  }

233 234 235 236 237 238 239 240
  /**
   * Performs extra processing on plugin definitions.
   *
   * By default we add defaults for the type to the definition. If a type has
   * additional processing logic they can do that by replacing or extending the
   * method.
   */
  public function processDefinition(&$definition, $plugin_id) {
241 242 243
    // Only array-based definitions can have defaults merged in.
    if (is_array($definition) && !empty($this->defaults) && is_array($this->defaults)) {
      $definition = NestedArray::mergeDeep($this->defaults, $definition);
244 245
    }

246 247 248 249 250 251
    // Keep class definitions standard with no leading slash.
    if ($definition instanceof PluginDefinitionInterface) {
      $definition->setClass(ltrim($definition->getClass(), '\\'));
    }
    elseif (is_array($definition) && isset($definition['class'])) {
      $definition['class'] = ltrim($definition['class'], '\\');
252 253 254
    }
  }

255 256 257 258 259
  /**
   * {@inheritdoc}
   */
  protected function getDiscovery() {
    if (!$this->discovery) {
260
      $discovery = new AnnotatedClassDiscovery($this->subdir, $this->namespaces, $this->pluginDefinitionAnnotationName, $this->additionalAnnotationNamespaces);
261 262 263 264 265 266 267 268 269 270 271 272 273 274 275
      $this->discovery = new ContainerDerivativeDiscoveryDecorator($discovery);
    }
    return $this->discovery;
  }

  /**
   * {@inheritdoc}
   */
  protected function getFactory() {
    if (!$this->factory) {
      $this->factory = new ContainerFactory($this, $this->pluginInterface);
    }
    return $this->factory;
  }

276 277 278 279 280 281 282
  /**
   * Finds plugin definitions.
   *
   * @return array
   *   List of definitions to store in cache.
   */
  protected function findDefinitions() {
283
    $definitions = $this->getDiscovery()->getDefinitions();
284 285 286
    foreach ($definitions as $plugin_id => &$definition) {
      $this->processDefinition($definition, $plugin_id);
    }
287
    $this->alterDefinitions($definitions);
288 289 290
    // If this plugin was provided by a module that does not exist, remove the
    // plugin definition.
    foreach ($definitions as $plugin_id => $plugin_definition) {
291
      $provider = $this->extractProviderFromDefinition($plugin_definition);
292
      if ($provider && !in_array($provider, ['core', 'component']) && !$this->providerExists($provider)) {
293 294 295
        unset($definitions[$plugin_id]);
      }
    }
296 297 298
    return $definitions;
  }

299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323
  /**
   * Extracts the provider from a plugin definition.
   *
   * @param mixed $plugin_definition
   *   The plugin definition. Usually either an array or an instance of
   *   \Drupal\Component\Plugin\Definition\PluginDefinitionInterface
   *
   * @return string|null
   *   The provider string, if it exists. NULL otherwise.
   */
  protected function extractProviderFromDefinition($plugin_definition) {
    if ($plugin_definition instanceof PluginDefinitionInterface) {
      return $plugin_definition->getProvider();
    }

    // Attempt to convert the plugin definition to an array.
    if (is_object($plugin_definition)) {
      $plugin_definition = (array) $plugin_definition;
    }

    if (isset($plugin_definition['provider'])) {
      return $plugin_definition['provider'];
    }
  }

324 325 326 327
  /**
   * Invokes the hook to alter the definitions if the alter hook is set.
   *
   * @param $definitions
328
   *   The discovered plugin definitions.
329 330 331 332 333 334 335
   */
  protected function alterDefinitions(&$definitions) {
    if ($this->alterHook) {
      $this->moduleHandler->alter($this->alterHook, $definitions);
    }
  }

336 337 338
  /**
   * Determines if the provider of a definition exists.
   *
339
   * @return bool
340 341 342 343 344 345
   *   TRUE if provider exists, FALSE otherwise.
   */
  protected function providerExists($provider) {
    return $this->moduleHandler->moduleExists($provider);
  }

346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366
  /**
   * {@inheritdoc}
   */
  public function getCacheContexts() {
    return [];
  }

  /**
   * {@inheritdoc}
   */
  public function getCacheTags() {
    return $this->cacheTags;
  }

  /**
   * {@inheritdoc}
   */
  public function getCacheMaxAge() {
    return CACHE::PERMANENT;
  }

367
}