1 | <?php |
||
25 | class LoaderFactory |
||
26 | { |
||
27 | |||
28 | /** |
||
29 | * Array of fully qualified class names of known loaders. |
||
30 | * |
||
31 | * @var array<string> |
||
32 | * |
||
33 | * @since 0.4.0 |
||
34 | */ |
||
35 | protected static $loaders = [ |
||
36 | 'BrightNucleus\Config\Loader\PHPLoader', |
||
37 | ]; |
||
38 | |||
39 | /** |
||
40 | * Array of instantiated loaders. |
||
41 | * |
||
42 | * These are lazily instantiated and added as needed. |
||
43 | * |
||
44 | * @var LoaderInterface[] |
||
45 | * |
||
46 | * @since 0.4.0 |
||
47 | */ |
||
48 | protected static $loaderInstances = []; |
||
49 | |||
50 | /** |
||
51 | * Create a new Loader from an URI. |
||
52 | * |
||
53 | * @since 0.4.0 |
||
54 | * |
||
55 | * @param string $uri URI of the resource to create a loader for. |
||
56 | * |
||
57 | * @return LoaderInterface Loader that is able to load the given URI. |
||
58 | * @throws FailedToLoadConfigException If no suitable loader was found. |
||
59 | */ |
||
60 | 2 | public static function createFromUri($uri) |
|
61 | { |
||
62 | 2 | foreach (static::$loaders as $loader) { |
|
63 | 2 | if ($loader::canLoad($uri)) { |
|
64 | 2 | return static::getLoader($loader); |
|
65 | } |
||
66 | } |
||
67 | |||
68 | throw new FailedToLoadConfigException( |
||
69 | sprintf( |
||
70 | _('Could not find a suitable loader for URI "%1$s".'), |
||
71 | $uri |
||
72 | ) |
||
73 | ); |
||
74 | } |
||
75 | |||
76 | /** |
||
77 | * Get an instance of a specific loader. |
||
78 | * |
||
79 | * The loader is lazily instantiated if needed. |
||
80 | * |
||
81 | * @since 0.4.0 |
||
82 | * |
||
83 | * @param string $loaderClass Fully qualified class name of the loader to get. |
||
84 | * |
||
85 | * @return LoaderInterface Instance of the requested loader. |
||
86 | * @throws FailedToLoadConfigException If the loader class could not be instantiated. |
||
87 | */ |
||
88 | 2 | public static function getLoader($loaderClass) |
|
89 | { |
||
90 | try { |
||
91 | 2 | if (! array_key_exists($loaderClass, static::$loaderInstances)) { |
|
92 | static::$loaderInstances[$loaderClass] = new $loaderClass; |
||
93 | } |
||
94 | |||
95 | 2 | return static::$loaderInstances[$loaderClass]; |
|
96 | } catch (Exception $exception) { |
||
97 | throw new FailedToLoadConfigException( |
||
98 | sprintf( |
||
99 | _('Could not instantiate the requested loader class "%1$s".'), |
||
100 | $loaderClass |
||
101 | ) |
||
102 | ); |
||
103 | } |
||
104 | } |
||
105 | |||
106 | /** |
||
107 | * Register a new loader. |
||
108 | * |
||
109 | * @since 0.4.0 |
||
110 | * |
||
111 | * @param string $loader Fully qualified class name of a loader implementing LoaderInterface. |
||
112 | */ |
||
113 | public static function registerLoader($loader) |
||
121 | } |
||
122 |