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 158

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 | \FilesystemIterator::FOLLOW_SYMLINKS);
    $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 . '/' . $fileinfo->getBasename('.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']);
                }
            }
        }
        if ($extension === 'inc') {
            $parts = explode('.', $fileinfo->getFilename());
            if (count($parts) === 3 && $parts[0] === $module) {
                $this->groupIncludes[$parts[1]][] = $fileinfo->getPathname();
            }
        }
    }
}

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