1
0
mirror of https://github.com/danog/psalm.git synced 2025-01-21 21:31:13 +01:00

add stubs for min/max (#5353)

This commit is contained in:
orklah 2021-03-11 06:13:17 +01:00 committed by GitHub
parent 9793f92ba1
commit 0a4ad5733b
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 88 additions and 0 deletions

View File

@ -68,6 +68,7 @@ class FunctionReturnTypeProvider
$this->registerClass(ReturnTypeProvider\GetClassMethodsReturnTypeProvider::class);
$this->registerClass(ReturnTypeProvider\FirstArgStringReturnTypeProvider::class);
$this->registerClass(ReturnTypeProvider\HexdecReturnTypeProvider::class);
$this->registerClass(ReturnTypeProvider\MinMaxReturnTypeProvider::class);
}
/**

View File

@ -0,0 +1,57 @@
<?php declare(strict_types=1);
namespace Psalm\Internal\Provider\ReturnTypeProvider;
use Psalm\Plugin\EventHandler\Event\FunctionReturnTypeProviderEvent;
use Psalm\Plugin\EventHandler\FunctionReturnTypeProviderInterface;
use function count;
use Psalm\Internal\Type\ArrayType;
use Psalm\Type;
class MinMaxReturnTypeProvider implements FunctionReturnTypeProviderInterface
{
/**
* @return array<lowercase-string>
*/
public static function getFunctionIds(): array
{
return ['min', 'max'];
}
public static function getFunctionReturnType(FunctionReturnTypeProviderEvent $event): ?Type\Union
{
$call_args = $event->getCallArgs();
if (count($call_args) === 0) {
return null;
}
$statements_source = $event->getStatementsSource();
$nodeTypeProvider = $statements_source->getNodeTypeProvider();
if (count($call_args) === 1
&& ($array_arg_type = $nodeTypeProvider->getType($call_args[0]->value))
&& $array_arg_type->isSingle()
&& $array_arg_type->hasArray()
&& ($array_type = ArrayType::infer($array_arg_type->getAtomicTypes()['array']))
) {
return $array_type->value;
}
$atomics = [];
foreach ($call_args as $arg) {
if ($array_arg_type = $nodeTypeProvider->getType($arg->value)) {
foreach ($array_arg_type->getAtomicTypes() as $atomicType) {
$atomics[] = $atomicType;
}
} else {
return Type::getMixed();
}
}
if ($atomics === []) {
return Type::getMixed();
}
return new Type\Union($atomics);
}
}

View File

@ -1530,6 +1530,29 @@ class FunctionCallTest extends TestCase
[],
'8.0'
],
'maxWithFloats' => [
'<?php
function foo(float $_float): void
{}
foo(max(1.1, 1.2));',
],
'maxWithObjects' => [
'<?php
function foo(DateTimeImmutable $fooDate): string
{
return $fooDate->format("Y");
}
foo(max(new DateTimeImmutable(), new DateTimeImmutable()));',
],
'maxWithMisc' => [
'<?php
$a = max(new DateTimeImmutable(), 1.2);',
[
'$a' => 'DateTimeImmutable|float',
],
],
];
}
@ -2055,6 +2078,13 @@ class FunctionCallTest extends TestCase
}',
'error_message' => 'InvalidReturnStatement'
],
'maxWithMixed' => [
'<?php
/** @var mixed $b */;
/** @var mixed $c */;
$a = max($b, $c);',
'error_message' => 'MixedAssignment'
],
];
}
}