ReflectionCaster.php 15 KB

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