DefaultPluginManager.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368
  1. <?php
  2. namespace Drupal\Core\Plugin;
  3. use Drupal\Component\Assertion\Inspector;
  4. use Drupal\Component\Plugin\Definition\PluginDefinitionInterface;
  5. use Drupal\Component\Plugin\Discovery\CachedDiscoveryInterface;
  6. use Drupal\Core\Cache\CacheableDependencyInterface;
  7. use Drupal\Core\Cache\CacheBackendInterface;
  8. use Drupal\Core\Cache\UseCacheBackendTrait;
  9. use Drupal\Component\Plugin\Discovery\DiscoveryCachedTrait;
  10. use Drupal\Core\Plugin\Discovery\ContainerDerivativeDiscoveryDecorator;
  11. use Drupal\Component\Plugin\PluginManagerBase;
  12. use Drupal\Component\Plugin\PluginManagerInterface;
  13. use Drupal\Component\Utility\NestedArray;
  14. use Drupal\Core\Cache\Cache;
  15. use Drupal\Core\Extension\ModuleHandlerInterface;
  16. use Drupal\Core\Plugin\Discovery\AnnotatedClassDiscovery;
  17. use Drupal\Core\Plugin\Factory\ContainerFactory;
  18. /**
  19. * Base class for plugin managers.
  20. *
  21. * @ingroup plugin_api
  22. */
  23. class DefaultPluginManager extends PluginManagerBase implements PluginManagerInterface, CachedDiscoveryInterface, CacheableDependencyInterface {
  24. use DiscoveryCachedTrait;
  25. use UseCacheBackendTrait;
  26. /**
  27. * The cache key.
  28. *
  29. * @var string
  30. */
  31. protected $cacheKey;
  32. /**
  33. * An array of cache tags to use for the cached definitions.
  34. *
  35. * @var array
  36. */
  37. protected $cacheTags = [];
  38. /**
  39. * Name of the alter hook if one should be invoked.
  40. *
  41. * @var string
  42. */
  43. protected $alterHook;
  44. /**
  45. * The subdirectory within a namespace to look for plugins, or FALSE if the
  46. * plugins are in the top level of the namespace.
  47. *
  48. * @var string|bool
  49. */
  50. protected $subdir;
  51. /**
  52. * The module handler to invoke the alter hook.
  53. *
  54. * @var \Drupal\Core\Extension\ModuleHandlerInterface
  55. */
  56. protected $moduleHandler;
  57. /**
  58. * A set of defaults to be referenced by $this->processDefinition() if
  59. * additional processing of plugins is necessary or helpful for development
  60. * purposes.
  61. *
  62. * @var array
  63. */
  64. protected $defaults = [];
  65. /**
  66. * The name of the annotation that contains the plugin definition.
  67. *
  68. * @var string
  69. */
  70. protected $pluginDefinitionAnnotationName;
  71. /**
  72. * The interface each plugin should implement.
  73. *
  74. * @var string|null
  75. */
  76. protected $pluginInterface;
  77. /**
  78. * An object that implements \Traversable which contains the root paths
  79. * keyed by the corresponding namespace to look for plugin implementations.
  80. *
  81. * @var \Traversable
  82. */
  83. protected $namespaces;
  84. /**
  85. * Additional namespaces the annotation discovery mechanism should scan for
  86. * annotation definitions.
  87. *
  88. * @var string[]
  89. */
  90. protected $additionalAnnotationNamespaces = [];
  91. /**
  92. * Creates the discovery object.
  93. *
  94. * @param string|bool $subdir
  95. * The plugin's subdirectory, for example Plugin/views/filter.
  96. * @param \Traversable $namespaces
  97. * An object that implements \Traversable which contains the root paths
  98. * keyed by the corresponding namespace to look for plugin implementations.
  99. * @param \Drupal\Core\Extension\ModuleHandlerInterface $module_handler
  100. * The module handler.
  101. * @param string|null $plugin_interface
  102. * (optional) The interface each plugin should implement.
  103. * @param string $plugin_definition_annotation_name
  104. * (optional) The name of the annotation that contains the plugin definition.
  105. * Defaults to 'Drupal\Component\Annotation\Plugin'.
  106. * @param string[] $additional_annotation_namespaces
  107. * (optional) Additional namespaces to scan for annotation definitions.
  108. */
  109. public function __construct($subdir, \Traversable $namespaces, ModuleHandlerInterface $module_handler, $plugin_interface = NULL, $plugin_definition_annotation_name = 'Drupal\Component\Annotation\Plugin', array $additional_annotation_namespaces = []) {
  110. $this->subdir = $subdir;
  111. $this->namespaces = $namespaces;
  112. $this->pluginDefinitionAnnotationName = $plugin_definition_annotation_name;
  113. $this->pluginInterface = $plugin_interface;
  114. $this->moduleHandler = $module_handler;
  115. $this->additionalAnnotationNamespaces = $additional_annotation_namespaces;
  116. }
  117. /**
  118. * Initialize the cache backend.
  119. *
  120. * Plugin definitions are cached using the provided cache backend.
  121. *
  122. * @param \Drupal\Core\Cache\CacheBackendInterface $cache_backend
  123. * Cache backend instance to use.
  124. * @param string $cache_key
  125. * Cache key prefix to use.
  126. * @param array $cache_tags
  127. * (optional) When providing a list of cache tags, the cached plugin
  128. * definitions are tagged with the provided cache tags. These cache tags can
  129. * then be used to clear the corresponding cached plugin definitions. Note
  130. * that this should be used with care! For clearing all cached plugin
  131. * definitions of a plugin manager, call that plugin manager's
  132. * clearCachedDefinitions() method. Only use cache tags when cached plugin
  133. * definitions should be cleared along with other, related cache entries.
  134. */
  135. public function setCacheBackend(CacheBackendInterface $cache_backend, $cache_key, array $cache_tags = []) {
  136. assert(Inspector::assertAllStrings($cache_tags), 'Cache Tags must be strings.');
  137. $this->cacheBackend = $cache_backend;
  138. $this->cacheKey = $cache_key;
  139. $this->cacheTags = $cache_tags;
  140. }
  141. /**
  142. * Sets the alter hook name.
  143. *
  144. * @param string $alter_hook
  145. * Name of the alter hook; for example, to invoke
  146. * hook_mymodule_data_alter() pass in "mymodule_data".
  147. */
  148. protected function alterInfo($alter_hook) {
  149. $this->alterHook = $alter_hook;
  150. }
  151. /**
  152. * {@inheritdoc}
  153. */
  154. public function getDefinitions() {
  155. $definitions = $this->getCachedDefinitions();
  156. if (!isset($definitions)) {
  157. $definitions = $this->findDefinitions();
  158. $this->setCachedDefinitions($definitions);
  159. }
  160. return $definitions;
  161. }
  162. /**
  163. * {@inheritdoc}
  164. */
  165. public function clearCachedDefinitions() {
  166. if ($this->cacheBackend) {
  167. if ($this->cacheTags) {
  168. // Use the cache tags to clear the cache.
  169. Cache::invalidateTags($this->cacheTags);
  170. }
  171. else {
  172. $this->cacheBackend->delete($this->cacheKey);
  173. }
  174. }
  175. $this->definitions = NULL;
  176. }
  177. /**
  178. * Returns the cached plugin definitions of the decorated discovery class.
  179. *
  180. * @return array|null
  181. * On success this will return an array of plugin definitions. On failure
  182. * this should return NULL, indicating to other methods that this has not
  183. * yet been defined. Success with no values should return as an empty array
  184. * and would actually be returned by the getDefinitions() method.
  185. */
  186. protected function getCachedDefinitions() {
  187. if (!isset($this->definitions) && $cache = $this->cacheGet($this->cacheKey)) {
  188. $this->definitions = $cache->data;
  189. }
  190. return $this->definitions;
  191. }
  192. /**
  193. * Sets a cache of plugin definitions for the decorated discovery class.
  194. *
  195. * @param array $definitions
  196. * List of definitions to store in cache.
  197. */
  198. protected function setCachedDefinitions($definitions) {
  199. $this->cacheSet($this->cacheKey, $definitions, Cache::PERMANENT, $this->cacheTags);
  200. $this->definitions = $definitions;
  201. }
  202. /**
  203. * {@inheritdoc}
  204. */
  205. public function useCaches($use_caches = FALSE) {
  206. $this->useCaches = $use_caches;
  207. if (!$use_caches) {
  208. $this->definitions = NULL;
  209. }
  210. }
  211. /**
  212. * Performs extra processing on plugin definitions.
  213. *
  214. * By default we add defaults for the type to the definition. If a type has
  215. * additional processing logic they can do that by replacing or extending the
  216. * method.
  217. */
  218. public function processDefinition(&$definition, $plugin_id) {
  219. // Only array-based definitions can have defaults merged in.
  220. if (is_array($definition) && !empty($this->defaults) && is_array($this->defaults)) {
  221. $definition = NestedArray::mergeDeep($this->defaults, $definition);
  222. }
  223. // Keep class definitions standard with no leading slash.
  224. if ($definition instanceof PluginDefinitionInterface) {
  225. $definition->setClass(ltrim($definition->getClass(), '\\'));
  226. }
  227. elseif (is_array($definition) && isset($definition['class'])) {
  228. $definition['class'] = ltrim($definition['class'], '\\');
  229. }
  230. }
  231. /**
  232. * {@inheritdoc}
  233. */
  234. protected function getDiscovery() {
  235. if (!$this->discovery) {
  236. $discovery = new AnnotatedClassDiscovery($this->subdir, $this->namespaces, $this->pluginDefinitionAnnotationName, $this->additionalAnnotationNamespaces);
  237. $this->discovery = new ContainerDerivativeDiscoveryDecorator($discovery);
  238. }
  239. return $this->discovery;
  240. }
  241. /**
  242. * {@inheritdoc}
  243. */
  244. protected function getFactory() {
  245. if (!$this->factory) {
  246. $this->factory = new ContainerFactory($this, $this->pluginInterface);
  247. }
  248. return $this->factory;
  249. }
  250. /**
  251. * Finds plugin definitions.
  252. *
  253. * @return array
  254. * List of definitions to store in cache.
  255. */
  256. protected function findDefinitions() {
  257. $definitions = $this->getDiscovery()->getDefinitions();
  258. foreach ($definitions as $plugin_id => &$definition) {
  259. $this->processDefinition($definition, $plugin_id);
  260. }
  261. $this->alterDefinitions($definitions);
  262. // If this plugin was provided by a module that does not exist, remove the
  263. // plugin definition.
  264. foreach ($definitions as $plugin_id => $plugin_definition) {
  265. $provider = $this->extractProviderFromDefinition($plugin_definition);
  266. if ($provider && !in_array($provider, ['core', 'component']) && !$this->providerExists($provider)) {
  267. unset($definitions[$plugin_id]);
  268. }
  269. }
  270. return $definitions;
  271. }
  272. /**
  273. * Extracts the provider from a plugin definition.
  274. *
  275. * @param mixed $plugin_definition
  276. * The plugin definition. Usually either an array or an instance of
  277. * \Drupal\Component\Plugin\Definition\PluginDefinitionInterface
  278. *
  279. * @return string|null
  280. * The provider string, if it exists. NULL otherwise.
  281. */
  282. protected function extractProviderFromDefinition($plugin_definition) {
  283. if ($plugin_definition instanceof PluginDefinitionInterface) {
  284. return $plugin_definition->getProvider();
  285. }
  286. // Attempt to convert the plugin definition to an array.
  287. if (is_object($plugin_definition)) {
  288. $plugin_definition = (array) $plugin_definition;
  289. }
  290. if (isset($plugin_definition['provider'])) {
  291. return $plugin_definition['provider'];
  292. }
  293. }
  294. /**
  295. * Invokes the hook to alter the definitions if the alter hook is set.
  296. *
  297. * @param $definitions
  298. * The discovered plugin definitions.
  299. */
  300. protected function alterDefinitions(&$definitions) {
  301. if ($this->alterHook) {
  302. $this->moduleHandler->alter($this->alterHook, $definitions);
  303. }
  304. }
  305. /**
  306. * Determines if the provider of a definition exists.
  307. *
  308. * @return bool
  309. * TRUE if provider exists, FALSE otherwise.
  310. */
  311. protected function providerExists($provider) {
  312. return $this->moduleHandler->moduleExists($provider);
  313. }
  314. /**
  315. * {@inheritdoc}
  316. */
  317. public function getCacheContexts() {
  318. return [];
  319. }
  320. /**
  321. * {@inheritdoc}
  322. */
  323. public function getCacheTags() {
  324. return $this->cacheTags;
  325. }
  326. /**
  327. * {@inheritdoc}
  328. */
  329. public function getCacheMaxAge() {
  330. return Cache::PERMANENT;
  331. }
  332. }