Skip to content

Commit

Permalink
Catch DateTime Exception
Browse files Browse the repository at this point in the history
  • Loading branch information
alphp committed Apr 1, 2022
1 parent 2b4642b commit 9ecd3c6
Show file tree
Hide file tree
Showing 3 changed files with 14 additions and 2 deletions.
2 changes: 1 addition & 1 deletion composer.json
@@ -1,6 +1,6 @@
{
"name": "php81_bc/strftime",
"version": "0.0.6",
"version": "0.0.7",
"description": "Locale-formatted strftime using IntlDateFormatter (PHP 8.1 compatible)",
"license": "MIT",
"authors": [
Expand Down
7 changes: 6 additions & 1 deletion src/php-8.1-strftime.php
Expand Up @@ -4,6 +4,7 @@
use DateTime;
use DateTimeZone;
use DateTimeInterface;
use Exception;
use IntlDateFormatter;
use InvalidArgumentException;

Expand All @@ -29,7 +30,11 @@ function strftime (string $format, $timestamp = null, ?string $locale = null) :
if (!($timestamp instanceof DateTimeInterface)) {
$timestamp = is_int($timestamp) ? '@' . $timestamp : (string) $timestamp;

$timestamp = new DateTime($timestamp);
try {
$timestamp = new DateTime($timestamp);
} catch (Exception $e) {
throw new InvalidArgumentException('$timestamp argument is neither a valid UNIX timestamp, a valid date-time string or a DateTime object.', 0, $e);
}
}

$timestamp->setTimezone(new DateTimeZone(date_default_timezone_get()));
Expand Down
7 changes: 7 additions & 0 deletions tests/strftimeTest.php
@@ -1,4 +1,6 @@
<?php
declare(strict_types=1);

use PHPUnit\Framework\TestCase;
use function PHP81_BC\strftime;

Expand All @@ -24,4 +26,9 @@ public function test_datetime_timestamp () {
$result = strftime('%Y-%m-%d %H:%M:%S', new DateTime($this->str_date));
$this->assertEquals('2022-03-12 01:02:03', $result);
}

public function test_exception () {
$this->expectException(InvalidArgumentException::class);
$result = strftime('%Y-%m-%d %H:%M:%S', 'InvalidArgumentException');
}
}

0 comments on commit 9ecd3c6

Please sign in to comment.