Dashboard sipadu mbip
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

DebugClassLoader.php 20KB

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