aboutsummaryrefslogtreecommitdiffhomepage
path: root/Digitigrade/PluginLoader.php
blob: 094f1b6b30a286c2706b437dda526966af24df8d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
<?php
namespace Digitigrade;

abstract class PluginLoader {
    public static array $loadedPlugins = [];

    public static function load(string $path): bool {
        try {
            $phar = @new \Phar($path);
        } catch (\Exception $e) {
            Logger::getInstance()->warning("$path doesn't appear to be a valid phar file!");
        }
        $metadata = $phar->getMetadata();
        if (!($metadata instanceof PluginMetadata)) {
            Logger::getInstance()->warning("$path doesn't appear to be a valid plugin!");
            return false;
        }
        self::$loadedPlugins[$path] = $metadata;

        // setup autoloads
        spl_autoload_register(function (string $className) use ($path, $metadata, $phar) {
            /** @var PluginMetadata $metadata */
            /** @var \Phar $phar */
            if (str_starts_with($className, $metadata->autoloadPrefix)) {
                require "phar://$path/"
                    . $metadata->autoloadDir
                    . str_replace('\\', '/',
                        substr_replace($className, '', 0, strlen($metadata->autoloadPrefix)))
                    . '.php';
            }
        });

        // run entrypoint if defined
        if (isset($metadata->entrypoint)) {
            require "phar://$path/$metadata->entrypoint";
        }

        return true;
    }

    public static function loadDir(string $directory) {
        foreach (glob("$directory/*.phar") as $file) {
            self::load($file);
        }
    }
}