MDL-82747 core: Register composer autoload files

Unfortunately PHP does not provide any means to autoload the files that
a functions is located in, even if they are in an namespace.

To work around this, Composer makes use of an `autoload.files` section
in the `composer.json` file. Shortly after the Composer autoloader is
registered with the `spl_autoload_register` call it also includes any
files listed in this section.

Moodle does not do this and really we should be doing so.

This change adds a section to the autoloader registration method which
loads all of the files defined in any third-party library included in
our `lib` directory which contains any `composer.json` file with such a
stanza.
This commit is contained in:
Andrew Nicols 2024-08-08 12:58:33 +08:00
parent be3482f339
commit 08f8b58945
No known key found for this signature in database
GPG Key ID: 6D1E3157C8CFBF14

View File

@ -149,6 +149,24 @@ class component {
\Slim::class => 'lib/slim/slim/Slim',
];
/**
* An array containing files which are normally in a package's composer/autoload.files section.
*
* PHP does not provide a mechanism for automatically including the files that methods are in.
*
* The Composer autoloader includes all files in this section of the composer.json file during the instantiation of the loader.
*
* @var array<string>
*/
protected static $composerautoloadfiles = [
'lib/aws-sdk/src/functions.php',
'lib/guzzlehttp/guzzle/src/functions_include.php',
'lib/jmespath/src/JmesPath.php',
'lib/php-di/php-di/src/functions.php',
'lib/ralouphi/getallheaders/src/getallheaders.php',
'lib/symfony/deprecation-contracts/function.php',
];
/**
* Register the Moodle class autoloader.
*/
@ -158,6 +176,15 @@ class component {
} else {
spl_autoload_register([self::class, 'classloader']);
}
// Load any composer-driven autoload files.
// This is intended to mimic the behaviour of the standard Composer Autoloader.
foreach (static::$composerautoloadfiles as $file) {
$path = dirname(__DIR__, 2) . '/' . $file;
if (file_exists($path)) {
require_once($path);
}
}
}
/**