diff --git a/src/CartItem.php b/src/CartItem.php index 2a1ea36..4283c2e 100644 --- a/src/CartItem.php +++ b/src/CartItem.php @@ -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; } diff --git a/tests/CartItemTest.php b/tests/CartItemTest.php index 5e81e15..4e85434 100644 --- a/tests/CartItemTest.php +++ b/tests/CartItemTest.php @@ -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); + } }