Skip to content

Commit

Permalink
more precise $argc, $argv global var type
Browse files Browse the repository at this point in the history
  • Loading branch information
staabm authored and clxmstaab committed Sep 20, 2022
1 parent d61b9f9 commit ba9d2f6
Show file tree
Hide file tree
Showing 3 changed files with 47 additions and 0 deletions.
13 changes: 13 additions & 0 deletions src/Analyser/MutatingScope.php
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,7 @@
use PHPStan\Type\Accessory\AccessoryNonEmptyStringType;
use PHPStan\Type\Accessory\AccessoryNonFalsyStringType;
use PHPStan\Type\Accessory\HasOffsetValueType;
use PHPStan\Type\Accessory\NonEmptyArrayType;
use PHPStan\Type\ArrayType;
use PHPStan\Type\BooleanType;
use PHPStan\Type\ClosureType;
Expand Down Expand Up @@ -500,6 +501,18 @@ public function hasVariableType(string $variableName): TrinaryLogic
/** @api */
public function getVariableType(string $variableName): Type
{
if ($this->hasVariableType($variableName)->maybe()) {
if ($variableName === 'argc') {
return IntegerRangeType::fromInterval(1, null);
}
if ($variableName === 'argv') {
return TypeCombinator::intersect(
new ArrayType(new IntegerType(), new StringType()),
new NonEmptyArrayType(),
);
}
}

if ($this->isGlobalVariable($variableName)) {
return new ArrayType(new StringType(), new MixedType($this->explicitMixedForGlobalVariables));
}
Expand Down
1 change: 1 addition & 0 deletions tests/PHPStan/Analyser/NodeScopeResolverTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -1035,6 +1035,7 @@ public function dataFileAsserts(): iterable
yield from $this->gatherAssertTypes(__DIR__ . '/../Rules/Arrays/data/bug-7954.php');
yield from $this->gatherAssertTypes(__DIR__ . '/data/bug-7993.php');
yield from $this->gatherAssertTypes(__DIR__ . '/data/bug-7141.php');
yield from $this->gatherAssertTypes(__DIR__ . '/data/cli-globals.php');
}

/**
Expand Down
33 changes: 33 additions & 0 deletions tests/PHPStan/Analyser/data/cli-globals.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
<?php

namespace CliGlobals;

use function PHPStan\Testing\assertType;

assertType('int<1, max>', $argc);
assertType('non-empty-array<int, string>', $argv);

function f() {
assertType('*ERROR*', $argc);
assertType('*ERROR*', $argv);
}

function g($argc, $argv) {
assertType('mixed', $argc);
assertType('mixed', $argv);
}

function h() {
global $argc, $argv;
assertType('mixed', $argc); // should be int<1, max>
assertType('mixed', $argv); // should be non-empty-array<int, string>
}

function i() {
// user created local variable
$argc = 'hallo';
$argv = 'welt';

assertType("'hallo'", $argc);
assertType("'welt'", $argv);
}

0 comments on commit ba9d2f6

Please sign in to comment.