DebugClassLoader::checkAnnotations()   F
last analyzed

Complexity

Conditions 40
Paths > 20000

Size

Total Lines 98

Duplication

Lines 10
Ratio 10.2 %

Importance

Changes 0
Metric Value
cc 40
nc 188860
nop 2
dl 10
loc 98
rs 0
c 0
b 0
f 0

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
/*
4
 * This file is part of the Symfony package.
5
 *
6
 * (c) Fabien Potencier <[email protected]>
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
12
namespace Symfony\Component\Debug;
13
14
/**
15
 * Autoloader checking if the class is really defined in the file found.
16
 *
17
 * The ClassLoader will wrap all registered autoloaders
18
 * and will throw an exception if a file is found but does
19
 * not declare the class.
20
 *
21
 * @author Fabien Potencier <[email protected]>
22
 * @author Christophe Coevoet <[email protected]>
23
 * @author Nicolas Grekas <[email protected]>
24
 */
25
class DebugClassLoader
26
{
27
    private $classLoader;
28
    private $isFinder;
29
    private $loaded = array();
30
    private static $caseCheck;
31
    private static $checkedClasses = array();
32
    private static $final = array();
33
    private static $finalMethods = array();
34
    private static $deprecated = array();
35
    private static $internal = array();
36
    private static $internalMethods = array();
37
    private static $darwinCache = array('/' => array('/', array()));
38
39
    public function __construct(callable $classLoader)
40
    {
41
        $this->classLoader = $classLoader;
42
        $this->isFinder = \is_array($classLoader) && method_exists($classLoader[0], 'findFile');
43
44
        if (!isset(self::$caseCheck)) {
45
            $file = file_exists(__FILE__) ? __FILE__ : rtrim(realpath('.'), \DIRECTORY_SEPARATOR);
46
            $i = strrpos($file, \DIRECTORY_SEPARATOR);
47
            $dir = substr($file, 0, 1 + $i);
48
            $file = substr($file, 1 + $i);
49
            $test = strtoupper($file) === $file ? strtolower($file) : strtoupper($file);
50
            $test = realpath($dir.$test);
51
52
            if (false === $test || false === $i) {
53
                // filesystem is case sensitive
54
                self::$caseCheck = 0;
55
            } elseif (substr($test, -\strlen($file)) === $file) {
56
                // filesystem is case insensitive and realpath() normalizes the case of characters
57
                self::$caseCheck = 1;
58
            } elseif (false !== stripos(PHP_OS, 'darwin')) {
59
                // on MacOSX, HFS+ is case insensitive but realpath() doesn't normalize the case of characters
60
                self::$caseCheck = 2;
61
            } else {
62
                // filesystem case checks failed, fallback to disabling them
63
                self::$caseCheck = 0;
64
            }
65
        }
66
    }
67
68
    /**
69
     * Gets the wrapped class loader.
70
     *
71
     * @return callable The wrapped class loader
72
     */
73
    public function getClassLoader()
74
    {
75
        return $this->classLoader;
76
    }
77
78
    /**
79
     * Wraps all autoloaders.
80
     */
81
    public static function enable()
82
    {
83
        // Ensures we don't hit https://bugs.php.net/42098
84
        class_exists('Symfony\Component\Debug\ErrorHandler');
85
        class_exists('Psr\Log\LogLevel');
86
87
        if (!\is_array($functions = spl_autoload_functions())) {
88
            return;
89
        }
90
91
        foreach ($functions as $function) {
92
            spl_autoload_unregister($function);
93
        }
94
95
        foreach ($functions as $function) {
96
            if (!\is_array($function) || !$function[0] instanceof self) {
97
                $function = array(new static($function), 'loadClass');
98
            }
99
100
            spl_autoload_register($function);
101
        }
102
    }
103
104
    /**
105
     * Disables the wrapping.
106
     */
107
    public static function disable()
108
    {
109
        if (!\is_array($functions = spl_autoload_functions())) {
110
            return;
111
        }
112
113
        foreach ($functions as $function) {
114
            spl_autoload_unregister($function);
115
        }
116
117
        foreach ($functions as $function) {
118
            if (\is_array($function) && $function[0] instanceof self) {
119
                $function = $function[0]->getClassLoader();
120
            }
121
122
            spl_autoload_register($function);
123
        }
124
    }
125
126
    /**
127
     * Loads the given class or interface.
128
     *
129
     * @param string $class The name of the class
130
     *
131
     * @throws \RuntimeException
132
     */
133
    public function loadClass($class)
134
    {
135
        $e = error_reporting(error_reporting() | E_PARSE | E_ERROR | E_CORE_ERROR | E_COMPILE_ERROR);
136
137
        try {
138
            if ($this->isFinder && !isset($this->loaded[$class])) {
139
                $this->loaded[$class] = true;
140
                if ($file = $this->classLoader[0]->findFile($class) ?: false) {
141
                    $wasCached = \function_exists('opcache_is_script_cached') && @opcache_is_script_cached($file);
142
143
                    require $file;
144
145
                    if ($wasCached) {
146
                        return;
147
                    }
148
                }
149
            } else {
150
                \call_user_func($this->classLoader, $class);
151
                $file = false;
152
            }
153
        } finally {
154
            error_reporting($e);
155
        }
156
157
        $this->checkClass($class, $file);
0 ignored issues
show
Bug introduced by
The variable $file does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
158
    }
159
160
    private function checkClass($class, $file = null)
161
    {
162
        $exists = null === $file || \class_exists($class, false) || \interface_exists($class, false) || \trait_exists($class, false);
163
164
        if (null !== $file && $class && '\\' === $class[0]) {
165
            $class = substr($class, 1);
166
        }
167
168
        if ($exists) {
169
            if (isset(self::$checkedClasses[$class])) {
170
                return;
171
            }
172
            self::$checkedClasses[$class] = true;
173
174
            $refl = new \ReflectionClass($class);
175
            if (null === $file && $refl->isInternal()) {
176
                return;
177
            }
178
            $name = $refl->getName();
179
180
            if ($name !== $class && 0 === \strcasecmp($name, $class)) {
181
                throw new \RuntimeException(sprintf('Case mismatch between loaded and declared class names: "%s" vs "%s".', $class, $name));
182
            }
183
184
            $deprecations = $this->checkAnnotations($refl, $name);
185
186
            foreach ($deprecations as $message) {
187
                @trigger_error($message, E_USER_DEPRECATED);
188
            }
189
        }
190
191
        if (!$file) {
192
            return;
193
        }
194
195
        if (!$exists) {
196
            if (false !== strpos($class, '/')) {
197
                throw new \RuntimeException(sprintf('Trying to autoload a class with an invalid name "%s". Be careful that the namespace separator is "\" in PHP, not "/".', $class));
198
            }
199
200
            throw new \RuntimeException(sprintf('The autoloader expected class "%s" to be defined in file "%s". The file was found but the class was not in it, the class name or namespace probably has a typo.', $class, $file));
201
        }
202
203
        if (self::$caseCheck && $message = $this->checkCase($refl, $file, $class)) {
0 ignored issues
show
Bug introduced by
The variable $refl does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
204
            throw new \RuntimeException(sprintf('Case mismatch between class and real file names: "%s" vs "%s" in "%s".', $message[0], $message[1], $message[2]));
205
        }
206
    }
207
208
    public function checkAnnotations(\ReflectionClass $refl, $class)
209
    {
210
        $deprecations = array();
211
212
        // Don't trigger deprecations for classes in the same vendor
213
        if (2 > $len = 1 + (\strpos($class, '\\') ?: \strpos($class, '_'))) {
214
            $len = 0;
215
            $ns = '';
216
        } else {
217
            $ns = \substr($class, 0, $len);
218
        }
219
220
        // Detect annotations on the class
221
        if (false !== $doc = $refl->getDocComment()) {
222
            foreach (array('final', 'deprecated', 'internal') as $annotation) {
223
                if (false !== \strpos($doc, $annotation) && preg_match('#\n \* @'.$annotation.'(?:( .+?)\.?)?\r?\n \*(?: @|/$)#s', $doc, $notice)) {
224
                    self::${$annotation}[$class] = isset($notice[1]) ? preg_replace('#\s*\r?\n \* +#', ' ', $notice[1]) : '';
225
                }
226
            }
227
        }
228
229
        $parent = \get_parent_class($class);
230
        $parentAndOwnInterfaces = $this->getOwnInterfaces($class, $parent);
231
        if ($parent) {
232
            $parentAndOwnInterfaces[$parent] = $parent;
233
234
            if (!isset(self::$checkedClasses[$parent])) {
235
                $this->checkClass($parent);
236
            }
237
238
            if (isset(self::$final[$parent])) {
239
                $deprecations[] = sprintf('The "%s" class is considered final%s. It may change without further notice as of its next major version. You should not extend it from "%s".', $parent, self::$final[$parent], $class);
240
            }
241
        }
242
243
        // Detect if the parent is annotated
244
        foreach ($parentAndOwnInterfaces + \class_uses($class, false) as $use) {
245
            if (!isset(self::$checkedClasses[$use])) {
246
                $this->checkClass($use);
247
            }
248
            if (isset(self::$deprecated[$use]) && \strncmp($ns, $use, $len)) {
249
                $type = class_exists($class, false) ? 'class' : (interface_exists($class, false) ? 'interface' : 'trait');
250
                $verb = class_exists($use, false) || interface_exists($class, false) ? 'extends' : (interface_exists($use, false) ? 'implements' : 'uses');
251
252
                $deprecations[] = sprintf('The "%s" %s %s "%s" that is deprecated%s.', $class, $type, $verb, $use, self::$deprecated[$use]);
253
            }
254
            if (isset(self::$internal[$use]) && \strncmp($ns, $use, $len)) {
255
                $deprecations[] = sprintf('The "%s" %s is considered internal%s. It may change without further notice. You should not use it from "%s".', $use, class_exists($use, false) ? 'class' : (interface_exists($use, false) ? 'interface' : 'trait'), self::$internal[$use], $class);
256
            }
257
        }
258
259
        if (\trait_exists($class)) {
260
            return $deprecations;
261
        }
262
263
        // Inherit @final and @internal annotations for methods
264
        self::$finalMethods[$class] = array();
265
        self::$internalMethods[$class] = array();
266
        foreach ($parentAndOwnInterfaces as $use) {
267
            foreach (array('finalMethods', 'internalMethods') as $property) {
268
                if (isset(self::${$property}[$use])) {
269
                    self::${$property}[$class] = self::${$property}[$class] ? self::${$property}[$use] + self::${$property}[$class] : self::${$property}[$use];
270
                }
271
            }
272
        }
273
274
        foreach ($refl->getMethods(\ReflectionMethod::IS_PUBLIC | \ReflectionMethod::IS_PROTECTED) as $method) {
275
            if ($method->class !== $class) {
276
                continue;
277
            }
278
279 View Code Duplication
            if ($parent && isset(self::$finalMethods[$parent][$method->name])) {
280
                list($declaringClass, $message) = self::$finalMethods[$parent][$method->name];
281
                $deprecations[] = sprintf('The "%s::%s()" method is considered final%s. It may change without further notice as of its next major version. You should not extend it from "%s".', $declaringClass, $method->name, $message, $class);
282
            }
283
284 View Code Duplication
            if (isset(self::$internalMethods[$class][$method->name])) {
285
                list($declaringClass, $message) = self::$internalMethods[$class][$method->name];
286
                if (\strncmp($ns, $declaringClass, $len)) {
287
                    $deprecations[] = sprintf('The "%s::%s()" method is considered internal%s. It may change without further notice. You should not extend it from "%s".', $declaringClass, $method->name, $message, $class);
288
                }
289
            }
290
291
            // Detect method annotations
292
            if (false === $doc = $method->getDocComment()) {
293
                continue;
294
            }
295
296
            foreach (array('final', 'internal') as $annotation) {
297
                if (false !== \strpos($doc, $annotation) && preg_match('#\n\s+\* @'.$annotation.'(?:( .+?)\.?)?\r?\n\s+\*(?: @|/$)#s', $doc, $notice)) {
298
                    $message = isset($notice[1]) ? preg_replace('#\s*\r?\n \* +#', ' ', $notice[1]) : '';
299
                    self::${$annotation.'Methods'}[$class][$method->name] = array($class, $message);
300
                }
301
            }
302
        }
303
304
        return $deprecations;
305
    }
306
307
    public function checkCase(\ReflectionClass $refl, $file, $class)
308
    {
309
        $real = explode('\\', $class.strrchr($file, '.'));
310
        $tail = explode(\DIRECTORY_SEPARATOR, str_replace('/', \DIRECTORY_SEPARATOR, $file));
311
312
        $i = \count($tail) - 1;
313
        $j = \count($real) - 1;
314
315
        while (isset($tail[$i], $real[$j]) && $tail[$i] === $real[$j]) {
316
            --$i;
317
            --$j;
318
        }
319
320
        array_splice($tail, 0, $i + 1);
321
322
        if (!$tail) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $tail of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
323
            return;
324
        }
325
326
        $tail = \DIRECTORY_SEPARATOR.implode(\DIRECTORY_SEPARATOR, $tail);
327
        $tailLen = \strlen($tail);
328
        $real = $refl->getFileName();
329
330
        if (2 === self::$caseCheck) {
331
            $real = $this->darwinRealpath($real);
332
        }
333
334
        if (0 === substr_compare($real, $tail, -$tailLen, $tailLen, true)
335
            && 0 !== substr_compare($real, $tail, -$tailLen, $tailLen, false)
336
        ) {
337
            return array(substr($tail, -$tailLen + 1), substr($real, -$tailLen + 1), substr($real, 0, -$tailLen + 1));
338
        }
339
    }
