From 7b4b767d6eaefd27705dbac307e944edf0e779b0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E0=B2=A0=5F=E0=B2=A0?= Date: Mon, 12 Dec 2022 10:20:21 +0100 Subject: [PATCH] implement DateIntervalDynamicReturnTypeExtension --- conf/config.neon | 5 +++ resources/functionMap.php | 2 +- ...DateIntervalDynamicReturnTypeExtension.php | 45 +++++++++++++++++++ 3 files changed, 51 insertions(+), 1 deletion(-) create mode 100644 src/Type/Php/DateIntervalDynamicReturnTypeExtension.php diff --git a/conf/config.neon b/conf/config.neon index 56b79657630..d8cb63f198a 100644 --- a/conf/config.neon +++ b/conf/config.neon @@ -1320,6 +1320,11 @@ services: tags: - phpstan.dynamicStaticMethodThrowTypeExtension + - + class: PHPStan\Type\Php\DateIntervalDynamicReturnTypeExtension + tags: + - phpstan.broker.dynamicStaticMethodReturnTypeExtension + - class: PHPStan\Type\Php\DateTimeCreateDynamicReturnTypeExtension tags: diff --git a/resources/functionMap.php b/resources/functionMap.php index 54ab61ed335..0b25c6784b7 100644 --- a/resources/functionMap.php +++ b/resources/functionMap.php @@ -1583,7 +1583,7 @@ 'DateInterval::__construct' => ['void', 'spec'=>'string'], 'DateInterval::__set_state' => ['DateInterval', 'array'=>'array'], 'DateInterval::__wakeup' => ['void'], -'DateInterval::createFromDateString' => ['DateInterval', 'time'=>'string'], +'DateInterval::createFromDateString' => ['DateInterval|false', 'time'=>'string'], 'DateInterval::format' => ['string', 'format'=>'string'], 'DatePeriod::__construct' => ['void', 'start'=>'DateTimeInterface', 'interval'=>'DateInterval', 'recur'=>'int', 'options='=>'int'], 'DatePeriod::__construct\'1' => ['void', 'start'=>'DateTimeInterface', 'interval'=>'DateInterval', 'end'=>'DateTimeInterface', 'options='=>'int'], diff --git a/src/Type/Php/DateIntervalDynamicReturnTypeExtension.php b/src/Type/Php/DateIntervalDynamicReturnTypeExtension.php new file mode 100644 index 00000000000..73f85f39cb7 --- /dev/null +++ b/src/Type/Php/DateIntervalDynamicReturnTypeExtension.php @@ -0,0 +1,45 @@ +getName() === 'createFromDateString'; + } + + public function getTypeFromStaticMethodCall( MethodReflection $methodReflection, StaticCall $methodCall, Scope $scope ): ?\PHPStan\Type\Type + { + $defaultReturnType = ParametersAcceptorSelector::selectFromArgs( + $scope, + $methodCall->getArgs(), + $methodReflection->getVariants(), + )->getReturnType(); + + $dateTimeString = $scope->getType($methodCall->getArgs()[0]->value); + + if (!($dateTimeString instanceof ConstantStringType)) { + return $defaultReturnType; + } + + $isValid = DateInterval::createFromDateString($dateTimeString->getValue()) !== false; + + return $isValid ? new ObjectType(DateInterval::class) : new ConstantBooleanType(false); + } +}