Skip to content

Commit eb531c2

Browse files
authored
Fix item::item_category index conversion (#77)
Item_category is currently grouped in an array but is supposed to be sent to Google Analytics as individual lines appended by index number like: ```json items: [ { index: 0, item_brand: "Google", item_category: "Apparel", item_category2: "Adult", item_category3: "Shirts", //... ``` - https://developers.google.com/analytics/devguides/collection/ga4/item-scoped-ecommerce
2 parents 722b7d7 + b1147b8 commit eb531c2

File tree

2 files changed

+40
-1
lines changed

2 files changed

+40
-1
lines changed

src/Item.php

+22
Original file line numberDiff line numberDiff line change
@@ -154,6 +154,28 @@ public function getRequiredParams(): array
154154
return $return;
155155
}
156156

157+
public function toArray(): array
158+
{
159+
$res = parent::toArray();
160+
161+
if (!isset($res['item_category'])) {
162+
return $res;
163+
}
164+
165+
$categories = $res['item_category'];
166+
unset($res['item_category']);
167+
168+
if (is_array($categories)) {
169+
foreach ($categories as $k => $val) {
170+
$tag = 'item_category' . ($k > 0 ? $k + 1 : '');
171+
172+
$res[$tag] = $val;
173+
}
174+
}
175+
176+
return $res;
177+
}
178+
157179
public static function new(): static
158180
{
159181
return new static();

test/Unit/ItemTest.php

+18-1
Original file line numberDiff line numberDiff line change
@@ -44,7 +44,7 @@ public function test_can_configure_and_export()
4444
$this->assertArrayHasKey('quantity', $asArray);
4545
$this->assertArrayHasKey('index', $asArray);
4646
$this->assertArrayHasKey('item_category', $asArray);
47-
$this->assertIsArray($asArray['item_category']);
47+
$this->assertIsNotArray($asArray['item_category']);
4848
}
4949

5050
public function test_can_configure_arrayable()
@@ -118,4 +118,21 @@ public function test_can_import_from_array()
118118
$this->assertArrayHasKey('price', $arr);
119119
$this->assertArrayHasKey('quantity', $arr);
120120
}
121+
122+
public function test_can_convert_item_category_to_index_names()
123+
{
124+
$arr = Item::new()
125+
->setItemId("123")
126+
->addItemCategory("a")
127+
->addItemCategory("b")
128+
->addItemCategory("c")
129+
->toArray();
130+
131+
$this->assertArrayHasKey('item_category', $arr);
132+
$this->assertArrayHasKey('item_category2', $arr);
133+
$this->assertArrayHasKey('item_category3', $arr);
134+
135+
$this->assertArrayNotHasKey('item_category0', $arr);
136+
$this->assertArrayNotHasKey('item_category1', $arr);
137+
}
121138
}

0 commit comments

Comments
 (0)