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

orisai / phpstan-nette / 43698240932

15 Nov 2026 05:30AM UTC coverage: 78.278% (-0.9%) from 79.16%
43698240932

push

github

mabar
Record the measured cost of the reflection cache bypass

21744 of 27778 relevant lines covered (78.28%)

84.06 hits per line

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

84.08
/src/Forms/Inference/FormAccessExpressionTypeResolver.php
1
<?php declare(strict_types = 1);
2

3
namespace OriPhpstan\Nette\Forms\Inference;
4

5
use Nette\Forms\Container as NetteContainer;
6
use Nette\Utils\ArrayHash;
7
use OriPhpstan\Nette\Configuration\ConfigurationGuard;
8
use OriPhpstan\Nette\Forms\Analyzer\AnalyzerStackFactory;
9
use OriPhpstan\Nette\Forms\Analyzer\FormShapeAnalyzer;
10
use OriPhpstan\Nette\Forms\Analyzer\MappedTypeDetector;
11
use OriPhpstan\Nette\Forms\Cache\FormShapeCache;
12
use OriPhpstan\Nette\Forms\Catalog\Stub\ControlAnnotationValueTypeReader;
13
use OriPhpstan\Nette\Forms\Component\ReturnShapeSupport;
14
use OriPhpstan\Nette\Forms\Shape\ComponentPath;
15
use OriPhpstan\Nette\Forms\Shape\FormShape;
16
use OriPhpstan\Nette\Forms\Type\FormControlType;
17
use OriPhpstan\Nette\Forms\Type\FormReplicatorType;
18
use OriPhpstan\Nette\Forms\Type\FormShapeProjector;
19
use OriPhpstan\Nette\Forms\Type\FormShapeType;
20
use OriPhpstan\Nette\Forms\Type\FormValuesProjector;
21
use PhpParser\Node\Expr;
22
use PhpParser\Node\Expr\ArrayDimFetch;
23
use PhpParser\Node\Expr\MethodCall;
24
use PhpParser\Node\Expr\PropertyFetch;
25
use PhpParser\Node\Expr\Variable;
26
use PhpParser\Node\Identifier;
27
use PHPStan\Analyser\Scope;
28
use PHPStan\Parser\Parser;
29
use PHPStan\Type\ErrorType;
30
use PHPStan\Type\ExpressionTypeResolverExtension;
31
use PHPStan\Type\MixedType;
32
use PHPStan\Type\ObjectType;
33
use PHPStan\Type\Type;
34
use PHPStan\Type\TypeCombinator;
35
use function count;
36
use function in_array;
37
use function is_string;
38
use function ltrim;
39
use function spl_object_id;
40

