ReflectionCaster.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438
  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 (false === strpos($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) {
  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() - 1,
  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. try {
  237. $a[$prefix.'default'] = $v = $c->getDefaultValue();
  238. if ($c->isDefaultValueConstant()) {
  239. $a[$prefix.'default'] = new ConstStub($c->getDefaultValueConstantName(), $v);
  240. }
  241. if (null === $v) {
  242. unset($a[$prefix.'allowsNull']);
  243. }
  244. } catch (\ReflectionException $e) {
  245. }
  246. return $a;
  247. }
  248. public static function castProperty(\ReflectionProperty $c, array $a, Stub $stub, bool $isNested)
  249. {
  250. $a[Caster::PREFIX_VIRTUAL.'modifiers'] = implode(' ', \Reflection::getModifierNames($c->getModifiers()));
  251. self::addAttributes($a, $c);
  252. self::addExtra($a, $c);
  253. return $a;
  254. }
  255. public static function castReference(\ReflectionReference $c, array $a, Stub $stub, bool $isNested)
  256. {
  257. $a[Caster::PREFIX_VIRTUAL.'id'] = $c->getId();
  258. return $a;
  259. }
  260. public static function castExtension(\ReflectionExtension $c, array $a, Stub $stub, bool $isNested)
  261. {
  262. self::addMap($a, $c, [
  263. 'version' => 'getVersion',
  264. 'dependencies' => 'getDependencies',
  265. 'iniEntries' => 'getIniEntries',
  266. 'isPersistent' => 'isPersistent',
  267. 'isTemporary' => 'isTemporary',
  268. 'constants' => 'getConstants',
  269. 'functions' => 'getFunctions',
  270. 'classes' => 'getClasses',
  271. ]);
  272. return $a;
  273. }
  274. public static function castZendExtension(\ReflectionZendExtension $c, array $a, Stub $stub, bool $isNested)
  275. {
  276. self::addMap($a, $c, [
  277. 'version' => 'getVersion',
  278. 'author' => 'getAuthor',
  279. 'copyright' => 'getCopyright',
  280. 'url' => 'getURL',
  281. ]);
  282. return $a;
  283. }
  284. public static function getSignature(array $a)
  285. {
  286. $prefix = Caster::PREFIX_VIRTUAL;
  287. $signature = '';
  288. if (isset($a[$prefix.'parameters'])) {
  289. foreach ($a[$prefix.'parameters']->value as $k => $param) {
  290. $signature .= ', ';
  291. if ($type = $param->getType()) {
  292. if (!$type instanceof \ReflectionNamedType) {
  293. $signature .= $type.' ';
  294. } else {
  295. if (!$param->isOptional() && $param->allowsNull() && 'mixed' !== $type->getName()) {
  296. $signature .= '?';
  297. }
  298. $signature .= substr(strrchr('\\'.$type->getName(), '\\'), 1).' ';
  299. }
  300. }
  301. $signature .= $k;
  302. if (!$param->isDefaultValueAvailable()) {
  303. continue;
  304. }
  305. $v = $param->getDefaultValue();
  306. $signature .= ' = ';
  307. if ($param->isDefaultValueConstant()) {
  308. $signature .= substr(strrchr('\\'.$param->getDefaultValueConstantName(), '\\'), 1);
  309. } elseif (null === $v) {
  310. $signature .= 'null';
  311. } elseif (\is_array($v)) {
  312. $signature .= $v ? '[…'.\count($v).']' : '[]';
  313. } elseif (\is_string($v)) {
  314. $signature .= 10 > \strlen($v) && false === strpos($v, '\\') ? "'{$v}'" : "'…".\strlen($v)."'";
  315. } elseif (\is_bool($v)) {
  316. $signature .= $v ? 'true' : 'false';
  317. } else {
  318. $signature .= $v;
  319. }
  320. }
  321. }
  322. $signature = (empty($a[$prefix.'returnsReference']) ? '' : '&').'('.substr($signature, 2).')';
  323. if (isset($a[$prefix.'returnType'])) {
  324. $signature .= ': '.substr(strrchr('\\'.$a[$prefix.'returnType'], '\\'), 1);
  325. }
  326. return $signature;
  327. }
  328. private static function addExtra(array &$a, \Reflector $c)
  329. {
  330. $x = isset($a[Caster::PREFIX_VIRTUAL.'extra']) ? $a[Caster::PREFIX_VIRTUAL.'extra']->value : [];
  331. if (method_exists($c, 'getFileName') && $m = $c->getFileName()) {
  332. $x['file'] = new LinkStub($m, $c->getStartLine());
  333. $x['line'] = $c->getStartLine().' to '.$c->getEndLine();
  334. }
  335. self::addMap($x, $c, self::EXTRA_MAP, '');
  336. if ($x) {
  337. $a[Caster::PREFIX_VIRTUAL.'extra'] = new EnumStub($x);
  338. }
  339. }
  340. private static function addMap(array &$a, object $c, array $map, string $prefix = Caster::PREFIX_VIRTUAL)
  341. {
  342. foreach ($map as $k => $m) {
  343. if (\PHP_VERSION_ID >= 80000 && 'isDisabled' === $k) {
  344. continue;
  345. }
  346. if (method_exists($c, $m) && false !== ($m = $c->$m()) && null !== $m) {
  347. $a[$prefix.$k] = $m instanceof \Reflector ? $m->name : $m;
  348. }
  349. }
  350. }
  351. private static function addAttributes(array &$a, \Reflector $c, string $prefix = Caster::PREFIX_VIRTUAL): void
  352. {
  353. if (\PHP_VERSION_ID >= 80000) {
  354. foreach ($c->getAttributes() as $n) {
  355. $a[$prefix.'attributes'][] = $n;
  356. }
  357. }
  358. }
  359. }