Skip to content

Commit

Permalink
Convert items->item_category[] to items->item_categodyX where X repre…
Browse files Browse the repository at this point in the history
…sents ID
  • Loading branch information
aawnu committed Jan 14, 2024
1 parent 722b7d7 commit 397887d
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 0 deletions.
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
17 changes: 17 additions & 0 deletions test/Unit/ItemTest.php
Original file line number Diff line number Diff line change
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 397887d

Please sign in to comment.