340
341
    /**
342
     * `realpath` on MacOSX doesn't normalize the case of characters.
343
     */
344
    private function darwinRealpath($real)
345
    {
346
        $i = 1 + strrpos($real, '/');
347
        $file = substr($real, $i);
348
        $real = substr($real, 0, $i);
349
350
        if (isset(self::$darwinCache[$real])) {
351
            $kDir = $real;
352
        } else {
353
            $kDir = strtolower($real);
354
355
            if (isset(self::$darwinCache[$kDir])) {
356
                $real = self::$darwinCache[$kDir][0];
357
            } else {
358
                $dir = getcwd();
359
                chdir($real);
360
                $real = getcwd().'/';
361
                chdir($dir);
362
363
                $dir = $real;
364
                $k = $kDir;
365
                $i = \strlen($dir) - 1;
366
                while (!isset(self::$darwinCache[$k])) {
367
                    self::$darwinCache[$k] = array($dir, array());
368
                    self::$darwinCache[$dir] = &self::$darwinCache[$k];
369
370
                    while ('/' !== $dir[--$i]) {
371
                    }
372
                    $k = substr($k, 0, ++$i);
373
                    $dir = substr($dir, 0, $i--);
374
                }
375
            }
376
        }
377
378
        $dirFiles = self::$darwinCache[$kDir][1];
379
380
        if (isset($dirFiles[$file])) {
381
            return $real .= $dirFiles[$file];
382
        }
383
384
        $kFile = strtolower($file);
385
386
        if (!isset($dirFiles[$kFile])) {
387
            foreach (scandir($real, 2) as $f) {
388
                if ('.' !== $f[0]) {
389
                    $dirFiles[$f] = $f;
390
                    if ($f === $file) {
391
                        $kFile = $k = $file;
0 ignored issues
show
Unused Code introduced by
$k 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...
392
                    } elseif ($f !== $k = strtolower($f)) {
393
                        $dirFiles[$k] = $f;
394
                    }
395
                }
396
            }
397
            self::$darwinCache[$kDir][1] = $dirFiles;
398
        }
399
400
        return $real .= $dirFiles[$kFile];
401
    }
402
403
    /**
404
     * `class_implements` includes interfaces from the parents so we have to manually exclude them.
405
     *
406
     * @param string       $class
407
     * @param string|false $parent
408
     *
409
     * @return string[]
410
     */
411
    private function getOwnInterfaces($class, $parent)
412
    {
413
        $ownInterfaces = class_implements($class, false);
414
415
        if ($parent) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $parent of type string|false 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...
416
            foreach (class_implements($parent, false) as $interface) {
417
                unset($ownInterfaces[$interface]);
418
            }
419
        }
420
421
        foreach ($ownInterfaces as $interface) {
422
            foreach (class_implements($interface) as $interface) {
423
                unset($ownInterfaces[$interface]);
424
            }
425
        }
426
427
        return $ownInterfaces;
428
    }
429
}
430