Skip to content

Commit

Permalink
DateTimeInstantiationRule - fix error message for new with wrong na…
Browse files Browse the repository at this point in the history
…me case
  • Loading branch information
ondrejmirtes committed May 20, 2023
1 parent 87256f3 commit 59ac31a
Show file tree
Hide file tree
Showing 3 changed files with 19 additions and 4 deletions.
12 changes: 8 additions & 4 deletions src/Rules/DateTimeInstantiationRule.php
Original file line number Diff line number Diff line change
Expand Up @@ -28,10 +28,14 @@ public function getNodeType(): string
*/
public function processNode(Node $node, Scope $scope): array
{
if (!$node->class instanceof Node\Name) {
return [];
}

$lowerClassName = strtolower((string) $node->class);
if (
!($node->class instanceof Node\Name)
|| count($node->getArgs()) === 0
|| !in_array(strtolower((string) $node->class), ['datetime', 'datetimeimmutable'], true)
count($node->getArgs()) === 0
|| !in_array($lowerClassName, ['datetime', 'datetimeimmutable'], true)
) {
return [];
}
Expand All @@ -54,7 +58,7 @@ public function processNode(Node $node, Scope $scope): array
foreach ($lastErrors['errors'] as $error) {
$errors[] = RuleErrorBuilder::message(sprintf(
'Instantiating %s with %s produces an error: %s',
(string) $node->class,
$lowerClassName === 'datetime' ? 'DateTime' : 'DateTimeImmutable',
$dateString,
$error,
))->build();
Expand Down
8 changes: 8 additions & 0 deletions tests/PHPStan/Rules/DateTimeInstantiationRuleTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,14 @@ public function test(): void
'Instantiating DateTime with 2020-04-31 produces a warning: The parsed date was invalid',
20,
],*/
[
'Instantiating DateTime with 2020.11.17 produces an error: Double time specification',
22,
],
[
'Instantiating DateTimeImmutable with 2020.11.17 produces an error: Double time specification',
23,
],
],
);
}
Expand Down
3 changes: 3 additions & 0 deletions tests/PHPStan/Rules/data/datetime-instantiation.php
Original file line number Diff line number Diff line change
Expand Up @@ -18,3 +18,6 @@ function foo(string $date, string $date2): void {
}

new \DateTime('2020-04-31');

new \dateTime('2020.11.17');
new \dateTimeImmutablE('2020.11.17');

0 comments on commit 59ac31a

Please sign in to comment.