CPsr4Autoloader::requireFile()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 8
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 8
rs 9.4285
ccs 0
cts 5
cp 0
cc 2
eloc 5
nc 2
nop 1
crap 6
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
132
            // retain the trailing namespace separator in the prefix
133
            $prefix = substr($class, 0, $pos + 1);
134
135
            // the rest is the relative class name
136
            $relative_class = substr($class, $pos + 1);
137
138
            // try to load a mapped file for the prefix and relative class
139
            $mapped_file = $this->loadMappedFile($prefix, $relative_class);
140
141
            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...
142
                return $mapped_file;
143
            }
144
145
            // remove the trailing namespace separator for the next iteration
146
            // of strrpos()
147
            $prefix = rtrim($prefix, '\\');
148
        }
149
150
        // try to load a mapped file for the default prefix and relative class
151
        $mapped_file = $this->loadMappedFile('\\', $relative_class);
152
        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...
153
            return $mapped_file;
154
        }
155
156
        // never found a mapped file
157
        return false;
158
    }
159
160
161
162
    /**
163
     * Load the mapped file for a namespace prefix and relative class.
164
     *
165
     * @param string $prefix         The namespace prefix.
166
     * @param string $relative_class The relative class name.
167
     *
168
     * @return mixed Boolean false if no mapped file can be loaded, or the
169
     * name of the mapped file that was loaded.
170
     */
171
    protected function loadMappedFile($prefix, $relative_class)
172
    {
173
        // are there any base directories for this namespace prefix?
174
        if (isset($this->prefixes[$prefix]) === false) {
175
            return false;
176
        }
177
178
        // look through base directories for this namespace prefix
179
        foreach ($this->prefixes[$prefix] as $base_dir) {
180
            // replace the namespace prefix with the base directory,
181
            // replace namespace separators with directory separators
182
            // in the relative class name, append with .php
183
            $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...
184
                  . str_replace('\\', DIRECTORY_SEPARATOR, $relative_class)
185
                  . '.php';
186
            $file = $base_dir
187
                  . str_replace('\\', '/', $relative_class)
188
                  . '.php';
189
190
            // if the mapped file exists, require it
191
            if ($this->requireFile($file)) {
192
                // yes, we're done
193
                return $file;
194
            }
195
        }
196
197
        // never found it
198
        return false;
199
    }
200
201
202
203
    /**
204
     * If a file exists, require it from the file system.
205
     *
206
     * @param string $file The file to require.
207
     * @return bool True if the file exists, false if not.
208
     */
209
    protected function requireFile($file)
210
    {
211
        if (file_exists($file)) {
212
            require $file;
213
            return true;
214
        }
215
        return false;
216
    }
217
}
218