Reflection.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418
  1. <?php
  2. /**
  3. * This file is part of the Nette Framework (https://nette.org)
  4. * Copyright (c) 2004 David Grudl (https://davidgrudl.com)
  5. */
  6. declare(strict_types=1);
  7. namespace Nette\Utils;
  8. use Nette;
  9. /**
  10. * PHP reflection helpers.
  11. */
  12. final class Reflection
  13. {
  14. use Nette\StaticClass;
  15. private const BUILTIN_TYPES = [
  16. 'string' => 1, 'int' => 1, 'float' => 1, 'bool' => 1, 'array' => 1, 'object' => 1,
  17. 'callable' => 1, 'iterable' => 1, 'void' => 1, 'null' => 1, 'mixed' => 1, 'false' => 1,
  18. ];
  19. /**
  20. * Determines if type is PHP built-in type. Otherwise, it is the class name.
  21. */
  22. public static function isBuiltinType(string $type): bool
  23. {
  24. return isset(self::BUILTIN_TYPES[strtolower($type)]);
  25. }
  26. /**
  27. * Returns the type of return value of given function or method and normalizes `self`, `static`, and `parent` to actual class names.
  28. * If the function does not have a return type, it returns null.
  29. * If the function has union type, it throws Nette\InvalidStateException.
  30. */
  31. public static function getReturnType(\ReflectionFunctionAbstract $func): ?string
  32. {
  33. return self::getType($func, $func->getReturnType());
  34. }
  35. /**
  36. * Returns the types of return value of given function or method and normalizes `self`, `static`, and `parent` to actual class names.
  37. */
  38. public static function getReturnTypes(\ReflectionFunctionAbstract $func): array
  39. {
  40. return self::getType($func, $func->getReturnType(), true);
  41. }
  42. /**
  43. * Returns the type of given parameter and normalizes `self` and `parent` to the actual class names.
  44. * If the parameter does not have a type, it returns null.
  45. * If the parameter has union type, it throws Nette\InvalidStateException.
  46. */
  47. public static function getParameterType(\ReflectionParameter $param): ?string
  48. {
  49. return self::getType($param, $param->getType());
  50. }
  51. /**
  52. * Returns the types of given parameter and normalizes `self` and `parent` to the actual class names.
  53. */
  54. public static function getParameterTypes(\ReflectionParameter $param): array
  55. {
  56. return self::getType($param, $param->getType(), true);
  57. }
  58. /**
  59. * Returns the type of given property and normalizes `self` and `parent` to the actual class names.
  60. * If the property does not have a type, it returns null.
  61. * If the property has union type, it throws Nette\InvalidStateException.
  62. */
  63. public static function getPropertyType(\ReflectionProperty $prop): ?string
  64. {
  65. return self::getType($prop, PHP_VERSION_ID >= 70400 ? $prop->getType() : null);
  66. }
  67. /**
  68. * Returns the types of given property and normalizes `self` and `parent` to the actual class names.
  69. */
  70. public static function getPropertyTypes(\ReflectionProperty $prop): array
  71. {
  72. return self::getType($prop, PHP_VERSION_ID >= 70400 ? $prop->getType() : null, true);
  73. }
  74. /**
  75. * @param \ReflectionFunction|\ReflectionMethod|\ReflectionParameter|\ReflectionProperty $reflection
  76. * @return string|array|null
  77. */
  78. private static function getType($reflection, ?\ReflectionType $type, bool $asArray = false)
  79. {
  80. if ($type === null) {
  81. return $asArray ? [] : null;
  82. } elseif ($type instanceof \ReflectionNamedType) {
  83. $name = self::normalizeType($type->getName(), $reflection);
  84. if ($asArray) {
  85. return $type->allowsNull() && $type->getName() !== 'mixed'
  86. ? [$name, 'null']
  87. : [$name];
  88. }
  89. return $name;
  90. } elseif ($type instanceof \ReflectionUnionType) {
  91. if ($asArray) {
  92. $types = [];
  93. foreach ($type->getTypes() as $type) {
  94. $types[] = self::normalizeType($type->getName(), $reflection);
  95. }
  96. return $types;
  97. }
  98. throw new Nette\InvalidStateException('The ' . self::toString($reflection) . ' is not expected to have a union type.');
  99. } else {
  100. throw new Nette\InvalidStateException('Unexpected type of ' . self::toString($reflection));
  101. }
  102. }
  103. /**
  104. * @param \ReflectionFunction|\ReflectionMethod|\ReflectionParameter|\ReflectionProperty $reflection
  105. */
  106. private static function normalizeType(string $type, $reflection): string
  107. {
  108. $lower = strtolower($type);
  109. if ($reflection instanceof \ReflectionFunction) {
  110. return $type;
  111. } elseif ($lower === 'self' || $lower === 'static') {
  112. return $reflection->getDeclaringClass()->name;
  113. } elseif ($lower === 'parent' && $reflection->getDeclaringClass()->getParentClass()) {
  114. return $reflection->getDeclaringClass()->getParentClass()->name;
  115. } else {
  116. return $type;
  117. }
  118. }
  119. /**
  120. * Returns the default value of parameter. If it is a constant, it returns its value.
  121. * @return mixed
  122. * @throws \ReflectionException If the parameter does not have a default value or the constant cannot be resolved
  123. */
  124. public static function getParameterDefaultValue(\ReflectionParameter $param)
  125. {
  126. if ($param->isDefaultValueConstant()) {
  127. $const = $orig = $param->getDefaultValueConstantName();
  128. $pair = explode('::', $const);
  129. if (isset($pair[1])) {
  130. $pair[0] = self::normalizeType($pair[0], $param);
  131. try {
  132. $rcc = new \ReflectionClassConstant($pair[0], $pair[1]);
  133. } catch (\ReflectionException $e) {
  134. $name = self::toString($param);
  135. throw new \ReflectionException("Unable to resolve constant $orig used as default value of $name.", 0, $e);
  136. }
  137. return $rcc->getValue();
  138. } elseif (!defined($const)) {
  139. $const = substr((string) strrchr($const, '\\'), 1);
  140. if (!defined($const)) {
  141. $name = self::toString($param);
  142. throw new \ReflectionException("Unable to resolve constant $orig used as default value of $name.");
  143. }
  144. }
  145. return constant($const);
  146. }
  147. return $param->getDefaultValue();
  148. }
  149. /**
  150. * Returns a reflection of a class or trait that contains a declaration of given property. Property can also be declared in the trait.
  151. */
  152. public static function getPropertyDeclaringClass(\ReflectionProperty $prop): \ReflectionClass
  153. {
  154. foreach ($prop->getDeclaringClass()->getTraits() as $trait) {
  155. if ($trait->hasProperty($prop->name)
  156. // doc-comment guessing as workaround for insufficient PHP reflection
  157. && $trait->getProperty($prop->name)->getDocComment() === $prop->getDocComment()
  158. ) {
  159. return self::getPropertyDeclaringClass($trait->getProperty($prop->name));
  160. }
  161. }
  162. return $prop->getDeclaringClass();
  163. }
  164. /**
  165. * Returns a reflection of a method that contains a declaration of $method.
  166. * Usually, each method is its own declaration, but the body of the method can also be in the trait and under a different name.
  167. */
  168. public static function getMethodDeclaringMethod(\ReflectionMethod $method): \ReflectionMethod
  169. {
  170. // file & line guessing as workaround for insufficient PHP reflection
  171. $decl = $method->getDeclaringClass();
  172. if ($decl->getFileName() === $method->getFileName()
  173. && $decl->getStartLine() <= $method->getStartLine()
  174. && $decl->getEndLine() >= $method->getEndLine()
  175. ) {
  176. return $method;
  177. }
  178. $hash = [$method->getFileName(), $method->getStartLine(), $method->getEndLine()];
  179. if (($alias = $decl->getTraitAliases()[$method->name] ?? null)
  180. && ($m = new \ReflectionMethod($alias))
  181. && $hash === [$m->getFileName(), $m->getStartLine(), $m->getEndLine()]
  182. ) {
  183. return self::getMethodDeclaringMethod($m);
  184. }
  185. foreach ($decl->getTraits() as $trait) {
  186. if ($trait->hasMethod($method->name)
  187. && ($m = $trait->getMethod($method->name))
  188. && $hash === [$m->getFileName(), $m->getStartLine(), $m->getEndLine()]
  189. ) {
  190. return self::getMethodDeclaringMethod($m);
  191. }
  192. }
  193. return $method;
  194. }
  195. /**
  196. * Finds out if reflection has access to PHPdoc comments. Comments may not be available due to the opcode cache.
  197. */
  198. public static function areCommentsAvailable(): bool
  199. {
  200. static $res;
  201. return $res ?? $res = (bool) (new \ReflectionMethod(__METHOD__))->getDocComment();
  202. }
  203. public static function toString(\Reflector $ref): string
  204. {
  205. if ($ref instanceof \ReflectionClass) {
  206. return $ref->name;
  207. } elseif ($ref instanceof \ReflectionMethod) {
  208. return $ref->getDeclaringClass()->name . '::' . $ref->name . '()';
  209. } elseif ($ref instanceof \ReflectionFunction) {
  210. return $ref->name . '()';
  211. } elseif ($ref instanceof \ReflectionProperty) {
  212. return self::getPropertyDeclaringClass($ref)->name . '::$' . $ref->name;
  213. } elseif ($ref instanceof \ReflectionParameter) {
  214. return '$' . $ref->name . ' in ' . self::toString($ref->getDeclaringFunction());
  215. } else {
  216. throw new Nette\InvalidArgumentException;
  217. }
  218. }
  219. /**
  220. * Expands the name of the class to full name in the given context of given class.
  221. * Thus, it returns how the PHP parser would understand $name if it were written in the body of the class $context.
  222. * @throws Nette\InvalidArgumentException
  223. */
  224. public static function expandClassName(string $name, \ReflectionClass $context): string
  225. {
  226. $lower = strtolower($name);
  227. if (empty($name)) {
  228. throw new Nette\InvalidArgumentException('Class name must not be empty.');
  229. } elseif (isset(self::BUILTIN_TYPES[$lower])) {
  230. return $lower;
  231. } elseif ($lower === 'self' || $lower === 'static') {
  232. return $context->name;
  233. } elseif ($name[0] === '\\') { // fully qualified name
  234. return ltrim($name, '\\');
  235. }
  236. $uses = self::getUseStatements($context);
  237. $parts = explode('\\', $name, 2);
  238. if (isset($uses[$parts[0]])) {
  239. $parts[0] = $uses[$parts[0]];
  240. return implode('\\', $parts);
  241. } elseif ($context->inNamespace()) {
  242. return $context->getNamespaceName() . '\\' . $name;
  243. } else {
  244. return $name;
  245. }
  246. }
  247. /** @return array of [alias => class] */
  248. public static function getUseStatements(\ReflectionClass $class): array
  249. {
  250. if ($class->isAnonymous()) {
  251. throw new Nette\NotImplementedException('Anonymous classes are not supported.');
  252. }
  253. static $cache = [];
  254. if (!isset($cache[$name = $class->name])) {
  255. if ($class->isInternal()) {
  256. $cache[$name] = [];
  257. } else {
  258. $code = file_get_contents($class->getFileName());
  259. $cache = self::parseUseStatements($code, $name) + $cache;
  260. }
  261. }
  262. return $cache[$name];
  263. }
  264. /**
  265. * Parses PHP code to [class => [alias => class, ...]]
  266. */
  267. private static function parseUseStatements(string $code, string $forClass = null): array
  268. {
  269. try {
  270. $tokens = token_get_all($code, TOKEN_PARSE);
  271. } catch (\ParseError $e) {
  272. trigger_error($e->getMessage(), E_USER_NOTICE);
  273. $tokens = [];
  274. }
  275. $namespace = $class = $classLevel = $level = null;
  276. $res = $uses = [];
  277. $nameTokens = PHP_VERSION_ID < 80000
  278. ? [T_STRING, T_NS_SEPARATOR]
  279. : [T_STRING, T_NS_SEPARATOR, T_NAME_QUALIFIED, T_NAME_FULLY_QUALIFIED];
  280. while ($token = current($tokens)) {
  281. next($tokens);
  282. switch (is_array($token) ? $token[0] : $token) {
  283. case T_NAMESPACE:
  284. $namespace = ltrim(self::fetch($tokens, $nameTokens) . '\\', '\\');
  285. $uses = [];
  286. break;
  287. case T_CLASS:
  288. case T_INTERFACE:
  289. case T_TRAIT:
  290. if ($name = self::fetch($tokens, T_STRING)) {
  291. $class = $namespace . $name;
  292. $classLevel = $level + 1;
  293. $res[$class] = $uses;
  294. if ($class === $forClass) {
  295. return $res;
  296. }
  297. }
  298. break;
  299. case T_USE:
  300. while (!$class && ($name = self::fetch($tokens, $nameTokens))) {
  301. $name = ltrim($name, '\\');
  302. if (self::fetch($tokens, '{')) {
  303. while ($suffix = self::fetch($tokens, $nameTokens)) {
  304. if (self::fetch($tokens, T_AS)) {
  305. $uses[self::fetch($tokens, T_STRING)] = $name . $suffix;
  306. } else {
  307. $tmp = explode('\\', $suffix);
  308. $uses[end($tmp)] = $name . $suffix;
  309. }
  310. if (!self::fetch($tokens, ',')) {
  311. break;
  312. }
  313. }
  314. } elseif (self::fetch($tokens, T_AS)) {
  315. $uses[self::fetch($tokens, T_STRING)] = $name;
  316. } else {
  317. $tmp = explode('\\', $name);
  318. $uses[end($tmp)] = $name;
  319. }
  320. if (!self::fetch($tokens, ',')) {
  321. break;
  322. }
  323. }
  324. break;
  325. case T_CURLY_OPEN:
  326. case T_DOLLAR_OPEN_CURLY_BRACES:
  327. case '{':
  328. $level++;
  329. break;
  330. case '}':
  331. if ($level === $classLevel) {
  332. $class = $classLevel = null;
  333. }
  334. $level--;
  335. }
  336. }
  337. return $res;
  338. }
  339. private static function fetch(array &$tokens, $take): ?string
  340. {
  341. $res = null;
  342. while ($token = current($tokens)) {
  343. [$token, $s] = is_array($token) ? $token : [$token, $token];
  344. if (in_array($token, (array) $take, true)) {
  345. $res .= $s;
  346. } elseif (!in_array($token, [T_DOC_COMMENT, T_WHITESPACE, T_COMMENT], true)) {
  347. break;
  348. }
  349. next($tokens);
  350. }
  351. return $res;
  352. }
  353. }