Completed
Branch FET-9795-new-interfaces (ef7df2)
by
unknown
1355:51 queued 1341:30
created

Psr4Autoloader::prefixes()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
cc 1
eloc 2
c 1
b 0
f 1
nc 1
nop 0
dl 0
loc 3
rs 10
1
<?php
2
namespace EventEspresso\core;
3
4
/**
5
 * Class Psr4Autoloader
6
 *
7
 * A general-purpose autoloader implementation that includes the optional
8
 * functionality of allowing multiple base directories for a single namespace
9
 * prefix.
10
 *
11
 * Given a foo-bar package of classes in the file system at the following
12
 * paths ...
13
 *
14
 *     /path/to/packages/foo-bar/
15
 *         src/
16
 *             Baz.php             # Foo\Bar\Baz
17
 *             Qux/
18
 *                 Quux.php        # Foo\Bar\Qux\Quux
19
 *         tests/
20
 *             BazTest.php         # Foo\Bar\BazTest
21
 *             Qux/
22
 *                 QuuxTest.php    # Foo\Bar\Qux\QuuxTest
23
 *
24
 * ... add the path to the class files for the \Foo\Bar\ namespace prefix
25
 * as follows:
26
 *
27
 *      <?php
28
 *      // instantiate the loader
29
 *      $loader = new \Example\Psr4Autoloader;
30
 *
31
 *      // register the autoloader
32
 *      $loader->register();
33
 *
34
 *      // register the base directories for the namespace prefix
35
 *      $loader->addNamespace('Foo\Bar', '/path/to/packages/foo-bar/src');
36
 *      $loader->addNamespace('Foo\Bar', '/path/to/packages/foo-bar/tests');
37
 *
38
 * The following line would cause the autoloader to attempt to load the
39
 * \Foo\Bar\Qux\Quux class from /path/to/packages/foo-bar/src/Qux/Quux.php:
40
 *
41
 *      <?php
42
 *      new \Foo\Bar\Qux\Quux;
43
 *
44
 * The following line would cause the autoloader to attempt to load the
45
 * \Foo\Bar\Qux\QuuxTest class from /path/to/packages/foo-bar/tests/Qux/QuuxTest.php:
46
 *
47
 *      <?php
48
 *      new \Foo\Bar\Qux\QuuxTest;
49
 *
50
 * @package 			Event Espresso
51
 * @subpackage 	core
52
 * @author 				php-fig.org
53
 * @see                    http://www.php-fig.org/psr/psr-4/examples/
54
 * @since 				$VID:$
55
 *
56
 */
57
class Psr4Autoloader {
58
59
	/**
60
	 * An associative array where the key is a namespace prefix and the value
61
	 * is an array of base directories for classes in that namespace.
62
	 *
63
	 * @var array
64
	 */
65
	protected $prefixes = array();
66
67
68
69
	/**
70
	 * @return array
71
	 */
72
	public function prefixes() {
73
		return $this->prefixes;
74
	}
75
76
77
78
	/**
79
	 * Register loader with SPL autoloader stack.
80
	 *
81
	 * @return void
82
	 */
83
	public function register() {
84
		spl_autoload_register( array( $this, 'loadClass' ) );
85
	}
86
87
88
89
	/**
90
	 * Adds a base directory for a namespace prefix.
91
	 *
92
	 * @param string $prefix The namespace prefix.
93
	 * @param string $base_dir A base directory for class files in the
94
	 * namespace.
95
	 * @param bool $prepend If true, prepend the base directory to the stack
96
	 * instead of appending it; this causes it to be searched first rather
97
	 * than last.
98
	 * @return void
99
	 */
100
	public function addNamespace( $prefix, $base_dir, $prepend = false ) {
101
		// normalize namespace prefix
102
		$prefix = trim( $prefix, '\\' ) . '\\';
103
		// normalize the base directory with a trailing separator
104
		$base_dir = rtrim( $base_dir, DIRECTORY_SEPARATOR ) . '/';
105
		// initialize the namespace prefix array
106
		if ( isset( $this->prefixes[ $prefix ] ) === false ) {
107
			$this->prefixes[ $prefix ] = array();
108
		}
109
		// retain the base directory for the namespace prefix
110
		if ( $prepend ) {
111
			array_unshift( $this->prefixes[ $prefix ], $base_dir );
112
		} else {
113
			array_push( $this->prefixes[ $prefix ], $base_dir );
114
		}
115
	}
116
117
118
119
	/**
120
	 * Loads the class file for a given class name.
121
	 *
122
	 * @param string $class The fully-qualified class name.
123
	 * @return mixed The mapped file name on success, or boolean false on
124
	 * failure.
125
	 */
126
	public function loadClass( $class ) {
127
		// the current namespace prefix
128
		$prefix = $class;
129
		// work backwards through the namespace names of the fully-qualified
130
		// class name to find a mapped file name
131
		while ( false !== $pos = strrpos( $prefix, '\\' ) ) {
132
			// retain the trailing namespace separator in the prefix
133
			$prefix = substr( $class, 0, $pos + 1 );
134
			// the rest is the relative class name
135
			$relative_class = substr( $class, $pos + 1 );
136
			// try to load a mapped file for the prefix and relative class
137
			$mapped_file = $this->loadMappedFile( $prefix, $relative_class );
138
			if ( $mapped_file ) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $mapped_file of type false|string is loosely compared to true; this is ambiguous if the string can be empty. You might want to explicitly use !== false instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
139
				return $mapped_file;
140
			}
141
			// remove the trailing namespace separator for the next iteration
142
			// of strrpos()
143
			$prefix = rtrim( $prefix, '\\' );
144
		}
145
		// never found a mapped file
146
		return false;
147
	}
148
149
150
151
	/**
152
	 * Load the mapped file for a namespace prefix and relative class.
153
	 *
154
	 * @param string $prefix The namespace prefix.
155
	 * @param string $relative_class The relative class name.
156
	 * @return mixed Boolean false if no mapped file can be loaded, or the
157
	 * name of the mapped file that was loaded.
158
	 */
159
	protected function loadMappedFile( $prefix, $relative_class ) {
160
		// are there any base directories for this namespace prefix?
161
		if ( isset( $this->prefixes[ $prefix ] ) === false ) {
162
			return false;
163
		}
164
		// look through base directories for this namespace prefix
165
		foreach ( $this->prefixes[ $prefix ] as $base_dir ) {
166
			// replace the namespace prefix with the base directory,
167
			// replace namespace separators with directory separators
168
			// in the relative class name, append with .php
169
			$file = $base_dir
170
				. str_replace( '\\', '/', $relative_class )
171
				. '.php';
172
			// if the mapped file exists, require it
173
			if ( $this->requireFile( $file ) ) {
174
				// yes, we're done
175
				return $file;
176
			}
177
		}
178
		// never found it
179
		return false;
180
	}
181
182
183
184
	/**
185
	 * If a file exists, require it from the file system.
186
	 *
187
	 * @param string $file The file to require.
188
	 * @return bool True if the file exists, false if not.
189
	 */
190
	protected function requireFile( $file ) {
191
		if ( file_exists( $file ) ) {
192
			require $file;
193
			return true;
194
		}
195
		return false;
196
	}
197
198
199
200
}
201
// End of file Psr4Autoloader.php
202
// Location: /core/Psr4Autoloader.php