CPsr4Autoloader::loadClass()   A
last analyzed

Complexity

Conditions 4
Paths 5

Size

Total Lines 36

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 20

Importance

Changes 0
Metric Value
cc 4
nc 5
nop 1
dl 0
loc 36
ccs 0
cts 15
cp 0
crap 20
rs 9.344
c 0
b 0
f 0
1
<?php
2
/**
3
 * An example of a general-purpose implementation that includes the optional
4
 * functionality of allowing multiple base directories for a single namespace
5
 * prefix.
6
 *
7
 * Added feature to have a default directory for unresolved namespaces.
8
 *
9
 * Given a foo-bar package of classes in the file system at the following
10
 * paths ...
11
 *
12
 *     /path/to/packages/foo-bar/
13
 *         src/
14
 *             Baz.php             # Foo\Bar\Baz
15
 *             Qux/
16
 *                 Quux.php        # Foo\Bar\Qux\Quux
17
 *         tests/
18
 *             BazTest.php         # Foo\Bar\BazTest
19
 *             Qux/
20
 *                 QuuxTest.php    # Foo\Bar\Qux\QuuxTest
21
 *
22
 * ... add the path to the class files for the \Foo\Bar\ namespace prefix
23
 * as follows:
24
 *
25
 *      <?php
26
 *      // instantiate the loader
27
 *      $loader = new \Example\Psr4AutoloaderClass;
28
 *
29
 *      // register the autoloader
30
 *      $loader->register();
31
 *
32
 *      // register the base directories for the namespace prefix
33
 *      $loader->addNamespace('Foo\Bar', '/path/to/packages/foo-bar/src');
34
 *      $loader->addNamespace('Foo\Bar', '/path/to/packages/foo-bar/tests');
35
 *
36
 * The following line would cause the autoloader to attempt to load the
37
 * \Foo\Bar\Qux\Quux class from /path/to/packages/foo-bar/src/Qux/Quux.php:
38
 *
39
 *      <?php
40
 *      new \Foo\Bar\Qux\Quux;
41
 *
42
 * The following line would cause the autoloader to attempt to load the
43
 * \Foo\Bar\Qux\QuuxTest class from /path/to/packages/foo-bar/tests/Qux/QuuxTest.php:
44
 *
45
 *      <?php
46
 *      new \Foo\Bar\Qux\QuuxTest;
47
 *
48
 * @link https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-4-autoloader-examples.md
49
 */
50
51
namespace Anax\Loader;
52
53
class CPsr4Autoloader
54
{
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
65
    /**
66
     * Register loader with SPL autoloader stack.
67
     *
68
     * @return $this
69
     */
70
    public function register()
71
    {
72
        spl_autoload_register(array($this, 'loadClass'));
73
        return $this;
74
    }
75
76
77
78
    /**
79
     * Adds a base directory for a namespace prefix.
80
     *
81
     * @param string $prefix The namespace prefix.
82
     * @param string $base_dir A base directory for class files in the
83
     * namespace.
84
     * @param bool $prepend If true, prepend the base directory to the stack
85
     * instead of appending it; this causes it to be searched first rather
86
     * than last.
87
     * @return $this
88
     */
89
    public function addNamespace($prefix, $base_dir, $prepend = false)
90
    {
91
        // normalize namespace prefix
92
        $prefix = trim($prefix, '\\') . '\\';
93
94
        // normalize the base directory with a trailing separator
95
        $base_dir = rtrim($base_dir, '/') . DIRECTORY_SEPARATOR;
96
        $base_dir = rtrim($base_dir, DIRECTORY_SEPARATOR) . '/';
97
98
        // initialize the namespace prefix array
99
        if (isset($this->prefixes[$prefix]) === false) {
100
            $this->prefixes[$prefix] = array();
101
        }
102
103
        // retain the base directory for the namespace prefix
104
        if ($prepend) {
105
            array_unshift($this->prefixes[$prefix], $base_dir);
106
        } else {
107
            array_push($this->prefixes[$prefix], $base_dir);
108
        }
109
110
        return $this;
111
    }
112
113
114
115
    /**
116
     * Loads the class file for a given class name.
117
     *
118
     * @param string $class The fully-qualified class name.
119
     * @return mixed The mapped file name on success, or boolean false on
120
     * failure.
121
     */
122
    public function loadClass($class)
123
    {
124
        // the current namespace prefix
125
        $prefix = $class;
126
127
        // work backwards through the namespace names of the fully-qualified
128
        // class name to find a mapped file name
129
        $relative_class = null;
130
        while (false !== $pos = strrpos($prefix, '\\')) {
131
            // retain the trailing namespace separator in the prefix
132
            $prefix = substr($class, 0, $pos + 1);
133
134
            // the rest is the relative class name
135
            $relative_class = substr($class, $pos + 1);
136
137
            // try to load a mapped file for the prefix and relative class
138
            $mapped_file = $this->loadMappedFile($prefix, $relative_class);
139
140
            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...
141
                return $mapped_file;
142
            }
143
144
            // remove the trailing namespace separator for the next iteration
145
            // of strrpos()
146
            $prefix = rtrim($prefix, '\\');
147
        }
148
149
        // try to load a mapped file for the default prefix and relative class
150
        $mapped_file = $this->loadMappedFile('\\', $relative_class);
151
        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
            return $mapped_file;
153
        }
154
155
        // never found a mapped file
156
        return false;
157
    }
158
159
160
161
    /**
162
     * Load the mapped file for a namespace prefix and relative class.
163
     *
164
     * @param string $prefix         The namespace prefix.
165
     * @param string $relative_class The relative class name.
166
     *
167
     * @return mixed Boolean false if no mapped file can be loaded, or the
168
     * name of the mapped file that was loaded.
169
     */
170
    protected function loadMappedFile($prefix, $relative_class)
171
    {
172
        // are there any base directories for this namespace prefix?
173
        if (isset($this->prefixes[$prefix]) === false) {
174
            return false;
175
        }
176
177
        // look through base directories for this namespace prefix
178
        foreach ($this->prefixes[$prefix] as $base_dir) {
179
            // replace the namespace prefix with the base directory,
180
            // replace namespace separators with directory separators
181
            // in the relative class name, append with .php
182
            $file = $base_dir
0 ignored issues
show
Unused Code introduced by
$file is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
183
                  . str_replace('\\', DIRECTORY_SEPARATOR, $relative_class)
184
                  . '.php';
185
            $file = $base_dir
186
                  . str_replace('\\', '/', $relative_class)
187
                  . '.php';
188
189
            // if the mapped file exists, require it
190
            if ($this->requireFile($file)) {
191
                // yes, we're done
192
                return $file;
193
            }
194
        }
195
196
        // never found it
197
        return false;
198
    }
199
200
201
202
    /**
203
     * If a file exists, require it from the file system.
204
     *
205
     * @param string $file The file to require.
206
     * @return bool True if the file exists, false if not.
207
     */
208
    protected function requireFile($file)
209
    {
210
        if (file_exists($file)) {
211
            require $file;
212
            return true;
213
        }
214
        return false;
215
    }
216
}
217