c9fa76cfe705803b1ef883abc830c3259241cf43
[yaffs-website] / vendor / symfony / debug / DebugClassLoader.php
1 <?php
2
3 /*
4  * This file is part of the Symfony package.
5  *
6  * (c) Fabien Potencier <fabien@symfony.com>
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 <fabien@symfony.com>
22  * @author Christophe Coevoet <stof@notk.org>
23  * @author Nicolas Grekas <p@tchwork.com>
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 $php7Reserved = array('int' => 1, 'float' => 1, 'bool' => 1, 'string' => 1, 'true' => 1, 'false' => 1, 'null' => 1);
38     private static $darwinCache = array('/' => array('/', array()));
39
40     public function __construct(callable $classLoader)
41     {
42         $this->classLoader = $classLoader;
43         $this->isFinder = \is_array($classLoader) && method_exists($classLoader[0], 'findFile');
44
45         if (!isset(self::$caseCheck)) {
46             $file = file_exists(__FILE__) ? __FILE__ : rtrim(realpath('.'), \DIRECTORY_SEPARATOR);
47             $i = strrpos($file, \DIRECTORY_SEPARATOR);
48             $dir = substr($file, 0, 1 + $i);
49             $file = substr($file, 1 + $i);
50             $test = strtoupper($file) === $file ? strtolower($file) : strtoupper($file);
51             $test = realpath($dir.$test);
52
53             if (false === $test || false === $i) {
54                 // filesystem is case sensitive
55                 self::$caseCheck = 0;
56             } elseif (substr($test, -\strlen($file)) === $file) {
57                 // filesystem is case insensitive and realpath() normalizes the case of characters
58                 self::$caseCheck = 1;
59             } elseif (false !== stripos(PHP_OS, 'darwin')) {
60                 // on MacOSX, HFS+ is case insensitive but realpath() doesn't normalize the case of characters
61                 self::$caseCheck = 2;
62             } else {
63                 // filesystem case checks failed, fallback to disabling them
64                 self::$caseCheck = 0;
65             }
66         }
67     }
68
69     /**
70      * Gets the wrapped class loader.
71      *
72      * @return callable The wrapped class loader
73      */
74     public function getClassLoader()
75     {
76         return $this->classLoader;
77     }
78
79     /**
80      * Wraps all autoloaders.
81      */
82     public static function enable()
83     {
84         // Ensures we don't hit https://bugs.php.net/42098
85         class_exists('Symfony\Component\Debug\ErrorHandler');
86         class_exists('Psr\Log\LogLevel');
87
88         if (!\is_array($functions = spl_autoload_functions())) {
89             return;
90         }
91
92         foreach ($functions as $function) {
93             spl_autoload_unregister($function);
94         }
95
96         foreach ($functions as $function) {
97             if (!\is_array($function) || !$function[0] instanceof self) {
98                 $function = array(new static($function), 'loadClass');
99             }
100
101             spl_autoload_register($function);
102         }
103     }
104
105     /**
106      * Disables the wrapping.
107      */
108     public static function disable()
109     {
110         if (!\is_array($functions = spl_autoload_functions())) {
111             return;
112         }
113
114         foreach ($functions as $function) {
115             spl_autoload_unregister($function);
116         }
117
118         foreach ($functions as $function) {
119             if (\is_array($function) && $function[0] instanceof self) {
120                 $function = $function[0]->getClassLoader();
121             }
122
123             spl_autoload_register($function);
124         }
125     }
126
127     /**
128      * Loads the given class or interface.
129      *
130      * @param string $class The name of the class
131      *
132      * @throws \RuntimeException
133      */
134     public function loadClass($class)
135     {
136         $e = error_reporting(error_reporting() | E_PARSE | E_ERROR | E_CORE_ERROR | E_COMPILE_ERROR);
137
138         try {
139             if ($this->isFinder && !isset($this->loaded[$class])) {
140                 $this->loaded[$class] = true;
141                 if ($file = $this->classLoader[0]->findFile($class) ?: false) {
142                     $wasCached = \function_exists('opcache_is_script_cached') && @opcache_is_script_cached($file);
143
144                     require $file;
145
146                     if ($wasCached) {
147                         return;
148                     }
149                 }
150             } else {
151                 \call_user_func($this->classLoader, $class);
152                 $file = false;
153             }
154         } finally {
155             error_reporting($e);
156         }
157
158         $this->checkClass($class, $file);
159     }
160
161     private function checkClass($class, $file = null)
162     {
163         $exists = null === $file || \class_exists($class, false) || \interface_exists($class, false) || \trait_exists($class, false);
164
165         if (null !== $file && $class && '\\' === $class[0]) {
166             $class = substr($class, 1);
167         }
168
169         if ($exists) {
170             if (isset(self::$checkedClasses[$class])) {
171                 return;
172             }
173             self::$checkedClasses[$class] = true;
174
175             $refl = new \ReflectionClass($class);
176             if (null === $file && $refl->isInternal()) {
177                 return;
178             }
179             $name = $refl->getName();
180
181             if ($name !== $class && 0 === \strcasecmp($name, $class)) {
182                 throw new \RuntimeException(sprintf('Case mismatch between loaded and declared class names: "%s" vs "%s".', $class, $name));
183             }
184
185             $deprecations = $this->checkAnnotations($refl, $name);
186
187             if (isset(self::$php7Reserved[\strtolower($refl->getShortName())])) {
188                 $deprecations[] = sprintf('The "%s" class uses the reserved name "%s", it will break on PHP 7 and higher', $name, $refl->getShortName());
189             }
190
191             foreach ($deprecations as $message) {
192                 @trigger_error($message, E_USER_DEPRECATED);
193             }
194         }
195
196         if (!$file) {
197             return;
198         }
199
200         if (!$exists) {
201             if (false !== strpos($class, '/')) {
202                 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));
203             }
204
205             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));
206         }
207
208         if (self::$caseCheck && $message = $this->checkCase($refl, $file, $class)) {
209             throw new \RuntimeException(sprintf('Case mismatch between class and real file names: "%s" vs "%s" in "%s".', $message[0], $message[1], $message[2]));
210         }
211     }
212
213     public function checkAnnotations(\ReflectionClass $refl, $class)
214     {
215         $deprecations = array();
216
217         // Don't trigger deprecations for classes in the same vendor
218         if (2 > $len = 1 + (\strpos($class, '\\') ?: \strpos($class, '_'))) {
219             $len = 0;
220             $ns = '';
221         } else {
222             $ns = \substr($class, 0, $len);
223         }
224
225         // Detect annotations on the class
226         if (false !== $doc = $refl->getDocComment()) {
227             foreach (array('final', 'deprecated', 'internal') as $annotation) {
228                 if (false !== \strpos($doc, $annotation) && preg_match('#\n \* @'.$annotation.'(?:( .+?)\.?)?\r?\n \*(?: @|/$)#s', $doc, $notice)) {
229                     self::${$annotation}[$class] = isset($notice[1]) ? preg_replace('#\s*\r?\n \* +#', ' ', $notice[1]) : '';
230                 }
231             }
232         }
233
234         $parent = \get_parent_class($class);
235         $parentAndOwnInterfaces = $this->getOwnInterfaces($class, $parent);
236         if ($parent) {
237             $parentAndOwnInterfaces[$parent] = $parent;
238
239             if (!isset(self::$checkedClasses[$parent])) {
240                 $this->checkClass($parent);
241             }
242
243             if (isset(self::$final[$parent])) {
244                 $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);
245             }
246         }
247
248         // Detect if the parent is annotated
249         foreach ($parentAndOwnInterfaces + \class_uses($class, false) as $use) {
250             if (!isset(self::$checkedClasses[$use])) {
251                 $this->checkClass($use);
252             }
253             if (isset(self::$deprecated[$use]) && \strncmp($ns, $use, $len)) {
254                 $type = class_exists($class, false) ? 'class' : (interface_exists($class, false) ? 'interface' : 'trait');
255                 $verb = class_exists($use, false) || interface_exists($class, false) ? 'extends' : (interface_exists($use, false) ? 'implements' : 'uses');
256
257                 $deprecations[] = sprintf('The "%s" %s %s "%s" that is deprecated%s.', $class, $type, $verb, $use, self::$deprecated[$use]);
258             }
259             if (isset(self::$internal[$use]) && \strncmp($ns, $use, $len)) {
260                 $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);
261             }
262         }
263
264         if (\trait_exists($class)) {
265             return $deprecations;
266         }
267
268         // Inherit @final and @internal annotations for methods
269         self::$finalMethods[$class] = array();
270         self::$internalMethods[$class] = array();
271         foreach ($parentAndOwnInterfaces as $use) {
272             foreach (array('finalMethods', 'internalMethods') as $property) {
273                 if (isset(self::${$property}[$use])) {
274                     self::${$property}[$class] = self::${$property}[$class] ? self::${$property}[$use] + self::${$property}[$class] : self::${$property}[$use];
275                 }
276             }
277         }
278
279         foreach ($refl->getMethods(\ReflectionMethod::IS_PUBLIC | \ReflectionMethod::IS_PROTECTED) as $method) {
280             if ($method->class !== $class) {
281                 continue;
282             }
283
284             if ($parent && isset(self::$finalMethods[$parent][$method->name])) {
285                 list($declaringClass, $message) = self::$finalMethods[$parent][$method->name];
286                 $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);
287             }
288
289             if (isset(self::$internalMethods[$class][$method->name])) {
290                 list($declaringClass, $message) = self::$internalMethods[$class][$method->name];
291                 if (\strncmp($ns, $declaringClass, $len)) {
292                     $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);
293                 }
294             }
295
296             // Detect method annotations
297             if (false === $doc = $method->getDocComment()) {
298                 continue;
299             }
300
301             foreach (array('final', 'internal') as $annotation) {
302                 if (false !== \strpos($doc, $annotation) && preg_match('#\n\s+\* @'.$annotation.'(?:( .+?)\.?)?\r?\n\s+\*(?: @|/$)#s', $doc, $notice)) {
303                     $message = isset($notice[1]) ? preg_replace('#\s*\r?\n \* +#', ' ', $notice[1]) : '';
304                     self::${$annotation.'Methods'}[$class][$method->name] = array($class, $message);
305                 }
306             }
307         }
308
309         return $deprecations;
310     }
311
312     public function checkCase(\ReflectionClass $refl, $file, $class)
313     {
314         $real = explode('\\', $class.strrchr($file, '.'));
315         $tail = explode(\DIRECTORY_SEPARATOR, str_replace('/', \DIRECTORY_SEPARATOR, $file));
316
317         $i = \count($tail) - 1;
318         $j = \count($real) - 1;
319
320         while (isset($tail[$i], $real[$j]) && $tail[$i] === $real[$j]) {
321             --$i;
322             --$j;
323         }
324
325         array_splice($tail, 0, $i + 1);
326
327         if (!$tail) {
328             return;
329         }
330
331         $tail = \DIRECTORY_SEPARATOR.implode(\DIRECTORY_SEPARATOR, $tail);
332         $tailLen = \strlen($tail);
333         $real = $refl->getFileName();
334
335         if (2 === self::$caseCheck) {
336             $real = $this->darwinRealpath($real);
337         }
338
339         if (0 === substr_compare($real, $tail, -$tailLen, $tailLen, true)
340             && 0 !== substr_compare($real, $tail, -$tailLen, $tailLen, false)
341         ) {
342             return array(substr($tail, -$tailLen + 1), substr($real, -$tailLen + 1), substr($real, 0, -$tailLen + 1));
343         }
344     }
345
346     /**
347      * `realpath` on MacOSX doesn't normalize the case of characters.
348      */
349     private function darwinRealpath($real)
350     {
351         $i = 1 + strrpos($real, '/');
352         $file = substr($real, $i);
353         $real = substr($real, 0, $i);
354
355         if (isset(self::$darwinCache[$real])) {
356             $kDir = $real;
357         } else {
358             $kDir = strtolower($real);
359
360             if (isset(self::$darwinCache[$kDir])) {
361                 $real = self::$darwinCache[$kDir][0];
362             } else {
363                 $dir = getcwd();
364                 chdir($real);
365                 $real = getcwd().'/';
366                 chdir($dir);
367
368                 $dir = $real;
369                 $k = $kDir;
370                 $i = \strlen($dir) - 1;
371                 while (!isset(self::$darwinCache[$k])) {
372                     self::$darwinCache[$k] = array($dir, array());
373                     self::$darwinCache[$dir] = &self::$darwinCache[$k];
374
375                     while ('/' !== $dir[--$i]) {
376                     }
377                     $k = substr($k, 0, ++$i);
378                     $dir = substr($dir, 0, $i--);
379                 }
380             }
381         }
382
383         $dirFiles = self::$darwinCache[$kDir][1];
384
385         if (isset($dirFiles[$file])) {
386             return $real .= $dirFiles[$file];
387         }
388
389         $kFile = strtolower($file);
390
391         if (!isset($dirFiles[$kFile])) {
392             foreach (scandir($real, 2) as $f) {
393                 if ('.' !== $f[0]) {
394                     $dirFiles[$f] = $f;
395                     if ($f === $file) {
396                         $kFile = $k = $file;
397                     } elseif ($f !== $k = strtolower($f)) {
398                         $dirFiles[$k] = $f;
399                     }
400                 }
401             }
402             self::$darwinCache[$kDir][1] = $dirFiles;
403         }
404
405         return $real .= $dirFiles[$kFile];
406     }
407
408     /**
409      * `class_implements` includes interfaces from the parents so we have to manually exclude them.
410      *
411      * @param string       $class
412      * @param string|false $parent
413      *
414      * @return string[]
415      */
416     private function getOwnInterfaces($class, $parent)
417     {
418         $ownInterfaces = class_implements($class, false);
419
420         if ($parent) {
421             foreach (class_implements($parent, false) as $interface) {
422                 unset($ownInterfaces[$interface]);
423             }
424         }
425
426         foreach ($ownInterfaces as $interface) {
427             foreach (class_implements($interface) as $interface) {
428                 unset($ownInterfaces[$interface]);
429             }
430         }
431
432         return $ownInterfaces;
433     }
434 }