Repository navigation
Expand file tree
/
Copy pathArrayHandler.php
More file actions
640 lines (577 loc) · 24.1 KB
/
Copy pathArrayHandler.php
File metadata and controls
640 lines (577 loc) · 24.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
<?php declare(strict_types = 1);
namespace PHPStan\Analyser\ExprHandler;
use Closure as PhpClosure;
use PhpParser\Node;
use PhpParser\Node\Arg;
use PhpParser\Node\ArrayItem;
use PhpParser\Node\Expr;
use PhpParser\Node\Expr\Array_;
use PhpParser\Node\Expr\ArrowFunction;
use PhpParser\Node\Expr\Closure;
use PhpParser\Node\Expr\FuncCall;
use PhpParser\Node\Name\FullyQualified;
use PhpParser\Node\Scalar;
use PhpParser\Node\Stmt;
use PHPStan\Analyser\ExpressionContext;
use PHPStan\Analyser\ExpressionResult;
use PHPStan\Analyser\ExpressionResultFactory;
use PHPStan\Analyser\ExpressionResultStorage;
use PHPStan\Analyser\ExprHandler;
use PHPStan\Analyser\ExprHandler\Helper\ClosureTypeResolver;
use PHPStan\Analyser\ExprHandler\Helper\IllegalOffsetTypeHelper;
use PHPStan\Analyser\Generics\ClosureSignatureInference;
use PHPStan\Analyser\InternalThrowPoint;
use PHPStan\Analyser\MutatingScope;
use PHPStan\Analyser\NodeScopeResolver;
use PHPStan\Analyser\Scope;
use PHPStan\Analyser\SpecifiedTypes;
use PHPStan\Analyser\VariableFlow;
use PHPStan\Analyser\VariableFlowBuilder;
use PHPStan\Analyser\VariableWriteOffset;
use PHPStan\Dependency\Dependencies;
use PHPStan\DependencyInjection\AutowiredService;
use PHPStan\Node\LiteralArrayItem;
use PHPStan\Node\LiteralArrayNode;
use PHPStan\Node\Variable\VariableWrite;
use PHPStan\Php\PhpVersion;
use PHPStan\Reflection\InitializerExprTypeResolver;
use PHPStan\ShouldNotHappenException;
use PHPStan\Turbo\ShadowedByTurboExtension;
use PHPStan\Type\ArrayType;
use PHPStan\Type\CallableType;
use PHPStan\Type\Constant\ConstantIntegerType;
use PHPStan\Type\IntegerType;
use PHPStan\Type\MixedType;
use PHPStan\Type\ObjectType;
use PHPStan\Type\Type;
use PHPStan\Type\TypeCombinator;
use TypeError;
use function array_key_exists;
use function array_map;
use function array_merge;
use function array_values;
use function count;
use function in_array;
use function is_int;
use function is_string;
use function max;
use function spl_object_id;
use const PHP_INT_MAX;
/**
* @implements ExprHandler<Array_>
* @phpstan-type ArrayItemWalk array{arrayItem: ArrayItem, entryScope: MutatingScope, valueScope: MutatingScope, keyResult: ExpressionResult|null, valueResult: ExpressionResult|null, nested: mixed, itemWrite: VariableWrite|null}
* @phpstan-type ArrayWalk array{expr: Array_, beforeScope: MutatingScope, scope: MutatingScope, context: ExpressionContext, items: list<ArrayItemWalk>, literalWrite: VariableWrite|null}
*/
#[AutowiredService]
#[ShadowedByTurboExtension(implementation: __DIR__ . '/../../../turbo-ext/src/ArrayHandler.cpp')]
final class ArrayHandler implements ExprHandler
{
public function __construct(
private InitializerExprTypeResolver $initializerExprTypeResolver,
private ExpressionResultFactory $expressionResultFactory,
private ClosureTypeResolver $closureTypeResolver,
private PhpVersion $phpVersion,
)
{
}
public function supports(Expr $expr): bool
{
return $expr instanceof Array_;
}
public function processExpr(NodeScopeResolver $nodeScopeResolver, Stmt $stmt, Expr $expr, MutatingScope $scope, ExpressionResultStorage $storage, callable $nodeCallback, ExpressionContext $context): ExpressionResult
{
$passedToTypeResolver = $context->getPassedToTypeResolver();
if ($passedToTypeResolver === null || !self::hasClosureItems($expr)) {
return $this->createResult($nodeScopeResolver, $this->walkItems($nodeScopeResolver, $stmt, $expr, $scope, $storage, $nodeCallback, $context, $context->getPassedToType(), $context->getNativePassedToType(), null), $storage, $nodeCallback);
}
// the closures in the literal are typed from the parameter the call
// resolves for the literal - priced from the other items, walked first,
// and the closures' declared signatures
$resolve = fn (array $walk): array => $passedToTypeResolver($this->getWalkedArrayType($nodeScopeResolver, $walk));
$walk = $this->walkItems($nodeScopeResolver, $stmt, $expr, $scope, $storage, $nodeCallback, $context, null, null, $resolve);
[$passedToType, $nativePassedToType] = $resolve($walk);
return $this->createResult($nodeScopeResolver, $this->completeWalk($nodeScopeResolver, $stmt, $walk, $storage, $nodeCallback, $passedToType, $nativePassedToType), $storage, $nodeCallback);
}
/**
* Walks the items in evaluation order. With $resolve, a closure / arrow
* function item and the closures of a nested literal are left for
* completeWalk(): the expected type they are walked with depends on the
* types of the items walked here. Creating a closure changes nothing in the
* scope but its template argument constraints - except a by-reference use,
* which binds the variable where the closure is created: such a closure is
* walked in place, with the expected type $resolve prices from the items
* walked before it.
*
* @param callable(Node $node, Scope $scope): void $nodeCallback
* @param (PhpClosure(ArrayWalk): array{?Type, ?Type})|null $resolve
* @return ArrayWalk
*/
private function walkItems(NodeScopeResolver $nodeScopeResolver, Stmt $stmt, Array_ $expr, MutatingScope $scope, ExpressionResultStorage $storage, callable $nodeCallback, ExpressionContext $context, ?Type $passedToType, ?Type $nativePassedToType, ?PhpClosure $resolve): array
{
$walk = [
'expr' => $expr,
'beforeScope' => $scope,
'scope' => $scope,
'context' => $context,
'items' => [],
'literalWrite' => null,
];
$literalWrite = $context->isValueFlowDirect() ? $context->getValueFlowTarget() : null;
if ($literalWrite !== null && !$literalWrite->isOffsetWrite()) {
$walk['literalWrite'] = $literalWrite;
}
$passedToType = $this->getExpectedArrayType($passedToType);
$nativePassedToType = $this->getExpectedArrayType($nativePassedToType);
$tracksKeys = $walk['literalWrite'] !== null || $passedToType !== null || $nativePassedToType !== null || $resolve !== null;
$nextIndex = 0;
foreach ($expr->items as $arrayItem) {
$item = [
'arrayItem' => $arrayItem,
'entryScope' => $scope,
'keyResult' => null,
'valueResult' => null,
'nested' => null,
'itemWrite' => null,
];
$keyFirst = self::isKeyWalkedFirst($arrayItem);
if ($arrayItem->key !== null && $keyFirst) {
$item['keyResult'] = $nodeScopeResolver->processExprNode($stmt, $arrayItem->key, $scope, $storage, $nodeCallback, $context->enterDeepKeepingValueFlow());
$scope = $item['keyResult']->getScope();
}
$item['valueScope'] = $scope;
$keyType = null;
if ($tracksKeys) {
[$keyType, $offset] = $this->getKeyTypeAndOffset($nodeScopeResolver, $arrayItem, $item['keyResult'], $scope, $nextIndex);
if ($walk['literalWrite'] !== null) {
$item['itemWrite'] = new VariableWrite($walk['literalWrite']->getVariableName(), $arrayItem, spl_object_id($arrayItem), VariableWrite::KIND_ARRAY_LITERAL_ITEM, true, $offset, $walk['literalWrite']->getId());
}
}
$deferred = false;
$itemPassedToType = $passedToType;
$itemNativePassedToType = $nativePassedToType;
if ($resolve !== null && !$arrayItem->unpack) {
if ($arrayItem->value instanceof Array_ && self::hasClosureItems($arrayItem->value)) {
$item['nested'] = $this->walkItems(
$nodeScopeResolver,
$stmt,
$arrayItem->value,
$scope,
$storage,
$nodeCallback,
$this->getValueContext($context, $item, null, null, null),
null,
null,
function (array $nestedWalk) use ($resolve, $walk, $item, $keyType): array {
$item['nested'] = $nestedWalk;
$walk['items'][] = $item;
[$passedToType, $nativePassedToType] = $resolve($walk);
$keyType = $keyType->toArrayKey();
return [
$this->getExpectedValueType($this->getExpectedArrayType($passedToType), $keyType),
$this->getExpectedValueType($this->getExpectedArrayType($nativePassedToType), $keyType),
];
},
);
$scope = $item['nested']['scope'];
$deferred = true;
} elseif ($arrayItem->value instanceof ArrowFunction || ($arrayItem->value instanceof Closure && !self::hasByRefUse($arrayItem->value))) {
$deferred = true;
} elseif ($arrayItem->value instanceof Closure) {
$walkSoFar = $walk;
$walkSoFar['items'][] = $item;
[$itemPassedToType, $itemNativePassedToType] = $resolve($walkSoFar);
$itemPassedToType = $this->getExpectedArrayType($itemPassedToType);
$itemNativePassedToType = $this->getExpectedArrayType($itemNativePassedToType);
}
}
if (!$deferred) {
$item['valueResult'] = $nodeScopeResolver->processExprNode($stmt, $arrayItem->value, $scope, $storage, $nodeCallback, $this->getValueContext($context, $item, $itemPassedToType, $itemNativePassedToType, $keyType));
$scope = $item['valueResult']->getScope();
}
if ($arrayItem->key !== null && !$keyFirst) {
$item['keyResult'] = $nodeScopeResolver->processExprNode($stmt, $arrayItem->key, $scope, $storage, $nodeCallback, $context->enterDeepKeepingValueFlow());
$scope = $item['keyResult']->getScope();
}
if (!$deferred) {
// the item's callback fires after its key and value were processed,
// with the item's entry scope - callback-side asks answer from the
// storage instead of re-walking the yet-unstored sub-expressions
$nodeScopeResolver->callNodeCallback($nodeCallback, $arrayItem, $item['entryScope'], $storage);
}
$walk['items'][] = $item;
$walk['scope'] = $scope;
}
return $walk;
}
/**
* Walks the closures walkItems() deferred, each on the scope at its own
* position, with the expected types resolved from the walked items; their
* template argument constraints are carried over to the literal's scope.
*
* @param ArrayWalk $walk
* @param callable(Node $node, Scope $scope): void $nodeCallback
* @return ArrayWalk
*/
private function completeWalk(NodeScopeResolver $nodeScopeResolver, Stmt $stmt, array $walk, ExpressionResultStorage $storage, callable $nodeCallback, ?Type $passedToType, ?Type $nativePassedToType): array
{
$passedToType = $this->getExpectedArrayType($passedToType);
$nativePassedToType = $this->getExpectedArrayType($nativePassedToType);
$context = $walk['context'];
$nextIndex = 0;
foreach ($walk['items'] as $i => $item) {
$arrayItem = $item['arrayItem'];
[$keyType] = $this->getKeyTypeAndOffset($nodeScopeResolver, $arrayItem, $item['keyResult'], $item['valueScope'], $nextIndex);
if ($item['valueResult'] !== null) {
continue;
}
$valueContext = $this->getValueContext($context, $item, $passedToType, $nativePassedToType, $keyType);
if ($item['nested'] !== null) {
$item['valueResult'] = $this->createResult(
$nodeScopeResolver,
$this->completeWalk($nodeScopeResolver, $stmt, $item['nested'], $storage, $nodeCallback, $valueContext->getPassedToType(), $valueContext->getNativePassedToType()),
$storage,
$nodeCallback,
);
// the nested literal is walked here instead of by processExprNode() -
// store its result and fire its callback the same way
$nodeScopeResolver->storeExpressionResult($storage, $arrayItem->value, $item['valueResult']);
$nodeScopeResolver->callNodeCallbackWithExpression($nodeCallback, $arrayItem->value, $item['valueScope'], $storage, $valueContext);
} else {
$item['valueResult'] = $nodeScopeResolver->processExprNode($stmt, $arrayItem->value, $item['valueScope'], $storage, $nodeCallback, $valueContext);
}
$walk['scope'] = $walk['scope']->addTemplateArgumentConstraints($item['valueResult']->getScope()->getTemplateArgumentConstraints());
$nodeScopeResolver->callNodeCallback($nodeCallback, $arrayItem, $item['entryScope'], $storage);
$walk['items'][$i] = $item;
}
return $walk;
}
/**
* The literal's type from the items walked so far. A deferred closure
* contributes its declared signature; an item not reached yet - when a
* closure with a by-reference use is resolved early - what does not depend
* on its position: a literal, a closure's declared signature, mixed for
* anything else.
*
* @param ArrayWalk $walk
*/
private function getWalkedArrayType(NodeScopeResolver $nodeScopeResolver, array $walk): Type
{
$types = [];
foreach ($walk['items'] as $item) {
$arrayItem = $item['arrayItem'];
if ($arrayItem->key !== null) {
// a plain variable key is walked after its value - read it from the scope meanwhile
$types[spl_object_id($arrayItem->key)] = $item['keyResult'] !== null
? $item['keyResult']->getType()
: ($nodeScopeResolver->findScopeStateType($arrayItem->key, $item['valueScope']) ?? new MixedType());
}
if ($item['valueResult'] !== null) {
$types[spl_object_id($arrayItem->value)] = $item['valueResult']->getType();
} elseif ($item['nested'] !== null) {
$types[spl_object_id($arrayItem->value)] = $this->getWalkedArrayType($nodeScopeResolver, $item['nested']);
}
}
$scope = $walk['scope'];
$getType = function (Expr $inner) use (&$getType, $types, $nodeScopeResolver, $scope): Type {
$id = spl_object_id($inner);
if (array_key_exists($id, $types)) {
return $types[$id];
}
if ($inner instanceof Closure || $inner instanceof ArrowFunction) {
return $this->closureTypeResolver->getDeclaredClosureType($scope, $inner);
}
if ($inner instanceof Array_) {
return $this->initializerExprTypeResolver->getArrayType($inner, $getType);
}
if ($inner instanceof Scalar\String_ || $inner instanceof Scalar\Int_ || $inner instanceof Scalar\Float_) {
return $nodeScopeResolver->findScopeStateType($inner, $scope) ?? new MixedType();
}
return new MixedType();
};
return $this->initializerExprTypeResolver->getArrayType($walk['expr'], $getType);
}
/**
* @param ArrayWalk $walk
* @param callable(Node $node, Scope $scope): void $nodeCallback
*/
private function createResult(NodeScopeResolver $nodeScopeResolver, array $walk, ExpressionResultStorage $storage, callable $nodeCallback): ExpressionResult
{
$expr = $walk['expr'];
$beforeScope = $walk['beforeScope'];
$scope = $walk['scope'];
$itemNodes = [];
$itemResults = [];
$variableFlows = [];
$hasYield = false;
$throwPoints = [];
$impurePoints = [];
$isAlwaysTerminating = false;
foreach ($walk['items'] as $item) {
$arrayItem = $item['arrayItem'];
$keyResult = $item['keyResult'];
$valueResult = $item['valueResult'];
if ($valueResult === null) {
throw new ShouldNotHappenException();
}
$itemNodes[] = new LiteralArrayItem($item['entryScope'], $arrayItem);
$keyFirst = self::isKeyWalkedFirst($arrayItem);
$walkedResults = [];
if ($arrayItem->key !== null && $keyResult !== null) {
$itemResults[spl_object_id($arrayItem->key)] = $keyResult;
if ($keyFirst) {
$walkedResults[] = $keyResult;
}
}
$itemResults[spl_object_id($arrayItem->value)] = $valueResult;
$walkedResults[] = $valueResult;
if ($keyResult !== null && !$keyFirst) {
$walkedResults[] = $keyResult;
}
foreach ($walkedResults as $walkedResult) {
if ($walkedResult === $valueResult && $item['itemWrite'] !== null) {
$variableFlows[] = VariableFlow::write($item['itemWrite']);
}
$variableFlows[] = $walkedResult->getVariableFlow();
$hasYield = $hasYield || $walkedResult->hasYield();
$throwPoints = array_merge($throwPoints, $walkedResult->getThrowPoints());
$impurePoints = array_merge($impurePoints, $walkedResult->getImpurePoints());
$isAlwaysTerminating = $isAlwaysTerminating || $walkedResult->isAlwaysTerminating();
}
if (
$arrayItem->key !== null
&& $keyResult !== null
&& $this->phpVersion->throwsTypeErrorForIllegalOffsets()
&& IllegalOffsetTypeHelper::mayOffsetThrowTypeError($keyResult->getType())
) {
// an array or an object key throws TypeError once the key and the value were evaluated
$throwPoints[] = InternalThrowPoint::createExplicit($walkedResults[count($walkedResults) - 1]->getScope(), new ObjectType(TypeError::class), $arrayItem->key, false);
$variableFlows[] = VariableFlow::throwing(new ObjectType(TypeError::class), true);
}
if (!$arrayItem->byRef) {
continue;
}
$variableFlows[] = VariableFlowBuilder::escapeRoot($arrayItem->value);
}
$nodeScopeResolver->callNodeCallback($nodeCallback, new LiteralArrayNode($expr, $itemNodes), $scope, $storage);
if ($nodeScopeResolver->observingTemplateArgumentFrame($scope) !== null) {
$scope = $this->collectAbsorbedItems($expr, $itemResults, $scope);
}
$result = $this->expressionResultFactory->create(
$scope,
beforeScope: $beforeScope,
expr: $expr,
variableFlow: VariableFlow::sequence(...$variableFlows),
hasYield: $hasYield,
isAlwaysTerminating: $isAlwaysTerminating,
throwPoints: $throwPoints,
impurePoints: $impurePoints,
typeCallback: function (bool $nativeTypesPromoted) use ($expr, $itemResults, $beforeScope): Type {
// each item type was captured at its own evaluation point in the
// sequence - resolving all items on any single scope (the old world)
// cannot handle items with side effects like [$b = 1, $b + 1, $b++]
$type = $this->initializerExprTypeResolver->getArrayType($expr, static function (Expr $inner) use ($itemResults, $nativeTypesPromoted): Type {
$id = spl_object_id($inner);
if (array_key_exists($id, $itemResults)) {
return $nativeTypesPromoted
? $itemResults[$id]->getNativeType()
: $itemResults[$id]->getType();
}
throw new ShouldNotHappenException();
});
if (
count($expr->items) === 2
&& isset($expr->items[0], $expr->items[1])
) {
$isCallableCall = new FuncCall(
new FullyQualified('is_callable'),
[new Arg($expr)],
);
// isCallable() is asked last - it reflects the class named by the
// first item, which is expensive and unnecessary for arrays never
// narrowed by is_callable()
if (
$beforeScope->hasExpressionType($isCallableCall)->yes()
// read the narrowed type from expressionTypes directly (the
// synthetic is_callable() call was never processed as a child),
// mirroring ConstFetchHandler's narrowed-constant lookup
&& $beforeScope->expressionTypes[$beforeScope->getNodeKey($isCallableCall)]->getType()->isTrue()->yes()
&& $type->isCallable()->maybe()
) {
$type = TypeCombinator::intersect($type, new CallableType());
}
}
return $type;
},
specifyTypesCallback: SpecifiedTypes::emptySpecifyCallback(),
);
return $result->withDependencies(Dependencies::merge(
$this->getCallableDependencies($beforeScope, $expr, $itemResults, $result),
...array_map(static fn (ExpressionResult $itemResult): ?Dependencies => $itemResult->getDependencies(), array_values($itemResults)),
));
}
/**
* @param ArrayItemWalk $item
*/
private function getValueContext(ExpressionContext $context, array $item, ?Type $passedToType, ?Type $nativePassedToType, ?Type $keyType): ExpressionContext
{
$arrayItem = $item['arrayItem'];
$valueContext = $item['itemWrite'] !== null
? $context->enterDeep()->enterValueFlow($item['itemWrite'], false)
: $context->enterDeepKeepingValueFlow();
if (
$keyType !== null
&& ($passedToType !== null || $nativePassedToType !== null)
&& !$arrayItem->unpack
&& ($arrayItem->value instanceof Array_ || $arrayItem->value instanceof Closure || $arrayItem->value instanceof ArrowFunction)
) {
$keyType = $keyType->toArrayKey();
$valueContext = $valueContext->enterPassedToType(
$this->getExpectedValueType($passedToType, $keyType),
$this->getExpectedValueType($nativePassedToType, $keyType),
);
}
return $valueContext;
}
/**
* The type of the item's key and the offset its value is written to,
* advancing the next implicit index - unknown past PHP_INT_MAX, where PHP
* cannot append. A plain variable key not walked yet is read from the scope.
*
* @return array{Type, int|string|null}
*/
private function getKeyTypeAndOffset(NodeScopeResolver $nodeScopeResolver, ArrayItem $arrayItem, ?ExpressionResult $keyResult, MutatingScope $scope, ?int &$nextIndex): array
{
if ($arrayItem->unpack) {
$nextIndex = null;
return [new IntegerType(), null];
}
if ($arrayItem->key === null) {
$keyType = $nextIndex !== null ? new ConstantIntegerType($nextIndex) : new IntegerType();
$offset = $nextIndex;
if ($nextIndex !== null) {
$nextIndex = $nextIndex === PHP_INT_MAX ? null : $nextIndex + 1;
}
return [$keyType, $offset];
}
$writtenKeyType = $keyResult !== null
? $keyResult->getType()
: ($nodeScopeResolver->findScopeStateType($arrayItem->key, $scope) ?? new MixedType());
$offset = VariableWriteOffset::fromType($writtenKeyType);
if ($offset === null) {
$nextIndex = null;
} elseif (is_int($offset) && $nextIndex !== null) {
$nextIndex = $offset === PHP_INT_MAX ? null : max($nextIndex, $offset + 1);
}
return [$writtenKeyType, $offset];
}
/** A plain variable key is read when PHP adds the item - after its value is evaluated. */
private static function isKeyWalkedFirst(ArrayItem $arrayItem): bool
{
$key = $arrayItem->key;
if ($key === null) {
return false;
}
return !$key instanceof Expr\Variable
|| !is_string($key->name)
|| $key->name === 'this'
|| in_array($key->name, Scope::SUPERGLOBAL_VARIABLES, true);
}
private static function hasClosureItems(Array_ $expr): bool
{
foreach ($expr->items as $arrayItem) {
if ($arrayItem->unpack) {
continue;
}
if (
$arrayItem->value instanceof Closure
|| $arrayItem->value instanceof ArrowFunction
|| ($arrayItem->value instanceof Array_ && self::hasClosureItems($arrayItem->value))
) {
return true;
}
}
return false;
}
private static function hasByRefUse(Closure $closure): bool
{
foreach ($closure->uses as $use) {
if ($use->byRef) {
return true;
}
}
return false;
}
/**
* An array that may be a callable - `[Foo::class, 'method']` - depends on what calling it returns.
*
* @param array<int, ExpressionResult> $itemResults
*/
private function getCallableDependencies(MutatingScope $scope, Array_ $expr, array $itemResults, ExpressionResult $result): ?Dependencies
{
if (count($expr->items) !== 2 || !isset($expr->items[0])) {
return null;
}
// a class constant, property default or enum case value is not called where it is
// declared - testing it would reflect whatever class its first item happens to name
if (
$scope->isInClass()
&& $scope->getFunction() === null
&& !$scope->isInAnonymousFunction()
&& $scope->getFunctionCallStack() === []
) {
return null;
}
$firstItemResult = $itemResults[spl_object_id($expr->items[0]->value)] ?? null;
if ($firstItemResult === null || !$firstItemResult->getType()->isClassString()->yes()) {
return null;
}
$arrayType = $result->getType();
if ($arrayType->isCallable()->no()) {
return null;
}
$returnTypes = [];
foreach ($arrayType->getCallableParametersAcceptors($scope) as $variant) {
$returnTypes[] = $variant->getReturnType();
}
return Dependencies::create($scope->getFile(), $returnTypes);
}
/**
* A literal generalized by an unpacked item absorbs the closures of its items
* into a wider value type - see ClosureSignatureInference::collectAbsorbed().
*
* @param array<int, ExpressionResult> $itemResults
*/
private function collectAbsorbedItems(Array_ $expr, array $itemResults, MutatingScope $scope): MutatingScope
{
$itemTypes = [];
foreach ($expr->items as $arrayItem) {
$itemType = $itemResults[spl_object_id($arrayItem->value)]->getType();
if (!ClosureSignatureInference::hasMarkers($itemType)) {
continue;
}
$itemTypes[] = $itemType;
}
if ($itemTypes === []) {
return $scope;
}
$arrayType = $this->initializerExprTypeResolver->getArrayType($expr, static fn (Expr $inner): Type => $itemResults[spl_object_id($inner)]->getType());
return $scope->addTemplateArgumentConstraints(ClosureSignatureInference::collectAbsorbedInto($itemTypes, $arrayType));
}
private function getExpectedArrayType(?Type $type): ?Type
{
if ($type === null || $type->isIterable()->no()) {
return null;
}
if ($type->isArray()->yes()) {
return $type;
}
return TypeCombinator::intersect($type, new ArrayType(new MixedType(), new MixedType()));
}
private function getExpectedValueType(?Type $arrayType, Type $keyType): ?Type
{
if ($arrayType === null || $arrayType->hasOffsetValueType($keyType)->no()) {
return null;
}
return $arrayType->getOffsetValueType($keyType);
}
}