Skip to content

Commit 9cf0015

Browse files
committed
allow datetime as an argument to CloudEvent
1 parent e9e403d commit 9cf0015

File tree

2 files changed

+46
-4
lines changed

2 files changed

+46
-4
lines changed

src/CloudEvent.php

Lines changed: 10 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -47,7 +47,7 @@ public function __construct(
4747
?string $datacontenttype,
4848
?string $dataschema,
4949
?string $subject,
50-
?string $time,
50+
$time,
5151
$data
5252
) {
5353
$this->id = $id;
@@ -154,10 +154,16 @@ public function __toString()
154154
return $output;
155155
}
156156

157-
private static function timeAsDateTime(?string $time): ?DateTime
157+
private static function timeAsDateTime($time): ?DateTime
158158
{
159-
if (is_null($time)) {
160-
return null;
159+
if ($time instanceof DateTime || is_null($time)) {
160+
return $time;
161+
}
162+
163+
if (!is_string($time)) {
164+
throw new \UnexpectedValueException(
165+
'time must be a string, DateTime, or null'
166+
);
161167
}
162168

163169
return new DateTime($time);

tests/CloudEventTest.php

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -68,4 +68,40 @@ public function testJsonSerialize()
6868

6969
$this->assertEquals(json_encode($event, JSON_PRETTY_PRINT), $want);
7070
}
71+
72+
public function testTimeCanBeDateTime()
73+
{
74+
$time = new \DateTime();
75+
$event = new CloudEvent(
76+
'1413058901901494',
77+
'//pubsub.googleapis.com/projects/MY-PROJECT/topics/MY-TOPIC',
78+
'1.0',
79+
'com.google.cloud.pubsub.topic.publish',
80+
'application/json',
81+
'type.googleapis.com/google.logging.v2.LogEntry',
82+
'My Subject',
83+
$time, // can be a datetime
84+
null
85+
);
86+
87+
$this->assertEquals($time, $event->getTime());
88+
}
89+
90+
public function testInvalidTime()
91+
{
92+
$this->expectException(\UnexpectedValueException::class);
93+
$this->expectExceptionMessage('time must be a string, DateTime, or null');
94+
95+
$event = new CloudEvent(
96+
'1413058901901494',
97+
'//pubsub.googleapis.com/projects/MY-PROJECT/topics/MY-TOPIC',
98+
'1.0',
99+
'com.google.cloud.pubsub.topic.publish',
100+
'application/json',
101+
'type.googleapis.com/google.logging.v2.LogEntry',
102+
'My Subject',
103+
123456, // not a string, datetime, or null
104+
null
105+
);
106+
}
71107
}

0 commit comments

Comments
 (0)