Completed
Push — master ( 8f4937...fedf49 )
by smiley
03:03
created

Psr4AutoloaderClass::addNamespace()   A

Complexity

Conditions 3
Paths 4

Size

Total Lines 20
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 20
rs 9.4285
cc 3
eloc 9
nc 4
nop 3
1
<?php
2
/**
3
 * Class Psr4AutoloaderClass
4
 *
5
 * @filesource   Psr4AutoloaderClass.php
6
 * @created      19.09.2015
7
 * @link         https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-4-autoloader-examples.md
8
 */
9
10
namespace Example;
11
12
/**
13
 * An example of a general-purpose implementation that includes the optional
14
 * functionality of allowing multiple base directories for a single namespace
15
 * prefix.
16
 *
17
 * Given a foo-bar package of classes in the file system at the following
18
 * paths ...
19
 *
20
 *     /path/to/packages/foo-bar/
21
 *         src/
22
 *             Baz.php             # Foo\Bar\Baz
23
 *             Qux/
24
 *                 Quux.php        # Foo\Bar\Qux\Quux
25
 *         tests/
26
 *             BazTest.php         # Foo\Bar\BazTest
27
 *             Qux/
28
 *                 QuuxTest.php    # Foo\Bar\Qux\QuuxTest
29
 *
30
 * ... add the path to the class files for the \Foo\Bar\ namespace prefix
31
 * as follows:
32
 *
33
 *      <?php
34
 *      // instantiate the loader
35
 *      $loader = new \Example\Psr4AutoloaderClass;
36
 *
37
 *      // register the autoloader
38
 *      $loader->register();
39
 *
40
 *      // register the base directories for the namespace prefix
41
 *      $loader->addNamespace('Foo\Bar', '/path/to/packages/foo-bar/src');
42
 *      $loader->addNamespace('Foo\Bar', '/path/to/packages/foo-bar/tests');
43
 *
44
 * The following line would cause the autoloader to attempt to load the
45
 * \Foo\Bar\Qux\Quux class from /path/to/packages/foo-bar/src/Qux/Quux.php:
46
 *
47
 *      <?php
48
 *      new \Foo\Bar\Qux\Quux;
49
 *
50
 * The following line would cause the autoloader to attempt to load the
51
 * \Foo\Bar\Qux\QuuxTest class from /path/to/packages/foo-bar/tests/Qux/QuuxTest.php:
52
 *
53
 *      <?php
54
 *      new \Foo\Bar\Qux\QuuxTest;
55
 */
56
class Psr4AutoloaderClass
57
{
58
	/**
59
	 * An associative array where the key is a namespace prefix and the value
60
	 * is an array of base directories for classes in that namespace.
61
	 *
62
	 * @var array
63
	 */
64
	protected $prefixes = array();
65
66
	/**
67
	 * Register loader with SPL autoloader stack.
68
	 *
69
	 * @return void
70
	 */
71
	public function register()
72
	{
73
		spl_autoload_register(array($this, 'loadClass'));
74
	}
75
76
	/**
77
	 * Adds a base directory for a namespace prefix.
78
	 *
79
	 * @param string $prefix The namespace prefix.
80
	 * @param string $base_dir A base directory for class files in the
81
	 * namespace.
82
	 * @param bool $prepend If true, prepend the base directory to the stack
83
	 * instead of appending it; this causes it to be searched first rather
84
	 * than last.
85
	 * @return void
86
	 */
87
	public function addNamespace($prefix, $base_dir, $prepend = false)
88
	{
89
		// normalize namespace prefix
90
		$prefix = trim($prefix, '\\') . '\\';
91
92
		// normalize the base directory with a trailing separator
93
		$base_dir = rtrim($base_dir, DIRECTORY_SEPARATOR) . '/';
94
95
		// initialize the namespace prefix array
96
		if (isset($this->prefixes[$prefix]) === false) {
97
			$this->prefixes[$prefix] = array();
98
		}
99
100
		// retain the base directory for the namespace prefix
101
		if ($prepend) {
102
			array_unshift($this->prefixes[$prefix], $base_dir);
103
		} else {
104
			array_push($this->prefixes[$prefix], $base_dir);
105
		}
106
	}
107
108
	/**
109
	 * Loads the class file for a given class name.
110
	 *
111
	 * @param string $class The fully-qualified class name.
112
	 * @return mixed The mapped file name on success, or boolean false on
113
	 * failure.
114
	 */
115
	public function loadClass($class)
116
	{
117
		// the current namespace prefix
118
		$prefix = $class;
119
120
		// work backwards through the namespace names of the fully-qualified
121
		// class name to find a mapped file name
122
		while (false !== $pos = strrpos($prefix, '\\')) {
123
124
			// retain the trailing namespace separator in the prefix
125
			$prefix = substr($class, 0, $pos + 1);
126
127
			// the rest is the relative class name
128
			$relative_class = substr($class, $pos + 1);
129
130
			// try to load a mapped file for the prefix and relative class
131
			$mapped_file = $this->loadMappedFile($prefix, $relative_class);
132
			if ($mapped_file) {
133
				return $mapped_file;
134
			}
135
136
			// remove the trailing namespace separator for the next iteration
137
			// of strrpos()
138
			$prefix = rtrim($prefix, '\\');
139
		}
140
141
		// never found a mapped file
142
		return false;
143
	}
144
145
	/**
146
	 * Load the mapped file for a namespace prefix and relative class.
147
	 *
148
	 * @param string $prefix The namespace prefix.
149
	 * @param string $relative_class The relative class name.
150
	 * @return mixed Boolean false if no mapped file can be loaded, or the
151
	 * name of the mapped file that was loaded.
152
	 */
153
	protected function loadMappedFile($prefix, $relative_class)
154
	{
155
		// are there any base directories for this namespace prefix?
156
		if (isset($this->prefixes[$prefix]) === false) {
157
			return false;
158
		}
159
160
		// look through base directories for this namespace prefix
161
		foreach ($this->prefixes[$prefix] as $base_dir) {
162
163
			// replace the namespace prefix with the base directory,
164
			// replace namespace separators with directory separators
165
			// in the relative class name, append with .php
166
			$file = $base_dir
167
				. str_replace('\\', '/', $relative_class)
168
				. '.php';
169
170
			// if the mapped file exists, require it
171
			if ($this->requireFile($file)) {
172
				// yes, we're done
173
				return $file;
174
			}
175
		}
176
177
		// never found it
178
		return false;
179
	}
180
181
	/**
182
	 * If a file exists, require it from the file system.
183
	 *
184
	 * @param string $file The file to require.
185
	 * @return bool True if the file exists, false if not.
186
	 */
187
	protected function requireFile($file)
188
	{
189
		if (file_exists($file)) {
190
			require $file;
191
			return true;
192
		}
193
		return false;
194
	}
195
}
196