ObjectHelpers.php 6.7 KB

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