|
| 1 | +<?php declare(strict_types = 1); |
| 2 | + |
| 3 | +namespace PHPStan\Type\Php; |
| 4 | + |
| 5 | +use DateInterval; |
| 6 | +use PhpParser\Node\Expr\StaticCall; |
| 7 | +use PHPStan\Analyser\Scope; |
| 8 | +use PHPStan\DependencyInjection\AutowiredService; |
| 9 | +use PHPStan\Php\PhpVersion; |
| 10 | +use PHPStan\Reflection\MethodReflection; |
| 11 | +use PHPStan\Type\DynamicStaticMethodThrowTypeExtension; |
| 12 | +use PHPStan\Type\NeverType; |
| 13 | +use PHPStan\Type\Type; |
| 14 | +use PHPStan\Type\TypeCombinator; |
| 15 | +use function count; |
| 16 | + |
| 17 | +#[AutowiredService] |
| 18 | +final class DateIntervalCreateFromDateStringMethodThrowTypeExtension implements DynamicStaticMethodThrowTypeExtension |
| 19 | +{ |
| 20 | + |
| 21 | + public function __construct(private PhpVersion $phpVersion) |
| 22 | + { |
| 23 | + } |
| 24 | + |
| 25 | + public function isStaticMethodSupported(MethodReflection $methodReflection): bool |
| 26 | + { |
| 27 | + return $methodReflection->getName() === 'createFromDateString' && $methodReflection->getDeclaringClass()->getName() === DateInterval::class; |
| 28 | + } |
| 29 | + |
| 30 | + public function getThrowTypeFromStaticMethodCall(MethodReflection $methodReflection, StaticCall $methodCall, Scope $scope): ?Type |
| 31 | + { |
| 32 | + if (count($methodCall->getArgs()) === 0) { |
| 33 | + return null; |
| 34 | + } |
| 35 | + |
| 36 | + if (!$this->phpVersion->hasDateTimeExceptions()) { |
| 37 | + return null; |
| 38 | + } |
| 39 | + |
| 40 | + $valueType = $scope->getType($methodCall->getArgs()[0]->value); |
| 41 | + $constantStrings = $valueType->getConstantStrings(); |
| 42 | + |
| 43 | + foreach ($constantStrings as $constantString) { |
| 44 | + try { |
| 45 | + DateInterval::createFromDateString($constantString->getValue()); |
| 46 | + } catch (\Exception) { // phpcs:ignore |
| 47 | + return $methodReflection->getThrowType(); |
| 48 | + } |
| 49 | + |
| 50 | + $valueType = TypeCombinator::remove($valueType, $constantString); |
| 51 | + } |
| 52 | + |
| 53 | + if (!$valueType instanceof NeverType) { |
| 54 | + return $methodReflection->getThrowType(); |
| 55 | + } |
| 56 | + |
| 57 | + return null; |
| 58 | + } |
| 59 | + |
| 60 | +} |
0 commit comments