MDL-66903 core: Add helper to get component name from classname

Note: This change is backported from MDL-81063.
This commit is contained in:
Andrew Nicols
2024-07-15 12:22:19 +08:00
parent 85845b13d7
commit 651ecb52d9
2 changed files with 96 additions and 0 deletions
+29
View File
@@ -1070,6 +1070,35 @@ $cache = '.var_export($cache, true).';
return array($type, $plugin);
}
/**
* Fetch the component name from a Moodle PSR-like namespace.
*
* Note: Classnames in the flat underscore_class_name_format are not supported.
*
* @param string $classname
* @return null|string The component name, or null if a matching component was not found
*/
public static function get_component_from_classname(string $classname): ?string {
$components = static::get_component_names(true);
$classname = ltrim($classname, '\\');
// Prefer PSR-4 classnames.
$parts = explode('\\', $classname);
if ($parts) {
$component = array_shift($parts);
if (array_search($component, $components) !== false) {
return $component;
}
}
// Note: Frankenstyle classnames are not supported as they lead to false positives, for example:
// \core_typo\example => \core instead of \core_typo because it does not exist
// Please *do not* add support for Frankenstyle classnames. They will break other things.
return null;
}
/**
* Return exact absolute path to a plugin directory.
*