vendor/symfony/symfony/src/Symfony/Component/Debug/DebugClassLoader.php line 163

Open in your IDE?
  1. <?php
  2. /*
  3.  * This file is part of the Symfony package.
  4.  *
  5.  * (c) Fabien Potencier <fabien@symfony.com>
  6.  *
  7.  * For the full copyright and license information, please view the LICENSE
  8.  * file that was distributed with this source code.
  9.  */
  10. namespace Symfony\Component\Debug;
  11. use PHPUnit\Framework\MockObject\Matcher\StatelessInvocation;
  12. @trigger_error(sprintf('The "%s" class is deprecated since Symfony 4.4, use "%s" instead.'DebugClassLoader::class, \Symfony\Component\ErrorHandler\DebugClassLoader::class), \E_USER_DEPRECATED);
  13. /**
  14.  * Autoloader checking if the class is really defined in the file found.
  15.  *
  16.  * The ClassLoader will wrap all registered autoloaders
  17.  * and will throw an exception if a file is found but does
  18.  * not declare the class.
  19.  *
  20.  * @author Fabien Potencier <fabien@symfony.com>
  21.  * @author Christophe Coevoet <stof@notk.org>
  22.  * @author Nicolas Grekas <p@tchwork.com>
  23.  * @author Guilhem Niot <guilhem.niot@gmail.com>
  24.  *
  25.  * @deprecated since Symfony 4.4, use Symfony\Component\ErrorHandler\DebugClassLoader instead.
  26.  */
  27. class DebugClassLoader
  28. {
  29.     private $classLoader;
  30.     private $isFinder;
  31.     private $loaded = [];
  32.     private static $caseCheck;
  33.     private static $checkedClasses = [];
  34.     private static $final = [];
  35.     private static $finalMethods = [];
  36.     private static $deprecated = [];
  37.     private static $internal = [];
  38.     private static $internalMethods = [];
  39.     private static $annotatedParameters = [];
  40.     private static $darwinCache = ['/' => ['/', []]];
  41.     private static $method = [];
  42.     public function __construct(callable $classLoader)
  43.     {
  44.         $this->classLoader $classLoader;
  45.         $this->isFinder = \is_array($classLoader) && method_exists($classLoader[0], 'findFile');
  46.         if (!isset(self::$caseCheck)) {
  47.             $file file_exists(__FILE__) ? __FILE__ rtrim(realpath('.'), \DIRECTORY_SEPARATOR);
  48.             $i strrpos($file, \DIRECTORY_SEPARATOR);
  49.             $dir substr($file0$i);
  50.             $file substr($file$i);
  51.             $test strtoupper($file) === $file strtolower($file) : strtoupper($file);
  52.             $test realpath($dir.$test);
  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.      * 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.      * Wraps all autoloaders.
  79.      */
  80.     public static function enable()
  81.     {
  82.         // Ensures we don't hit https://bugs.php.net/42098
  83.         class_exists(\Symfony\Component\Debug\ErrorHandler::class);
  84.         class_exists(\Psr\Log\LogLevel::class);
  85.         if (!\is_array($functions spl_autoload_functions())) {
  86.             return;
  87.         }
  88.         foreach ($functions as $function) {
  89.             spl_autoload_unregister($function);
  90.         }
  91.         foreach ($functions as $function) {
  92.             if (!\is_array($function) || !$function[0] instanceof self) {
  93.                 $function = [new static($function), 'loadClass'];
  94.             }
  95.             spl_autoload_register($function);
  96.         }
  97.     }
  98.     /**
  99.      * Disables the wrapping.
  100.      */
  101.     public static function disable()
  102.     {
  103.         if (!\is_array($functions spl_autoload_functions())) {
  104.             return;
  105.         }
  106.         foreach ($functions as $function) {
  107.             spl_autoload_unregister($function);
  108.         }
  109.         foreach ($functions as $function) {
  110.             if (\is_array($function) && $function[0] instanceof self) {
  111.                 $function $function[0]->getClassLoader();
  112.             }
  113.             spl_autoload_register($function);
  114.         }
  115.     }
  116.     /**
  117.      * @return string|null
  118.      */
  119.     public function findFile($class)
  120.     {
  121.         return $this->isFinder $this->classLoader[0]->findFile($class) ?: null null;
  122.     }
  123.     /**
  124.      * Loads the given class or interface.
  125.      *
  126.      * @param string $class The name of the class
  127.      *
  128.      * @throws \RuntimeException
  129.      */
  130.     public function loadClass($class)
  131.     {
  132.         $e error_reporting(error_reporting() | \E_PARSE | \E_ERROR | \E_CORE_ERROR | \E_COMPILE_ERROR);
  133.         try {
  134.             if ($this->isFinder && !isset($this->loaded[$class])) {
  135.                 $this->loaded[$class] = true;
  136.                 if (!$file $this->classLoader[0]->findFile($class) ?: false) {
  137.                     // no-op
  138.                 } elseif (\function_exists('opcache_is_script_cached') && @opcache_is_script_cached($file)) {
  139.                     include $file;
  140.                     return;
  141.                 } elseif (false === include $file) {
  142.                     return;
  143.                 }
  144.             } else {
  145.                 ($this->classLoader)($class);
  146.                 $file false;
  147.             }
  148.         } finally {
  149.             error_reporting($e);
  150.         }
  151.         $this->checkClass($class$file);
  152.     }
  153.     private function checkClass(string $classstring $file null)
  154.     {
  155.         $exists null === $file || class_exists($classfalse) || interface_exists($classfalse) || trait_exists($classfalse);
  156.         if (null !== $file && $class && '\\' === $class[0]) {
  157.             $class substr($class1);
  158.         }
  159.         if ($exists) {
  160.             if (isset(self::$checkedClasses[$class])) {
  161.                 return;
  162.             }
  163.             self::$checkedClasses[$class] = true;
  164.             $refl = new \ReflectionClass($class);
  165.             if (null === $file && $refl->isInternal()) {
  166.                 return;
  167.             }
  168.             $name $refl->getName();
  169.             if ($name !== $class && === strcasecmp($name$class)) {
  170.                 throw new \RuntimeException(sprintf('Case mismatch between loaded and declared class names: "%s" vs "%s".'$class$name));
  171.             }
  172.             $deprecations $this->checkAnnotations($refl$name);
  173.             foreach ($deprecations as $message) {
  174.                 @trigger_error($message, \E_USER_DEPRECATED);
  175.             }
  176.         }
  177.         if (!$file) {
  178.             return;
  179.         }
  180.         if (!$exists) {
  181.             if (false !== strpos($class'/')) {
  182.                 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));
  183.             }
  184.             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));
  185.         }
  186.         if (self::$caseCheck && $message $this->checkCase($refl$file$class)) {
  187.             throw new \RuntimeException(sprintf('Case mismatch between class and real file names: "%s" vs "%s" in "%s".'$message[0], $message[1], $message[2]));
  188.         }
  189.     }
  190.     public function checkAnnotations(\ReflectionClass $refl$class)
  191.     {
  192.         $deprecations = [];
  193.         // Don't trigger deprecations for classes in the same vendor
  194.         if ($len + (strpos($class'\\') ?: strpos($class'_'))) {
  195.             $len 0;
  196.             $ns '';
  197.         } else {
  198.             $ns str_replace('_''\\'substr($class0$len));
  199.         }
  200.         // Detect annotations on the class
  201.         if (false !== $doc $refl->getDocComment()) {
  202.             foreach (['final''deprecated''internal'] as $annotation) {
  203.                 if (false !== strpos($doc$annotation) && preg_match('#\n\s+\* @'.$annotation.'(?:( .+?)\.?)?\r?\n\s+\*(?: @|/$|\r?\n)#s'$doc$notice)) {
  204.                     self::${$annotation}[$class] = isset($notice[1]) ? preg_replace('#\.?\r?\n( \*)? *(?= |\r?\n|$)#'''$notice[1]) : '';
  205.                 }
  206.             }
  207.             if ($refl->isInterface() && false !== strpos($doc'method') && preg_match_all('#\n \* @method\s+(static\s+)?+(?:[\w\|&\[\]\\\]+\s+)?(\w+(?:\s*\([^\)]*\))?)+(.+?([[:punct:]]\s*)?)?(?=\r?\n \*(?: @|/$|\r?\n))#'$doc$notice, \PREG_SET_ORDER)) {
  208.                 foreach ($notice as $method) {
  209.                     $static '' !== $method[1];
  210.                     $name $method[2];
  211.                     $description $method[3] ?? null;
  212.                     if (false === strpos($name'(')) {
  213.                         $name .= '()';
  214.                     }
  215.                     if (null !== $description) {
  216.                         $description trim($description);
  217.                         if (!isset($method[4])) {
  218.                             $description .= '.';
  219.                         }
  220.                     }
  221.                     self::$method[$class][] = [$class$name$static$description];
  222.                 }
  223.             }
  224.         }
  225.         $parent get_parent_class($class);
  226.         $parentAndOwnInterfaces $this->getOwnInterfaces($class$parent ?: null);
  227.         if ($parent) {
  228.             $parentAndOwnInterfaces[$parent] = $parent;
  229.             if (!isset(self::$checkedClasses[$parent])) {
  230.                 $this->checkClass($parent);
  231.             }
  232.             if (isset(self::$final[$parent])) {
  233.                 $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".'$parentself::$final[$parent], $class);
  234.             }
  235.         }
  236.         // Detect if the parent is annotated
  237.         foreach ($parentAndOwnInterfaces class_uses($classfalse) as $use) {
  238.             if (!isset(self::$checkedClasses[$use])) {
  239.                 $this->checkClass($use);
  240.             }
  241.             if (isset(self::$deprecated[$use]) && strncmp($nsstr_replace('_''\\'$use), $len) && !isset(self::$deprecated[$class])) {
  242.                 $type class_exists($classfalse) ? 'class' : (interface_exists($classfalse) ? 'interface' 'trait');
  243.                 $verb class_exists($usefalse) || interface_exists($classfalse) ? 'extends' : (interface_exists($usefalse) ? 'implements' 'uses');
  244.                 $deprecations[] = sprintf('The "%s" %s %s "%s" that is deprecated%s.'$class$type$verb$useself::$deprecated[$use]);
  245.             }
  246.             if (isset(self::$internal[$use]) && strncmp($nsstr_replace('_''\\'$use), $len)) {
  247.                 $deprecations[] = sprintf('The "%s" %s is considered internal%s. It may change without further notice. You should not use it from "%s".'$useclass_exists($usefalse) ? 'class' : (interface_exists($usefalse) ? 'interface' 'trait'), self::$internal[$use], $class);
  248.             }
  249.             if (isset(self::$method[$use])) {
  250.                 if ($refl->isAbstract()) {
  251.                     if (isset(self::$method[$class])) {
  252.                         self::$method[$class] = array_merge(self::$method[$class], self::$method[$use]);
  253.                     } else {
  254.                         self::$method[$class] = self::$method[$use];
  255.                     }
  256.                 } elseif (!$refl->isInterface()) {
  257.                     $hasCall $refl->hasMethod('__call');
  258.                     $hasStaticCall $refl->hasMethod('__callStatic');
  259.                     foreach (self::$method[$use] as $method) {
  260.                         [$interface$name$static$description] = $method;
  261.                         if ($static $hasStaticCall $hasCall) {
  262.                             continue;
  263.                         }
  264.                         $realName substr($name0strpos($name'('));
  265.                         if (!$refl->hasMethod($realName) || !($methodRefl $refl->getMethod($realName))->isPublic() || ($static && !$methodRefl->isStatic()) || (!$static && $methodRefl->isStatic())) {
  266.                             $deprecations[] = sprintf('Class "%s" should implement method "%s::%s"%s'$class, ($static 'static ' '').$interface$namenull == $description '.' ': '.$description);
  267.                         }
  268.                     }
  269.                 }
  270.             }
  271.         }
  272.         if (trait_exists($class)) {
  273.             return $deprecations;
  274.         }
  275.         // Inherit @final, @internal and @param annotations for methods
  276.         self::$finalMethods[$class] = [];
  277.         self::$internalMethods[$class] = [];
  278.         self::$annotatedParameters[$class] = [];
  279.         foreach ($parentAndOwnInterfaces as $use) {
  280.             foreach (['finalMethods''internalMethods''annotatedParameters'] as $property) {
  281.                 if (isset(self::${$property}[$use])) {
  282.                     self::${$property}[$class] = self::${$property}[$class] ? self::${$property}[$use] + self::${$property}[$class] : self::${$property}[$use];
  283.                 }
  284.             }
  285.         }
  286.         foreach ($refl->getMethods(\ReflectionMethod::IS_PUBLIC | \ReflectionMethod::IS_PROTECTED) as $method) {
  287.             if ($method->class !== $class) {
  288.                 continue;
  289.             }
  290.             if ($parent && isset(self::$finalMethods[$parent][$method->name])) {
  291.                 [$declaringClass$message] = self::$finalMethods[$parent][$method->name];
  292.                 $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);
  293.             }
  294.             if (isset(self::$internalMethods[$class][$method->name])) {
  295.                 [$declaringClass$message] = self::$internalMethods[$class][$method->name];
  296.                 if (strncmp($ns$declaringClass$len)) {
  297.                     $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);
  298.                 }
  299.             }
  300.             // To read method annotations
  301.             $doc $method->getDocComment();
  302.             if (isset(self::$annotatedParameters[$class][$method->name])) {
  303.                 $definedParameters = [];
  304.                 foreach ($method->getParameters() as $parameter) {
  305.                     $definedParameters[$parameter->name] = true;
  306.                 }
  307.                 foreach (self::$annotatedParameters[$class][$method->name] as $parameterName => $deprecation) {
  308.                     if (!isset($definedParameters[$parameterName]) && !($doc && preg_match("/\\n\\s+\\* @param +((?(?!callable *\().*?|callable *\(.*\).*?))(?<= )\\\${$parameterName}\\b/"$doc))) {
  309.                         $deprecations[] = sprintf($deprecation$class);
  310.                     }
  311.                 }
  312.             }
  313.             if (!$doc) {
  314.                 continue;
  315.             }
  316.             $finalOrInternal false;
  317.             foreach (['final''internal'] as $annotation) {
  318.                 if (false !== strpos($doc$annotation) && preg_match('#\n\s+\* @'.$annotation.'(?:( .+?)\.?)?\r?\n\s+\*(?: @|/$|\r?\n)#s'$doc$notice)) {
  319.                     $message = isset($notice[1]) ? preg_replace('#\.?\r?\n( \*)? *(?= |\r?\n|$)#'''$notice[1]) : '';
  320.                     self::${$annotation.'Methods'}[$class][$method->name] = [$class$message];
  321.                     $finalOrInternal true;
  322.                 }
  323.             }
  324.             if ($finalOrInternal || $method->isConstructor() || false === strpos($doc'@param') || StatelessInvocation::class === $class) {
  325.                 continue;
  326.             }
  327.             if (!preg_match_all('#\n\s+\* @param +((?(?!callable *\().*?|callable *\(.*\).*?))(?<= )\$([a-zA-Z0-9_\x7f-\xff]++)#'$doc$matches, \PREG_SET_ORDER)) {
  328.                 continue;
  329.             }
  330.             if (!isset(self::$annotatedParameters[$class][$method->name])) {
  331.                 $definedParameters = [];
  332.                 foreach ($method->getParameters() as $parameter) {
  333.                     $definedParameters[$parameter->name] = true;
  334.                 }
  335.             }
  336.             foreach ($matches as [, $parameterType$parameterName]) {
  337.                 if (!isset($definedParameters[$parameterName])) {
  338.                     $parameterType trim($parameterType);
  339.                     self::$annotatedParameters[$class][$method->name][$parameterName] = sprintf('The "%%s::%s()" method will require a new "%s$%s" argument in the next major version of its %s "%s", not defining it is deprecated.'$method->name$parameterType $parameterType.' ' ''$parameterNameinterface_exists($class) ? 'interface' 'parent class'$method->class);
  340.                 }
  341.             }
  342.         }
  343.         return $deprecations;
  344.     }
  345.     /**
  346.      * @param string $file
  347.      * @param string $class
  348.      *
  349.      * @return array|null
  350.      */
  351.     public function checkCase(\ReflectionClass $refl$file$class)
  352.     {
  353.         $real explode('\\'$class.strrchr($file'.'));
  354.         $tail explode(\DIRECTORY_SEPARATORstr_replace('/', \DIRECTORY_SEPARATOR$file));
  355.         $i = \count($tail) - 1;
  356.         $j = \count($real) - 1;
  357.         while (isset($tail[$i], $real[$j]) && $tail[$i] === $real[$j]) {
  358.             --$i;
  359.             --$j;
  360.         }
  361.         array_splice($tail0$i 1);
  362.         if (!$tail) {
  363.             return null;
  364.         }
  365.         $tail = \DIRECTORY_SEPARATOR.implode(\DIRECTORY_SEPARATOR$tail);
  366.         $tailLen = \strlen($tail);
  367.         $real $refl->getFileName();
  368.         if (=== self::$caseCheck) {
  369.             $real $this->darwinRealpath($real);
  370.         }
  371.         if (=== substr_compare($real$tail, -$tailLen$tailLentrue)
  372.             && !== substr_compare($real$tail, -$tailLen$tailLenfalse)
  373.         ) {
  374.             return [substr($tail, -$tailLen 1), substr($real, -$tailLen 1), substr($real0, -$tailLen 1)];
  375.         }
  376.         return null;
  377.     }
  378.     /**
  379.      * `realpath` on MacOSX doesn't normalize the case of characters.
  380.      */
  381.     private function darwinRealpath(string $real): string
  382.     {
  383.         $i strrpos($real'/');
  384.         $file substr($real$i);
  385.         $real substr($real0$i);
  386.         if (isset(self::$darwinCache[$real])) {
  387.             $kDir $real;
  388.         } else {
  389.             $kDir strtolower($real);
  390.             if (isset(self::$darwinCache[$kDir])) {
  391.                 $real self::$darwinCache[$kDir][0];
  392.             } else {
  393.                 $dir getcwd();
  394.                 if (!@chdir($real)) {
  395.                     return $real.$file;
  396.                 }
  397.                 $real getcwd().'/';
  398.                 chdir($dir);
  399.                 $dir $real;
  400.                 $k $kDir;
  401.                 $i = \strlen($dir) - 1;
  402.                 while (!isset(self::$darwinCache[$k])) {
  403.                     self::$darwinCache[$k] = [$dir, []];
  404.                     self::$darwinCache[$dir] = &self::$darwinCache[$k];
  405.                     while ('/' !== $dir[--$i]) {
  406.                     }
  407.                     $k substr($k0, ++$i);
  408.                     $dir substr($dir0$i--);
  409.                 }
  410.             }
  411.         }
  412.         $dirFiles self::$darwinCache[$kDir][1];
  413.         if (!isset($dirFiles[$file]) && ') : eval()\'d code' === substr($file, -17)) {
  414.             // Get the file name from "file_name.php(123) : eval()'d code"
  415.             $file substr($file0strrpos($file'(', -17));
  416.         }
  417.         if (isset($dirFiles[$file])) {
  418.             return $real.$dirFiles[$file];
  419.         }
  420.         $kFile strtolower($file);
  421.         if (!isset($dirFiles[$kFile])) {
  422.             foreach (scandir($real2) as $f) {
  423.                 if ('.' !== $f[0]) {
  424.                     $dirFiles[$f] = $f;
  425.                     if ($f === $file) {
  426.                         $kFile $k $file;
  427.                     } elseif ($f !== $k strtolower($f)) {
  428.                         $dirFiles[$k] = $f;
  429.                     }
  430.                 }
  431.             }
  432.             self::$darwinCache[$kDir][1] = $dirFiles;
  433.         }
  434.         return $real.$dirFiles[$kFile];
  435.     }
  436.     /**
  437.      * `class_implements` includes interfaces from the parents so we have to manually exclude them.
  438.      *
  439.      * @return string[]
  440.      */
  441.     private function getOwnInterfaces(string $class, ?string $parent): array
  442.     {
  443.         $ownInterfaces class_implements($classfalse);
  444.         if ($parent) {
  445.             foreach (class_implements($parentfalse) as $interface) {
  446.                 unset($ownInterfaces[$interface]);
  447.             }
  448.         }
  449.         foreach ($ownInterfaces as $interface) {
  450.             foreach (class_implements($interface) as $interface) {
  451.                 unset($ownInterfaces[$interface]);
  452.             }
  453.         }
  454.         return $ownInterfaces;
  455.     }
  456. }