|
| 1 | +<?php declare(strict_types = 1); |
| 2 | + |
| 3 | +namespace PHPStan\Rules; |
| 4 | + |
| 5 | +use DateTime; |
| 6 | +use PhpParser\Node; |
| 7 | +use PhpParser\Node\Expr\New_; |
| 8 | +use PHPStan\Analyser\Scope; |
| 9 | +use PHPStan\Type\Constant\ConstantStringType; |
| 10 | + |
| 11 | +/** |
| 12 | + * @implements \PHPStan\Rules\Rule<\PhpParser\Node\Expr\New_> |
| 13 | + */ |
| 14 | +class DateTimeInstantiationRule implements \PHPStan\Rules\Rule |
| 15 | +{ |
| 16 | + |
| 17 | + public function getNodeType(): string |
| 18 | + { |
| 19 | + return New_::class; |
| 20 | + } |
| 21 | + |
| 22 | + /** |
| 23 | + * @param New_ $node |
| 24 | + */ |
| 25 | + public function processNode(Node $node, Scope $scope): array |
| 26 | + { |
| 27 | + if ( |
| 28 | + !($node->class instanceof \PhpParser\Node\Name) |
| 29 | + || \count($node->args) === 0 |
| 30 | + || !\in_array(strtolower((string) $node->class), ['datetime', 'datetimeimmutable'], true) |
| 31 | + ) { |
| 32 | + return []; |
| 33 | + } |
| 34 | + |
| 35 | + $arg = $scope->getType($node->args[0]->value); |
| 36 | + if (!($arg instanceof ConstantStringType)) { |
| 37 | + return []; |
| 38 | + } |
| 39 | + |
| 40 | + $errors = []; |
| 41 | + $dateString = $arg->getValue(); |
| 42 | + try { |
| 43 | + new DateTime($dateString); |
| 44 | + } catch (\Throwable $e) { |
| 45 | + // an exception is thrown for errors only but we want to catch warnings too |
| 46 | + } |
| 47 | + $lastErrors = DateTime::getLastErrors(); |
| 48 | + if ($lastErrors !== false) { |
| 49 | + foreach ($lastErrors['warnings'] as $warning) { |
| 50 | + $errors[] = RuleErrorBuilder::message(sprintf( |
| 51 | + 'Instantiating %s with %s produces a warning: %s', |
| 52 | + (string) $node->class, |
| 53 | + $dateString, |
| 54 | + $warning |
| 55 | + ))->build(); |
| 56 | + } |
| 57 | + foreach ($lastErrors['errors'] as $error) { |
| 58 | + $errors[] = RuleErrorBuilder::message(sprintf( |
| 59 | + 'Instantiating %s with %s produces an error: %s', |
| 60 | + (string) $node->class, |
| 61 | + $dateString, |
| 62 | + $error |
| 63 | + ))->build(); |
| 64 | + } |
| 65 | + } |
| 66 | + |
| 67 | + return $errors; |
| 68 | + } |
| 69 | + |
| 70 | +} |
0 commit comments