ObjectHelpers.php 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228
  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. use Nette\MemberAccessException;
  10. /**
  11. * Nette\SmartObject helpers.
  12. */
  13. final class ObjectHelpers
  14. {
  15. use Nette\StaticClass;
  16. /**
  17. * @return never
  18. * @throws MemberAccessException
  19. */
  20. public static function strictGet(string $class, string $name): void
  21. {
  22. $rc = new \ReflectionClass($class);
  23. $hint = self::getSuggestion(array_merge(
  24. array_filter($rc->getProperties(\ReflectionProperty::IS_PUBLIC), function ($p) { return !$p->isStatic(); }),
  25. self::parseFullDoc($rc, '~^[ \t*]*@property(?:-read)?[ \t]+(?:\S+[ \t]+)??\$(\w+)~m')
  26. ), $name);
  27. throw new MemberAccessException("Cannot read an undeclared property $class::\$$name" . ($hint ? ", did you mean \$$hint?" : '.'));
  28. }
  29. /**
  30. * @return never
  31. * @throws MemberAccessException
  32. */
  33. public static function strictSet(string $class, string $name): void
  34. {
  35. $rc = new \ReflectionClass($class);
  36. $hint = self::getSuggestion(array_merge(
  37. array_filter($rc->getProperties(\ReflectionProperty::IS_PUBLIC), function ($p) { return !$p->isStatic(); }),
  38. self::parseFullDoc($rc, '~^[ \t*]*@property(?:-write)?[ \t]+(?:\S+[ \t]+)??\$(\w+)~m')
  39. ), $name);
  40. throw new MemberAccessException("Cannot write to an undeclared property $class::\$$name" . ($hint ? ", did you mean \$$hint?" : '.'));
  41. }
  42. /**
  43. * @return never
  44. * @throws MemberAccessException
  45. */
  46. public static function strictCall(string $class, string $method, array $additionalMethods = []): void
  47. {
  48. $trace = debug_backtrace(0, 3); // suppose this method is called from __call()
  49. $context = ($trace[1]['function'] ?? null) === '__call'
  50. ? ($trace[2]['class'] ?? null)
  51. : null;
  52. if ($context && is_a($class, $context, true) && method_exists($context, $method)) { // called parent::$method()
  53. $class = get_parent_class($context);
  54. }
  55. if (method_exists($class, $method)) { // insufficient visibility
  56. $rm = new \ReflectionMethod($class, $method);
  57. $visibility = $rm->isPrivate()
  58. ? 'private '
  59. : ($rm->isProtected() ? 'protected ' : '');
  60. throw new MemberAccessException("Call to {$visibility}method $class::$method() from " . ($context ? "scope $context." : 'global scope.'));
  61. } else {
  62. $hint = self::getSuggestion(array_merge(
  63. get_class_methods($class),
  64. self::parseFullDoc(new \ReflectionClass($class), '~^[ \t*]*@method[ \t]+(?:static[ \t]+)?(?:\S+[ \t]+)??(\w+)\(~m'),
  65. $additionalMethods
  66. ), $method);
  67. throw new MemberAccessException("Call to undefined method $class::$method()" . ($hint ? ", did you mean $hint()?" : '.'));
  68. }
  69. }
  70. /**
  71. * @return never
  72. * @throws MemberAccessException
  73. */
  74. public static function strictStaticCall(string $class, string $method): void
  75. {
  76. $trace = debug_backtrace(0, 3); // suppose this method is called from __callStatic()
  77. $context = ($trace[1]['function'] ?? null) === '__callStatic'
  78. ? ($trace[2]['class'] ?? null)
  79. : null;
  80. if ($context && is_a($class, $context, true) && method_exists($context, $method)) { // called parent::$method()
  81. $class = get_parent_class($context);
  82. }
  83. if (method_exists($class, $method)) { // insufficient visibility
  84. $rm = new \ReflectionMethod($class, $method);
  85. $visibility = $rm->isPrivate()
  86. ? 'private '
  87. : ($rm->isProtected() ? 'protected ' : '');
  88. throw new MemberAccessException("Call to {$visibility}method $class::$method() from " . ($context ? "scope $context." : 'global scope.'));
  89. } else {
  90. $hint = self::getSuggestion(
  91. array_filter((new \ReflectionClass($class))->getMethods(\ReflectionMethod::IS_PUBLIC), function ($m) { return $m->isStatic(); }),
  92. $method
  93. );
  94. throw new MemberAccessException("Call to undefined static method $class::$method()" . ($hint ? ", did you mean $hint()?" : '.'));
  95. }
  96. }
  97. /**
  98. * Returns array of magic properties defined by annotation @property.
  99. * @return array of [name => bit mask]
  100. * @internal
  101. */
  102. public static function getMagicProperties(string $class): array
  103. {
  104. static $cache;
  105. $props = &$cache[$class];
  106. if ($props !== null) {
  107. return $props;
  108. }
  109. $rc = new \ReflectionClass($class);
  110. preg_match_all(
  111. '~^ [ \t*]* @property(|-read|-write|-deprecated) [ \t]+ [^\s$]+ [ \t]+ \$ (\w+) ()~mx',
  112. (string) $rc->getDocComment(),
  113. $matches,
  114. PREG_SET_ORDER
  115. );
  116. $props = [];
  117. foreach ($matches as [, $type, $name]) {
  118. $uname = ucfirst($name);
  119. $write = $type !== '-read'
  120. && $rc->hasMethod($nm = 'set' . $uname)
  121. && ($rm = $rc->getMethod($nm))->name === $nm && !$rm->isPrivate() && !$rm->isStatic();
  122. $read = $type !== '-write'
  123. && ($rc->hasMethod($nm = 'get' . $uname) || $rc->hasMethod($nm = 'is' . $uname))
  124. && ($rm = $rc->getMethod($nm))->name === $nm && !$rm->isPrivate() && !$rm->isStatic();
  125. if ($read || $write) {
  126. $props[$name] = $read << 0 | ($nm[0] === 'g') << 1 | $rm->returnsReference() << 2 | $write << 3 | ($type === '-deprecated') << 4;
  127. }
  128. }
  129. foreach ($rc->getTraits() as $trait) {
  130. $props += self::getMagicProperties($trait->name);
  131. }
  132. if ($parent = get_parent_class($class)) {
  133. $props += self::getMagicProperties($parent);
  134. }
  135. return $props;
  136. }
  137. /**
  138. * Finds the best suggestion (for 8-bit encoding).
  139. * @param (\ReflectionFunctionAbstract|\ReflectionParameter|\ReflectionClass|\ReflectionProperty|string)[] $possibilities
  140. * @internal
  141. */
  142. public static function getSuggestion(array $possibilities, string $value): ?string
  143. {
  144. $norm = preg_replace($re = '#^(get|set|has|is|add)(?=[A-Z])#', '+', $value);
  145. $best = null;
  146. $min = (strlen($value) / 4 + 1) * 10 + .1;
  147. foreach (array_unique($possibilities, SORT_REGULAR) as $item) {
  148. $item = $item instanceof \Reflector ? $item->name : $item;
  149. if ($item !== $value && (
  150. ($len = levenshtein($item, $value, 10, 11, 10)) < $min
  151. || ($len = levenshtein(preg_replace($re, '*', $item), $norm, 10, 11, 10)) < $min
  152. )) {
  153. $min = $len;
  154. $best = $item;
  155. }
  156. }
  157. return $best;
  158. }
  159. private static function parseFullDoc(\ReflectionClass $rc, string $pattern): array
  160. {
  161. do {
  162. $doc[] = $rc->getDocComment();
  163. $traits = $rc->getTraits();
  164. while ($trait = array_pop($traits)) {
  165. $doc[] = $trait->getDocComment();
  166. $traits += $trait->getTraits();
  167. }
  168. } while ($rc = $rc->getParentClass());
  169. return preg_match_all($pattern, implode($doc), $m) ? $m[1] : [];
  170. }
  171. /**
  172. * Checks if the public non-static property exists.
  173. * @return bool|string returns 'event' if the property exists and has event like name
  174. * @internal
  175. */
  176. public static function hasProperty(string $class, string $name)
  177. {
  178. static $cache;
  179. $prop = &$cache[$class][$name];
  180. if ($prop === null) {
  181. $prop = false;
  182. try {
  183. $rp = new \ReflectionProperty($class, $name);
  184. if ($rp->isPublic() && !$rp->isStatic()) {
  185. $prop = $name >= 'onA' && $name < 'on_' ? 'event' : true;
  186. }
  187. } catch (\ReflectionException $e) {
  188. }
  189. }
  190. return $prop;
  191. }
  192. }