Completed
Push — master ( 8bffa3...d70731 )
by Sudar
06:01 queued 03:08
created

EmailLogAutoloader::add_file()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 2

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 2
eloc 3
c 1
b 0
f 0
nc 2
nop 1
dl 0
loc 5
ccs 5
cts 5
cp 1
crap 2
rs 9.4285
1
<?php namespace EmailLog;
2
3
/**
4
 * Autoloader for EmailLog, based on the PSR-4 general purpose implemetation.
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 \Example\Psr4AutoloaderClass;
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
 *
52
 * @since 2.0
53
 */
54
class EmailLogAutoloader {
55
	/**
56
	 * An associative array where the key is a namespace prefix and the value
57
	 * is an array of base directories for classes in that namespace.
58
	 *
59
	 * @var array
60
	 */
61
	protected $prefixes = array();
62
63
	/**
64
	 * An associative array containing the list files that needs to be autoloaded.
65
	 *
66
	 * @var array
67
	 */
68
	protected $files = array();
69
70
	/**
71
	 * Register loader with SPL autoloader stack.
72
	 *
73
	 * @return void
74
	 */
75
	public function register() {
76
		spl_autoload_register( array( $this, 'load_class' ) );
77
78
		// file exists check is already done in `add_file`.
79
		foreach ( $this->files as $file ) {
80
			$this->require_file( $file );
81
		}
82
	}
83
84
	/**
85
	 * Adds a base directory for a namespace prefix.
86
	 *
87
	 * @param string $prefix   The namespace prefix.
88
	 * @param string $base_dir A base directory for class files in the
89
	 *                         namespace.
90
	 * @param bool   $prepend  If true, prepend the base directory to the stack
91
	 *                         instead of appending it; this causes it to be searched first rather
92
	 *                         than last.
93
	 *
94
	 * @return void
95
	 */
96 12
	public function add_namespace( $prefix, $base_dir, $prepend = false ) {
97
		// normalize namespace prefix
98 12
		$prefix = trim( $prefix, '\\' ) . '\\';
99
100
		// normalize the base directory with a trailing separator
101 12
		$base_dir = rtrim( $base_dir, DIRECTORY_SEPARATOR ) . '/';
102
103
		// initialize the namespace prefix array
104 12
		if ( false === isset( $this->prefixes[ $prefix ] ) ) {
105 12
			$this->prefixes[ $prefix ] = array();
106 12
		}
107
108
		// retain the base directory for the namespace prefix
109 12
		if ( $prepend ) {
110
			array_unshift( $this->prefixes[ $prefix ], $base_dir );
111
		} else {
112 12
			array_push( $this->prefixes[ $prefix ], $base_dir );
113
		}
114 12
	}
115
116
	/**
117
	 * Add a file to be autoloaded.
118
	 *
119
	 * @param $filename File to be autoloaded.
120
	 */
121 4
	public function add_file( $filename ) {
122 4
		if ( file_exists( $filename ) ) {
123 2
			$this->files[] = $filename;
124 2
		}
125 4
	}
126
127
	/**
128
	 * Loads the class file for a given class name.
129
	 *
130
	 * @param string $class The fully-qualified class name.
131
	 *
132
	 * @return string|false The mapped file name on success, or boolean false on
133
	 * failure.
134
	 */
135 8
	public function load_class( $class ) {
136
		// the current namespace prefix
137 8
		$prefix = $class;
138
139
		// work backwards through the namespace names of the fully-qualified
140
		// class name to find a mapped file name
141 8
		while ( false !== $pos = strrpos( $prefix, '\\' ) ) {
142
143
			// retain the trailing namespace separator in the prefix
144 8
			$prefix = substr( $class, 0, $pos + 1 );
145
146
			// the rest is the relative class name
147 8
			$relative_class = substr( $class, $pos + 1 );
148
149
			// try to load a mapped file for the prefix and relative class
150 8
			$mapped_file = $this->load_mapped_file( $prefix, $relative_class );
151 8
			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...
152 6
				return $mapped_file;
153
			}
154
155
			// remove the trailing namespace separator for the next iteration
156
			// of strrpos()
157 2
			$prefix = rtrim( $prefix, '\\' );
158 2
		}
159
160
		// never found a mapped file
161 2
		return false;
162
	}
163
164
	/**
165
	 * Load the mapped file for a namespace prefix and relative class.
166
	 *
167
	 * @param string $prefix         The namespace prefix.
168
	 * @param string $relative_class The relative class name.
169
	 *
170
	 * @return false|string Boolean false if no mapped file can be loaded, or the
171
	 * name of the mapped file that was loaded.
172
	 */
173 8
	protected function load_mapped_file( $prefix, $relative_class ) {
174
		// are there any base directories for this namespace prefix?
175 8
		if ( false === isset( $this->prefixes[ $prefix ] ) ) {
176 2
			return false;
177
		}
178
179
		// look through base directories for this namespace prefix
180 6
		foreach ( $this->prefixes[ $prefix ] as $base_dir ) {
181
182
			// replace the namespace prefix with the base directory,
183
			// replace namespace separators with directory separators
184
			// in the relative class name, append with .php
185
			$file = $base_dir
186 6
			        . str_replace( '\\', '/', $relative_class )
187 6
			        . '.php';
188
189
			// if the mapped file exists, require it
190 6
			if ( $this->require_file( $file ) ) {
191
				// yes, we're done
192 6
				return $file;
193
			}
194 2
		}
195
196
		// never found it
197
		return false;
198
	}
199
200
	/**
201
	 * If a file exists, require it from the file system.
202
	 *
203
	 * @param string $file The file to require.
204
	 *
205
	 * @return bool True if the file exists, false if not.
206
	 */
207
	protected function require_file( $file ) {
208
		if ( file_exists( $file ) ) {
209
			require $file;
210
211
			return true;
212
		}
213
214
		return false;
215
	}
216
}