EmailLogAutoloader::add_file()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 3
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 2

Importance

Changes 0
Metric Value
cc 2
eloc 2
nc 2
nop 1
dl 0
loc 3
ccs 3
cts 3
cp 1
crap 2
rs 10
c 0
b 0
f 0
1
<?php namespace EmailLog;
2
3
/**
4
 * Autoloader for EmailLog, based on the PSR-4 general purpose implementation.
5
 *
6
 * @see http://www.php-fig.org/psr/psr-4/
7
 *
8
 * This differs from WordPress coding standard in the following ways.
9
 *
10
 * - Class name and directory names use Snake case.
11
 * - Use of namespaces.
12
 *
13
 * Given a foo-bar package of classes in the file system at the following
14
 * paths ...
15
 *
16
 *     /path/to/packages/foo-bar/
17
 *         src/
18
 *             Baz.php             # Foo\Bar\Baz
19
 *             Qux/
20
 *                 Quux.php        # Foo\Bar\Qux\Quux
21
 *         tests/
22
 *             BazTest.php         # Foo\Bar\BazTest
23
 *             Qux/
24
 *                 QuuxTest.php    # Foo\Bar\Qux\QuuxTest
25
 *
26
 * ... add the path to the class files for the \Foo\Bar\ namespace prefix
27
 * as follows:
28
 *
29
 *      <?php
30
 *      // instantiate the loader
31
 *      $loader = new \EmailLog\EmailLogAutoloader;
32
 *
33
 *      // register the autoloader
34
 *      $loader->register();
35
 *
36
 *      // register the base directories for the namespace prefix
37
 *      $loader->addNamespace('Foo\Bar', '/path/to/packages/foo-bar/src');
38
 *      $loader->addNamespace('Foo\Bar', '/path/to/packages/foo-bar/tests');
39
 *
40
 * The following line would cause the autoloader to attempt to load the
41
 * \Foo\Bar\Qux\Quux class from /path/to/packages/foo-bar/src/Qux/Quux.php:
42
 *
43
 *      <?php
44
 *      new \Foo\Bar\Qux\Quux;
45
 *
46
 * The following line would cause the autoloader to attempt to load the
47
 * \Foo\Bar\Qux\QuuxTest class from /path/to/packages/foo-bar/tests/Qux/QuuxTest.php:
48
 *
49
 *      <?php
50
 *      new \Foo\Bar\Qux\QuuxTest;
51
 * @since 2.0
52
 */
53
class EmailLogAutoloader {
54
	/**
55
	 * An associative array where the key is a namespace prefix and the value
56
	 * is an array of base directories for classes in that namespace.
57
	 *
58
	 * @var array
59
	 */
60
	protected $prefixes = array();
61
62
	/**
63
	 * An associative array containing the list files that needs to be autoloaded.
64
	 *
65
	 * @var array
66
	 */
67
	protected $files = array();
68
69
	/**
70
	 * Register loader with SPL autoloader stack.
71
	 *
72
	 * @return void
73
	 */
74
	public function register() {
75
		spl_autoload_register( array( $this, 'load_class' ) );
76
77
		// file exists check is already done in `add_file`.
78
		foreach ( $this->files as $file ) {
79
			$this->require_file( $file );
80
		}
81
	}
82
83
	/**
84
	 * Adds a base directory for a namespace prefix.
85
	 *
86
	 * @param string $prefix   The namespace prefix.
87
	 * @param string $base_dir A base directory for class files in the
88
	 *                         namespace.
89
	 * @param bool   $prepend  If true, prepend the base directory to the stack
90
	 *                         instead of appending it; this causes it to be searched first rather
91
	 *                         than last.
92
	 *
93
	 * @return void
94
	 */
95 5
	public function add_namespace( $prefix, $base_dir, $prepend = false ) {
96
		// normalize namespace prefix
97 5
		$prefix = trim( $prefix, '\\' ) . '\\';
98
99
		// normalize the base directory with a trailing separator
100 5
		$base_dir = rtrim( $base_dir, DIRECTORY_SEPARATOR ) . '/';
101
102
		// initialize the namespace prefix array
103 5
		if ( false === isset( $this->prefixes[ $prefix ] ) ) {
104 5
			$this->prefixes[ $prefix ] = array();
105
		}
106
107
		// retain the base directory for the namespace prefix
108 5
		if ( $prepend ) {
109
			array_unshift( $this->prefixes[ $prefix ], $base_dir );
110
		} else {
111 5
			array_push( $this->prefixes[ $prefix ], $base_dir );
112
		}
113 5
	}
114
115
	/**
116
	 * Add a file to be autoloaded.
117
	 *
118
	 * @param string $filename File to be autoloaded.
119
	 */
120 1
	public function add_file( $filename ) {
121 1
		if ( ! in_array( $filename, $this->files, true ) ) {
122 1
			$this->files[] = $filename;
123
		}
124 1
	}
125
126
	/**
127
	 * Loads the class file for a given class name.
128
	 *
129
	 * @param string $class The fully-qualified class name.
130
	 *
131
	 * @return false|string The mapped file name on success, or boolean false on
132
	 *                      failure.
133
	 */
134 6
	public function load_class( $class ) {
135
		// the current namespace prefix
136 6
		$prefix = $class;
137
138
		// work backwards through the namespace names of the fully-qualified
139
		// class name to find a mapped file name
140 6
		while ( false !== $pos = strrpos( $prefix, '\\' ) ) {
141
142
			// retain the trailing namespace separator in the prefix
143 6
			$prefix = substr( $class, 0, $pos + 1 );
144
145
			// the rest is the relative class name
146 6
			$relative_class = substr( $class, $pos + 1 );
147
148
			// try to load a mapped file for the prefix and relative class
149 6
			$mapped_file = $this->load_mapped_file( $prefix, $relative_class );
150 6
			if ( $mapped_file !== false ) {
151 5
				return $mapped_file;
152
			}
153
154
			// remove the trailing namespace separator for the next iteration
155
			// of strrpos()
156 3
			$prefix = rtrim( $prefix, '\\' );
157
		}
158
159
		// never found a mapped file
160 1
		return false;
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
	 *
169
	 * @return false|string Boolean false if no mapped file can be loaded, or the
170
	 *                      name of the mapped file that was loaded.
171
	 */
172 6
	protected function load_mapped_file( $prefix, $relative_class ) {
173
		// are there any base directories for this namespace prefix?
174 6
		if ( false === isset( $this->prefixes[ $prefix ] ) ) {
175 3
			return false;
176
		}
177
178
		// look through base directories for this namespace prefix
179 5
		foreach ( $this->prefixes[ $prefix ] as $base_dir ) {
180
181
			// replace the namespace prefix with the base directory,
182
			// replace namespace separators with directory separators
183
			// in the relative class name, append with .php
184
			$file = $base_dir
185 5
			        . str_replace( '\\', '/', $relative_class )
186 5
			        . '.php';
187
188
			// if the mapped file exists, require it
189 5
			if ( $this->require_file( $file ) ) {
190
				// yes, we're done
191 5
				return $file;
192
			}
193
		}
194
195
		// never found it
196
		return false;
197
	}
198
199
	/**
200
	 * If a file exists, require it from the file system.
201
	 *
202
	 * @param string $file The file to require.
203
	 *
204
	 * @return bool True if the file exists, false if not.
205
	 */
206 2
	protected function require_file( $file ) {
207 2
		if ( file_exists( $file ) ) {
208 2
			require_once $file;
209
210 2
			return true;
211
		}
212
213
		return false;
214
	}
215
}
216