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