function HookCollectorPass::collectModuleHookImplementations

Collects procedural and Attribute hook implementations.

Parameters

$dir: The directory in which the module resides.

$module: The name of the module.

$module_preg: A regular expression matching every module, longer module names are matched first.

Return value

void

File

core/lib/Drupal/Core/Hook/HookCollectorPass.php, line 140

Class

HookCollectorPass
Collects and registers hook implementations.

Namespace

Drupal\Core\Hook

Code

protected function collectModuleHookImplementations($dir, $module, $module_preg) : void {
    $iterator = new \RecursiveDirectoryIterator($dir, \FilesystemIterator::SKIP_DOTS | \FilesystemIterator::UNIX_PATHS);
    $iterator = new \RecursiveCallbackFilterIterator($iterator, static::filterIterator(...));
    $iterator = new \RecursiveIteratorIterator($iterator);
    
    /** @var \RecursiveDirectoryIterator | \RecursiveIteratorIterator $iterator*/
    foreach ($iterator as $fileinfo) {
        assert($fileinfo instanceof \SplFileInfo);
        $extension = $fileinfo->getExtension();
        if ($extension === 'module' && !$iterator->getDepth()) {
            // There is an expectation for all modules to be loaded. However,
            // .module files are not supposed to be in subdirectories.
            include_once $fileinfo->getPathname();
        }
        if ($extension === 'php') {
            $namespace = preg_replace('#^src/#', "Drupal/{$module}/", $iterator->getSubPath());
            $class = $namespace . '/' . basename($fileinfo->getFilename(), '.php');
            $class = str_replace('/', '\\', $class);
            foreach (static::getHookAttributesInClass($class) as $attribute) {
                $this->addFromAttribute($attribute, $class, $module);
            }
        }
        else {
            $finder = MockFileFinder::create($fileinfo->getPathName());
            $parser = new StaticReflectionParser('', $finder);
            foreach ($parser->getMethodAttributes() as $function => $attributes) {
                if (!StaticReflectionParser::hasAttribute($attributes, LegacyHook::class) && preg_match($module_preg, $function, $matches)) {
                    $this->addProceduralImplementation($fileinfo, $matches['hook'], $matches['module'], $matches['function']);
                }
            }
        }
    }
}

Buggy or inaccurate documentation? Please file an issue. Need support? Need help programming? Connect with the Drupal community.