annotate core/lib/Drupal/Core/Theme/ThemeManager.php @ 19:fa3358dc1485 tip

Add ndrum files
author Chris Cannam
date Wed, 28 Aug 2019 13:14:47 +0100
parents af1871eacc83
children
rev   line source
Chris@0 1 <?php
Chris@0 2
Chris@0 3 namespace Drupal\Core\Theme;
Chris@0 4
Chris@0 5 use Drupal\Component\Render\MarkupInterface;
Chris@0 6 use Drupal\Core\Render\Markup;
Chris@0 7 use Drupal\Core\Routing\RouteMatchInterface;
Chris@0 8 use Drupal\Core\Routing\StackedRouteMatchInterface;
Chris@0 9 use Drupal\Core\Extension\ModuleHandlerInterface;
Chris@0 10 use Drupal\Core\Template\Attribute;
Chris@0 11
Chris@0 12 /**
Chris@0 13 * Provides the default implementation of a theme manager.
Chris@0 14 */
Chris@0 15 class ThemeManager implements ThemeManagerInterface {
Chris@0 16
Chris@0 17 /**
Chris@0 18 * The theme negotiator.
Chris@0 19 *
Chris@0 20 * @var \Drupal\Core\Theme\ThemeNegotiatorInterface
Chris@0 21 */
Chris@0 22 protected $themeNegotiator;
Chris@0 23
Chris@0 24 /**
Chris@0 25 * The theme registry used to render an output.
Chris@0 26 *
Chris@0 27 * @var \Drupal\Core\Theme\Registry
Chris@0 28 */
Chris@0 29 protected $themeRegistry;
Chris@0 30
Chris@0 31 /**
Chris@0 32 * Contains the current active theme.
Chris@0 33 *
Chris@0 34 * @var \Drupal\Core\Theme\ActiveTheme
Chris@0 35 */
Chris@0 36 protected $activeTheme;
Chris@0 37
Chris@0 38 /**
Chris@0 39 * The theme initialization.
Chris@0 40 *
Chris@0 41 * @var \Drupal\Core\Theme\ThemeInitializationInterface
Chris@0 42 */
Chris@0 43 protected $themeInitialization;
Chris@0 44
Chris@0 45 /**
Chris@0 46 * The module handler.
Chris@0 47 *
Chris@0 48 * @var \Drupal\Core\Extension\ModuleHandlerInterface
Chris@0 49 */
Chris@0 50 protected $moduleHandler;
Chris@0 51
Chris@0 52 /**
Chris@0 53 * The app root.
Chris@0 54 *
Chris@0 55 * @var string
Chris@0 56 */
Chris@0 57 protected $root;
Chris@0 58
Chris@0 59 /**
Chris@0 60 * Constructs a new ThemeManager object.
Chris@0 61 *
Chris@0 62 * @param string $root
Chris@0 63 * The app root.
Chris@0 64 * @param \Drupal\Core\Theme\ThemeNegotiatorInterface $theme_negotiator
Chris@0 65 * The theme negotiator.
Chris@0 66 * @param \Drupal\Core\Theme\ThemeInitializationInterface $theme_initialization
Chris@0 67 * The theme initialization.
Chris@0 68 * @param \Drupal\Core\Extension\ModuleHandlerInterface $module_handler
Chris@0 69 * The module handler.
Chris@0 70 */
Chris@0 71 public function __construct($root, ThemeNegotiatorInterface $theme_negotiator, ThemeInitializationInterface $theme_initialization, ModuleHandlerInterface $module_handler) {
Chris@0 72 $this->root = $root;
Chris@0 73 $this->themeNegotiator = $theme_negotiator;
Chris@0 74 $this->themeInitialization = $theme_initialization;
Chris@0 75 $this->moduleHandler = $module_handler;
Chris@0 76 }
Chris@0 77
Chris@0 78 /**
Chris@0 79 * Sets the theme registry.
Chris@0 80 *
Chris@0 81 * @param \Drupal\Core\Theme\Registry $theme_registry
Chris@0 82 * The theme registry.
Chris@0 83 *
Chris@0 84 * @return $this
Chris@0 85 */
Chris@0 86 public function setThemeRegistry(Registry $theme_registry) {
Chris@0 87 $this->themeRegistry = $theme_registry;
Chris@0 88 return $this;
Chris@0 89 }
Chris@0 90
Chris@0 91 /**
Chris@0 92 * {@inheritdoc}
Chris@0 93 */
Chris@0 94 public function getActiveTheme(RouteMatchInterface $route_match = NULL) {
Chris@0 95 if (!isset($this->activeTheme)) {
Chris@0 96 $this->initTheme($route_match);
Chris@0 97 }
Chris@0 98 return $this->activeTheme;
Chris@0 99 }
Chris@0 100
Chris@0 101 /**
Chris@0 102 * {@inheritdoc}
Chris@0 103 */
Chris@0 104 public function hasActiveTheme() {
Chris@0 105 return isset($this->activeTheme);
Chris@0 106 }
Chris@0 107
Chris@0 108 /**
Chris@0 109 * {@inheritdoc}
Chris@0 110 */
Chris@0 111 public function resetActiveTheme() {
Chris@0 112 $this->activeTheme = NULL;
Chris@0 113 return $this;
Chris@0 114 }
Chris@0 115
Chris@0 116 /**
Chris@0 117 * {@inheritdoc}
Chris@0 118 */
Chris@0 119 public function setActiveTheme(ActiveTheme $active_theme) {
Chris@0 120 $this->activeTheme = $active_theme;
Chris@0 121 if ($active_theme) {
Chris@0 122 $this->themeInitialization->loadActiveTheme($active_theme);
Chris@0 123 }
Chris@0 124 return $this;
Chris@0 125 }
Chris@0 126
Chris@0 127 /**
Chris@0 128 * {@inheritdoc}
Chris@0 129 */
Chris@0 130 public function render($hook, array $variables) {
Chris@0 131 static $default_attributes;
Chris@0 132
Chris@0 133 $active_theme = $this->getActiveTheme();
Chris@0 134
Chris@0 135 // If called before all modules are loaded, we do not necessarily have a
Chris@0 136 // full theme registry to work with, and therefore cannot process the theme
Chris@0 137 // request properly. See also \Drupal\Core\Theme\Registry::get().
Chris@0 138 if (!$this->moduleHandler->isLoaded() && !defined('MAINTENANCE_MODE')) {
Chris@0 139 throw new \Exception('The theme implementations may not be rendered until all modules are loaded.');
Chris@0 140 }
Chris@0 141
Chris@0 142 $theme_registry = $this->themeRegistry->getRuntime();
Chris@0 143
Chris@0 144 // If an array of hook candidates were passed, use the first one that has an
Chris@0 145 // implementation.
Chris@0 146 if (is_array($hook)) {
Chris@0 147 foreach ($hook as $candidate) {
Chris@0 148 if ($theme_registry->has($candidate)) {
Chris@0 149 break;
Chris@0 150 }
Chris@0 151 }
Chris@0 152 $hook = $candidate;
Chris@0 153 }
Chris@0 154 // Save the original theme hook, so it can be supplied to theme variable
Chris@0 155 // preprocess callbacks.
Chris@0 156 $original_hook = $hook;
Chris@0 157
Chris@0 158 // If there's no implementation, check for more generic fallbacks.
Chris@0 159 // If there's still no implementation, log an error and return an empty
Chris@0 160 // string.
Chris@0 161 if (!$theme_registry->has($hook)) {
Chris@0 162 // Iteratively strip everything after the last '__' delimiter, until an
Chris@0 163 // implementation is found.
Chris@0 164 while ($pos = strrpos($hook, '__')) {
Chris@0 165 $hook = substr($hook, 0, $pos);
Chris@0 166 if ($theme_registry->has($hook)) {
Chris@0 167 break;
Chris@0 168 }
Chris@0 169 }
Chris@0 170 if (!$theme_registry->has($hook)) {
Chris@0 171 // Only log a message when not trying theme suggestions ($hook being an
Chris@0 172 // array).
Chris@0 173 if (!isset($candidate)) {
Chris@0 174 \Drupal::logger('theme')->warning('Theme hook %hook not found.', ['%hook' => $hook]);
Chris@0 175 }
Chris@0 176 // There is no theme implementation for the hook passed. Return FALSE so
Chris@0 177 // the function calling
Chris@0 178 // \Drupal\Core\Theme\ThemeManagerInterface::render() can differentiate
Chris@0 179 // between a hook that exists and renders an empty string, and a hook
Chris@0 180 // that is not implemented.
Chris@0 181 return FALSE;
Chris@0 182 }
Chris@0 183 }
Chris@0 184
Chris@0 185 $info = $theme_registry->get($hook);
Chris@0 186
Chris@0 187 // If a renderable array is passed as $variables, then set $variables to
Chris@0 188 // the arguments expected by the theme function.
Chris@0 189 if (isset($variables['#theme']) || isset($variables['#theme_wrappers'])) {
Chris@0 190 $element = $variables;
Chris@0 191 $variables = [];
Chris@0 192 if (isset($info['variables'])) {
Chris@0 193 foreach (array_keys($info['variables']) as $name) {
Chris@0 194 if (isset($element["#$name"]) || array_key_exists("#$name", $element)) {
Chris@0 195 $variables[$name] = $element["#$name"];
Chris@0 196 }
Chris@0 197 }
Chris@0 198 }
Chris@0 199 else {
Chris@0 200 $variables[$info['render element']] = $element;
Chris@0 201 // Give a hint to render engines to prevent infinite recursion.
Chris@0 202 $variables[$info['render element']]['#render_children'] = TRUE;
Chris@0 203 }
Chris@0 204 }
Chris@0 205
Chris@0 206 // Merge in argument defaults.
Chris@0 207 if (!empty($info['variables'])) {
Chris@0 208 $variables += $info['variables'];
Chris@0 209 }
Chris@0 210 elseif (!empty($info['render element'])) {
Chris@0 211 $variables += [$info['render element'] => []];
Chris@0 212 }
Chris@0 213 // Supply original caller info.
Chris@0 214 $variables += [
Chris@0 215 'theme_hook_original' => $original_hook,
Chris@0 216 ];
Chris@0 217
Chris@0 218 // Set base hook for later use. For example if '#theme' => 'node__article'
Chris@0 219 // is called, we run hook_theme_suggestions_node_alter() rather than
Chris@0 220 // hook_theme_suggestions_node__article_alter(), and also pass in the base
Chris@0 221 // hook as the last parameter to the suggestions alter hooks.
Chris@0 222 if (isset($info['base hook'])) {
Chris@0 223 $base_theme_hook = $info['base hook'];
Chris@0 224 }
Chris@0 225 else {
Chris@0 226 $base_theme_hook = $hook;
Chris@0 227 }
Chris@0 228
Chris@0 229 // Invoke hook_theme_suggestions_HOOK().
Chris@0 230 $suggestions = $this->moduleHandler->invokeAll('theme_suggestions_' . $base_theme_hook, [$variables]);
Chris@0 231 // If the theme implementation was invoked with a direct theme suggestion
Chris@0 232 // like '#theme' => 'node__article', add it to the suggestions array before
Chris@0 233 // invoking suggestion alter hooks.
Chris@0 234 if (isset($info['base hook'])) {
Chris@0 235 $suggestions[] = $hook;
Chris@0 236 }
Chris@0 237
Chris@0 238 // Invoke hook_theme_suggestions_alter() and
Chris@0 239 // hook_theme_suggestions_HOOK_alter().
Chris@0 240 $hooks = [
Chris@0 241 'theme_suggestions',
Chris@0 242 'theme_suggestions_' . $base_theme_hook,
Chris@0 243 ];
Chris@0 244 $this->moduleHandler->alter($hooks, $suggestions, $variables, $base_theme_hook);
Chris@0 245 $this->alter($hooks, $suggestions, $variables, $base_theme_hook);
Chris@0 246
Chris@0 247 // Check if each suggestion exists in the theme registry, and if so,
Chris@0 248 // use it instead of the base hook. For example, a function may use
Chris@0 249 // '#theme' => 'node', but a module can add 'node__article' as a suggestion
Chris@0 250 // via hook_theme_suggestions_HOOK_alter(), enabling a theme to have
Chris@0 251 // an alternate template file for article nodes.
Chris@0 252 foreach (array_reverse($suggestions) as $suggestion) {
Chris@0 253 if ($theme_registry->has($suggestion)) {
Chris@0 254 $info = $theme_registry->get($suggestion);
Chris@0 255 break;
Chris@0 256 }
Chris@0 257 }
Chris@0 258
Chris@0 259 // Include a file if the theme function or variable preprocessor is held
Chris@0 260 // elsewhere.
Chris@0 261 if (!empty($info['includes'])) {
Chris@0 262 foreach ($info['includes'] as $include_file) {
Chris@0 263 include_once $this->root . '/' . $include_file;
Chris@0 264 }
Chris@0 265 }
Chris@0 266
Chris@0 267 // Invoke the variable preprocessors, if any.
Chris@0 268 if (isset($info['base hook'])) {
Chris@0 269 $base_hook = $info['base hook'];
Chris@0 270 $base_hook_info = $theme_registry->get($base_hook);
Chris@0 271 // Include files required by the base hook, since its variable
Chris@0 272 // preprocessors might reside there.
Chris@0 273 if (!empty($base_hook_info['includes'])) {
Chris@0 274 foreach ($base_hook_info['includes'] as $include_file) {
Chris@0 275 include_once $this->root . '/' . $include_file;
Chris@0 276 }
Chris@0 277 }
Chris@0 278 if (isset($base_hook_info['preprocess functions'])) {
Chris@0 279 // Set a variable for the 'theme_hook_suggestion'. This is used to
Chris@0 280 // maintain backwards compatibility with template engines.
Chris@0 281 $theme_hook_suggestion = $hook;
Chris@0 282 }
Chris@0 283 }
Chris@0 284 if (isset($info['preprocess functions'])) {
Chris@0 285 foreach ($info['preprocess functions'] as $preprocessor_function) {
Chris@0 286 if (function_exists($preprocessor_function)) {
Chris@0 287 $preprocessor_function($variables, $hook, $info);
Chris@0 288 }
Chris@0 289 }
Chris@0 290 // Allow theme preprocess functions to set $variables['#attached'] and
Chris@0 291 // $variables['#cache'] and use them like the corresponding element
Chris@0 292 // properties on render arrays. In Drupal 8, this is the (only) officially
Chris@0 293 // supported method of attaching bubbleable metadata from preprocess
Chris@0 294 // functions. Assets attached here should be associated with the template
Chris@0 295 // that we are preprocessing variables for.
Chris@0 296 $preprocess_bubbleable = [];
Chris@0 297 foreach (['#attached', '#cache'] as $key) {
Chris@0 298 if (isset($variables[$key])) {
Chris@0 299 $preprocess_bubbleable[$key] = $variables[$key];
Chris@0 300 }
Chris@0 301 }
Chris@0 302 // We do not allow preprocess functions to define cacheable elements.
Chris@0 303 unset($preprocess_bubbleable['#cache']['keys']);
Chris@0 304 if ($preprocess_bubbleable) {
Chris@0 305 // @todo Inject the Renderer in https://www.drupal.org/node/2529438.
Chris@0 306 \Drupal::service('renderer')->render($preprocess_bubbleable);
Chris@0 307 }
Chris@0 308 }
Chris@0 309
Chris@0 310 // Generate the output using either a function or a template.
Chris@0 311 $output = '';
Chris@0 312 if (isset($info['function'])) {
Chris@0 313 if (function_exists($info['function'])) {
Chris@0 314 // Theme functions do not render via the theme engine, so the output is
Chris@0 315 // not autoescaped. However, we can only presume that the theme function
Chris@0 316 // has been written correctly and that the markup is safe.
Chris@0 317 $output = Markup::create($info['function']($variables));
Chris@0 318 }
Chris@0 319 }
Chris@0 320 else {
Chris@0 321 $render_function = 'twig_render_template';
Chris@0 322 $extension = '.html.twig';
Chris@0 323
Chris@0 324 // The theme engine may use a different extension and a different
Chris@0 325 // renderer.
Chris@0 326 $theme_engine = $active_theme->getEngine();
Chris@0 327 if (isset($theme_engine)) {
Chris@0 328 if ($info['type'] != 'module') {
Chris@0 329 if (function_exists($theme_engine . '_render_template')) {
Chris@0 330 $render_function = $theme_engine . '_render_template';
Chris@0 331 }
Chris@0 332 $extension_function = $theme_engine . '_extension';
Chris@0 333 if (function_exists($extension_function)) {
Chris@0 334 $extension = $extension_function();
Chris@0 335 }
Chris@0 336 }
Chris@0 337 }
Chris@0 338
Chris@0 339 // In some cases, a template implementation may not have had
Chris@0 340 // template_preprocess() run (for example, if the default implementation
Chris@0 341 // is a function, but a template overrides that default implementation).
Chris@0 342 // In these cases, a template should still be able to expect to have
Chris@0 343 // access to the variables provided by template_preprocess(), so we add
Chris@0 344 // them here if they don't already exist. We don't want the overhead of
Chris@0 345 // running template_preprocess() twice, so we use the 'directory' variable
Chris@0 346 // to determine if it has already run, which while not completely
Chris@0 347 // intuitive, is reasonably safe, and allows us to save on the overhead of
Chris@0 348 // adding some new variable to track that.
Chris@0 349 if (!isset($variables['directory'])) {
Chris@0 350 $default_template_variables = [];
Chris@0 351 template_preprocess($default_template_variables, $hook, $info);
Chris@0 352 $variables += $default_template_variables;
Chris@0 353 }
Chris@0 354 if (!isset($default_attributes)) {
Chris@0 355 $default_attributes = new Attribute();
Chris@0 356 }
Chris@0 357 foreach (['attributes', 'title_attributes', 'content_attributes'] as $key) {
Chris@0 358 if (isset($variables[$key]) && !($variables[$key] instanceof Attribute)) {
Chris@0 359 if ($variables[$key]) {
Chris@0 360 $variables[$key] = new Attribute($variables[$key]);
Chris@0 361 }
Chris@0 362 else {
Chris@0 363 // Create empty attributes.
Chris@0 364 $variables[$key] = clone $default_attributes;
Chris@0 365 }
Chris@0 366 }
Chris@0 367 }
Chris@0 368
Chris@0 369 // Render the output using the template file.
Chris@0 370 $template_file = $info['template'] . $extension;
Chris@0 371 if (isset($info['path'])) {
Chris@0 372 $template_file = $info['path'] . '/' . $template_file;
Chris@0 373 }
Chris@0 374 // Add the theme suggestions to the variables array just before rendering
Chris@0 375 // the template for backwards compatibility with template engines.
Chris@0 376 $variables['theme_hook_suggestions'] = $suggestions;
Chris@0 377 // For backwards compatibility, pass 'theme_hook_suggestion' on to the
Chris@0 378 // template engine. This is only set when calling a direct suggestion like
Chris@0 379 // '#theme' => 'menu__shortcut_default' when the template exists in the
Chris@0 380 // current theme.
Chris@0 381 if (isset($theme_hook_suggestion)) {
Chris@0 382 $variables['theme_hook_suggestion'] = $theme_hook_suggestion;
Chris@0 383 }
Chris@0 384 $output = $render_function($template_file, $variables);
Chris@0 385 }
Chris@0 386
Chris@0 387 return ($output instanceof MarkupInterface) ? $output : (string) $output;
Chris@0 388 }
Chris@0 389
Chris@0 390 /**
Chris@0 391 * Initializes the active theme for a given route match.
Chris@0 392 *
Chris@0 393 * @param \Drupal\Core\Routing\RouteMatchInterface $route_match
Chris@0 394 * The current route match.
Chris@0 395 */
Chris@0 396 protected function initTheme(RouteMatchInterface $route_match = NULL) {
Chris@0 397 // Determine the active theme for the theme negotiator service. This includes
Chris@0 398 // the default theme as well as really specific ones like the ajax base theme.
Chris@0 399 if (!$route_match) {
Chris@0 400 $route_match = \Drupal::routeMatch();
Chris@0 401 }
Chris@0 402 if ($route_match instanceof StackedRouteMatchInterface) {
Chris@0 403 $route_match = $route_match->getMasterRouteMatch();
Chris@0 404 }
Chris@0 405 $theme = $this->themeNegotiator->determineActiveTheme($route_match);
Chris@0 406 $this->activeTheme = $this->themeInitialization->initTheme($theme);
Chris@0 407 }
Chris@0 408
Chris@0 409 /**
Chris@0 410 * {@inheritdoc}
Chris@0 411 *
Chris@0 412 * @todo Should we cache some of these information?
Chris@0 413 */
Chris@0 414 public function alterForTheme(ActiveTheme $theme, $type, &$data, &$context1 = NULL, &$context2 = NULL) {
Chris@0 415 // Most of the time, $type is passed as a string, so for performance,
Chris@0 416 // normalize it to that. When passed as an array, usually the first item in
Chris@0 417 // the array is a generic type, and additional items in the array are more
Chris@0 418 // specific variants of it, as in the case of array('form', 'form_FORM_ID').
Chris@0 419 if (is_array($type)) {
Chris@0 420 $extra_types = $type;
Chris@0 421 $type = array_shift($extra_types);
Chris@0 422 // Allow if statements in this function to use the faster isset() rather
Chris@0 423 // than !empty() both when $type is passed as a string, or as an array with
Chris@0 424 // one item.
Chris@0 425 if (empty($extra_types)) {
Chris@0 426 unset($extra_types);
Chris@0 427 }
Chris@0 428 }
Chris@0 429
Chris@18 430 $theme_keys = array_keys($theme->getBaseThemeExtensions());
Chris@0 431 $theme_keys[] = $theme->getName();
Chris@0 432 $functions = [];
Chris@0 433 foreach ($theme_keys as $theme_key) {
Chris@0 434 $function = $theme_key . '_' . $type . '_alter';
Chris@0 435 if (function_exists($function)) {
Chris@0 436 $functions[] = $function;
Chris@0 437 }
Chris@0 438 if (isset($extra_types)) {
Chris@0 439 foreach ($extra_types as $extra_type) {
Chris@0 440 $function = $theme_key . '_' . $extra_type . '_alter';
Chris@0 441 if (function_exists($function)) {
Chris@0 442 $functions[] = $function;
Chris@0 443 }
Chris@0 444 }
Chris@0 445 }
Chris@0 446 }
Chris@0 447
Chris@0 448 foreach ($functions as $function) {
Chris@0 449 $function($data, $context1, $context2);
Chris@0 450 }
Chris@0 451 }
Chris@0 452
Chris@0 453 /**
Chris@0 454 * {@inheritdoc}
Chris@0 455 */
Chris@0 456 public function alter($type, &$data, &$context1 = NULL, &$context2 = NULL) {
Chris@0 457 $theme = $this->getActiveTheme();
Chris@0 458 $this->alterForTheme($theme, $type, $data, $context1, $context2);
Chris@0 459 }
Chris@0 460
Chris@0 461 }