0067ee8710aedea0897382635ffdc5942672d285
[yaffs-website] / web / core / lib / Drupal / Core / Theme / ThemeInitialization.php
1 <?php
2
3 namespace Drupal\Core\Theme;
4
5 use Drupal\Core\Cache\CacheBackendInterface;
6 use Drupal\Core\Extension\Extension;
7 use Drupal\Core\Extension\ModuleHandlerInterface;
8 use Drupal\Core\Extension\ThemeHandlerInterface;
9
10 /**
11  * Provides the theme initialization logic.
12  */
13 class ThemeInitialization implements ThemeInitializationInterface {
14
15   /**
16    * The theme handler.
17    *
18    * @var \Drupal\Core\Extension\ThemeHandlerInterface
19    */
20   protected $themeHandler;
21
22   /**
23    * The cache backend to use for the active theme.
24    *
25    * @var \Drupal\Core\Cache\CacheBackendInterface
26    */
27   protected $cache;
28
29   /**
30    * The app root.
31    *
32    * @var string
33    */
34   protected $root;
35
36   /**
37    * The extensions that might be attaching assets.
38    *
39    * @var array
40    */
41   protected $extensions;
42
43   /**
44    * The module handler.
45    *
46    * @var \Drupal\Core\Extension\ModuleHandlerInterface
47    */
48   protected $moduleHandler;
49
50   /**
51    * Constructs a new ThemeInitialization object.
52    *
53    * @param string $root
54    *   The app root.
55    * @param \Drupal\Core\Extension\ThemeHandlerInterface $theme_handler
56    *   The theme handler.
57    * @param \Drupal\Core\Cache\CacheBackendInterface $cache
58    *   The cache backend.
59    * @param \Drupal\Core\Extension\ModuleHandlerInterface $module_handler
60    *   The module handler to use to load modules.
61    */
62   public function __construct($root, ThemeHandlerInterface $theme_handler, CacheBackendInterface $cache, ModuleHandlerInterface $module_handler) {
63     $this->root = $root;
64     $this->themeHandler = $theme_handler;
65     $this->cache = $cache;
66     $this->moduleHandler = $module_handler;
67   }
68
69   /**
70    * {@inheritdoc}
71    */
72   public function initTheme($theme_name) {
73     $active_theme = $this->getActiveThemeByName($theme_name);
74     $this->loadActiveTheme($active_theme);
75
76     return $active_theme;
77   }
78
79   /**
80    * {@inheritdoc}
81    */
82   public function getActiveThemeByName($theme_name) {
83     if ($cached = $this->cache->get('theme.active_theme.' . $theme_name)) {
84       return $cached->data;
85     }
86     $themes = $this->themeHandler->listInfo();
87
88     // If no theme could be negotiated, or if the negotiated theme is not within
89     // the list of installed themes, fall back to the default theme output of
90     // core and modules (like Stark, but without a theme extension at all). This
91     // is possible, because loadActiveTheme() always loads the Twig theme
92     // engine. This is desired, because missing or malformed theme configuration
93     // should not leave the application in a broken state. By falling back to
94     // default output, the user is able to reconfigure the theme through the UI.
95     // Lastly, tests are expected to operate with no theme by default, so as to
96     // only assert the original theme output of modules (unless a test manually
97     // installs a specific theme).
98     if (empty($themes) || !$theme_name || !isset($themes[$theme_name])) {
99       $theme_name = 'core';
100       // /core/core.info.yml does not actually exist, but is required because
101       // Extension expects a pathname.
102       $active_theme = $this->getActiveTheme(new Extension($this->root, 'theme', 'core/core.info.yml'));
103
104       // Early-return and do not set state, because the initialized $theme_name
105       // differs from the original $theme_name.
106       return $active_theme;
107     }
108
109     // Find all our ancestor themes and put them in an array.
110     $base_themes = [];
111     $ancestor = $theme_name;
112     while ($ancestor && isset($themes[$ancestor]->base_theme)) {
113       $ancestor = $themes[$ancestor]->base_theme;
114       if (!$this->themeHandler->themeExists($ancestor)) {
115         if ($ancestor == 'stable') {
116           // Themes that depend on Stable will be fixed by system_update_8014().
117           // There is no harm in not adding it as an ancestor since at worst
118           // some people might experience slight visual regressions on
119           // update.php.
120           continue;
121         }
122         throw new MissingThemeDependencyException(sprintf('Base theme %s has not been installed.', $ancestor), $ancestor);
123       }
124       $base_themes[] = $themes[$ancestor];
125     }
126
127     $active_theme = $this->getActiveTheme($themes[$theme_name], $base_themes);
128
129     $this->cache->set('theme.active_theme.' . $theme_name, $active_theme);
130     return $active_theme;
131   }
132
133   /**
134    * {@inheritdoc}
135    */
136   public function loadActiveTheme(ActiveTheme $active_theme) {
137     // Initialize the theme.
138     if ($theme_engine = $active_theme->getEngine()) {
139       // Include the engine.
140       include_once $this->root . '/' . $active_theme->getOwner();
141
142       if (function_exists($theme_engine . '_init')) {
143         foreach ($active_theme->getBaseThemes() as $base) {
144           call_user_func($theme_engine . '_init', $base->getExtension());
145         }
146         call_user_func($theme_engine . '_init', $active_theme->getExtension());
147       }
148     }
149     else {
150       // include non-engine theme files
151       foreach ($active_theme->getBaseThemes() as $base) {
152         // Include the theme file or the engine.
153         if ($base->getOwner()) {
154           include_once $this->root . '/' . $base->getOwner();
155         }
156       }
157       // and our theme gets one too.
158       if ($active_theme->getOwner()) {
159         include_once $this->root . '/' . $active_theme->getOwner();
160       }
161     }
162
163     // Always include Twig as the default theme engine.
164     include_once $this->root . '/core/themes/engines/twig/twig.engine';
165   }
166
167   /**
168    * {@inheritdoc}
169    */
170   public function getActiveTheme(Extension $theme, array $base_themes = []) {
171     $theme_path = $theme->getPath();
172
173     $values['path'] = $theme_path;
174     $values['name'] = $theme->getName();
175
176     // @todo Remove in Drupal 9.0.x.
177     $values['stylesheets_remove'] = $this->prepareStylesheetsRemove($theme, $base_themes);
178
179     // Prepare libraries overrides from this theme and ancestor themes. This
180     // allows child themes to easily remove CSS files from base themes and
181     // modules.
182     $values['libraries_override'] = [];
183
184     // Get libraries overrides declared by base themes.
185     foreach ($base_themes as $base) {
186       if (!empty($base->info['libraries-override'])) {
187         foreach ($base->info['libraries-override'] as $library => $override) {
188           $values['libraries_override'][$base->getPath()][$library] = $override;
189         }
190       }
191     }
192
193     // Add libraries overrides declared by this theme.
194     if (!empty($theme->info['libraries-override'])) {
195       foreach ($theme->info['libraries-override'] as $library => $override) {
196         $values['libraries_override'][$theme->getPath()][$library] = $override;
197       }
198     }
199
200     // Get libraries extensions declared by base themes.
201     foreach ($base_themes as $base) {
202       if (!empty($base->info['libraries-extend'])) {
203         foreach ($base->info['libraries-extend'] as $library => $extend) {
204           if (isset($values['libraries_extend'][$library])) {
205             // Merge if libraries-extend has already been defined for this
206             // library.
207             $values['libraries_extend'][$library] = array_merge($values['libraries_extend'][$library], $extend);
208           }
209           else {
210             $values['libraries_extend'][$library] = $extend;
211           }
212         }
213       }
214     }
215     // Add libraries extensions declared by this theme.
216     if (!empty($theme->info['libraries-extend'])) {
217       foreach ($theme->info['libraries-extend'] as $library => $extend) {
218         if (isset($values['libraries_extend'][$library])) {
219           // Merge if libraries-extend has already been defined for this
220           // library.
221           $values['libraries_extend'][$library] = array_merge($values['libraries_extend'][$library], $extend);
222         }
223         else {
224           $values['libraries_extend'][$library] = $extend;
225         }
226       }
227     }
228
229     // Do basically the same as the above for libraries
230     $values['libraries'] = [];
231
232     // Grab libraries from base theme
233     foreach ($base_themes as $base) {
234       if (!empty($base->libraries)) {
235         foreach ($base->libraries as $library) {
236           $values['libraries'][] = $library;
237         }
238       }
239     }
240
241     // Add libraries used by this theme.
242     if (!empty($theme->libraries)) {
243       foreach ($theme->libraries as $library) {
244         $values['libraries'][] = $library;
245       }
246     }
247
248     $values['engine'] = isset($theme->engine) ? $theme->engine : NULL;
249     $values['owner'] = isset($theme->owner) ? $theme->owner : NULL;
250     $values['extension'] = $theme;
251
252     $base_active_themes = [];
253     foreach ($base_themes as $base_theme) {
254       $base_active_themes[$base_theme->getName()] = $this->getActiveTheme($base_theme, array_slice($base_themes, 1));
255     }
256
257     $values['base_themes'] = $base_active_themes;
258     if (!empty($theme->info['regions'])) {
259       $values['regions'] = $theme->info['regions'];
260     }
261
262     return new ActiveTheme($values);
263   }
264
265   /**
266    * Gets all extensions.
267    *
268    * @return array
269    */
270   protected function getExtensions() {
271     if (!isset($this->extensions)) {
272       $this->extensions = array_merge($this->moduleHandler->getModuleList(), $this->themeHandler->listInfo());
273     }
274     return $this->extensions;
275   }
276
277   /**
278    * Gets CSS file where tokens have been resolved.
279    *
280    * @param string $css_file
281    *   CSS file which may contain tokens.
282    *
283    * @return string
284    *   CSS file where placeholders are replaced.
285    *
286    * @todo Remove in Drupal 9.0.x.
287    */
288   protected function resolveStyleSheetPlaceholders($css_file) {
289     $token_candidate = explode('/', $css_file)[0];
290     if (!preg_match('/@[A-z0-9_-]+/', $token_candidate)) {
291       return $css_file;
292     }
293
294     $token = substr($token_candidate, 1);
295
296     // Prime extensions.
297     $extensions = $this->getExtensions();
298     if (isset($extensions[$token])) {
299       return str_replace($token_candidate, $extensions[$token]->getPath(), $css_file);
300     }
301   }
302
303   /**
304    * Prepares stylesheets-remove specified in the *.info.yml file.
305    *
306    * @param \Drupal\Core\Extension\Extension $theme
307    *   The theme extension object.
308    * @param \Drupal\Core\Extension\Extension[] $base_themes
309    *   An array of base themes.
310    *
311    * @return string[]
312    *   The list of stylesheets-remove specified in the *.info.yml file.
313    *
314    * @todo Remove in Drupal 9.0.x.
315    */
316   protected function prepareStylesheetsRemove(Extension $theme, $base_themes) {
317     // Prepare stylesheets from this theme as well as all ancestor themes.
318     // We work it this way so that we can have child themes remove CSS files
319     // easily from parent.
320     $stylesheets_remove = [];
321     // Grab stylesheets from base theme.
322     foreach ($base_themes as $base) {
323       if (!empty($base->info['stylesheets-remove'])) {
324         foreach ($base->info['stylesheets-remove'] as $css_file) {
325           $css_file = $this->resolveStyleSheetPlaceholders($css_file);
326           $stylesheets_remove[$css_file] = $css_file;
327         }
328       }
329     }
330
331     // Add stylesheets used by this theme.
332     if (!empty($theme->info['stylesheets-remove'])) {
333       foreach ($theme->info['stylesheets-remove'] as $css_file) {
334         $css_file = $this->resolveStyleSheetPlaceholders($css_file);
335         $stylesheets_remove[$css_file] = $css_file;
336       }
337     }
338     return $stylesheets_remove;
339   }
340
341 }