Skip to content

Commit f8d049d

Browse files
committed
fix: make sure requests contain at least 1 event
1 parent cc5c56e commit f8d049d

File tree

3 files changed

+14
-10
lines changed

3 files changed

+14
-10
lines changed

src/Analytics.php

Lines changed: 8 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -124,25 +124,23 @@ public function post(): void
124124
$url = $this->debug ? Facade\Type\AnalyticsType::URL_DEBUG : Facade\Type\AnalyticsType::URL_LIVE;
125125
$url .= '?' . http_build_query(['measurement_id' => $this->measurement_id, 'api_secret' => $this->api_secret]);
126126

127-
$body = $this->toArray();
128-
array_merge_recursive(
127+
$body = array_replace_recursive(
129128
$this->toArray(),
129+
["user_properties" => $this->user_properties],
130130
["consent" => $this->consent->toArray()],
131131
);
132132

133133
$chunkEvents = array_chunk($this->events, 25);
134+
135+
if (count($chunkEvents) < 1) {
136+
throw Ga4Exception::throwMissingEvents();
137+
}
138+
139+
$this->user_properties = [];
134140
$this->events = [];
135141

136142
foreach ($chunkEvents as $events) {
137-
$body['user_properties'] = $this->user_properties;
138-
if (empty($body['user_properties'])) {
139-
unset($body['user_properties']);
140-
}
141-
142143
$body['events'] = $events;
143-
if (empty($body['events'])) {
144-
unset($body['events']);
145-
}
146144

147145
$kB = 1024;
148146
if (($size = mb_strlen(json_encode($body))) > ($kB * 130)) {

src/Exception/Ga4Exception.php

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -81,4 +81,9 @@ public static function throwRequestInvalidBody(array $msg)
8181
static::REQUEST_INVALID_BODY
8282
);
8383
}
84+
85+
public static function throwMissingEvents()
86+
{
87+
return new static("Request must include at least 1 event with a name", static::REQUEST_EMPTY_EVENTLIST);
88+
}
8489
}

src/Facade/Type/Ga4ExceptionType.php

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,4 +24,5 @@ interface Ga4ExceptionType
2424
const REQUEST_INVALID_BODY = 104005;
2525
const REQUEST_MISSING_MEASUREMENT_ID = 104006;
2626
const REQUEST_MISSING_API_SECRET = 104007;
27+
const REQUEST_EMPTY_EVENTLIST = 104008;
2728
}

0 commit comments

Comments
 (0)