forked from phpstan/phpstan-src
-
Notifications
You must be signed in to change notification settings - Fork 0
/
DateTimeDynamicReturnTypeExtension.php
51 lines (41 loc) · 1.66 KB
/
DateTimeDynamicReturnTypeExtension.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
50
51
<?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 in_array;
class DateTimeDynamicReturnTypeExtension implements DynamicFunctionReturnTypeExtension
{
public function isFunctionSupported(FunctionReflection $functionReflection): bool
{
return in_array($functionReflection->getName(), ['date_create_from_format', 'date_create_immutable_from_format'], true);
}
public function getTypeFromFunctionCall(FunctionReflection $functionReflection, FuncCall $functionCall, Scope $scope): ?Type
{
if (count($functionCall->getArgs()) < 2) {
return null;
}
$formats = $scope->getType($functionCall->getArgs()[0]->value)->getConstantStrings();
$datetimes = $scope->getType($functionCall->getArgs()[1]->value)->getConstantStrings();
if (count($formats) === 0 || count($datetimes) === 0) {
return null;
}
$types = [];
$className = $functionReflection->getName() === 'date_create_from_format' ? DateTime::class : DateTimeImmutable::class;
foreach ($formats as $formatConstantString) {
foreach ($datetimes as $datetimeConstantString) {
$isValid = (DateTime::createFromFormat($formatConstantString->getValue(), $datetimeConstantString->getValue()) !== false);
$types[] = $isValid ? new ObjectType($className) : new ConstantBooleanType(false);
}
}
return TypeCombinator::union(...$types);
}
}