Deprecation.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402
  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\Bridge\PhpUnit\DeprecationErrorHandler;
  11. use PHPUnit\Framework\TestCase;
  12. use PHPUnit\Framework\TestSuite;
  13. use PHPUnit\Util\Test;
  14. use Symfony\Bridge\PhpUnit\Legacy\SymfonyTestsListenerFor;
  15. use Symfony\Component\Debug\DebugClassLoader as LegacyDebugClassLoader;
  16. use Symfony\Component\ErrorHandler\DebugClassLoader;
  17. /**
  18. * @internal
  19. */
  20. class Deprecation
  21. {
  22. const PATH_TYPE_VENDOR = 'path_type_vendor';
  23. const PATH_TYPE_SELF = 'path_type_internal';
  24. const PATH_TYPE_UNDETERMINED = 'path_type_undetermined';
  25. const TYPE_SELF = 'type_self';
  26. const TYPE_DIRECT = 'type_direct';
  27. const TYPE_INDIRECT = 'type_indirect';
  28. const TYPE_UNDETERMINED = 'type_undetermined';
  29. private $trace = [];
  30. private $message;
  31. private $originClass;
  32. private $originMethod;
  33. private $triggeringFile;
  34. /** @var string[] Absolute paths to vendor directories */
  35. private static $vendors;
  36. /**
  37. * @var string[] Absolute paths to source or tests of the project, cache
  38. * directories excluded because it is based on autoloading
  39. * rules and cache systems typically do not use those
  40. */
  41. private static $internalPaths = [];
  42. private $originalFilesStack;
  43. /**
  44. * @param string $message
  45. * @param string $file
  46. */
  47. public function __construct($message, array $trace, $file)
  48. {
  49. if (isset($trace[2]['function']) && 'trigger_deprecation' === $trace[2]['function']) {
  50. $file = $trace[2]['file'];
  51. array_splice($trace, 1, 1);
  52. }
  53. $this->trace = $trace;
  54. $this->message = $message;
  55. $i = \count($trace);
  56. while (1 < $i && $this->lineShouldBeSkipped($trace[--$i])) {
  57. // No-op
  58. }
  59. $line = $trace[$i];
  60. $this->triggeringFile = $file;
  61. for ($j = 1; $j < $i; ++$j) {
  62. if (!isset($trace[$j]['function'], $trace[1 + $j]['class'], $trace[1 + $j]['args'][0])) {
  63. continue;
  64. }
  65. if ('trigger_error' === $trace[$j]['function'] && !isset($trace[$j]['class'])) {
  66. if (\in_array($trace[1 + $j]['class'], [DebugClassLoader::class, LegacyDebugClassLoader::class], true)) {
  67. $class = $trace[1 + $j]['args'][0];
  68. $this->triggeringFile = isset($trace[1 + $j]['args'][1]) ? realpath($trace[1 + $j]['args'][1]) : (new \ReflectionClass($class))->getFileName();
  69. $this->getOriginalFilesStack();
  70. array_splice($this->originalFilesStack, 0, $j, [$this->triggeringFile]);
  71. if (preg_match('/(?|"([^"]++)" that is deprecated|should implement method "(?:static )?([^:]++))/', $message, $m) || preg_match('/^(?:The|Method) "([^":]++)/', $message, $m)) {
  72. $this->triggeringFile = (new \ReflectionClass($m[1]))->getFileName();
  73. array_unshift($this->originalFilesStack, $this->triggeringFile);
  74. }
  75. }
  76. break;
  77. }
  78. }
  79. if (!isset($line['object']) && !isset($line['class'])) {
  80. return;
  81. }
  82. set_error_handler(function () {});
  83. $parsedMsg = unserialize($this->message);
  84. restore_error_handler();
  85. if ($parsedMsg && isset($parsedMsg['deprecation'])) {
  86. $this->message = $parsedMsg['deprecation'];
  87. $this->originClass = $parsedMsg['class'];
  88. $this->originMethod = $parsedMsg['method'];
  89. if (isset($parsedMsg['files_stack'])) {
  90. $this->originalFilesStack = $parsedMsg['files_stack'];
  91. }
  92. // If the deprecation has been triggered via
  93. // \Symfony\Bridge\PhpUnit\Legacy\SymfonyTestsListenerTrait::endTest()
  94. // then we need to use the serialized information to determine
  95. // if the error has been triggered from vendor code.
  96. if (isset($parsedMsg['triggering_file'])) {
  97. $this->triggeringFile = $parsedMsg['triggering_file'];
  98. }
  99. return;
  100. }
  101. if (!isset($line['class'], $trace[$i - 2]['function']) || 0 !== strpos($line['class'], SymfonyTestsListenerFor::class)) {
  102. $this->originClass = isset($line['object']) ? \get_class($line['object']) : $line['class'];
  103. $this->originMethod = $line['function'];
  104. return;
  105. }
  106. $test = isset($line['args'][0]) ? $line['args'][0] : null;
  107. if (($test instanceof TestCase || $test instanceof TestSuite) && ('trigger_error' !== $trace[$i - 2]['function'] || isset($trace[$i - 2]['class']))) {
  108. $this->originClass = \get_class($test);
  109. $this->originMethod = $test->getName();
  110. return;
  111. }
  112. }
  113. /**
  114. * @return bool
  115. */
  116. private function lineShouldBeSkipped(array $line)
  117. {
  118. if (!isset($line['class'])) {
  119. return true;
  120. }
  121. $class = $line['class'];
  122. return 'ReflectionMethod' === $class || 0 === strpos($class, 'PHPUnit_') || 0 === strpos($class, 'PHPUnit\\');
  123. }
  124. /**
  125. * @return bool
  126. */
  127. public function originatesFromAnObject()
  128. {
  129. return isset($this->originClass);
  130. }
  131. /**
  132. * @return string
  133. */
  134. public function originatingClass()
  135. {
  136. if (null === $this->originClass) {
  137. throw new \LogicException('Check with originatesFromAnObject() before calling this method.');
  138. }
  139. $class = $this->originClass;
  140. return false !== strpos($class, "@anonymous\0") ? (get_parent_class($class) ?: key(class_implements($class)) ?: 'class').'@anonymous' : $class;
  141. }
  142. /**
  143. * @return string
  144. */
  145. public function originatingMethod()
  146. {
  147. if (null === $this->originMethod) {
  148. throw new \LogicException('Check with originatesFromAnObject() before calling this method.');
  149. }
  150. return $this->originMethod;
  151. }
  152. /**
  153. * @return string
  154. */
  155. public function getMessage()
  156. {
  157. return $this->message;
  158. }
  159. /**
  160. * @return bool
  161. */
  162. public function isLegacy()
  163. {
  164. if (!$this->originClass || (new \ReflectionClass($this->originClass))->isInternal()) {
  165. return false;
  166. }
  167. $method = $this->originatingMethod();
  168. return 0 === strpos($method, 'testLegacy')
  169. || 0 === strpos($method, 'provideLegacy')
  170. || 0 === strpos($method, 'getLegacy')
  171. || strpos($this->originClass, '\Legacy')
  172. || \in_array('legacy', Test::getGroups($this->originClass, $method), true);
  173. }
  174. /**
  175. * @return bool
  176. */
  177. public function isMuted()
  178. {
  179. if ('Function ReflectionType::__toString() is deprecated' !== $this->message) {
  180. return false;
  181. }
  182. if (isset($this->trace[1]['class'])) {
  183. return 0 === strpos($this->trace[1]['class'], 'PHPUnit\\');
  184. }
  185. return false !== strpos($this->triggeringFile, \DIRECTORY_SEPARATOR.'vendor'.\DIRECTORY_SEPARATOR.'phpunit'.\DIRECTORY_SEPARATOR);
  186. }
  187. /**
  188. * Tells whether both the calling package and the called package are vendor
  189. * packages.
  190. *
  191. * @return string
  192. */
  193. public function getType()
  194. {
  195. if (self::PATH_TYPE_SELF === $pathType = $this->getPathType($this->triggeringFile)) {
  196. return self::TYPE_SELF;
  197. }
  198. if (self::PATH_TYPE_UNDETERMINED === $pathType) {
  199. return self::TYPE_UNDETERMINED;
  200. }
  201. $erroringFile = $erroringPackage = null;
  202. foreach ($this->getOriginalFilesStack() as $file) {
  203. if ('-' === $file || 'Standard input code' === $file || !realpath($file)) {
  204. continue;
  205. }
  206. if (self::PATH_TYPE_SELF === $pathType = $this->getPathType($file)) {
  207. return self::TYPE_DIRECT;
  208. }
  209. if (self::PATH_TYPE_UNDETERMINED === $pathType) {
  210. return self::TYPE_UNDETERMINED;
  211. }
  212. if (null !== $erroringFile && null !== $erroringPackage) {
  213. $package = $this->getPackage($file);
  214. if ('composer' !== $package && $package !== $erroringPackage) {
  215. return self::TYPE_INDIRECT;
  216. }
  217. continue;
  218. }
  219. $erroringFile = $file;
  220. $erroringPackage = $this->getPackage($file);
  221. }
  222. return self::TYPE_DIRECT;
  223. }
  224. private function getOriginalFilesStack()
  225. {
  226. if (null === $this->originalFilesStack) {
  227. $this->originalFilesStack = [];
  228. foreach ($this->trace as $frame) {
  229. if (!isset($frame['file'], $frame['function']) || (!isset($frame['class']) && \in_array($frame['function'], ['require', 'require_once', 'include', 'include_once'], true))) {
  230. continue;
  231. }
  232. $this->originalFilesStack[] = $frame['file'];
  233. }
  234. }
  235. return $this->originalFilesStack;
  236. }
  237. /**
  238. * getPathType() should always be called prior to calling this method.
  239. *
  240. * @param string $path
  241. *
  242. * @return string
  243. */
  244. private function getPackage($path)
  245. {
  246. $path = realpath($path) ?: $path;
  247. foreach (self::getVendors() as $vendorRoot) {
  248. if (0 === strpos($path, $vendorRoot)) {
  249. $relativePath = substr($path, \strlen($vendorRoot) + 1);
  250. $vendor = strstr($relativePath, \DIRECTORY_SEPARATOR, true);
  251. if (false === $vendor) {
  252. return 'symfony';
  253. }
  254. return rtrim($vendor.'/'.strstr(substr($relativePath, \strlen($vendor) + 1), \DIRECTORY_SEPARATOR, true), '/');
  255. }
  256. }
  257. throw new \RuntimeException(sprintf('No vendors found for path "%s".', $path));
  258. }
  259. /**
  260. * @return string[] an array of paths
  261. */
  262. private static function getVendors()
  263. {
  264. if (null === self::$vendors) {
  265. self::$vendors = $paths = [];
  266. self::$vendors[] = \dirname(__DIR__).\DIRECTORY_SEPARATOR.'Legacy';
  267. if (class_exists(DebugClassLoader::class, false)) {
  268. self::$vendors[] = \dirname((new \ReflectionClass(DebugClassLoader::class))->getFileName());
  269. }
  270. if (class_exists(LegacyDebugClassLoader::class, false)) {
  271. self::$vendors[] = \dirname((new \ReflectionClass(LegacyDebugClassLoader::class))->getFileName());
  272. }
  273. foreach (get_declared_classes() as $class) {
  274. if ('C' === $class[0] && 0 === strpos($class, 'ComposerAutoloaderInit')) {
  275. $r = new \ReflectionClass($class);
  276. $v = \dirname(\dirname($r->getFileName()));
  277. if (file_exists($v.'/composer/installed.json')) {
  278. self::$vendors[] = $v;
  279. $loader = require $v.'/autoload.php';
  280. $paths = self::addSourcePathsFromPrefixes(
  281. array_merge($loader->getPrefixes(), $loader->getPrefixesPsr4()),
  282. $paths
  283. );
  284. }
  285. }
  286. }
  287. foreach ($paths as $path) {
  288. foreach (self::$vendors as $vendor) {
  289. if (0 !== strpos($path, $vendor)) {
  290. self::$internalPaths[] = $path;
  291. }
  292. }
  293. }
  294. }
  295. return self::$vendors;
  296. }
  297. private static function addSourcePathsFromPrefixes(array $prefixesByNamespace, array $paths)
  298. {
  299. foreach ($prefixesByNamespace as $prefixes) {
  300. foreach ($prefixes as $prefix) {
  301. if (false !== realpath($prefix)) {
  302. $paths[] = realpath($prefix);
  303. }
  304. }
  305. }
  306. return $paths;
  307. }
  308. /**
  309. * @param string $path
  310. *
  311. * @return string
  312. */
  313. private function getPathType($path)
  314. {
  315. $realPath = realpath($path);
  316. if (false === $realPath && '-' !== $path && 'Standard input code' !== $path) {
  317. return self::PATH_TYPE_UNDETERMINED;
  318. }
  319. foreach (self::getVendors() as $vendor) {
  320. if (0 === strpos($realPath, $vendor) && false !== strpbrk(substr($realPath, \strlen($vendor), 1), '/'.\DIRECTORY_SEPARATOR)) {
  321. return self::PATH_TYPE_VENDOR;
  322. }
  323. }
  324. foreach (self::$internalPaths as $internalPath) {
  325. if (0 === strpos($realPath, $internalPath)) {
  326. return self::PATH_TYPE_SELF;
  327. }
  328. }
  329. return self::PATH_TYPE_UNDETERMINED;
  330. }
  331. /**
  332. * @return string
  333. */
  334. public function toString()
  335. {
  336. $exception = new \Exception($this->message);
  337. $reflection = new \ReflectionProperty($exception, 'trace');
  338. $reflection->setAccessible(true);
  339. $reflection->setValue($exception, $this->trace);
  340. return ($this->originatesFromAnObject() ? 'deprecation triggered by '.$this->originatingClass().'::'.$this->originatingMethod().":\n" : '')
  341. .$this->message."\n"
  342. ."Stack trace:\n"
  343. .str_replace(' '.getcwd().\DIRECTORY_SEPARATOR, ' ', $exception->getTraceAsString())."\n";
  344. }
  345. }