ReflectionCaster.php 15 KB

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