• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

nette / utils / 21637220365

03 Feb 2026 03:46PM UTC coverage: 93.228% (-0.08%) from 93.312%
21637220365

push

github

dg
added CLAUDE.md

2065 of 2215 relevant lines covered (93.23%)

0.93 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

95.33
/src/Utils/ObjectHelpers.php
1
<?php
2

3
/**
4
 * This file is part of the Nette Framework (https://nette.org)
5
 * Copyright (c) 2004 David Grudl (https://davidgrudl.com)
6
 */
7

8
declare(strict_types=1);
9

10
namespace Nette\Utils;
11

12
use Nette;
13
use Nette\MemberAccessException;
14
use function array_filter, array_merge, array_pop, array_unique, get_class_methods, get_parent_class, implode, is_a, levenshtein, method_exists, preg_match_all, preg_replace, strlen, ucfirst;
15
use const PREG_SET_ORDER, SORT_REGULAR;
16

17

18
/**
19
 * Nette\SmartObject helpers.
20
 * @internal
21
 */
22
final class ObjectHelpers
23
{
24
        use Nette\StaticClass;
25

26
        /**
27
         * @throws MemberAccessException
28
         */
29
        public static function strictGet(string $class, string $name): never
1✔
30
        {
31
                $rc = new \ReflectionClass($class);
1✔
32
                $hint = self::getSuggestion(array_merge(
1✔
33
                        array_filter($rc->getProperties(\ReflectionProperty::IS_PUBLIC), fn($p) => !$p->isStatic()),
1✔
34
                        self::parseFullDoc($rc, '~^[ \t*]*@property(?:-read)?[ \t]+(?:\S+[ \t]+)??\$(\w+)~m'),
1✔
35
                ), $name);
36
                throw new MemberAccessException("Cannot read an undeclared property $class::\$$name" . ($hint ? ", did you mean \$$hint?" : '.'));
1✔
37
        }
×
38

39

40
        /**
41
         * @throws MemberAccessException
42
         */
43
        public static function strictSet(string $class, string $name): never
1✔
44
        {
45
                $rc = new \ReflectionClass($class);
1✔
46
                $hint = self::getSuggestion(array_merge(
1✔
47
                        array_filter($rc->getProperties(\ReflectionProperty::IS_PUBLIC), fn($p) => !$p->isStatic()),
1✔
48
                        self::parseFullDoc($rc, '~^[ \t*]*@property(?:-write)?[ \t]+(?:\S+[ \t]+)??\$(\w+)~m'),
1✔
49
                ), $name);
50
                throw new MemberAccessException("Cannot write to an undeclared property $class::\$$name" . ($hint ? ", did you mean \$$hint?" : '.'));
1✔
51
        }
×
52

53

54
        /**
55
         * @throws MemberAccessException
56
         */
57
        public static function strictCall(string $class, string $method, array $additionalMethods = []): never
1✔
58
        {
59
                $trace = debug_backtrace(0, 3); // suppose this method is called from __call()
1✔
60
                $context = ($trace[1]['function'] ?? null) === '__call'
1✔
61
                        ? ($trace[2]['class'] ?? null)
1✔
62
                        : null;
1✔
63

64
                if ($context && is_a($class, $context, true) && method_exists($context, $method)) { // called parent::$method()
1✔
65
                        $class = get_parent_class($context);
1✔
66
                }
67

68
                if (method_exists($class, $method)) { // insufficient visibility
1✔
69
                        $rm = new \ReflectionMethod($class, $method);
1✔
70
                        $visibility = $rm->isPrivate()
1✔
71
                                ? 'private '
1✔
72
                                : ($rm->isProtected() ? 'protected ' : '');
1✔
73
                        throw new MemberAccessException("Call to {$visibility}method $class::$method() from " . ($context ? "scope $context." : 'global scope.'));
1✔
74

75
                } else {
76
                        $hint = self::getSuggestion(array_merge(
1✔
77
                                get_class_methods($class),
1✔
78
                                self::parseFullDoc(new \ReflectionClass($class), '~^[ \t*]*@method[ \t]+(?:static[ \t]+)?(?:\S+[ \t]+)??(\w+)\(~m'),
1✔
79
                                $additionalMethods,
1✔
80
                        ), $method);
81
                        throw new MemberAccessException("Call to undefined method $class::$method()" . ($hint ? ", did you mean $hint()?" : '.'));
1✔
82
                }
83
        }
×
84

85

86
        /**
87
         * @throws MemberAccessException
88
         */
89
        public static function strictStaticCall(string $class, string $method): never
1✔
90
        {
91
                $trace = debug_backtrace(0, 3); // suppose this method is called from __callStatic()
1✔
92
                $context = ($trace[1]['function'] ?? null) === '__callStatic'
1✔
93
                        ? ($trace[2]['class'] ?? null)
1✔
94
                        : null;
1✔
95

96
                if ($context && is_a($class, $context, true) && method_exists($context, $method)) { // called parent::$method()
1✔
97
                        $class = get_parent_class($context);
1✔
98
                }
99

100
                if (method_exists($class, $method)) { // insufficient visibility
1✔
101
                        $rm = new \ReflectionMethod($class, $method);
1✔
102
                        $visibility = $rm->isPrivate()
1✔
103
                                ? 'private '
×
104
                                : ($rm->isProtected() ? 'protected ' : '');
1✔
105
                        throw new MemberAccessException("Call to {$visibility}method $class::$method() from " . ($context ? "scope $context." : 'global scope.'));
1✔
106

107
                } else {
108
                        $hint = self::getSuggestion(
1✔
109
                                array_filter((new \ReflectionClass($class))->getMethods(\ReflectionMethod::IS_PUBLIC), fn($m) => $m->isStatic()),
1✔
110
                                $method,
111
                        );
112
                        throw new MemberAccessException("Call to undefined static method $class::$method()" . ($hint ? ", did you mean $hint()?" : '.'));
1✔
113
                }
114
        }
×
115

116

117
        /**
118
         * Returns array of magic properties defined by annotation @property.
119
         * @param  class-string  $class
120
         * @return array<string, int>  [name => bit mask]
121
         * @internal
122
         */
123
        public static function getMagicProperties(string $class): array
1✔
124
        {
125
                static $cache;
1✔
126
                $props = &$cache[$class];
1✔
127
                if ($props !== null) {
1✔
128
                        return $props;
1✔
129
                }
130

131
                $rc = new \ReflectionClass($class);
1✔
132
                preg_match_all(
1✔
133
                        '~^  [ \t*]*  @property(|-read|-write|-deprecated)  [ \t]+  [^\s$]+  [ \t]+  \$  (\w+)  ()~mx',
1✔
134
                        (string) $rc->getDocComment(),
1✔
135
                        $matches,
1✔
136
                        PREG_SET_ORDER,
1✔
137
                );
138

139
                $props = [];
1✔
140
                foreach ($matches as [, $type, $name]) {
1✔
141
                        $uname = ucfirst($name);
1✔
142
                        $write = $type !== '-read'
1✔
143
                                && $rc->hasMethod($nm = 'set' . $uname)
1✔
144
                                && ($rm = $rc->getMethod($nm))->name === $nm && !$rm->isPrivate() && !$rm->isStatic();
1✔
145
                        $read = $type !== '-write'
1✔
146
                                && ($rc->hasMethod($nm = 'get' . $uname) || $rc->hasMethod($nm = 'is' . $uname))
1✔
147
                                && ($rm = $rc->getMethod($nm))->name === $nm && !$rm->isPrivate() && !$rm->isStatic();
1✔
148

149
                        if ($read || $write) {
1✔
150
                                $props[$name] = $read << 0 | ($nm[0] === 'g') << 1 | $rm->returnsReference() << 2 | $write << 3 | ($type === '-deprecated') << 4;
1✔
151
                        }
152
                }
153

154
                foreach ($rc->getTraits() as $trait) {
1✔
155
                        $props += self::getMagicProperties($trait->name);
1✔
156
                }
157

158
                if ($parent = get_parent_class($class)) {
1✔
159
                        $props += self::getMagicProperties($parent);
1✔
160
                }
161

162
                return $props;
1✔
163
        }
164

165

166
        /**
167
         * Finds the best suggestion (for 8-bit encoding).
168
         * @param  (\ReflectionFunctionAbstract|\ReflectionParameter|\ReflectionClass|\ReflectionProperty|string)[]  $possibilities
169
         * @internal
170
         */
171
        public static function getSuggestion(array $possibilities, string $value): ?string
1✔
172
        {
173
                $norm = preg_replace($re = '#^(get|set|has|is|add)(?=[A-Z])#', '+', $value);
1✔
174
                $best = null;
1✔
175
                $min = (strlen($value) / 4 + 1) * 10 + .1;
1✔
176
                foreach (array_unique($possibilities, SORT_REGULAR) as $item) {
1✔
177
                        $item = $item instanceof \Reflector ? $item->name : $item;
1✔
178
                        if ($item !== $value && (
1✔
179
                                ($len = levenshtein($item, $value, 10, 11, 10)) < $min
1✔
180
                                || ($len = levenshtein(preg_replace($re, '*', $item), $norm, 10, 11, 10)) < $min
1✔
181
                        )) {
182
                                $min = $len;
1✔
183
                                $best = $item;
1✔
184
                        }
185
                }
186

187
                return $best;
1✔
188
        }
189

190

191
        private static function parseFullDoc(\ReflectionClass $rc, string $pattern): array
1✔
192
        {
193
                do {
194
                        $doc[] = $rc->getDocComment();
1✔
195
                        $traits = $rc->getTraits();
1✔
196
                        while ($trait = array_pop($traits)) {
1✔
197
                                $doc[] = $trait->getDocComment();
1✔
198
                                $traits += $trait->getTraits();
1✔
199
                        }
200
                } while ($rc = $rc->getParentClass());
1✔
201

202
                return preg_match_all($pattern, implode('', $doc), $m) ? $m[1] : [];
1✔
203
        }
204

205

206
        /**
207
         * Checks if the public non-static property exists.
208
         * Returns 'event' if the property exists and has event like name.
209
         * @param  class-string  $class
210
         * @internal
211
         */
212
        public static function hasProperty(string $class, string $name): bool|string
1✔
213
        {
214
                static $cache;
1✔
215
                $prop = &$cache[$class][$name];
1✔
216
                if ($prop === null) {
1✔
217
                        $prop = false;
1✔
218
                        try {
219
                                $rp = new \ReflectionProperty($class, $name);
1✔
220
                                if ($rp->isPublic() && !$rp->isStatic()) {
1✔
221
                                        $prop = $name >= 'onA' && $name < 'on_' ? 'event' : true;
1✔
222
                                }
223
                        } catch (\ReflectionException) {
1✔
224
                        }
225
                }
226

227
                return $prop;
1✔
228
        }
229
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc