From c902bf796ca6c9656c3cc8185b53afb9acbb7c72 Mon Sep 17 00:00:00 2001 From: Christian Flothmann Date: Wed, 6 Nov 2024 22:58:58 +0100 Subject: [PATCH] handle error results of DateTime::modify() Depending on the version of PHP the modify() method will either throw an exception or issue a warning. --- RateLimiterFactory.php | 22 ++++++++++++---------- 1 file changed, 12 insertions(+), 10 deletions(-) diff --git a/RateLimiterFactory.php b/RateLimiterFactory.php index 510f2e6..2bf2635 100644 --- a/RateLimiterFactory.php +++ b/RateLimiterFactory.php @@ -68,19 +68,21 @@ public function create(?string $key = null): LimiterInterface protected static function configureOptions(OptionsResolver $options): void { $intervalNormalizer = static function (Options $options, string $interval): \DateInterval { - try { - // Create DateTimeImmutable from unix timesatmp, so the default timezone is ignored and we don't need to - // deal with quirks happening when modifying dates using a timezone with DST. - $now = \DateTimeImmutable::createFromFormat('U', time()); + // Create DateTimeImmutable from unix timesatmp, so the default timezone is ignored and we don't need to + // deal with quirks happening when modifying dates using a timezone with DST. + $now = \DateTimeImmutable::createFromFormat('U', time()); - return $now->diff($now->modify('+'.$interval)); - } catch (\Exception $e) { - if (!preg_match('/Failed to parse time string \(\+([^)]+)\)/', $e->getMessage(), $m)) { - throw $e; - } + try { + $nowPlusInterval = @$now->modify('+' . $interval); + } catch (\DateMalformedStringException $e) { + throw new \LogicException(\sprintf('Cannot parse interval "%s", please use a valid unit as described on https://www.php.net/datetime.formats.relative.', $interval), 0, $e); + } - throw new \LogicException(sprintf('Cannot parse interval "%s", please use a valid unit as described on https://www.php.net/datetime.formats.relative.', $m[1])); + if (!$nowPlusInterval) { + throw new \LogicException(\sprintf('Cannot parse interval "%s", please use a valid unit as described on https://www.php.net/datetime.formats.relative.', $interval)); } + + return $now->diff($nowPlusInterval); }; $options