Completed
Branch BETA-4.9-messages-queue-fixed (941081)
by
unknown
30:24 queued 05:56
created

Psr4Autoloader   A

Complexity

Total Complexity 13

Size/Duplication

Total Lines 135
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 0
Metric Value
wmc 13
lcom 1
cbo 0
dl 0
loc 135
rs 10

5 Methods

Rating   Name   Duplication   Size   Complexity  
A register() 0 3 1
A loadClass() 0 22 3
A addNamespace() 0 16 3
B loadMappedFile() 0 22 4
A requireFile() 0 7 2
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
	 * Register loader with SPL autoloader stack.
71
	 *
72
	 * @return void
73
	 */
74
	public function register() {
75
		spl_autoload_register( array( $this, 'loadClass' ) );
76
	}
77
78
79
80
	/**
81
	 * Adds a base directory for a namespace prefix.
82
	 *
83
	 * @param string $prefix The namespace prefix.
84
	 * @param string $base_dir A base directory for class files in the
85
	 * namespace.
86
	 * @param bool $prepend If true, prepend the base directory to the stack
87
	 * instead of appending it; this causes it to be searched first rather
88
	 * than last.
89
	 * @return void
90
	 */
91
	public function addNamespace( $prefix, $base_dir, $prepend = false ) {
92
		// normalize namespace prefix
93
		$prefix = trim( $prefix, '\\' ) . '\\';
94
		// normalize the base directory with a trailing separator
95
		$base_dir = rtrim( $base_dir, DIRECTORY_SEPARATOR ) . '/';
96
		// initialize the namespace prefix array
97
		if ( isset( $this->prefixes[ $prefix ] ) === false ) {
98
			$this->prefixes[ $prefix ] = array();
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
110
	/**
111
	 * Loads the class file for a given class name.
112
	 *
113
	 * @param string $class The fully-qualified class name.
114
	 * @return mixed The mapped file name on success, or boolean false on
115
	 * failure.
116
	 */
117
	public function loadClass( $class ) {
118
		// the current namespace prefix
119
		$prefix = $class;
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
			// retain the trailing namespace separator in the prefix
124
			$prefix = substr( $class, 0, $pos + 1 );
125
			// the rest is the relative class name
126
			$relative_class = substr( $class, $pos + 1 );
127
			// try to load a mapped file for the prefix and relative class
128
			$mapped_file = $this->loadMappedFile( $prefix, $relative_class );
129
			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...
130
				return $mapped_file;
131
			}
132
			// remove the trailing namespace separator for the next iteration
133
			// of strrpos()
134
			$prefix = rtrim( $prefix, '\\' );
135
		}
136
		// never found a mapped file
137
		return false;
138
	}
139
140
141
142
	/**
143
	 * Load the mapped file for a namespace prefix and relative class.
144
	 *
145
	 * @param string $prefix The namespace prefix.
146
	 * @param string $relative_class The relative class name.
147
	 * @return mixed Boolean false if no mapped file can be loaded, or the
148
	 * name of the mapped file that was loaded.
149
	 */
150
	protected function loadMappedFile( $prefix, $relative_class ) {
151
		// are there any base directories for this namespace prefix?
152
		if ( isset( $this->prefixes[ $prefix ] ) === false ) {
153
			return false;
154
		}
155
		// look through base directories for this namespace prefix
156
		foreach ( $this->prefixes[ $prefix ] as $base_dir ) {
157
			// replace the namespace prefix with the base directory,
158
			// replace namespace separators with directory separators
159
			// in the relative class name, append with .php
160
			$file = $base_dir
161
				. str_replace( '\\', '/', $relative_class )
162
				. '.php';
163
			// if the mapped file exists, require it
164
			if ( $this->requireFile( $file ) ) {
165
				// yes, we're done
166
				return $file;
167
			}
168
		}
169
		// never found it
170
		return false;
171
	}
172
173
174
175
	/**
176
	 * If a file exists, require it from the file system.
177
	 *
178
	 * @param string $file The file to require.
179
	 * @return bool True if the file exists, false if not.
180
	 */
181
	protected function requireFile( $file ) {
182
		if ( file_exists( $file ) ) {
183
			require $file;
184
			return true;
185
		}
186
		return false;
187
	}
188
189
190
191
}
192
// End of file Psr4Autoloader.php
193
// Location: /core/Psr4Autoloader.php