Skip to content

Commit edb852e

Browse files
Fix Formatter:decodeTime() implementation (#24)
* Revert "Fix formatter decode time return type" Signed-off-by: Graham Campbell <[email protected]> * Throw ValueError when timestamp invalid Signed-off-by: Graham Campbell <[email protected]>
1 parent 7e97a82 commit edb852e

File tree

2 files changed

+24
-4
lines changed

2 files changed

+24
-4
lines changed

src/CloudEvents/Serializers/Formatters/Formatter.php

Lines changed: 12 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -27,11 +27,19 @@ public function encodeTime(?DateTimeInterface $time): ?string
2727

2828
public function decodeTime(?string $time): ?DateTimeInterface
2929
{
30-
$parsed = DateTimeImmutable::createFromFormat(self::TIME_FORMAT, $time, new DateTimeZone(self::TIME_ZONE));
30+
if ($time === null) {
31+
return null;
32+
}
33+
34+
$decoded = DateTimeImmutable::createFromFormat(self::TIME_FORMAT, $time, new DateTimeZone(self::TIME_ZONE));
35+
36+
if ($decoded === false) {
37+
throw new ValueError(
38+
\sprintf('%s::decodeTime(): Argument #1 ($time) is not a valid RFC3339 timestamp', self::class)
39+
);
40+
}
3141

32-
return $parsed === false
33-
? null
34-
: $parsed;
42+
return $decoded;
3543
}
3644

3745
/**

tests/CloudEvents/Serializers/Formatters/FormatterTest.php

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
use CloudEvents\Serializers\Formatters\Formatter;
66
use DateTimeImmutable;
77
use PHPUnit\Framework\TestCase;
8+
use ValueError;
89

910
/**
1011
* @coversDefaultClass \CloudEvents\Serializers\Formmaters\Formatter
@@ -22,6 +23,17 @@ public function testTime(): void
2223
$this->assertEquals(new DateTimeImmutable('2018-04-05T17:31:00Z'), $formatter->decodeTime('2018-04-05T17:31:00Z'));
2324
}
2425

26+
/**
27+
* @covers ::decodeTime
28+
*/
29+
public function testDecodeInvalidTime(): void
30+
{
31+
$formatter = new Formatter();
32+
$this->expectException(ValueError::class);
33+
$this->expectExceptionMessage('CloudEvents\\Serializers\\Formatters\\Formatter::decodeTime(): Argument #1 ($time) is not a valid RFC3339 timestamp');
34+
$formatter->decodeTime('2018asdsdsafd');
35+
}
36+
2537
/**
2638
* @covers ::encodeData
2739
* @covers ::decodeData

0 commit comments

Comments
 (0)