Pull merge.
[yaffs-website] / web / core / lib / Drupal / Core / Layout / LayoutPluginManager.php
1 <?php
2
3 namespace Drupal\Core\Layout;
4
5 use Drupal\Component\Annotation\Plugin\Discovery\AnnotationBridgeDecorator;
6 use Drupal\Component\Plugin\Exception\InvalidPluginDefinitionException;
7 use Drupal\Core\Cache\CacheBackendInterface;
8 use Drupal\Core\Extension\ModuleHandlerInterface;
9 use Drupal\Core\Extension\ThemeHandlerInterface;
10 use Drupal\Core\Plugin\DefaultPluginManager;
11 use Drupal\Core\Plugin\Discovery\AnnotatedClassDiscovery;
12 use Drupal\Core\Plugin\Discovery\ContainerDerivativeDiscoveryDecorator;
13 use Drupal\Core\Plugin\Discovery\YamlDiscoveryDecorator;
14 use Drupal\Core\Layout\Annotation\Layout;
15 use Drupal\Core\Plugin\FilteredPluginManagerTrait;
16 use Drupal\Core\StringTranslation\TranslatableMarkup;
17
18 /**
19  * Provides a plugin manager for layouts.
20  */
21 class LayoutPluginManager extends DefaultPluginManager implements LayoutPluginManagerInterface {
22
23   use FilteredPluginManagerTrait;
24
25   /**
26    * The theme handler.
27    *
28    * @var \Drupal\Core\Extension\ThemeHandlerInterface
29    */
30   protected $themeHandler;
31
32   /**
33    * LayoutPluginManager constructor.
34    *
35    * @param \Traversable $namespaces
36    *   An object that implements \Traversable which contains the root paths
37    *   keyed by the corresponding namespace to look for plugin implementations.
38    * @param \Drupal\Core\Cache\CacheBackendInterface $cache_backend
39    *   Cache backend instance to use.
40    * @param \Drupal\Core\Extension\ModuleHandlerInterface $module_handler
41    *   The module handler to invoke the alter hook with.
42    * @param \Drupal\Core\Extension\ThemeHandlerInterface $theme_handler
43    *   The theme handler to invoke the alter hook with.
44    */
45   public function __construct(\Traversable $namespaces, CacheBackendInterface $cache_backend, ModuleHandlerInterface $module_handler, ThemeHandlerInterface $theme_handler) {
46     parent::__construct('Plugin/Layout', $namespaces, $module_handler, LayoutInterface::class, Layout::class);
47     $this->themeHandler = $theme_handler;
48
49     $type = $this->getType();
50     $this->setCacheBackend($cache_backend, $type);
51     $this->alterInfo($type);
52   }
53
54   /**
55    * {@inheritdoc}
56    */
57   protected function getType() {
58     return 'layout';
59   }
60
61   /**
62    * {@inheritdoc}
63    */
64   protected function providerExists($provider) {
65     return $this->moduleHandler->moduleExists($provider) || $this->themeHandler->themeExists($provider);
66   }
67
68   /**
69    * {@inheritdoc}
70    */
71   protected function getDiscovery() {
72     if (!$this->discovery) {
73       $discovery = new AnnotatedClassDiscovery($this->subdir, $this->namespaces, $this->pluginDefinitionAnnotationName, $this->additionalAnnotationNamespaces);
74       $discovery = new YamlDiscoveryDecorator($discovery, 'layouts', $this->moduleHandler->getModuleDirectories() + $this->themeHandler->getThemeDirectories());
75       $discovery
76         ->addTranslatableProperty('label')
77         ->addTranslatableProperty('description')
78         ->addTranslatableProperty('category');
79       $discovery = new AnnotationBridgeDecorator($discovery, $this->pluginDefinitionAnnotationName);
80       $discovery = new ContainerDerivativeDiscoveryDecorator($discovery);
81       $this->discovery = $discovery;
82     }
83     return $this->discovery;
84   }
85
86   /**
87    * {@inheritdoc}
88    */
89   public function processDefinition(&$definition, $plugin_id) {
90     parent::processDefinition($definition, $plugin_id);
91
92     if (!$definition instanceof LayoutDefinition) {
93       throw new InvalidPluginDefinitionException($plugin_id, sprintf('The "%s" layout definition must extend %s', $plugin_id, LayoutDefinition::class));
94     }
95
96     // Add the module or theme path to the 'path'.
97     $provider = $definition->getProvider();
98     if ($this->moduleHandler->moduleExists($provider)) {
99       $base_path = $this->moduleHandler->getModule($provider)->getPath();
100     }
101     elseif ($this->themeHandler->themeExists($provider)) {
102       $base_path = $this->themeHandler->getTheme($provider)->getPath();
103     }
104     else {
105       $base_path = '';
106     }
107
108     $path = $definition->getPath();
109     $path = !empty($path) ? $base_path . '/' . $path : $base_path;
110     $definition->setPath($path);
111
112     // Add the base path to the icon path.
113     if ($icon_path = $definition->getIconPath()) {
114       $definition->setIconPath($path . '/' . $icon_path);
115     }
116
117     // Add a dependency on the provider of the library.
118     if ($library = $definition->getLibrary()) {
119       $config_dependencies = $definition->getConfigDependencies();
120       list($library_provider) = explode('/', $library, 2);
121       if ($this->moduleHandler->moduleExists($library_provider)) {
122         $config_dependencies['module'][] = $library_provider;
123       }
124       elseif ($this->themeHandler->themeExists($library_provider)) {
125         $config_dependencies['theme'][] = $library_provider;
126       }
127       $definition->setConfigDependencies($config_dependencies);
128     }
129
130     // If 'template' is set, then we'll derive 'template_path' and 'theme_hook'.
131     $template = $definition->getTemplate();
132     if (!empty($template)) {
133       $template_parts = explode('/', $template);
134
135       $template = array_pop($template_parts);
136       $template_path = $path;
137       if (count($template_parts) > 0) {
138         $template_path .= '/' . implode('/', $template_parts);
139       }
140       $definition->setTemplate($template);
141       $definition->setThemeHook(strtr($template, '-', '_'));
142       $definition->setTemplatePath($template_path);
143     }
144
145     if (!$definition->getDefaultRegion()) {
146       $definition->setDefaultRegion(key($definition->getRegions()));
147     }
148     // Makes sure region names are translatable.
149     $regions = array_map(function ($region) {
150       if (!$region['label'] instanceof TranslatableMarkup) {
151         // Region labels from YAML discovery needs translation.
152         $region['label'] = new TranslatableMarkup($region['label'], [], ['context' => 'layout_region']);
153       }
154       return $region;
155     }, $definition->getRegions());
156     $definition->setRegions($regions);
157   }
158
159   /**
160    * {@inheritdoc}
161    */
162   public function getThemeImplementations() {
163     $hooks = [];
164     $hooks['layout'] = [
165       'render element' => 'content',
166     ];
167     /** @var \Drupal\Core\Layout\LayoutDefinition[] $definitions */
168     $definitions = $this->getDefinitions();
169     foreach ($definitions as $definition) {
170       if ($template = $definition->getTemplate()) {
171         $hooks[$definition->getThemeHook()] = [
172           'render element' => 'content',
173           'base hook' => 'layout',
174           'template' => $template,
175           'path' => $definition->getTemplatePath(),
176         ];
177       }
178     }
179     return $hooks;
180   }
181
182   /**
183    * {@inheritdoc}
184    */
185   public function getCategories() {
186     // Fetch all categories from definitions and remove duplicates.
187     $categories = array_unique(array_values(array_map(function (LayoutDefinition $definition) {
188       return $definition->getCategory();
189     }, $this->getDefinitions())));
190     natcasesort($categories);
191     return $categories;
192   }
193
194   /**
195    * {@inheritdoc}
196    *
197    * @return \Drupal\Core\Layout\LayoutDefinition[]
198    */
199   public function getSortedDefinitions(array $definitions = NULL, $label_key = 'label') {
200     // Sort the plugins first by category, then by label.
201     $definitions = isset($definitions) ? $definitions : $this->getDefinitions();
202     // Suppress errors because PHPUnit will indirectly modify the contents,
203     // triggering https://bugs.php.net/bug.php?id=50688.
204     @uasort($definitions, function (LayoutDefinition $a, LayoutDefinition $b) {
205       if ($a->getCategory() != $b->getCategory()) {
206         return strnatcasecmp($a->getCategory(), $b->getCategory());
207       }
208       return strnatcasecmp($a->getLabel(), $b->getLabel());
209     });
210     return $definitions;
211   }
212
213   /**
214    * {@inheritdoc}
215    *
216    * @return \Drupal\Core\Layout\LayoutDefinition[][]
217    */
218   public function getGroupedDefinitions(array $definitions = NULL, $label_key = 'label') {
219     $definitions = $this->getSortedDefinitions(isset($definitions) ? $definitions : $this->getDefinitions(), $label_key);
220     $grouped_definitions = [];
221     foreach ($definitions as $id => $definition) {
222       $grouped_definitions[(string) $definition->getCategory()][$id] = $definition;
223     }
224     return $grouped_definitions;
225   }
226
227   /**
228    * {@inheritdoc}
229    */
230   public function getLayoutOptions() {
231     $layout_options = [];
232     foreach ($this->getGroupedDefinitions() as $category => $layout_definitions) {
233       foreach ($layout_definitions as $name => $layout_definition) {
234         $layout_options[$category][$name] = $layout_definition->getLabel();
235       }
236     }
237     return $layout_options;
238   }
239
240 }