41
final class FormAccessExpressionTypeResolver implements ExpressionTypeResolverExtension
42
{
43

44
        private ConfigurationGuard $guard;
45

46
        private bool $enabled;
47

48
        private FormShapeCache $cache;
49

50
        private Parser $parser;
51

52
        private EnclosingFunctionLikeLocator $locator;
53

54
        private FormShapeAnalyzer $analyzer;
55

56
        private FormFileIndex $index;
57

58
        /** @var array<string, true> */
59
        private array $resolving = [];
60

61
        /**
62
         * @param list<string> $analysedPaths
63
         */
64
        public function __construct(
65
                ConfigurationGuard $guard,
66
                bool $enabled,
67
                Parser $parser,
68
                Parser $richParser,
69
                FormShapeCache $cache,
70
                ControlAnnotationValueTypeReader $catalogReader,
71
                array $analysedPaths = []
72
        )
73
        {
74
                // PHPStan builds type extensions with the container, before the reflection provider knows the
75
                // analysed paths (and in the stub validator's container too), so validate on first use.
76
                $this->guard = $guard;
25 ✔
77
                $this->enabled = $enabled;
25 ✔
78
                $this->cache = $cache;
25 ✔
79
                $this->parser = $parser;
25 ✔
80
                $this->locator = new EnclosingFunctionLikeLocator();
25 ✔
81
                $this->analyzer = AnalyzerStackFactory::build($catalogReader, $cache, $richParser, $analysedPaths);
25 ✔
82
                $this->index = new FormFileIndex($parser, $this->locator, new IntraProceduralFormGate());
25 ✔
83
        }
84

85
        /**
86
         * Inside an onSuccess callback the form is valid, so getValues() projects the
87
         * post-validation (filled) shape — required fields are non-null/non-empty.
88
         */
89
        private function isValidatedContext(Expr $expr, Scope $scope): bool
90
        {
91
                return EventContextLocator::enclosingEventName(
38 ✔
92
                        $this->parser->parseFile($scope->getFile()),
38 ✔
93
                        $expr,
38 ✔
94
                ) === 'onSuccess';
38 ✔
95
        }
96

97
        public function getType(Expr $expr, Scope $scope): ?Type
98
        {
99
                if (!$this->enabled) {
168 ✔
100
                        return null;
8 ✔
101
                }
102

103
                if (
104
                        $expr instanceof PropertyFetch
160 ✔
105
                        && $expr->name instanceof Identifier
160 ✔
106
                        && $expr->name->toString() === 'values'
160 ✔
107
                ) {
108
                        return $this->valuesPropertyType($expr, $scope);
2 ✔
109
                }
110

111
                // Own-file gates only, ahead of the frame every other expression of the project would open.
112
                if (!$this->index->hasAnyTrackedForm($scope->getFile())) {
160 ✔
113
                        return null;
46 ✔
114
                }
115

116
                return $this->cache->trackDependencies($scope, fn (): ?Type => $this->getTypeUntracked($expr, $scope));
116 ✔
117
        }
118

119
        private function getTypeUntracked(Expr $expr, Scope $scope): ?Type
120
        {
121
                if (!$this->enabled) {
116 ✔
122
                        return null;
×
123
                }
124

125
                if (!$this->index->hasAnyTrackedForm($scope->getFile())) {
116 ✔
126
                        return null;
×
127
                }
128

129
                $this->guard->validate();
116 ✔
130

131
                if ($expr instanceof MethodCall) {
116 ✔
132
                        return $this->methodCallType($expr, $scope);
116 ✔
133
                }
134

135
                if ($expr instanceof ArrayDimFetch) {
116 ✔
136
                        return $this->offsetType($expr, $scope);
84 ✔
137
                }
138

139
                return $expr instanceof Variable ? $this->variableType($expr, $scope) : null;
116 ✔
140
        }
141

142
        private function variableType(Variable $expr, Scope $scope): ?Type
143
        {
144
                if (!is_string($expr->name)) {
116 ✔
145
                        return null;
×
146
                }
147

148
                // phpstan-nette compatibility — load-bearing, do not change to a DynamicMethodReturnTypeExtension:
149
                // PHPStan 2.1.x UNIONS the non-null results of ALL matching DynamicMethodReturnTypeExtensions, and
150
                // phpstan-nette's FormContainerValuesDynamicReturnTypeExtension ALWAYS returns non-null
151
                // (ObjectType 'Nette\Utils\ArrayHash') for getValues(). A method-return extension here would yield a
152
                // polluted `FormShape|ArrayHash` union. ExpressionTypeResolverExtension runs first and short-circuits
153
                // on the first non-null, so returning a carrier here cleanly OVERRIDES phpstan-nette while returning
154
                // null cleanly DEFERS to it (interprocedural / non-analysable forms stay exactly as before).
155
                $guardKey = $scope->getFile() . '|' . spl_object_id($expr);
116 ✔
156
                if (isset($this->resolving[$guardKey])) {
116 ✔
157
                        return null;
100 ✔
158
                }
159

160
                $this->resolving[$guardKey] = true;
116 ✔
161
                try {
162
                        $fn = $this->index->enclosingFunctionLike($scope->getFile(), $expr);
116 ✔
163
                        if ($fn === null) {
116 ✔
164
                                return null;
16 ✔
165
                        }
166

167
                        $tracked = $this->index->trackedVariable($scope->getFile(), $fn, $expr->name);
116 ✔
168
                        if ($tracked === null) {
116 ✔
169
                                return null;
102 ✔
170
                        }
171

172
                        $shape = $this->index->formShape(
116 ✔
173
                                $scope->getFile(),
116 ✔
174
                                $fn,
116 ✔
175
                                $tracked,
116 ✔
176
                                fn (): FormShape => $this->analyzer->analyzeFormValue(
116 ✔
177
                                        $expr,
116 ✔
178
                                        $fn,
116 ✔
179
                                        $this->locator->taggedRecords($fn, $scope),
116 ✔
180
                                        $scope,
116 ✔
181
                                ),
116 ✔
182
                        );
116 ✔
183

184
                        // A shape that names no class has nothing to wrap: FormShapeType IS an ObjectType, and an
185
                        // ObjectType over a placeholder class name is a class core reports class.notFound against
186
                        // on every later member access, not a degrade. Returning null is the degrade this method
187
                        // already documents above - the variable keeps whatever its own declared type says and
188
                        // phpstan-nette answers for it, exactly as for an interprocedural or non-analysable form.
189
                        // The `\mixed` spelling is checked through the shared predicate rather than against null
190
                        // alone, because analyzeFormValue() writes that class deliberately for an entry it could
191
                        // not type, and this carrier is the one place it could have escaped as a type.
192
                        $className = $shape->getClassName();
116 ✔
193

194
                        return ReturnShapeSupport::isClassNameUnresolved($className)
116 ✔
195
                                ? null
×
196
                                : new FormShapeType($className, $shape);
116 ✔
197
                } finally {
198
                        unset($this->resolving[$guardKey]);
116 ✔
199
                }
200
        }
201

202
        // PHPStan 2.3 resolves a variable's carrier outside Scope::getType(), while the analyzer's own
203
        // getType() of that variable inside the resolution caches the uncarried type in the scope, so
204
        // a receiver read through the scope can miss the carrier.
205
        private function receiverType(Expr $var, Scope $scope): Type
206
        {
207
                return ($var instanceof Variable ? $this->variableType($var, $scope) : null) ?? $scope->getType($var);
96 ✔
208
        }
209

210
        private function offsetType(ArrayDimFetch $expr, Scope $scope): ?Type
211
        {
212
                if ($expr->dim === null) {
84 ✔
213
                        return null;
×
214
                }
215

216
                $guardKey = $scope->getFile() . '|' . spl_object_id($expr);
84 ✔
217
                if (isset($this->resolving[$guardKey])) {
84 ✔
218
                        return null;
×
219
                }
220

221
                $this->resolving[$guardKey] = true;
84 ✔
222
                try {
223
                        $baseType = $this->receiverType($expr->var, $scope);
84 ✔
224
                        if ($baseType instanceof FormReplicatorType) {
84 ✔
225
                                // Delegates to the type's own getOffsetValueType(): an integer offset is the inner
226
                                // row (identical to the old hard-coded reconstruction below), a constant string
227
                                // matching a child added straight onto the replicator holder (e.g. an "addNode"
228
                                // submit button) is THAT child's type, and anything else degrades to IComponent -
229
                                // never hard-coding the row for every offset regardless of what it actually is.
230
                                return $baseType->getOffsetValueType($scope->getType($expr->dim));
10 ✔
231
                        }
232

233
                        if (!$baseType instanceof FormShapeType) {
84 ✔
234
                                return null;
36 ✔
235
                        }
236

237
                        $strings = $scope->getType($expr->dim)->getConstantStrings();
62 ✔
238
                        if ($strings === []) {
62 ✔
239
                                return null;
6 ✔
240
                        }
241

242
                        // Nette's Container::getComponent() splits a name on IComponent::NameSeparator and descends
243
                        // recursively (vendor/nette/component-model/src/ComponentModel/Container.php:116), so
244
                        // $form['filter']['rep-addNode'] is the SAME lookup as $form['filter']['rep']['addNode'] at
245
                        // runtime. Both spellings go through the shared ComponentPath walk here; a name with no
246
                        // separator is a one-segment path, which the projector resolves with plain offset().
247
                        if (count($strings) === 1) {
58 ✔
248
                                return FormShapeProjector::offsetPath(
58 ✔
249
                                        $baseType->getFormShape(),
58 ✔
250
                                        ComponentPath::split($strings[0]->getValue()),
58 ✔
251
                                );
58 ✔
252
                        }
253

254
                        $types = [];
×
255
                        foreach ($strings as $string) {
×
256
                                $type = FormShapeProjector::offsetPath(
×
257
                                        $baseType->getFormShape(),
×
258
                                        ComponentPath::split($string->getValue()),
×
259
                                );
×
260
                                if ($type === null || $type instanceof ErrorType || $type instanceof MixedType) {
×
261
                                        return null;
×
262
                                }
263

264
                                $types[] = $type;
×
265
                        }
266

267
                        return TypeCombinator::union(...$types);
×
268
                } finally {
269
                        unset($this->resolving[$guardKey]);
84 ✔
270
                }
271
        }
272

273
        private function methodCallType(MethodCall $expr, Scope $scope): ?Type
274
        {
275
                if (!$expr->name instanceof Identifier || $expr->isFirstClassCallable()) {
116 ✔
276
                        return null;
4 ✔
277
                }
278

279
                $method = $expr->name->toString();
116 ✔
280
                if ($method === 'getValue') {
116 ✔
281
                        return $this->getValueType($expr, $scope);
10 ✔
282
                }
283

284
                if (in_array($method, ['getValues', 'getUntrustedValues', 'getUnsafeValues'], true)) {
116 ✔
285
                        return $this->getValuesType($expr, $method, $scope);
48 ✔
286
                }
287

288
                return null;
116 ✔
289
        }
290

291
        private function getValueType(MethodCall $expr, Scope $scope): ?Type
292
        {
293
                if (count($expr->getArgs()) !== 0) {
10 ✔
294
                        return null;
×
295
                }
296

297
                $guardKey = $scope->getFile() . '|' . spl_object_id($expr);
10 ✔
298
                if (isset($this->resolving[$guardKey])) {
10 ✔
299
                        return null;
×
300
                }
301

302
                $this->resolving[$guardKey] = true;
10 ✔
303
                try {
304
                        $receiver = $this->receiverType($expr->var, $scope);
10 ✔
305
                        if (!$receiver instanceof FormControlType) {
10 ✔
306
                                return null;
2 ✔
307
                        }
308

309
                        return $receiver->getFormGetValueType();
10 ✔
310
                } finally {
311
                        unset($this->resolving[$guardKey]);
10 ✔
312
                }
313
        }
314

315
        private function getValuesType(MethodCall $expr, string $method, Scope $scope): ?Type
316
        {
317
                $args = $expr->getArgs();
48 ✔
318
                if (count($args) > 1) {
48 ✔
319
                        return null;
×
320
                }
321

322
                $guardKey = $scope->getFile() . '|' . spl_object_id($expr);
48 ✔
323
                if (isset($this->resolving[$guardKey])) {
48 ✔
324
                        return null;
×
325
                }
326

327
                $this->resolving[$guardKey] = true;
48 ✔
328
                try {
329
                        $hasArg = count($args) === 1 && !$scope->getType($args[0]->value)->isNull()->yes();
48 ✔
330
                        $argType = $hasArg ? $scope->getType($args[0]->value) : null;
48 ✔
331

332
                        $base = $this->receiverType($expr->var, $scope);
48 ✔
333
                        if (!$base instanceof FormShapeType) {
48 ✔
334
                                return null;
14 ✔
335
                        }
336

337
                        $filled = $base->isValidated() || $this->isValidatedContext($expr, $scope);
38 ✔
338

339
                        if ($argType !== null) {
38 ✔
340
                                if ($argType->isClassString()->yes()) {
10 ✔
341
                                        return $this->crateType($argType, $base->getFormShape(), $filled);
4 ✔
342
                                }
343

344
                                if ($argType->isTrue()->yes() || $this->isArrayLiteral($argType)) {
8 ✔
345
                                        return FormValuesProjector::projectArray($base->getFormShape(), $filled);
8 ✔
346
                                }
347

348
                                return null;
×
349
                        }
350

351
                        // Only no-arg getValues() applies the form's own setMappedType(); the
352
                        // getUntrustedValues()/getUnsafeValues() crate ignores it (Nette defaults their
353
                        // $returnType to ArrayHash, never consulting mappedType).
354
                        if ($method === 'getValues') {
36 ✔
355
                                $mapped = $base->getFormShape()->getMappedType() ?? $this->mappedType($expr, $scope);
36 ✔
356
                                if ($mapped !== null) {
36 ✔
357
                                        return new ObjectType($mapped);
2 ✔
358
                                }
359
                        }
360

361
                        return FormValuesProjector::projectObject($base->getFormShape(), ArrayHash::class, $filled);
36 ✔
362
                } finally {
363
                        unset($this->resolving[$guardKey]);
48 ✔
364
                }
365
        }
366

367
        /**
368
         * getValues($class) named a class, and which class decides whether the form's own values shape goes
369
         * into it: a universal CRATE (ArrayHash, stdClass) is a bag Nette fills with the form's fields and
370
         * carries no members of its own, so the projection is the only thing that can type a field read on
371
         * it, while a mapped DTO declares its own properties and PHPStan types those natively.
372
         * FormValuesProjector::isUniversalCrate() is the one place that line is drawn, asked here and by
373
         * FormGetValuesDynamicReturnTypeExtension, which is the channel the same call takes when the
374
         * receiver is not a tracked local.
375
         *
376
         * This used to hand back the bare class for BOTH, so `$form->getValues(stdClass::class)` resolved to
377
         * `stdClass` with every field `mixed` inside the file that builds the form, while
378
         * `$this['form']->getValues(stdClass::class)` in the same class kept `stdClass{name: string, …}`.
379
         * The no-arg spelling never lost anything, which is why the gap survived: it is the crate ARGUMENT
380
         * that was unreachable for the projection.
381
         *
382
         * A class-string the analysis cannot resolve to exactly one class name keeps the bare answer, which
383
         * is the degrade this method already had - there is no shape to choose a crate for.
384
         */
385
        private function crateType(Type $argType, FormShape $shape, bool $filled): Type
386
        {
387
                $object = $argType->getClassStringObjectType();
4 ✔
388
                $classNames = $object->getObjectClassNames();
4 ✔
389
                if (count($classNames) !== 1) {
4 ✔
390
                        return $object;
2 ✔
391
                }
392

393
                $className = ltrim($classNames[0], '\\');
4 ✔
394

395
                return FormValuesProjector::isUniversalCrate($className)
4 ✔
396
                        ? FormValuesProjector::projectObject($shape, $className, $filled)
2 ✔
397
                        : $object;
4 ✔
398
        }
399

400
        private function isArrayLiteral(Type $type): bool
401
        {
402
                $strings = $type->getConstantStrings();
2 ✔
403

404
                return count($strings) === 1 && $strings[0]->getValue() === 'array';
2 ✔
405
        }
406

407
        private function mappedType(MethodCall $expr, Scope $scope): ?string
408
        {
409
                if (!$expr->var instanceof Variable || !is_string($expr->var->name)) {
34 ✔
410
                        return null;
×
411
                }
412

413
                $fn = $this->index->enclosingFunctionLike($scope->getFile(), $expr);
34 ✔
414
                if ($fn === null) {
34 ✔
415
                        return null;
×
416
                }
417

418
                return MappedTypeDetector::detect($fn->getStmts() ?? [], $expr->var->name);
34 ✔
419
        }
420

421
        // SmartObject reads `$form->values` through getValues(), so the property is typed as that call wherever it is
422
        // answered: by the methodCallType() above for a tracked local, by FormGetValuesDynamicReturnTypeExtension otherwise.
423
        private function valuesPropertyType(PropertyFetch $expr, Scope $scope): ?Type
424
        {
425
                $guardKey = $scope->getFile() . '|' . spl_object_id($expr);
2 ✔
426
                if (isset($this->resolving[$guardKey])) {
2 ✔
427
                        return null;
×
428
                }
429

430
                $this->resolving[$guardKey] = true;
2 ✔
431
                try {
432
                        if (!(new ObjectType(NetteContainer::class))->isSuperTypeOf($scope->getType($expr->var))->yes()) {
2 ✔
433
                                return null;
×
434
                        }
435

436
                        return $scope->getType(new MethodCall($expr->var, new Identifier('getValues'), [], $expr->getAttributes()));
2 ✔
437
                } finally {
438
                        unset($this->resolving[$guardKey]);
2 ✔
439
                }
440
        }
441

442
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE TRIAL · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc