/
DateTimeCreateDynamicReturnTypeExtension.php
49 lines (39 loc) · 1.43 KB
/
DateTimeCreateDynamicReturnTypeExtension.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
<?php declare(strict_types = 1);
namespace PHPStan\Type\Php;
use DateTime;
use DateTimeImmutable;
use PhpParser\Node\Expr\FuncCall;
use PHPStan\Analyser\Scope;
use PHPStan\Reflection\FunctionReflection;
use PHPStan\Type\Constant\ConstantBooleanType;
use PHPStan\Type\DynamicFunctionReturnTypeExtension;
use PHPStan\Type\ObjectType;
use PHPStan\Type\Type;
use PHPStan\Type\TypeCombinator;
use function count;
use function date_create;
use function in_array;
class DateTimeCreateDynamicReturnTypeExtension implements DynamicFunctionReturnTypeExtension
{
public function isFunctionSupported(FunctionReflection $functionReflection): bool
{
return in_array($functionReflection->getName(), ['date_create', 'date_create_immutable'], true);
}
public function getTypeFromFunctionCall(FunctionReflection $functionReflection, FuncCall $functionCall, Scope $scope): ?Type
{
if (count($functionCall->getArgs()) < 1) {
return null;
}
$datetimes = $scope->getType($functionCall->getArgs()[0]->value)->getConstantStrings();
if (count($datetimes) === 0) {
return null;
}
$types = [];
$className = $functionReflection->getName() === 'date_create' ? DateTime::class : DateTimeImmutable::class;
foreach ($datetimes as $constantString) {
$isValid = date_create($constantString->getValue()) !== false;
$types[] = $isValid ? new ObjectType($className) : new ConstantBooleanType(false);
}
return TypeCombinator::union(...$types);
}
}