Chris@0: registry. Chris@0: */ Chris@0: class Registry implements DestructableInterface { Chris@0: Chris@0: /** Chris@0: * The theme object representing the active theme for this registry. Chris@0: * Chris@0: * @var \Drupal\Core\Theme\ActiveTheme Chris@0: */ Chris@0: protected $theme; Chris@0: Chris@0: /** Chris@0: * The lock backend that should be used. Chris@0: * Chris@0: * @var \Drupal\Core\Lock\LockBackendInterface Chris@0: */ Chris@0: protected $lock; Chris@0: Chris@0: /** Chris@0: * The complete theme registry. Chris@0: * Chris@0: * @var array Chris@0: * An array of theme registries, keyed by the theme name. Each registry is Chris@0: * an associative array keyed by theme hook names, whose values are Chris@0: * associative arrays containing the aggregated hook definition: Chris@0: * - type: The type of the extension the original theme hook originates Chris@0: * from; e.g., 'module' for theme hook 'node' of Node module. Chris@0: * - name: The name of the extension the original theme hook originates Chris@0: * from; e.g., 'node' for theme hook 'node' of Node module. Chris@0: * - theme path: The effective \Drupal\Core\Theme\ActiveTheme::getPath() Chris@0: * during \Drupal\Core\Theme\ThemeManagerInterface::render(), available Chris@0: * as 'directory' variable in templates. For functions, it should point Chris@0: * to the respective theme. For templates, it should point to the Chris@0: * directory that contains the template. Chris@0: * - includes: (optional) An array of include files to load when the theme Chris@0: * hook is executed by \Drupal\Core\Theme\ThemeManagerInterface::render(). Chris@0: * - file: (optional) A filename to add to 'includes', either prefixed with Chris@0: * the value of 'path', or the path of the extension implementing Chris@0: * hook_theme(). Chris@0: * In case of a theme base hook, one of the following: Chris@0: * - variables: An associative array whose keys are variable names and whose Chris@0: * values are default values of the variables to use for this theme hook. Chris@0: * - render element: A string denoting the name of the variable name, in Chris@0: * which the render element for this theme hook is provided. Chris@0: * In case of a theme template file: Chris@0: * - path: The path to the template file to use. Defaults to the Chris@0: * subdirectory 'templates' of the path of the extension implementing Chris@0: * hook_theme(); e.g., 'core/modules/node/templates' for Node module. Chris@0: * - template: The basename of the template file to use, without extension Chris@0: * (as the extension is specific to the theme engine). The template file Chris@0: * is in the directory defined by 'path'. Chris@0: * - template_file: A full path and file name to a template file to use. Chris@0: * Allows any extension to override the effective template file. Chris@0: * - engine: The theme engine to use for the template file. Chris@0: * In case of a theme function: Chris@0: * - function: The function name to call to generate the output. Chris@0: * For any registered theme hook, including theme hook suggestions: Chris@0: * - preprocess: An array of theme variable preprocess callbacks to invoke Chris@0: * before invoking final theme variable processors. Chris@0: * - process: An array of theme variable process callbacks to invoke Chris@0: * before invoking the actual theme function or template. Chris@0: */ Chris@0: protected $registry = []; Chris@0: Chris@0: /** Chris@0: * The cache backend to use for the complete theme registry data. Chris@0: * Chris@0: * @var \Drupal\Core\Cache\CacheBackendInterface Chris@0: */ Chris@0: protected $cache; Chris@0: Chris@0: /** Chris@0: * The module handler to use to load modules. Chris@0: * Chris@0: * @var \Drupal\Core\Extension\ModuleHandlerInterface Chris@0: */ Chris@0: protected $moduleHandler; Chris@0: Chris@0: /** Chris@0: * An array of incomplete, runtime theme registries, keyed by theme name. Chris@0: * Chris@0: * @var \Drupal\Core\Utility\ThemeRegistry[] Chris@0: */ Chris@0: protected $runtimeRegistry = []; Chris@0: Chris@0: /** Chris@0: * Stores whether the registry was already initialized. Chris@0: * Chris@0: * @var bool Chris@0: */ Chris@0: protected $initialized = FALSE; Chris@0: Chris@0: /** Chris@0: * The name of the theme for which to construct the registry, if given. Chris@0: * Chris@0: * @var string|null Chris@0: */ Chris@0: protected $themeName; Chris@0: Chris@0: /** Chris@0: * The app root. Chris@0: * Chris@0: * @var string Chris@0: */ Chris@0: protected $root; Chris@0: Chris@0: /** Chris@0: * The theme handler. Chris@0: * Chris@0: * @var \Drupal\Core\Extension\ThemeHandlerInterface Chris@0: */ Chris@0: protected $themeHandler; Chris@0: Chris@0: /** Chris@0: * The theme manager. Chris@0: * Chris@0: * @var \Drupal\Core\Theme\ThemeManagerInterface Chris@0: */ Chris@0: protected $themeManager; Chris@0: Chris@0: /** Chris@0: * The runtime cache. Chris@0: * Chris@0: * @var \Drupal\Core\Cache\CacheBackendInterface Chris@0: */ Chris@0: protected $runtimeCache; Chris@0: Chris@0: /** Chris@0: * Constructs a \Drupal\Core\Theme\Registry object. Chris@0: * Chris@0: * @param string $root Chris@0: * The app root. Chris@0: * @param \Drupal\Core\Cache\CacheBackendInterface $cache Chris@0: * The cache backend interface to use for the complete theme registry data. Chris@0: * @param \Drupal\Core\Lock\LockBackendInterface $lock Chris@0: * The lock backend. Chris@0: * @param \Drupal\Core\Extension\ModuleHandlerInterface $module_handler Chris@0: * The module handler to use to load modules. Chris@0: * @param \Drupal\Core\Extension\ThemeHandlerInterface $theme_handler Chris@0: * The theme handler. Chris@0: * @param \Drupal\Core\Theme\ThemeInitializationInterface $theme_initialization Chris@0: * The theme initialization. Chris@0: * @param string $theme_name Chris@0: * (optional) The name of the theme for which to construct the registry. Chris@0: * @param \Drupal\Core\Cache\CacheBackendInterface $runtime_cache Chris@0: * The cache backend interface to use for the runtime theme registry data. Chris@0: */ Chris@0: public function __construct($root, CacheBackendInterface $cache, LockBackendInterface $lock, ModuleHandlerInterface $module_handler, ThemeHandlerInterface $theme_handler, ThemeInitializationInterface $theme_initialization, $theme_name = NULL, CacheBackendInterface $runtime_cache = NULL) { Chris@0: $this->root = $root; Chris@0: $this->cache = $cache; Chris@0: $this->lock = $lock; Chris@0: $this->moduleHandler = $module_handler; Chris@0: $this->themeName = $theme_name; Chris@0: $this->themeHandler = $theme_handler; Chris@0: $this->themeInitialization = $theme_initialization; Chris@0: $this->runtimeCache = $runtime_cache; Chris@0: } Chris@0: Chris@0: /** Chris@0: * Sets the theme manager. Chris@0: * Chris@0: * @param \Drupal\Core\Theme\ThemeManagerInterface $theme_manager Chris@0: * The theme manager. Chris@0: */ Chris@0: public function setThemeManager(ThemeManagerInterface $theme_manager) { Chris@0: $this->themeManager = $theme_manager; Chris@0: } Chris@0: Chris@0: /** Chris@0: * Initializes a theme with a certain name. Chris@0: * Chris@0: * This function does to much magic, so it should be replaced by another Chris@0: * services which holds the current active theme information. Chris@0: * Chris@0: * @param string $theme_name Chris@0: * (optional) The name of the theme for which to construct the registry. Chris@0: */ Chris@0: protected function init($theme_name = NULL) { Chris@0: if ($this->initialized) { Chris@0: return; Chris@0: } Chris@0: // Unless instantiated for a specific theme, use globals. Chris@0: if (!isset($theme_name)) { Chris@0: $this->theme = $this->themeManager->getActiveTheme(); Chris@0: } Chris@0: // Instead of the active theme, a specific theme was requested. Chris@0: else { Chris@0: $this->theme = $this->themeInitialization->getActiveThemeByName($theme_name); Chris@0: $this->themeInitialization->loadActiveTheme($this->theme); Chris@0: } Chris@0: } Chris@0: Chris@0: /** Chris@0: * Returns the complete theme registry from cache or rebuilds it. Chris@0: * Chris@0: * @return array Chris@0: * The complete theme registry data array. Chris@0: * Chris@0: * @see Registry::$registry Chris@0: */ Chris@0: public function get() { Chris@0: $this->init($this->themeName); Chris@0: if (isset($this->registry[$this->theme->getName()])) { Chris@0: return $this->registry[$this->theme->getName()]; Chris@0: } Chris@0: if ($cache = $this->cache->get('theme_registry:' . $this->theme->getName())) { Chris@0: $this->registry[$this->theme->getName()] = $cache->data; Chris@0: } Chris@0: else { Chris@0: $this->build(); Chris@0: // Only persist it if all modules are loaded to ensure it is complete. Chris@0: if ($this->moduleHandler->isLoaded()) { Chris@0: $this->setCache(); Chris@0: } Chris@0: } Chris@0: return $this->registry[$this->theme->getName()]; Chris@0: } Chris@0: Chris@0: /** Chris@0: * Returns the incomplete, runtime theme registry. Chris@0: * Chris@0: * @return \Drupal\Core\Utility\ThemeRegistry Chris@0: * A shared instance of the ThemeRegistry class, provides an ArrayObject Chris@0: * that allows it to be accessed with array syntax and isset(), and is more Chris@0: * lightweight than the full registry. Chris@0: */ Chris@0: public function getRuntime() { Chris@0: $this->init($this->themeName); Chris@0: if (!isset($this->runtimeRegistry[$this->theme->getName()])) { Chris@0: $this->runtimeRegistry[$this->theme->getName()] = new ThemeRegistry('theme_registry:runtime:' . $this->theme->getName(), $this->runtimeCache ?: $this->cache, $this->lock, ['theme_registry'], $this->moduleHandler->isLoaded()); Chris@0: } Chris@0: return $this->runtimeRegistry[$this->theme->getName()]; Chris@0: } Chris@0: Chris@0: /** Chris@0: * Persists the theme registry in the cache backend. Chris@0: */ Chris@0: protected function setCache() { Chris@0: $this->cache->set('theme_registry:' . $this->theme->getName(), $this->registry[$this->theme->getName()], Cache::PERMANENT, ['theme_registry']); Chris@0: } Chris@0: Chris@0: /** Chris@0: * Returns the base hook for a given hook suggestion. Chris@0: * Chris@0: * @param string $hook Chris@0: * The name of a theme hook whose base hook to find. Chris@0: * Chris@0: * @return string|false Chris@0: * The name of the base hook or FALSE. Chris@0: */ Chris@0: public function getBaseHook($hook) { Chris@0: $this->init($this->themeName); Chris@0: $base_hook = $hook; Chris@0: // Iteratively strip everything after the last '__' delimiter, until a Chris@0: // base hook definition is found. Recursive base hooks of base hooks are Chris@0: // not supported, so the base hook must be an original implementation that Chris@0: // points to a theme function or template. Chris@0: while ($pos = strrpos($base_hook, '__')) { Chris@0: $base_hook = substr($base_hook, 0, $pos); Chris@0: if (isset($this->registry[$base_hook]['exists'])) { Chris@0: break; Chris@0: } Chris@0: } Chris@0: if ($pos !== FALSE && $base_hook !== $hook) { Chris@0: return $base_hook; Chris@0: } Chris@0: return FALSE; Chris@0: } Chris@0: Chris@0: /** Chris@0: * Builds the theme registry cache. Chris@0: * Chris@0: * Theme hook definitions are collected in the following order: Chris@0: * - Modules Chris@0: * - Base theme engines Chris@0: * - Base themes Chris@0: * - Theme engine Chris@0: * - Theme Chris@0: * Chris@0: * All theme hook definitions are essentially just collated and merged in the Chris@0: * above order. However, various extension-specific default values and Chris@0: * customizations are required; e.g., to record the effective file path for Chris@0: * theme template. Therefore, this method first collects all extensions per Chris@0: * type, and then dispatches the processing for each extension to Chris@0: * processExtension(). Chris@0: * Chris@0: * After completing the collection, modules are allowed to alter it. Lastly, Chris@0: * any derived and incomplete theme hook definitions that are hook suggestions Chris@0: * for base hooks (e.g., 'block__node' for the base hook 'block') need to be Chris@0: * determined based on the full registry and classified as 'base hook'. Chris@0: * Chris@0: * See the @link themeable Default theme implementations topic @endlink for Chris@0: * details. Chris@0: * Chris@0: * @return \Drupal\Core\Utility\ThemeRegistry Chris@0: * The build theme registry. Chris@0: * Chris@0: * @see hook_theme_registry_alter() Chris@0: */ Chris@0: protected function build() { Chris@0: $cache = []; Chris@0: // First, preprocess the theme hooks advertised by modules. This will Chris@0: // serve as the basic registry. Since the list of enabled modules is the Chris@0: // same regardless of the theme used, this is cached in its own entry to Chris@0: // save building it for every theme. Chris@0: if ($cached = $this->cache->get('theme_registry:build:modules')) { Chris@0: $cache = $cached->data; Chris@0: } Chris@0: else { Chris@0: foreach ($this->moduleHandler->getImplementations('theme') as $module) { Chris@0: $this->processExtension($cache, $module, 'module', $module, $this->getPath($module)); Chris@0: } Chris@0: // Only cache this registry if all modules are loaded. Chris@0: if ($this->moduleHandler->isLoaded()) { Chris@0: $this->cache->set("theme_registry:build:modules", $cache, Cache::PERMANENT, ['theme_registry']); Chris@0: } Chris@0: } Chris@0: Chris@0: // Process each base theme. Chris@0: // Ensure that we start with the root of the parents, so that both CSS files Chris@0: // and preprocess functions comes first. Chris@18: foreach (array_reverse($this->theme->getBaseThemeExtensions()) as $base) { Chris@0: // If the base theme uses a theme engine, process its hooks. Chris@0: $base_path = $base->getPath(); Chris@0: if ($this->theme->getEngine()) { Chris@0: $this->processExtension($cache, $this->theme->getEngine(), 'base_theme_engine', $base->getName(), $base_path); Chris@0: } Chris@0: $this->processExtension($cache, $base->getName(), 'base_theme', $base->getName(), $base_path); Chris@0: } Chris@0: Chris@0: // And then the same thing, but for the theme. Chris@0: if ($this->theme->getEngine()) { Chris@0: $this->processExtension($cache, $this->theme->getEngine(), 'theme_engine', $this->theme->getName(), $this->theme->getPath()); Chris@0: } Chris@0: Chris@0: // Hooks provided by the theme itself. Chris@0: $this->processExtension($cache, $this->theme->getName(), 'theme', $this->theme->getName(), $this->theme->getPath()); Chris@0: Chris@0: // Discover and add all preprocess functions for theme hook suggestions. Chris@0: $this->postProcessExtension($cache, $this->theme); Chris@0: Chris@0: // Let modules and themes alter the registry. Chris@0: $this->moduleHandler->alter('theme_registry', $cache); Chris@0: $this->themeManager->alterForTheme($this->theme, 'theme_registry', $cache); Chris@0: Chris@0: // @todo Implement more reduction of the theme registry entry. Chris@0: // Optimize the registry to not have empty arrays for functions. Chris@0: foreach ($cache as $hook => $info) { Chris@0: if (empty($info['preprocess functions'])) { Chris@0: unset($cache[$hook]['preprocess functions']); Chris@0: } Chris@0: } Chris@0: $this->registry[$this->theme->getName()] = $cache; Chris@0: Chris@0: return $this->registry[$this->theme->getName()]; Chris@0: } Chris@0: Chris@0: /** Chris@0: * Process a single implementation of hook_theme(). Chris@0: * Chris@0: * @param array $cache Chris@0: * The theme registry that will eventually be cached; It is an associative Chris@0: * array keyed by theme hooks, whose values are associative arrays Chris@0: * describing the hook: Chris@0: * - 'type': The passed-in $type. Chris@0: * - 'theme path': The passed-in $path. Chris@0: * - 'function': The name of the function generating output for this theme Chris@0: * hook. Either defined explicitly in hook_theme() or, if neither Chris@0: * 'function' nor 'template' is defined, then the default theme function Chris@0: * name is used. The default theme function name is the theme hook Chris@0: * prefixed by either 'theme_' for modules or '$name_' for everything Chris@0: * else. If 'function' is defined, 'template' is not used. Chris@0: * - 'template': The filename of the template generating output for this Chris@0: * theme hook. The template is in the directory defined by the 'path' key Chris@0: * of hook_theme() or defaults to "$path/templates". Chris@0: * - 'variables': The variables for this theme hook as defined in Chris@0: * hook_theme(). If there is more than one implementation and 'variables' Chris@0: * is not specified in a later one, then the previous definition is kept. Chris@0: * - 'render element': The renderable element for this theme hook as defined Chris@0: * in hook_theme(). If there is more than one implementation and Chris@0: * 'render element' is not specified in a later one, then the previous Chris@0: * definition is kept. Chris@0: * - See the @link themeable Theme system overview topic @endlink for Chris@0: * detailed documentation. Chris@0: * @param string $name Chris@0: * The name of the module, theme engine, base theme engine, theme or base Chris@0: * theme implementing hook_theme(). Chris@0: * @param string $type Chris@0: * One of 'module', 'theme_engine', 'base_theme_engine', 'theme', or Chris@0: * 'base_theme'. Unlike regular hooks that can only be implemented by Chris@0: * modules, each of these can implement hook_theme(). This function is Chris@0: * called in aforementioned order and new entries override older ones. For Chris@0: * example, if a theme hook is both defined by a module and a theme, then Chris@0: * the definition in the theme will be used. Chris@0: * @param string $theme Chris@0: * The actual name of theme, module, etc. that is being processed. Chris@0: * @param string $path Chris@0: * The directory where $name is. For example, modules/system or Chris@0: * themes/bartik. Chris@0: * Chris@0: * @see \Drupal\Core\Theme\ThemeManagerInterface::render() Chris@0: * @see hook_theme() Chris@0: * @see \Drupal\Core\Extension\ThemeHandler::listInfo() Chris@0: * @see twig_render_template() Chris@0: * Chris@0: * @throws \BadFunctionCallException Chris@0: */ Chris@0: protected function processExtension(array &$cache, $name, $type, $theme, $path) { Chris@0: $result = []; Chris@0: Chris@0: $hook_defaults = [ Chris@0: 'variables' => TRUE, Chris@0: 'render element' => TRUE, Chris@0: 'pattern' => TRUE, Chris@0: 'base hook' => TRUE, Chris@0: ]; Chris@0: Chris@0: $module_list = array_keys($this->moduleHandler->getModuleList()); Chris@0: Chris@0: // Invoke the hook_theme() implementation, preprocess what is returned, and Chris@0: // merge it into $cache. Chris@0: $function = $name . '_theme'; Chris@0: if (function_exists($function)) { Chris@0: $result = $function($cache, $type, $theme, $path); Chris@0: foreach ($result as $hook => $info) { Chris@0: // When a theme or engine overrides a module's theme function Chris@0: // $result[$hook] will only contain key/value pairs for information being Chris@0: // overridden. Pull the rest of the information from what was defined by Chris@0: // an earlier hook. Chris@0: Chris@0: // Fill in the type and path of the module, theme, or engine that Chris@0: // implements this theme function. Chris@0: $result[$hook]['type'] = $type; Chris@0: $result[$hook]['theme path'] = $path; Chris@0: Chris@0: // If a theme hook has a base hook, mark its preprocess functions always Chris@0: // incomplete in order to inherit the base hook's preprocess functions. Chris@0: if (!empty($result[$hook]['base hook'])) { Chris@0: $result[$hook]['incomplete preprocess functions'] = TRUE; Chris@0: } Chris@0: Chris@0: if (isset($cache[$hook]['includes'])) { Chris@0: $result[$hook]['includes'] = $cache[$hook]['includes']; Chris@0: } Chris@0: Chris@0: // Load the includes, as they may contain preprocess functions. Chris@0: if (isset($info['includes'])) { Chris@0: foreach ($info['includes'] as $include_file) { Chris@0: include_once $this->root . '/' . $include_file; Chris@0: } Chris@0: } Chris@0: Chris@0: // If the theme implementation defines a file, then also use the path Chris@0: // that it defined. Otherwise use the default path. This allows Chris@0: // system.module to declare theme functions on behalf of core .include Chris@0: // files. Chris@0: if (isset($info['file'])) { Chris@0: $include_file = isset($info['path']) ? $info['path'] : $path; Chris@0: $include_file .= '/' . $info['file']; Chris@0: include_once $this->root . '/' . $include_file; Chris@0: $result[$hook]['includes'][] = $include_file; Chris@0: } Chris@0: Chris@0: // A template file is the default implementation for a theme hook, but Chris@0: // if the theme hook specifies a function callback instead, check to Chris@0: // ensure the function actually exists. Chris@0: if (isset($info['function'])) { Chris@0: if (!function_exists($info['function'])) { Chris@0: throw new \BadFunctionCallException(sprintf( Chris@0: 'Theme hook "%s" refers to a theme function callback that does not exist: "%s"', Chris@0: $hook, Chris@0: $info['function'] Chris@0: )); Chris@0: } Chris@0: } Chris@0: // Provide a default naming convention for 'template' based on the Chris@0: // hook used. If the template does not exist, the theme engine used Chris@0: // should throw an exception at runtime when attempting to include Chris@0: // the template file. Chris@0: elseif (!isset($info['template'])) { Chris@0: $info['template'] = strtr($hook, '_', '-'); Chris@0: $result[$hook]['template'] = $info['template']; Chris@0: } Chris@0: Chris@0: // Prepend the current theming path when none is set. This is required Chris@0: // for the default theme engine to know where the template lives. Chris@0: if (isset($result[$hook]['template']) && !isset($info['path'])) { Chris@0: $result[$hook]['path'] = $path . '/templates'; Chris@0: } Chris@0: Chris@0: // If the default keys are not set, use the default values registered Chris@0: // by the module. Chris@0: if (isset($cache[$hook])) { Chris@0: $result[$hook] += array_intersect_key($cache[$hook], $hook_defaults); Chris@0: } Chris@0: Chris@0: // Preprocess variables for all theming hooks, whether the hook is Chris@0: // implemented as a template or as a function. Ensure they are arrays. Chris@0: if (!isset($info['preprocess functions']) || !is_array($info['preprocess functions'])) { Chris@0: $info['preprocess functions'] = []; Chris@0: $prefixes = []; Chris@0: if ($type == 'module') { Chris@0: // Default variable preprocessor prefix. Chris@0: $prefixes[] = 'template'; Chris@0: // Add all modules so they can intervene with their own variable Chris@0: // preprocessors. This allows them to provide variable preprocessors Chris@0: // even if they are not the owner of the current hook. Chris@0: $prefixes = array_merge($prefixes, $module_list); Chris@0: } Chris@0: elseif ($type == 'theme_engine' || $type == 'base_theme_engine') { Chris@0: // Theme engines get an extra set that come before the normally Chris@0: // named variable preprocessors. Chris@0: $prefixes[] = $name . '_engine'; Chris@0: // The theme engine registers on behalf of the theme using the Chris@0: // theme's name. Chris@0: $prefixes[] = $theme; Chris@0: } Chris@0: else { Chris@0: // This applies when the theme manually registers their own variable Chris@0: // preprocessors. Chris@0: $prefixes[] = $name; Chris@0: } Chris@0: foreach ($prefixes as $prefix) { Chris@0: // Only use non-hook-specific variable preprocessors for theming Chris@0: // hooks implemented as templates. See the @defgroup themeable Chris@0: // topic. Chris@0: if (isset($info['template']) && function_exists($prefix . '_preprocess')) { Chris@0: $info['preprocess functions'][] = $prefix . '_preprocess'; Chris@0: } Chris@0: if (function_exists($prefix . '_preprocess_' . $hook)) { Chris@0: $info['preprocess functions'][] = $prefix . '_preprocess_' . $hook; Chris@0: } Chris@0: } Chris@0: } Chris@0: // Check for the override flag and prevent the cached variable Chris@0: // preprocessors from being used. This allows themes or theme engines Chris@0: // to remove variable preprocessors set earlier in the registry build. Chris@0: if (!empty($info['override preprocess functions'])) { Chris@0: // Flag not needed inside the registry. Chris@0: unset($result[$hook]['override preprocess functions']); Chris@0: } Chris@0: elseif (isset($cache[$hook]['preprocess functions']) && is_array($cache[$hook]['preprocess functions'])) { Chris@0: $info['preprocess functions'] = array_merge($cache[$hook]['preprocess functions'], $info['preprocess functions']); Chris@0: } Chris@0: $result[$hook]['preprocess functions'] = $info['preprocess functions']; Chris@14: Chris@14: // If a theme implementation definition provides both 'template' and Chris@14: // 'function', the 'function' will be used. In this case, if the new Chris@14: // result provides a 'template' value, any existing 'function' value Chris@14: // must be removed for the override to be called. Chris@14: if (isset($result[$hook]['template'])) { Chris@14: unset($cache[$hook]['function']); Chris@14: } Chris@0: } Chris@0: Chris@0: // Merge the newly created theme hooks into the existing cache. Chris@14: $cache = NestedArray::mergeDeep($cache, $result); Chris@0: } Chris@0: Chris@0: // Let themes have variable preprocessors even if they didn't register a Chris@0: // template. Chris@0: if ($type == 'theme' || $type == 'base_theme') { Chris@0: foreach ($cache as $hook => $info) { Chris@0: // Check only if not registered by the theme or engine. Chris@0: if (empty($result[$hook])) { Chris@0: if (!isset($info['preprocess functions'])) { Chris@0: $cache[$hook]['preprocess functions'] = []; Chris@0: } Chris@0: // Only use non-hook-specific variable preprocessors for theme hooks Chris@0: // implemented as templates. See the @defgroup themeable topic. Chris@0: if (isset($info['template']) && function_exists($name . '_preprocess')) { Chris@0: $cache[$hook]['preprocess functions'][] = $name . '_preprocess'; Chris@0: } Chris@0: if (function_exists($name . '_preprocess_' . $hook)) { Chris@0: $cache[$hook]['preprocess functions'][] = $name . '_preprocess_' . $hook; Chris@0: $cache[$hook]['theme path'] = $path; Chris@0: } Chris@0: } Chris@0: } Chris@0: } Chris@0: } Chris@0: Chris@0: /** Chris@0: * Completes the definition of the requested suggestion hook. Chris@0: * Chris@0: * @param string $hook Chris@0: * The name of the suggestion hook to complete. Chris@0: * @param array $cache Chris@0: * The theme registry, as documented in Chris@0: * \Drupal\Core\Theme\Registry::processExtension(). Chris@0: */ Chris@0: protected function completeSuggestion($hook, array &$cache) { Chris@0: $previous_hook = $hook; Chris@0: $incomplete_previous_hook = []; Chris@0: // Continue looping if the candidate hook doesn't exist or if the candidate Chris@0: // hook has incomplete preprocess functions, and if the candidate hook is a Chris@0: // suggestion (has a double underscore). Chris@0: while ((!isset($cache[$previous_hook]) || isset($cache[$previous_hook]['incomplete preprocess functions'])) Chris@0: && $pos = strrpos($previous_hook, '__')) { Chris@0: // Find the first existing candidate hook that has incomplete preprocess Chris@0: // functions. Chris@0: if (isset($cache[$previous_hook]) && !$incomplete_previous_hook && isset($cache[$previous_hook]['incomplete preprocess functions'])) { Chris@0: $incomplete_previous_hook = $cache[$previous_hook]; Chris@0: unset($incomplete_previous_hook['incomplete preprocess functions']); Chris@0: } Chris@0: $previous_hook = substr($previous_hook, 0, $pos); Chris@0: $this->mergePreprocessFunctions($hook, $previous_hook, $incomplete_previous_hook, $cache); Chris@0: } Chris@0: Chris@0: // In addition to processing suggestions, include base hooks. Chris@0: if (isset($cache[$hook]['base hook'])) { Chris@0: // In order to retain the additions from above, pass in the current hook Chris@0: // as the parent hook, otherwise it will be overwritten. Chris@0: $this->mergePreprocessFunctions($hook, $cache[$hook]['base hook'], $cache[$hook], $cache); Chris@0: } Chris@0: } Chris@0: Chris@0: /** Chris@0: * Merges the source hook's preprocess functions into the destination hook's. Chris@0: * Chris@0: * @param string $destination_hook_name Chris@0: * The name of the hook to merge preprocess functions to. Chris@0: * @param string $source_hook_name Chris@0: * The name of the hook to merge preprocess functions from. Chris@0: * @param array $parent_hook Chris@0: * The parent hook if it exists. Either an incomplete hook from suggestions Chris@0: * or a base hook. Chris@0: * @param array $cache Chris@0: * The theme registry, as documented in Chris@0: * \Drupal\Core\Theme\Registry::processExtension(). Chris@0: */ Chris@0: protected function mergePreprocessFunctions($destination_hook_name, $source_hook_name, $parent_hook, array &$cache) { Chris@0: // If base hook exists clone of it for the preprocess function Chris@0: // without a template. Chris@0: // @see https://www.drupal.org/node/2457295 Chris@0: if (isset($cache[$source_hook_name]) && (!isset($cache[$source_hook_name]['incomplete preprocess functions']) || !isset($cache[$destination_hook_name]['incomplete preprocess functions']))) { Chris@0: $cache[$destination_hook_name] = $parent_hook + $cache[$source_hook_name]; Chris@0: if (isset($parent_hook['preprocess functions'])) { Chris@0: $diff = array_diff($parent_hook['preprocess functions'], $cache[$source_hook_name]['preprocess functions']); Chris@0: $cache[$destination_hook_name]['preprocess functions'] = array_merge($cache[$source_hook_name]['preprocess functions'], $diff); Chris@0: } Chris@0: // If a base hook isn't set, this is the actual base hook. Chris@0: if (!isset($cache[$source_hook_name]['base hook'])) { Chris@0: $cache[$destination_hook_name]['base hook'] = $source_hook_name; Chris@0: } Chris@0: } Chris@0: } Chris@0: Chris@0: /** Chris@0: * Completes the theme registry adding discovered functions and hooks. Chris@0: * Chris@0: * @param array $cache Chris@0: * The theme registry as documented in Chris@0: * \Drupal\Core\Theme\Registry::processExtension(). Chris@0: * @param \Drupal\Core\Theme\ActiveTheme $theme Chris@0: * Current active theme. Chris@0: * Chris@0: * @see ::processExtension() Chris@0: */ Chris@0: protected function postProcessExtension(array &$cache, ActiveTheme $theme) { Chris@0: // Gather prefixes. This will be used to limit the found functions to the Chris@0: // expected naming conventions. Chris@0: $prefixes = array_keys((array) $this->moduleHandler->getModuleList()); Chris@18: foreach (array_reverse($theme->getBaseThemeExtensions()) as $base) { Chris@0: $prefixes[] = $base->getName(); Chris@0: } Chris@0: if ($theme->getEngine()) { Chris@0: $prefixes[] = $theme->getEngine() . '_engine'; Chris@0: } Chris@0: $prefixes[] = $theme->getName(); Chris@0: Chris@0: $grouped_functions = $this->getPrefixGroupedUserFunctions($prefixes); Chris@0: Chris@0: // Collect all variable preprocess functions in the correct order. Chris@0: $suggestion_level = []; Chris@0: $matches = []; Chris@0: // Look for functions named according to the pattern and add them if they Chris@0: // have matching hooks in the registry. Chris@0: foreach ($prefixes as $prefix) { Chris@0: // Grep only the functions which are within the prefix group. Chris@0: list($first_prefix,) = explode('_', $prefix, 2); Chris@0: if (!isset($grouped_functions[$first_prefix])) { Chris@0: continue; Chris@0: } Chris@0: // Add the function and the name of the associated theme hook to the list Chris@0: // of preprocess functions grouped by suggestion specificity if a matching Chris@0: // base hook is found. Chris@0: foreach ($grouped_functions[$first_prefix] as $candidate) { Chris@0: if (preg_match("/^{$prefix}_preprocess_(((?:[^_]++|_(?!_))+)__.*)/", $candidate, $matches)) { Chris@0: if (isset($cache[$matches[2]])) { Chris@0: $level = substr_count($matches[1], '__'); Chris@0: $suggestion_level[$level][$candidate] = $matches[1]; Chris@0: } Chris@0: } Chris@0: } Chris@0: } Chris@0: Chris@0: // Add missing variable preprocessors. This is needed for modules that do Chris@0: // not explicitly register the hook. For example, when a theme contains a Chris@0: // variable preprocess function but it does not implement a template, it Chris@0: // will go missing. This will add the expected function. It also allows Chris@0: // modules or themes to have a variable process function based on a pattern Chris@0: // even if the hook does not exist. Chris@0: ksort($suggestion_level); Chris@0: foreach ($suggestion_level as $level => $item) { Chris@0: foreach ($item as $preprocessor => $hook) { Chris@0: if (isset($cache[$hook]['preprocess functions']) && !in_array($hook, $cache[$hook]['preprocess functions'])) { Chris@0: // Add missing preprocessor to existing hook. Chris@0: $cache[$hook]['preprocess functions'][] = $preprocessor; Chris@0: } Chris@0: elseif (!isset($cache[$hook]) && strpos($hook, '__')) { Chris@0: // Process non-existing hook and register it. Chris@0: // Look for a previously defined hook that is either a less specific Chris@0: // suggestion hook or the base hook. Chris@0: $this->completeSuggestion($hook, $cache); Chris@0: $cache[$hook]['preprocess functions'][] = $preprocessor; Chris@0: } Chris@0: } Chris@0: } Chris@0: // Inherit all base hook variable preprocess functions into suggestion Chris@0: // hooks. This ensures that derivative hooks have a complete set of variable Chris@0: // preprocess functions. Chris@0: foreach ($cache as $hook => $info) { Chris@0: // The 'base hook' is only applied to derivative hooks already registered Chris@0: // from a pattern. This is typically set from Chris@0: // drupal_find_theme_functions() and drupal_find_theme_templates(). Chris@0: if (isset($info['incomplete preprocess functions'])) { Chris@0: $this->completeSuggestion($hook, $cache); Chris@0: unset($cache[$hook]['incomplete preprocess functions']); Chris@0: } Chris@0: Chris@0: // Optimize the registry. Chris@0: if (isset($cache[$hook]['preprocess functions']) && empty($cache[$hook]['preprocess functions'])) { Chris@0: unset($cache[$hook]['preprocess functions']); Chris@0: } Chris@0: // Ensure uniqueness. Chris@0: if (isset($cache[$hook]['preprocess functions'])) { Chris@0: $cache[$hook]['preprocess functions'] = array_unique($cache[$hook]['preprocess functions']); Chris@0: } Chris@0: } Chris@0: } Chris@0: Chris@0: /** Chris@0: * Invalidates theme registry caches. Chris@0: * Chris@0: * To be called when the list of enabled extensions is changed. Chris@0: */ Chris@0: public function reset() { Chris@0: // Reset the runtime registry. Chris@0: foreach ($this->runtimeRegistry as $runtime_registry) { Chris@0: $runtime_registry->clear(); Chris@0: } Chris@0: $this->runtimeRegistry = []; Chris@0: Chris@0: $this->registry = []; Chris@0: Cache::invalidateTags(['theme_registry']); Chris@0: return $this; Chris@0: } Chris@0: Chris@0: /** Chris@0: * {@inheritdoc} Chris@0: */ Chris@0: public function destruct() { Chris@0: foreach ($this->runtimeRegistry as $runtime_registry) { Chris@0: $runtime_registry->destruct(); Chris@0: } Chris@0: } Chris@0: Chris@0: /** Chris@0: * Gets all user functions grouped by the word before the first underscore. Chris@0: * Chris@0: * @param $prefixes Chris@0: * An array of function prefixes by which the list can be limited. Chris@0: * @return array Chris@0: * Functions grouped by the first prefix. Chris@0: */ Chris@0: public function getPrefixGroupedUserFunctions($prefixes = []) { Chris@0: $functions = get_defined_functions(); Chris@0: Chris@0: // If a list of prefixes is supplied, trim down the list to those items Chris@0: // only as efficiently as possible. Chris@0: if ($prefixes) { Chris@0: $theme_functions = preg_grep('/^(' . implode(')|(', $prefixes) . ')_/', $functions['user']); Chris@0: } Chris@0: else { Chris@0: $theme_functions = $functions['user']; Chris@0: } Chris@0: Chris@0: $grouped_functions = []; Chris@0: // Splitting user defined functions into groups by the first prefix. Chris@0: foreach ($theme_functions as $function) { Chris@0: list($first_prefix,) = explode('_', $function, 2); Chris@0: $grouped_functions[$first_prefix][] = $function; Chris@0: } Chris@0: Chris@0: return $grouped_functions; Chris@0: } Chris@0: Chris@0: /** Chris@0: * Wraps drupal_get_path(). Chris@0: * Chris@0: * @param string $module Chris@0: * The name of the item for which the path is requested. Chris@0: * Chris@0: * @return string Chris@0: */ Chris@0: protected function getPath($module) { Chris@0: return drupal_get_path('module', $module); Chris@0: } Chris@0: Chris@0: }