Completed
Push — feature/45-drop-php-52 ( f96425 )
by Sudar
11:51
created

EmailLogAutoloader::load_class()   B

Complexity

Conditions 3
Paths 3

Size

Total Lines 28
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
cc 3
eloc 10
c 1
b 0
f 1
nc 3
nop 1
dl 0
loc 28
rs 8.8571
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
class EmailLogAutoloader {
53
	/**
54
	 * An associative array where the key is a namespace prefix and the value
55
	 * is an array of base directories for classes in that namespace.
56
	 *
57
	 * @var array
58
	 */
59
	protected $prefixes = array();
60
61
	/**
62
	 * Register loader with SPL autoloader stack.
63
	 *
64
	 * @return void
65
	 */
66
	public function register() {
67
		spl_autoload_register( array( $this, 'load_class' ) );
68
	}
69
70
	/**
71
	 * Adds a base directory for a namespace prefix.
72
	 *
73
	 * @param string $prefix   The namespace prefix.
74
	 * @param string $base_dir A base directory for class files in the
75
	 *                         namespace.
76
	 * @param bool   $prepend  If true, prepend the base directory to the stack
77
	 *                         instead of appending it; this causes it to be searched first rather
78
	 *                         than last.
79
	 *
80
	 * @return void
81
	 */
82
	public function add_namespace( $prefix, $base_dir, $prepend = false ) {
83
		// normalize namespace prefix
84
		$prefix = trim( $prefix, '\\' ) . '\\';
85
86
		// normalize the base directory with a trailing separator
87
		$base_dir = rtrim( $base_dir, DIRECTORY_SEPARATOR ) . '/';
88
89
		// initialize the namespace prefix array
90
		if ( false === isset( $this->prefixes[ $prefix ] ) ) {
91
			$this->prefixes[ $prefix ] = array();
92
		}
93
94
		// retain the base directory for the namespace prefix
95
		if ( $prepend ) {
96
			array_unshift( $this->prefixes[ $prefix ], $base_dir );
97
		} else {
98
			array_push( $this->prefixes[ $prefix ], $base_dir );
99
		}
100
	}
101
102
	/**
103
	 * Loads the class file for a given class name.
104
	 *
105
	 * @param string $class The fully-qualified class name.
106
	 *
107
	 * @return mixed The mapped file name on success, or boolean false on
0 ignored issues
show
Documentation introduced by
Consider making the return type a bit more specific; maybe use string|false.

This check looks for the generic type array as a return type and suggests a more specific type. This type is inferred from the actual code.

Loading history...
108
	 * failure.
109
	 */
110
	public function load_class( $class ) {
111
		// the current namespace prefix
112
		$prefix = $class;
113
114
		// work backwards through the namespace names of the fully-qualified
115
		// class name to find a mapped file name
116
		while ( false !== $pos = strrpos( $prefix, '\\' ) ) {
117
118
			// retain the trailing namespace separator in the prefix
119
			$prefix = substr( $class, 0, $pos + 1 );
120
121
			// the rest is the relative class name
122
			$relative_class = substr( $class, $pos + 1 );
123
124
			// try to load a mapped file for the prefix and relative class
125
			$mapped_file = $this->load_mapped_file( $prefix, $relative_class );
126
			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...
127
				return $mapped_file;
128
			}
129
130
			// remove the trailing namespace separator for the next iteration
131
			// of strrpos()
132
			$prefix = rtrim( $prefix, '\\' );
133
		}
134
135
		// never found a mapped file
136
		return false;
137
	}
138
139
	/**
140
	 * Load the mapped file for a namespace prefix and relative class.
141
	 *
142
	 * @param string $prefix         The namespace prefix.
143
	 * @param string $relative_class The relative class name.
144
	 *
145
	 * @return mixed Boolean false if no mapped file can be loaded, or the
0 ignored issues
show
Documentation introduced by
Consider making the return type a bit more specific; maybe use false|string.

This check looks for the generic type array as a return type and suggests a more specific type. This type is inferred from the actual code.

Loading history...
146
	 * name of the mapped file that was loaded.
147
	 */
148
	protected function load_mapped_file( $prefix, $relative_class ) {
149
		// are there any base directories for this namespace prefix?
150
		if ( false === isset( $this->prefixes[ $prefix ] ) ) {
151
			return false;
152
		}
153
154
		// look through base directories for this namespace prefix
155
		foreach ( $this->prefixes[ $prefix ] as $base_dir ) {
156
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
164
			// if the mapped file exists, require it
165
			if ( $this->require_file( $file ) ) {
166
				// yes, we're done
167
				return $file;
168
			}
169
		}
170
171
		// never found it
172
		return false;
173
	}
174
175
	/**
176
	 * If a file exists, require it from the file system.
177
	 *
178
	 * @param string $file The file to require.
179
	 *
180
	 * @return bool True if the file exists, false if not.
181
	 */
182
	protected function require_file( $file ) {
183
		if ( file_exists( $file ) ) {
184
			require $file;
185
186
			return true;
187
		}
188
189
		return false;
190
	}
191
}