*/ final class UnsafeForeachRule implements Rule{ public function getNodeType() : string{ return Foreach_::class; } public function processNode(Node $node, Scope $scope) : array{ /** @var Foreach_ $node */ if($node->keyVar === null){ return []; } $iterableType = $scope->getType($node->expr); if($iterableType->isArray()->no()){ return []; } if($iterableType->isIterableAtLeastOnce()->no()){ return []; } $hasCastableKeyTypes = false; $expectsIntKeyTypes = false; $implicitType = false; $benevolentUnionDepth = 0; TypeTraverser::map($iterableType->getIterableKeyType(), function(Type $type, callable $traverse) use (&$hasCastableKeyTypes, &$expectsIntKeyTypes, &$benevolentUnionDepth, &$implicitType) : Type{ if($type instanceof BenevolentUnionType){ $implicitType = true; $benevolentUnionDepth++; $result = $traverse($type); $benevolentUnionDepth--; return $result; } if($type instanceof IntegerType){ $expectsIntKeyTypes = true; return $type; } if(!$type instanceof StringType){ return $traverse($type); } if($type->isNumericString()->no() || $type instanceof ClassStringType){ //class-string cannot be numeric, even if PHPStan thinks they can be return $type; } $hasCastableKeyTypes = true; return $type; }); $errors = []; if($implicitType){ $errors[] = RuleErrorBuilder::message("Possible unreported errors in foreach on array with unspecified key type.") ->tip(sprintf( <<identifier('pocketmine.foreach.implicitKeys')->build(); } if($hasCastableKeyTypes && !$expectsIntKeyTypes){ $errors[] = RuleErrorBuilder::message(sprintf( "Unsafe foreach on array with key type %s.", $iterableType->getIterableKeyType()->describe(VerbosityLevel::value()) )) ->tip(sprintf( <<identifier('pocketmine.foreach.stringKeys')->build(); } return $errors; } }