Skip to content

Commit

Permalink
Added dynamic return type extension to shut up getopt()
Browse files Browse the repository at this point in the history
  • Loading branch information
dktapps authored and ondrejmirtes committed May 12, 2021
1 parent 4359489 commit 36ba22e
Show file tree
Hide file tree
Showing 4 changed files with 46 additions and 0 deletions.
5 changes: 5 additions & 0 deletions conf/config.neon
Original file line number Diff line number Diff line change
Expand Up @@ -1060,6 +1060,11 @@ services:
tags:
- phpstan.broker.dynamicFunctionReturnTypeExtension

-
class: PHPStan\Type\Php\GetoptFunctionDynamicReturnTypeExtension
tags:
- phpstan.broker.dynamicFunctionReturnTypeExtension

-
class: PHPStan\Type\Php\GetParentClassDynamicFunctionReturnTypeExtension
tags:
Expand Down
31 changes: 31 additions & 0 deletions src/Type/Php/GetoptFunctionDynamicReturnTypeExtension.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
<?php declare(strict_types = 1);

namespace PHPStan\Type\Php;

use PhpParser\Node\Expr\FuncCall;
use PHPStan\Analyser\Scope;
use PHPStan\Reflection\FunctionReflection;
use PHPStan\Reflection\ParametersAcceptorSelector;
use PHPStan\Type\Constant\ConstantBooleanType;
use PHPStan\Type\DynamicFunctionReturnTypeExtension;
use PHPStan\Type\Type;
use PHPStan\Type\TypeCombinator;
use PHPStan\Type\TypeUtils;

class GetoptFunctionDynamicReturnTypeExtension implements DynamicFunctionReturnTypeExtension
{

public function isFunctionSupported(FunctionReflection $functionReflection): bool
{
return $functionReflection->getName() === 'getopt';
}

public function getTypeFromFunctionCall(FunctionReflection $functionReflection, FuncCall $functionCall, Scope $scope): Type
{
return TypeUtils::toBenevolentUnion(TypeCombinator::union(
ParametersAcceptorSelector::selectSingle($functionReflection->getVariants())->getReturnType(),
new ConstantBooleanType(false)
));
}

}
1 change: 1 addition & 0 deletions tests/PHPStan/Analyser/NodeScopeResolverTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -402,6 +402,7 @@ public function dataFileAsserts(): iterable
yield from $this->gatherAssertTypes(__DIR__ . '/data/bug-2640.php');
yield from $this->gatherAssertTypes(__DIR__ . '/data/bug-2413.php');
yield from $this->gatherAssertTypes(__DIR__ . '/data/bug-3446.php');
yield from $this->gatherAssertTypes(__DIR__ . '/data/getopt.php');
}

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

namespace Getopt;

use function getopt;
use function PHPStan\Testing\assertType;

$opts = getopt("ab:c::", ["longopt1", "longopt2:", "longopt3::"]);
assertType('(array<string, array<int, mixed>|string|false>|false)', $opts);

0 comments on commit 36ba22e

Please sign in to comment.