Skip to content

Improve date() return types #2888

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 5 commits into from
Mar 29, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions conf/config.neon
Original file line number Diff line number Diff line change
Expand Up @@ -1272,6 +1272,9 @@ services:
tags:
- phpstan.broker.dynamicFunctionReturnTypeExtension

-
class: PHPStan\Type\Php\DateFunctionReturnTypeHelper

-
class: PHPStan\Type\Php\DateFormatFunctionReturnTypeExtension
tags:
Expand Down
14 changes: 8 additions & 6 deletions src/Type/Php/DateFormatFunctionReturnTypeExtension.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@
namespace PHPStan\Type\Php;

use PhpParser\Node\Expr\FuncCall;
use PhpParser\Node\Name\FullyQualified;
use PHPStan\Analyser\Scope;
use PHPStan\Reflection\FunctionReflection;
use PHPStan\Type\DynamicFunctionReturnTypeExtension;
Expand All @@ -14,6 +13,10 @@
class DateFormatFunctionReturnTypeExtension implements DynamicFunctionReturnTypeExtension
{

public function __construct(private DateFunctionReturnTypeHelper $dateFunctionReturnTypeHelper)
{
}

public function isFunctionSupported(FunctionReflection $functionReflection): bool
{
return $functionReflection->getName() === 'date_format';
Expand All @@ -23,16 +26,15 @@ public function getTypeFromFunctionCall(
FunctionReflection $functionReflection,
FuncCall $functionCall,
Scope $scope,
): Type
): ?Type
{
if (count($functionCall->getArgs()) < 2) {
return new StringType();
}

return $scope->getType(
new FuncCall(new FullyQualified('date'), [
$functionCall->getArgs()[1],
]),
return $this->dateFunctionReturnTypeHelper->getTypeFromFormatType(
$scope->getType($functionCall->getArgs()[1]->value),
true,
);
}

Expand Down
15 changes: 8 additions & 7 deletions src/Type/Php/DateFormatMethodReturnTypeExtension.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,7 @@
namespace PHPStan\Type\Php;

use DateTimeInterface;
use PhpParser\Node\Expr\FuncCall;
use PhpParser\Node\Expr\MethodCall;
use PhpParser\Node\Name\FullyQualified;
use PHPStan\Analyser\Scope;
use PHPStan\Reflection\MethodReflection;
use PHPStan\Type\DynamicMethodReturnTypeExtension;
Expand All @@ -16,6 +14,10 @@
class DateFormatMethodReturnTypeExtension implements DynamicMethodReturnTypeExtension
{

public function __construct(private DateFunctionReturnTypeHelper $dateFunctionReturnTypeHelper)
{
}

public function getClass(): string
{
return DateTimeInterface::class;
Expand All @@ -26,16 +28,15 @@ public function isMethodSupported(MethodReflection $methodReflection): bool
return $methodReflection->getName() === 'format';
}

public function getTypeFromMethodCall(MethodReflection $methodReflection, MethodCall $methodCall, Scope $scope): Type
public function getTypeFromMethodCall(MethodReflection $methodReflection, MethodCall $methodCall, Scope $scope): ?Type
{
if (count($methodCall->getArgs()) === 0) {
return new StringType();
}

return $scope->getType(
new FuncCall(new FullyQualified('date'), [
$methodCall->getArgs()[0],
]),
return $this->dateFunctionReturnTypeHelper->getTypeFromFormatType(
$scope->getType($methodCall->getArgs()[0]->value),
true,
);
}

Expand Down
111 changes: 10 additions & 101 deletions src/Type/Php/DateFunctionReturnTypeExtension.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,23 +5,17 @@
use PhpParser\Node\Expr\FuncCall;
use PHPStan\Analyser\Scope;
use PHPStan\Reflection\FunctionReflection;
use PHPStan\Type\Accessory\AccessoryNonEmptyStringType;
use PHPStan\Type\Accessory\AccessoryNonFalsyStringType;
use PHPStan\Type\Accessory\AccessoryNumericStringType;
use PHPStan\Type\Constant\ConstantStringType;
use PHPStan\Type\DynamicFunctionReturnTypeExtension;
use PHPStan\Type\IntersectionType;
use PHPStan\Type\StringType;
use PHPStan\Type\Type;
use PHPStan\Type\TypeCombinator;
use PHPStan\Type\UnionType;
use function count;
use function date;
use function sprintf;

class DateFunctionReturnTypeExtension implements DynamicFunctionReturnTypeExtension
{

public function __construct(private DateFunctionReturnTypeHelper $dateFunctionReturnTypeHelper)
{
}

public function isFunctionSupported(FunctionReflection $functionReflection): bool
{
return $functionReflection->getName() === 'date';
Expand All @@ -31,101 +25,16 @@ public function getTypeFromFunctionCall(
FunctionReflection $functionReflection,
FuncCall $functionCall,
Scope $scope,
): Type
): ?Type
{
if (count($functionCall->getArgs()) === 0) {
return new StringType();
}
$argType = $scope->getType($functionCall->getArgs()[0]->value);
$constantStrings = $argType->getConstantStrings();

if (count($constantStrings) === 0) {
return new StringType();
}

if (count($constantStrings) === 1) {
$constantString = $constantStrings[0]->getValue();

// see see https://www.php.net/manual/en/datetime.format.php
switch ($constantString) {
case 'd':
return $this->buildNumericRangeType(1, 31, true);
case 'j':
return $this->buildNumericRangeType(1, 31, false);
case 'N':
return $this->buildNumericRangeType(1, 7, false);
case 'w':
return $this->buildNumericRangeType(0, 6, false);
case 'm':
return $this->buildNumericRangeType(1, 12, true);
case 'n':
return $this->buildNumericRangeType(1, 12, false);
case 't':
return $this->buildNumericRangeType(28, 31, false);
case 'L':
return $this->buildNumericRangeType(0, 1, false);
case 'g':
return $this->buildNumericRangeType(1, 12, false);
case 'G':
return $this->buildNumericRangeType(0, 23, false);
case 'h':
return $this->buildNumericRangeType(1, 12, true);
case 'H':
return $this->buildNumericRangeType(0, 23, true);
case 'I':
return $this->buildNumericRangeType(0, 1, false);
}
}

$types = [];
foreach ($constantStrings as $constantString) {
$types[] = new ConstantStringType(date($constantString->getValue()));
}

$type = TypeCombinator::union(...$types);
if ($type->isNumericString()->yes()) {
return new IntersectionType([
new StringType(),
new AccessoryNumericStringType(),
]);
}

if ($type->isNonFalsyString()->yes()) {
return new IntersectionType([
new StringType(),
new AccessoryNonFalsyStringType(),
]);
}

if ($type->isNonEmptyString()->yes()) {
return new IntersectionType([
new StringType(),
new AccessoryNonEmptyStringType(),
]);
}

if ($type->isNonEmptyString()->no()) {
return new ConstantStringType('');
}

return new StringType();
}

private function buildNumericRangeType(int $min, int $max, bool $zeroPad): Type
{
$types = [];

for ($i = $min; $i <= $max; $i++) {
$string = (string) $i;

if ($zeroPad) {
$string = sprintf('%02s', $string);
}

$types[] = new ConstantStringType($string);
return null;
}

return new UnionType($types);
return $this->dateFunctionReturnTypeHelper->getTypeFromFormatType(
$scope->getType($functionCall->getArgs()[0]->value),
false,
);
}

}
114 changes: 114 additions & 0 deletions src/Type/Php/DateFunctionReturnTypeHelper.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,114 @@
<?php declare(strict_types = 1);

namespace PHPStan\Type\Php;

use PHPStan\Type\Accessory\AccessoryNonEmptyStringType;
use PHPStan\Type\Accessory\AccessoryNonFalsyStringType;
use PHPStan\Type\Accessory\AccessoryNumericStringType;
use PHPStan\Type\Constant\ConstantStringType;
use PHPStan\Type\IntersectionType;
use PHPStan\Type\StringType;
use PHPStan\Type\Type;
use PHPStan\Type\TypeCombinator;
use PHPStan\Type\UnionType;
use function count;
use function date;
use function is_numeric;
use function str_pad;
use const STR_PAD_LEFT;

class DateFunctionReturnTypeHelper
{

public function getTypeFromFormatType(Type $formatType, bool $useMicrosec): ?Type
{
$types = [];
foreach ($formatType->getConstantStrings() as $formatString) {
$types[] = $this->buildReturnTypeFromFormat($formatString->getValue(), $useMicrosec);
}

if (count($types) === 0) {
$types[] = $formatType->isNonEmptyString()->yes()
? new IntersectionType([new StringType(), new AccessoryNonEmptyStringType()])
: new StringType();
}

$type = TypeCombinator::union(...$types);

if ($type->isNumericString()->no() && $formatType->isNonEmptyString()->yes()) {
$type = TypeCombinator::union($type, new IntersectionType([
new StringType(), new AccessoryNonEmptyStringType(),
]));
}

return $type;
}

public function buildReturnTypeFromFormat(string $formatString, bool $useMicrosec): Type
{
// see see https://www.php.net/manual/en/datetime.format.php
switch ($formatString) {
case 'd':
return $this->buildNumericRangeType(1, 31, true);
case 'j':
return $this->buildNumericRangeType(1, 31, false);
case 'N':
return $this->buildNumericRangeType(1, 7, false);
case 'w':
return $this->buildNumericRangeType(0, 6, false);
case 'm':
return $this->buildNumericRangeType(1, 12, true);
case 'n':
return $this->buildNumericRangeType(1, 12, false);
case 't':
return $this->buildNumericRangeType(28, 31, false);
case 'L':
return $this->buildNumericRangeType(0, 1, false);
case 'g':
return $this->buildNumericRangeType(1, 12, false);
case 'G':
return $this->buildNumericRangeType(0, 23, false);
case 'h':
return $this->buildNumericRangeType(1, 12, true);
case 'H':
return $this->buildNumericRangeType(0, 23, true);
case 'I':
return $this->buildNumericRangeType(0, 1, false);
case 'u':
return $useMicrosec
? new IntersectionType([new StringType(), new AccessoryNonFalsyStringType()])
: new ConstantStringType('000000');
}

$date = date($formatString);

// If parameter string is not included, returned as ConstantStringType
if ($date === $formatString) {
return new ConstantStringType($date);
}

if (is_numeric($date)) {
return new IntersectionType([new StringType(), new AccessoryNumericStringType()]);
}

return new IntersectionType([new StringType(), new AccessoryNonFalsyStringType()]);
}

private function buildNumericRangeType(int $min, int $max, bool $zeroPad): Type
{
$types = [];

for ($i = $min; $i <= $max; $i++) {
$string = (string) $i;

if ($zeroPad) {
$string = str_pad($string, 2, '0', STR_PAD_LEFT);
}

$types[] = new ConstantStringType($string);
}

return new UnionType($types);
}

}
2 changes: 2 additions & 0 deletions tests/PHPStan/Analyser/NodeScopeResolverTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -1450,6 +1450,8 @@ public function dataFileAsserts(): iterable
yield from $this->gatherAssertTypes(__DIR__ . '/data/bug-10037.php');
yield from $this->gatherAssertTypes(__DIR__ . '/../Rules/PhpDoc/data/bug-10594.php');
yield from $this->gatherAssertTypes(__DIR__ . '/data/set-type-type-specifying.php');
yield from $this->gatherAssertTypes(__DIR__ . '/data/bug-10468.php');
yield from $this->gatherAssertTypes(__DIR__ . '/data/bug-6613.php');
}

/**
Expand Down
14 changes: 14 additions & 0 deletions tests/PHPStan/Analyser/data/bug-10468.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
<?php

namespace Bug6613;

use function PHPStan\Testing\assertType;

/**
* @param non-empty-string $non_empty_format
*/
function foo(string $format, string $non_empty_format): void
{
assertType("string", date($format));
assertType("non-empty-string", date($non_empty_format));
}
11 changes: 11 additions & 0 deletions tests/PHPStan/Analyser/data/bug-6613.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
<?php

namespace Bug6613;

use function PHPStan\Testing\assertType;

function (\DateTime $dt) {
assertType("'000000'", date('u'));
assertType('non-falsy-string', date_format($dt, 'u'));
assertType('non-falsy-string', $dt->format('u'));
};