1: <?php
2: /**
3: * This file is part of the Autarky package.
4: *
5: * (c) Andreas Lutro <anlutro@gmail.com>
6: *
7: * For the full copyright and license information, please view the LICENSE
8: * file that was distributed with this source code.
9: */
10:
11: namespace Autarky\Config;
12:
13: use Autarky\Container\ClassResolverInterface;
14:
15: /**
16: * Factory for file-based loaders.
17: *
18: * Keeps an array of extension => class, where the class is lazily resolved out
19: * of the framework's service container when needed.
20: */
21: class LoaderFactory
22: {
23: /**
24: * The container instance.
25: *
26: * @var ClassResolverInterface
27: */
28: protected $container;
29:
30: /**
31: * The loader classes.
32: *
33: * @var string[]
34: */
35: protected $loaderClasses = [];
36:
37: /**
38: * The loader class instances.
39: *
40: * @var LoaderInterface[]
41: */
42: protected $loaders = [];
43:
44: /**
45: * The registered extensions.
46: *
47: * @var string[]
48: */
49: protected $extensions = [];
50:
51: /**
52: * @param ClassResolverInterface $container
53: */
54: public function __construct(ClassResolverInterface $container)
55: {
56: $this->container = $container;
57: }
58:
59: /**
60: * Add a loader.
61: *
62: * @param string $extensions
63: * @param string|LoaderInterface $loaderClass
64: *
65: * @return void
66: */
67: public function addLoader($extensions, $loaderClass)
68: {
69: foreach ((array) $extensions as $extension) {
70: $this->extensions[] = $extension;
71: if (is_string($loaderClass)) {
72: $this->loaderClasses[$extension] = $loaderClass;
73: } elseif ($loaderClass instanceof LoaderInterface) {
74: $this->loaders[$extension] = $loaderClass;
75: }
76: }
77: }
78:
79: /**
80: * Get the available extensions.
81: *
82: * @return array
83: */
84: public function getExtensions()
85: {
86: return $this->extensions;
87: }
88:
89: /**
90: * Get the loader for a given path.
91: *
92: * @param string $path
93: *
94: * @return LoaderInterface
95: */
96: public function getForPath($path)
97: {
98: $extension = $this->getExtension($path);
99:
100: if (!isset($this->loaders[$extension])) {
101: $this->resolveLoader($extension);
102: }
103:
104: return $this->loaders[$extension];
105: }
106:
107: protected function resolveLoader($extension)
108: {
109: if (!isset($this->loaderClasses[$extension])) {
110: throw new LoadException("No loader registered for extension: $extension");
111: }
112:
113: $this->loaders[$extension] = $this->container
114: ->resolve($this->loaderClasses[$extension]);
115: }
116:
117: protected function getExtension($path)
118: {
119: return substr($path, strrpos($path, '.'));
120: }
121: }
122: