Skip to content

Commit

Permalink
Fix item::item_category index conversion (#77)
Browse files Browse the repository at this point in the history
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
  • Loading branch information
aawnu authored Jan 14, 2024
2 parents 722b7d7 + b1147b8 commit eb531c2
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 1 deletion.
22 changes: 22 additions & 0 deletions src/Item.php
Original file line number Diff line number Diff line change
Expand Up @@ -154,6 +154,28 @@ public function getRequiredParams(): array
return $return;
}

public function toArray(): array
{
$res = parent::toArray();

if (!isset($res['item_category'])) {
return $res;
}

$categories = $res['item_category'];
unset($res['item_category']);

if (is_array($categories)) {
foreach ($categories as $k => $val) {
$tag = 'item_category' . ($k > 0 ? $k + 1 : '');

$res[$tag] = $val;
}
}

return $res;
}

public static function new(): static
{
return new static();
Expand Down
19 changes: 18 additions & 1 deletion test/Unit/ItemTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ public function test_can_configure_and_export()
$this->assertArrayHasKey('quantity', $asArray);
$this->assertArrayHasKey('index', $asArray);
$this->assertArrayHasKey('item_category', $asArray);
$this->assertIsArray($asArray['item_category']);
$this->assertIsNotArray($asArray['item_category']);
}

public function test_can_configure_arrayable()
Expand Down Expand Up @@ -118,4 +118,21 @@ public function test_can_import_from_array()
$this->assertArrayHasKey('price', $arr);
$this->assertArrayHasKey('quantity', $arr);
}

public function test_can_convert_item_category_to_index_names()
{
$arr = Item::new()
->setItemId("123")
->addItemCategory("a")
->addItemCategory("b")
->addItemCategory("c")
->toArray();

$this->assertArrayHasKey('item_category', $arr);
$this->assertArrayHasKey('item_category2', $arr);
$this->assertArrayHasKey('item_category3', $arr);

$this->assertArrayNotHasKey('item_category0', $arr);
$this->assertArrayNotHasKey('item_category1', $arr);
}
}

0 comments on commit eb531c2

Please sign in to comment.