Completed
Branch BUG-9871-email-validation (e62b1a)
by
unknown
350:41 queued 333:27
created

Psr4Autoloader::addNamespace()   A

Complexity

Conditions 3
Paths 4

Size

Total Lines 16
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 3
eloc 9
nc 4
nop 3
dl 0
loc 16
rs 9.4285
c 0
b 0
f 0
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
	 * namespace separator
61
	 */
62
	const NS = '\\';
63
64
	/**
65
	 * An associative array where the key is a namespace prefix and the value
66
	 * is an array of base directories for classes in that namespace.
67
	 *
68
	 * @var array
69
	 */
70
	protected $prefixes = array();
71
72
73
74
	/**
75
	 * returns an array of registered namespace prefixes
76
	 *
77
	 * @param string $prefix
78
	 * @return array
79
	 */
80
	public function prefixes( $prefix = '' ) {
81
		if ( ! empty( $prefix ) ) {
82
			// are there any base directories for this namespace prefix?
83
			return isset( $this->prefixes[ $prefix ] ) ? $this->prefixes[ $prefix ] : array();
84
		}
85
		return $this->prefixes;
86
	}
87
88
89
90
	/**
91
	 * Register loader with SPL autoloader stack.
92
	 *
93
	 * @return void
94
	 */
95
	public function register() {
96
		spl_autoload_register( array( $this, 'loadClass' ) );
97
	}
98
99
100
101
	/**
102
	 * Adds a base directory for a namespace prefix.
103
	 *
104
	 * @param string $prefix The namespace prefix.
105
	 * @param string $base_dir A base directory for class files in the
106
	 * namespace.
107
	 * @param bool $prepend If true, prepend the base directory to the stack
108
	 * instead of appending it; this causes it to be searched first rather
109
	 * than last.
110
	 * @return void
111
	 */
112
	public function addNamespace( $prefix, $base_dir, $prepend = false ) {
113
		// normalize namespace prefix
114
		$prefix = trim( $prefix, Psr4Autoloader::NS ) . Psr4Autoloader::NS;
115
		// normalize the base directory with a trailing separator
116
		$base_dir = \EEH_File::standardise_and_end_with_directory_separator( $base_dir );
117
		// initialize the namespace prefix array
118
		if ( isset( $this->prefixes[ $prefix ] ) === false ) {
119
			$this->prefixes[ $prefix ] = array();
120
		}
121
		// retain the base directory for the namespace prefix
122
		if ( $prepend ) {
123
			array_unshift( $this->prefixes[ $prefix ], $base_dir );
124
		} else {
125
			$this->prefixes[ $prefix ][] = $base_dir;
126
		}
127
	}
128
129
130
131
	/**
132
	 * Loads the class file for a given class name.
133
	 *
134
	 * @param string $class The fully-qualified class name.
135
	 * @return mixed The mapped file name on success, or boolean false on
136
	 * failure.
137
	 */
138
	public function loadClass( $class ) {
139
		// the current namespace prefix
140
		$prefix = $class;
141
		// work backwards through the namespace names of the fully-qualified
142
		// class name to find a mapped file name
143
		while ( false !== $pos = strrpos( $prefix, Psr4Autoloader::NS ) ) {
144
			// retain the trailing namespace separator in the prefix
145
			$prefix = substr( $class, 0, $pos + 1 );
146
			// the rest is the relative class name
147
			$relative_class = substr( $class, $pos + 1 );
148
			// try to load a mapped file for the prefix and relative class
149
			$mapped_file = $this->loadMappedFile( $prefix, $relative_class );
150
			if ( $mapped_file ) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $mapped_file of type string|false 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...
151
				return $mapped_file;
152
			}
153
			// remove the trailing namespace separator for the next iteration
154
			// of strrpos()
155
			$prefix = rtrim( $prefix, Psr4Autoloader::NS );
156
		}
157
		// never found a mapped file
158
		return false;
159
	}
160
161
162
163
	/**
164
	 * Load the mapped file for a namespace prefix and relative class.
165
	 *
166
	 * @param string $prefix The namespace prefix.
167
	 * @param string $relative_class The relative class name.
168
	 * @return mixed Boolean false if no mapped file can be loaded, or the
169
	 * name of the mapped file that was loaded.
170
	 */
171
	protected function loadMappedFile( $prefix, $relative_class ) {
172
		// look through base directories for this namespace prefix
173
		foreach ( $this->prefixes( $prefix ) as $base_dir ) {
174
			// replace the namespace prefix with the base directory,
175
			// replace namespace separators with directory separators
176
			// in the relative class name, append with .php
177
			$file = $base_dir
178
				. str_replace( Psr4Autoloader::NS, DS, $relative_class )
179
				. '.php';
180
			// if the mapped file exists, require it
181
			if ( $this->requireFile( $file ) ) {
182
				// yes, we're done
183
				return $file;
184
			}
185
		}
186
		// never found it
187
		return false;
188
	}
189
190
191
192
	/**
193
	 * If a file exists, require it from the file system.
194
	 *
195
	 * @param string $file The file to require.
196
	 * @return bool True if the file exists, false if not.
197
	 */
198
	protected function requireFile( $file ) {
199
		if ( file_exists( $file ) ) {
200
			require $file;
201
			return true;
202
		}
203
		return false;
204
	}
205
206
207
208
}
209
// End of file Psr4Autoloader.php
210
// Location: /core/Psr4Autoloader.php