|
| 1 | +<?php declare(strict_types = 1); |
| 2 | + |
| 3 | +namespace PHPStan\Analyser\StmtHandler; |
| 4 | + |
| 5 | +use PhpParser\Node\Expr\Variable; |
| 6 | +use PhpParser\Node\Stmt\Foreach_; |
| 7 | +use PHPStan\Analyser\ExpressionResultStorage; |
| 8 | +use PHPStan\Analyser\MutatingScope; |
| 9 | +use PHPStan\Analyser\NodeScopeResolver; |
| 10 | +use PHPStan\Analyser\NoopNodeCallback; |
| 11 | +use PHPStan\Analyser\ScopeContext; |
| 12 | +use PHPStan\Analyser\StatementContext; |
| 13 | +use PHPStan\Testing\PHPStanTestCase; |
| 14 | +use PHPStan\TrinaryLogic; |
| 15 | +use PHPStan\Type\Constant\ConstantArrayType; |
| 16 | +use PHPStan\Type\Constant\ConstantIntegerType; |
| 17 | +use PHPStan\Type\Constant\ConstantStringType; |
| 18 | +use PHPUnit\Framework\Attributes\DataProvider; |
| 19 | +use ReflectionClass; |
| 20 | + |
| 21 | +class ForeachHandlerTest extends PHPStanTestCase |
| 22 | +{ |
| 23 | + |
| 24 | + public static function dataConstantArrayConditionalHolders(): iterable |
| 25 | + { |
| 26 | + // no keys: both holder tables stay the empty array literal |
| 27 | + yield [new ConstantArrayType([], []), 0]; |
| 28 | + yield [new ConstantArrayType([new ConstantStringType('a')], [new ConstantIntegerType(1)]), 1]; |
| 29 | + } |
| 30 | + |
| 31 | + #[DataProvider('dataConstantArrayConditionalHolders')] |
| 32 | + public function testConstantArrayConditionalHoldersReachScopeOverride(ConstantArrayType $iterateeType, int $expectedHolders): void |
| 33 | + { |
| 34 | + $container = self::getContainer(); |
| 35 | + $scope = self::createScopeFactory(self::createReflectionProvider(), $container->getService('typeSpecifier')) |
| 36 | + ->create(ScopeContext::create(__FILE__)) |
| 37 | + ->assignVariable('a', $iterateeType, $iterateeType, TrinaryLogic::createYes()); |
| 38 | + // the scope factory only creates MutatingScope: rebuild the scope as |
| 39 | + // the subclass from its constructor arguments |
| 40 | + $args = []; |
| 41 | + $reflection = new ReflectionClass(MutatingScope::class); |
| 42 | + foreach ($reflection->getMethod('__construct')->getParameters() as $parameter) { |
| 43 | + $property = $reflection->getProperty($parameter->getName()); |
| 44 | + $property->setAccessible(true); |
| 45 | + $args[] = $property->getValue($scope); |
| 46 | + } |
| 47 | + $scope = new ConditionalExpressionsRecordingScope(...$args); |
| 48 | + |
| 49 | + $container->getByType(ForeachHandler::class)->processStmt( |
| 50 | + $container->getByType(NodeScopeResolver::class), |
| 51 | + new Foreach_(new Variable('a'), new Variable('v'), ['keyVar' => new Variable('k')]), |
| 52 | + $scope, |
| 53 | + new ExpressionResultStorage(), |
| 54 | + new NoopNodeCallback(), |
| 55 | + StatementContext::createDeep(), |
| 56 | + ); |
| 57 | + |
| 58 | + $this->assertSame([ |
| 59 | + ['$v', $expectedHolders], |
| 60 | + ['$a[$k]', $expectedHolders], |
| 61 | + ], $scope->added); |
| 62 | + } |
| 63 | + |
| 64 | +} |
0 commit comments