Skip to content

Commit

Permalink
Added integer range phpdoc support
Browse files Browse the repository at this point in the history
  • Loading branch information
clxmstaab authored and ondrejmirtes committed Jul 30, 2021
1 parent 28ac816 commit fdf3d0e
Show file tree
Hide file tree
Showing 2 changed files with 54 additions and 0 deletions.
21 changes: 21 additions & 0 deletions src/PhpDoc/TypeNodeResolver.php
Expand Up @@ -474,6 +474,27 @@ private function resolveGenericTypeNode(GenericTypeNode $typeNode, NameScope $na
}

return new ErrorType();
} elseif ($mainTypeName === 'int') {
if (count($genericTypes) === 2) { // int<min, max>, int<1, 3>

if ($genericTypes[0] instanceof ConstantIntegerType) {
$min = $genericTypes[0]->getValue();
} elseif ($typeNode->genericTypes[0] instanceof IdentifierTypeNode && $typeNode->genericTypes[0]->name === 'min') {
$min = null;
} else {
return new ErrorType();
}

if ($genericTypes[1] instanceof ConstantIntegerType) {
$max = $genericTypes[1]->getValue();
} elseif ($typeNode->genericTypes[1] instanceof IdentifierTypeNode && $typeNode->genericTypes[1]->name === 'max') {
$max = null;
} else {
return new ErrorType();
}

return IntegerRangeType::fromInterval($min, $max);
}
}

$mainType = $this->resolveIdentifierTypeNode($typeNode->type, $nameScope);
Expand Down
33 changes: 33 additions & 0 deletions tests/PHPStan/Analyser/data/integer-range-types.php
Expand Up @@ -156,3 +156,36 @@ function (int $a, int $b, int $c): void {
assertType('int', $b * $c);
assertType('int', $a * $b * $c);
};

class X {
/**
* @var int<0, 100>
*/
public $percentage;
/**
* @var int<min, 100>
*/
public $min;
/**
* @var int<0, max>
*/
public $max;

/**
* @var int<0, something>
*/
public $error1;
/**
* @var int<something, 100>
*/
public $error2;

public function supportsPhpdocIntegerRange() {
assertType('int<0, 100>', $this->percentage);
assertType('int<min, 100>', $this->min);
assertType('int<0, max>', $this->max);

assertType('*ERROR*', $this->error1);
assertType('*ERROR*', $this->error2);
}
}

0 comments on commit fdf3d0e

Please sign in to comment.