-
Notifications
You must be signed in to change notification settings - Fork 570
Expand file tree
/
Copy pathDateIntervalCreateFromDateStringMethodThrowTypeExtension.php
More file actions
60 lines (47 loc) · 1.63 KB
/
DateIntervalCreateFromDateStringMethodThrowTypeExtension.php
File metadata and controls
60 lines (47 loc) · 1.63 KB
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
52
53
54
55
56
57
58
59
60
<?php declare(strict_types = 1);
namespace PHPStan\Type\Php;
use DateInterval;
use PhpParser\Node\Expr\StaticCall;
use PHPStan\Analyser\Scope;
use PHPStan\DependencyInjection\AutowiredService;
use PHPStan\Php\PhpVersion;
use PHPStan\Reflection\MethodReflection;
use PHPStan\Type\DynamicStaticMethodThrowTypeExtension;
use PHPStan\Type\NeverType;
use PHPStan\Type\Type;
use PHPStan\Type\TypeCombinator;
use function count;
#[AutowiredService]
final class DateIntervalCreateFromDateStringMethodThrowTypeExtension implements DynamicStaticMethodThrowTypeExtension
{
public function __construct(private PhpVersion $phpVersion)
{
}
public function isStaticMethodSupported(MethodReflection $methodReflection): bool
{
return $methodReflection->getName() === 'createFromDateString' && $methodReflection->getDeclaringClass()->getName() === DateInterval::class;
}
public function getThrowTypeFromStaticMethodCall(MethodReflection $methodReflection, StaticCall $methodCall, Scope $scope): ?Type
{
if (count($methodCall->getArgs()) === 0) {
return null;
}
if (!$this->phpVersion->hasDateTimeExceptions()) {
return null;
}
$valueType = $scope->getType($methodCall->getArgs()[0]->value);
$constantStrings = $valueType->getConstantStrings();
foreach ($constantStrings as $constantString) {
try {
DateInterval::createFromDateString($constantString->getValue());
} catch (\Exception) { // phpcs:ignore
return $methodReflection->getThrowType();
}
$valueType = TypeCombinator::remove($valueType, $constantString);
}
if (!$valueType instanceof NeverType) {
return $methodReflection->getThrowType();
}
return null;
}
}