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.

442 lines
15 KiB

2 years ago
  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\VarDumper\Caster;
  11. use Symfony\Component\VarDumper\Cloner\Stub;
  12. /**
  13. * Casts Reflector related classes to array representation.
  14. *
  15. * @author Nicolas Grekas <p@tchwork.com>
  16. *
  17. * @final
  18. */
  19. class ReflectionCaster
  20. {
  21. public const UNSET_CLOSURE_FILE_INFO = ['Closure' => __CLASS__.'::unsetClosureFileInfo'];
  22. private const EXTRA_MAP = [
  23. 'docComment' => 'getDocComment',
  24. 'extension' => 'getExtensionName',
  25. 'isDisabled' => 'isDisabled',
  26. 'isDeprecated' => 'isDeprecated',
  27. 'isInternal' => 'isInternal',
  28. 'isUserDefined' => 'isUserDefined',
  29. 'isGenerator' => 'isGenerator',
  30. 'isVariadic' => 'isVariadic',
  31. ];
  32. public static function castClosure(\Closure $c, array $a, Stub $stub, bool $isNested, int $filter = 0)
  33. {
  34. $prefix = Caster::PREFIX_VIRTUAL;
  35. $c = new \ReflectionFunction($c);
  36. $a = static::castFunctionAbstract($c, $a, $stub, $isNested, $filter);
  37. if (!str_contains($c->name, '{closure}')) {
  38. $stub->class = isset($a[$prefix.'class']) ? $a[$prefix.'class']->value.'::'.$c->name : $c->name;
  39. unset($a[$prefix.'class']);
  40. }
  41. unset($a[$prefix.'extra']);
  42. $stub->class .= self::getSignature($a);
  43. if ($f = $c->getFileName()) {
  44. $stub->attr['file'] = $f;
  45. $stub->attr['line'] = $c->getStartLine();
  46. }
  47. unset($a[$prefix.'parameters']);
  48. if ($filter & Caster::EXCLUDE_VERBOSE) {
  49. $stub->cut += ($c->getFileName() ? 2 : 0) + \count($a);
  50. return [];
  51. }
  52. if ($f) {
  53. $a[$prefix.'file'] = new LinkStub($f, $c->getStartLine());
  54. $a[$prefix.'line'] = $c->getStartLine().' to '.$c->getEndLine();
  55. }
  56. return $a;
  57. }
  58. public static function unsetClosureFileInfo(\Closure $c, array $a)
  59. {
  60. unset($a[Caster::PREFIX_VIRTUAL.'file'], $a[Caster::PREFIX_VIRTUAL.'line']);
  61. return $a;
  62. }
  63. public static function castGenerator(\Generator $c, array $a, Stub $stub, bool $isNested)
  64. {
  65. // Cannot create ReflectionGenerator based on a terminated Generator
  66. try {
  67. $reflectionGenerator = new \ReflectionGenerator($c);
  68. } catch (\Exception $e) {
  69. $a[Caster::PREFIX_VIRTUAL.'closed'] = true;
  70. return $a;
  71. }
  72. return self::castReflectionGenerator($reflectionGenerator, $a, $stub, $isNested);
  73. }
  74. public static function castType(\ReflectionType $c, array $a, Stub $stub, bool $isNested)
  75. {
  76. $prefix = Caster::PREFIX_VIRTUAL;
  77. if ($c instanceof \ReflectionNamedType || \PHP_VERSION_ID < 80000) {
  78. $a += [
  79. $prefix.'name' => $c instanceof \ReflectionNamedType ? $c->getName() : (string) $c,
  80. $prefix.'allowsNull' => $c->allowsNull(),
  81. $prefix.'isBuiltin' => $c->isBuiltin(),
  82. ];
  83. } elseif ($c instanceof \ReflectionUnionType || $c instanceof \ReflectionIntersectionType) {
  84. $a[$prefix.'allowsNull'] = $c->allowsNull();
  85. self::addMap($a, $c, [
  86. 'types' => 'getTypes',
  87. ]);
  88. } else {
  89. $a[$prefix.'allowsNull'] = $c->allowsNull();
  90. }
  91. return $a;
  92. }
  93. public static function castAttribute(\ReflectionAttribute $c, array $a, Stub $stub, bool $isNested)
  94. {
  95. self::addMap($a, $c, [
  96. 'name' => 'getName',
  97. 'arguments' => 'getArguments',
  98. ]);
  99. return $a;
  100. }
  101. public static function castReflectionGenerator(\ReflectionGenerator $c, array $a, Stub $stub, bool $isNested)
  102. {
  103. $prefix = Caster::PREFIX_VIRTUAL;
  104. if ($c->getThis()) {
  105. $a[$prefix.'this'] = new CutStub($c->getThis());
  106. }
  107. $function = $c->getFunction();
  108. $frame = [
  109. 'class' => $function->class ?? null,
  110. 'type' => isset($function->class) ? ($function->isStatic() ? '::' : '->') : null,
  111. 'function' => $function->name,
  112. 'file' => $c->getExecutingFile(),
  113. 'line' => $c->getExecutingLine(),
  114. ];
  115. if ($trace = $c->getTrace(\DEBUG_BACKTRACE_IGNORE_ARGS)) {
  116. $function = new \ReflectionGenerator($c->getExecutingGenerator());
  117. array_unshift($trace, [
  118. 'function' => 'yield',
  119. 'file' => $function->getExecutingFile(),
  120. 'line' => $function->getExecutingLine() - (int) (\PHP_VERSION_ID < 80100),
  121. ]);
  122. $trace[] = $frame;
  123. $a[$prefix.'trace'] = new TraceStub($trace, false, 0, -1, -1);
  124. } else {
  125. $function = new FrameStub($frame, false, true);
  126. $function = ExceptionCaster::castFrameStub($function, [], $function, true);
  127. $a[$prefix.'executing'] = $function[$prefix.'src'];
  128. }
  129. $a[Caster::PREFIX_VIRTUAL.'closed'] = false;
  130. return $a;
  131. }
  132. public static function castClass(\ReflectionClass $c, array $a, Stub $stub, bool $isNested, int $filter = 0)
  133. {
  134. $prefix = Caster::PREFIX_VIRTUAL;
  135. if ($n = \Reflection::getModifierNames($c->getModifiers())) {
  136. $a[$prefix.'modifiers'] = implode(' ', $n);
  137. }
  138. self::addMap($a, $c, [
  139. 'extends' => 'getParentClass',
  140. 'implements' => 'getInterfaceNames',
  141. 'constants' => 'getReflectionConstants',
  142. ]);
  143. foreach ($c->getProperties() as $n) {
  144. $a[$prefix.'properties'][$n->name] = $n;
  145. }
  146. foreach ($c->getMethods() as $n) {
  147. $a[$prefix.'methods'][$n->name] = $n;
  148. }
  149. self::addAttributes($a, $c, $prefix);
  150. if (!($filter & Caster::EXCLUDE_VERBOSE) && !$isNested) {
  151. self::addExtra($a, $c);
  152. }
  153. return $a;
  154. }
  155. public static function castFunctionAbstract(\ReflectionFunctionAbstract $c, array $a, Stub $stub, bool $isNested, int $filter = 0)
  156. {
  157. $prefix = Caster::PREFIX_VIRTUAL;
  158. self::addMap($a, $c, [
  159. 'returnsReference' => 'returnsReference',
  160. 'returnType' => 'getReturnType',
  161. 'class' => 'getClosureScopeClass',
  162. 'this' => 'getClosureThis',
  163. ]);
  164. if (isset($a[$prefix.'returnType'])) {
  165. $v = $a[$prefix.'returnType'];
  166. $v = $v instanceof \ReflectionNamedType ? $v->getName() : (string) $v;
  167. $a[$prefix.'returnType'] = new ClassStub($a[$prefix.'returnType'] instanceof \ReflectionNamedType && $a[$prefix.'returnType']->allowsNull() && 'mixed' !== $v ? '?'.$v : $v, [class_exists($v, false) || interface_exists($v, false) || trait_exists($v, false) ? $v : '', '']);
  168. }
  169. if (isset($a[$prefix.'class'])) {
  170. $a[$prefix.'class'] = new ClassStub($a[$prefix.'class']);
  171. }
  172. if (isset($a[$prefix.'this'])) {
  173. $a[$prefix.'this'] = new CutStub($a[$prefix.'this']);
  174. }
  175. foreach ($c->getParameters() as $v) {
  176. $k = '$'.$v->name;
  177. if ($v->isVariadic()) {
  178. $k = '...'.$k;
  179. }
  180. if ($v->isPassedByReference()) {
  181. $k = '&'.$k;
  182. }
  183. $a[$prefix.'parameters'][$k] = $v;
  184. }
  185. if (isset($a[$prefix.'parameters'])) {
  186. $a[$prefix.'parameters'] = new EnumStub($a[$prefix.'parameters']);
  187. }
  188. self::addAttributes($a, $c, $prefix);
  189. if (!($filter & Caster::EXCLUDE_VERBOSE) && $v = $c->getStaticVariables()) {
  190. foreach ($v as $k => &$v) {
  191. if (\is_object($v)) {
  192. $a[$prefix.'use']['$'.$k] = new CutStub($v);
  193. } else {
  194. $a[$prefix.'use']['$'.$k] = &$v;
  195. }
  196. }
  197. unset($v);
  198. $a[$prefix.'use'] = new EnumStub($a[$prefix.'use']);
  199. }
  200. if (!($filter & Caster::EXCLUDE_VERBOSE) && !$isNested) {
  201. self::addExtra($a, $c);
  202. }
  203. return $a;
  204. }
  205. public static function castClassConstant(\ReflectionClassConstant $c, array $a, Stub $stub, bool $isNested)
  206. {
  207. $a[Caster::PREFIX_VIRTUAL.'modifiers'] = implode(' ', \Reflection::getModifierNames($c->getModifiers()));
  208. $a[Caster::PREFIX_VIRTUAL.'value'] = $c->getValue();
  209. self::addAttributes($a, $c);
  210. return $a;
  211. }
  212. public static function castMethod(\ReflectionMethod $c, array $a, Stub $stub, bool $isNested)
  213. {
  214. $a[Caster::PREFIX_VIRTUAL.'modifiers'] = implode(' ', \Reflection::getModifierNames($c->getModifiers()));
  215. return $a;
  216. }
  217. public static function castParameter(\ReflectionParameter $c, array $a, Stub $stub, bool $isNested)
  218. {
  219. $prefix = Caster::PREFIX_VIRTUAL;
  220. self::addMap($a, $c, [
  221. 'position' => 'getPosition',
  222. 'isVariadic' => 'isVariadic',
  223. 'byReference' => 'isPassedByReference',
  224. 'allowsNull' => 'allowsNull',
  225. ]);
  226. self::addAttributes($a, $c, $prefix);
  227. if ($v = $c->getType()) {
  228. $a[$prefix.'typeHint'] = $v instanceof \ReflectionNamedType ? $v->getName() : (string) $v;
  229. }
  230. if (isset($a[$prefix.'typeHint'])) {
  231. $v = $a[$prefix.'typeHint'];
  232. $a[$prefix.'typeHint'] = new ClassStub($v, [class_exists($v, false) || interface_exists($v, false) || trait_exists($v, false) ? $v : '', '']);
  233. } else {
  234. unset($a[$prefix.'allowsNull']);
  235. }
  236. if ($c->isOptional()) {
  237. try {
  238. $a[$prefix.'default'] = $v = $c->getDefaultValue();
  239. if ($c->isDefaultValueConstant()) {
  240. $a[$prefix.'default'] = new ConstStub($c->getDefaultValueConstantName(), $v);
  241. }
  242. if (null === $v) {
  243. unset($a[$prefix.'allowsNull']);
  244. }
  245. } catch (\ReflectionException $e) {
  246. }
  247. }
  248. return $a;
  249. }
  250. public static function castProperty(\ReflectionProperty $c, array $a, Stub $stub, bool $isNested)
  251. {
  252. $a[Caster::PREFIX_VIRTUAL.'modifiers'] = implode(' ', \Reflection::getModifierNames($c->getModifiers()));
  253. self::addAttributes($a, $c);
  254. self::addExtra($a, $c);
  255. return $a;
  256. }
  257. public static function castReference(\ReflectionReference $c, array $a, Stub $stub, bool $isNested)
  258. {
  259. $a[Caster::PREFIX_VIRTUAL.'id'] = $c->getId();
  260. return $a;
  261. }
  262. public static function castExtension(\ReflectionExtension $c, array $a, Stub $stub, bool $isNested)
  263. {
  264. self::addMap($a, $c, [
  265. 'version' => 'getVersion',
  266. 'dependencies' => 'getDependencies',
  267. 'iniEntries' => 'getIniEntries',
  268. 'isPersistent' => 'isPersistent',
  269. 'isTemporary' => 'isTemporary',
  270. 'constants' => 'getConstants',
  271. 'functions' => 'getFunctions',
  272. 'classes' => 'getClasses',
  273. ]);
  274. return $a;
  275. }
  276. public static function castZendExtension(\ReflectionZendExtension $c, array $a, Stub $stub, bool $isNested)
  277. {
  278. self::addMap($a, $c, [
  279. 'version' => 'getVersion',
  280. 'author' => 'getAuthor',
  281. 'copyright' => 'getCopyright',
  282. 'url' => 'getURL',
  283. ]);
  284. return $a;
  285. }
  286. public static function getSignature(array $a)
  287. {
  288. $prefix = Caster::PREFIX_VIRTUAL;
  289. $signature = '';
  290. if (isset($a[$prefix.'parameters'])) {
  291. foreach ($a[$prefix.'parameters']->value as $k => $param) {
  292. $signature .= ', ';
  293. if ($type = $param->getType()) {
  294. if (!$type instanceof \ReflectionNamedType) {
  295. $signature .= $type.' ';
  296. } else {
  297. if (!$param->isOptional() && $param->allowsNull() && 'mixed' !== $type->getName()) {
  298. $signature .= '?';
  299. }
  300. $signature .= substr(strrchr('\\'.$type->getName(), '\\'), 1).' ';
  301. }
  302. }
  303. $signature .= $k;
  304. if (!$param->isDefaultValueAvailable()) {
  305. continue;
  306. }
  307. $v = $param->getDefaultValue();
  308. $signature .= ' = ';
  309. if ($param->isDefaultValueConstant()) {
  310. $signature .= substr(strrchr('\\'.$param->getDefaultValueConstantName(), '\\'), 1);
  311. } elseif (null === $v) {
  312. $signature .= 'null';
  313. } elseif (\is_array($v)) {
  314. $signature .= $v ? '[…'.\count($v).']' : '[]';
  315. } elseif (\is_string($v)) {
  316. $signature .= 10 > \strlen($v) && !str_contains($v, '\\') ? "'{$v}'" : "'…".\strlen($v)."'";
  317. } elseif (\is_bool($v)) {
  318. $signature .= $v ? 'true' : 'false';
  319. } elseif (\is_object($v)) {
  320. $signature .= 'new '.substr(strrchr('\\'.get_debug_type($v), '\\'), 1);
  321. } else {
  322. $signature .= $v;
  323. }
  324. }
  325. }
  326. $signature = (empty($a[$prefix.'returnsReference']) ? '' : '&').'('.substr($signature, 2).')';
  327. if (isset($a[$prefix.'returnType'])) {
  328. $signature .= ': '.substr(strrchr('\\'.$a[$prefix.'returnType'], '\\'), 1);
  329. }
  330. return $signature;
  331. }
  332. private static function addExtra(array &$a, \Reflector $c)
  333. {
  334. $x = isset($a[Caster::PREFIX_VIRTUAL.'extra']) ? $a[Caster::PREFIX_VIRTUAL.'extra']->value : [];
  335. if (method_exists($c, 'getFileName') && $m = $c->getFileName()) {
  336. $x['file'] = new LinkStub($m, $c->getStartLine());
  337. $x['line'] = $c->getStartLine().' to '.$c->getEndLine();
  338. }
  339. self::addMap($x, $c, self::EXTRA_MAP, '');
  340. if ($x) {
  341. $a[Caster::PREFIX_VIRTUAL.'extra'] = new EnumStub($x);
  342. }
  343. }
  344. private static function addMap(array &$a, object $c, array $map, string $prefix = Caster::PREFIX_VIRTUAL)
  345. {
  346. foreach ($map as $k => $m) {
  347. if (\PHP_VERSION_ID >= 80000 && 'isDisabled' === $k) {
  348. continue;
  349. }
  350. if (method_exists($c, $m) && false !== ($m = $c->$m()) && null !== $m) {
  351. $a[$prefix.$k] = $m instanceof \Reflector ? $m->name : $m;
  352. }
  353. }
  354. }
  355. private static function addAttributes(array &$a, \Reflector $c, string $prefix = Caster::PREFIX_VIRTUAL): void
  356. {
  357. if (\PHP_VERSION_ID >= 80000) {
  358. foreach ($c->getAttributes() as $n) {
  359. $a[$prefix.'attributes'][] = $n;
  360. }
  361. }
  362. }
  363. }