ReflectionCaster.php 15 KB

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