Skip to content

Commit

Permalink
Merge pull request #33 from offline-agency/fix-cart-item-associate-me…
Browse files Browse the repository at this point in the history
…thod

Fix cart item associate method
  • Loading branch information
Giacomo92 authored May 26, 2022
2 parents 0374f73 + 3462040 commit 4f4c105
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 6 deletions.
20 changes: 14 additions & 6 deletions src/CartItem.php
Original file line number Diff line number Diff line change
Expand Up @@ -140,15 +140,23 @@ public function updateFromArray(array $attributes)
}

/**
* Associate the cart item with the given model.
* Associate the cart item with a given model or something else.
*
* @param mixed $model
* @return CartItem
* @param $item
* @param bool $is_model
* @return $this
*/
public function associate($model): CartItem
public function associate($item, bool $is_model = true): CartItem
{
$this->associatedModel = is_string($model) ? $model : get_class($model);
$this->model = $model;
if ($is_model) {
$this->associatedModel = is_string($item) ? $item : get_class($item);
$this->model = $item;

return $this;
}

$this->associatedModel = Arr::has($item, 'associatedModel') ? Arr::get($item, 'associatedModel') : null;
$this->model = Arr::has($item, 'modelId') ? Arr::get($item, 'modelId') : null;

return $this;
}
Expand Down
26 changes: 26 additions & 0 deletions tests/CartItemTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -355,4 +355,30 @@ public function it_can_sum_discount()

$this->assertTrue($cartItem->hasCoupons());
}

/** @test */
public function it_can_associate_model_id()
{
$cartItem = new CartItem(
1,
'First Cart item',
'This is a simple description',
1,
100.00,
122.00,
'0',
'0',
22.00,
'https://ecommerce.test/images/item-name.png',
['size' => 'XL', 'color' => 'red']
);

$cartItem->associate([
'associatedModel' => 'OfflineAgency\LaravelCart\Tests\Fixtures\ProductModel',
'modelId' => 'fake_id',
], false);

$this->assertEquals('OfflineAgency\LaravelCart\Tests\Fixtures\ProductModel', $cartItem->associatedModel);
$this->assertEquals('fake_id', $cartItem->model);
}
}

0 comments on commit 4f4c105

Please sign in to comment.