refactor: update Cart to use CartDriver interface

Replace the v2 Cart implementation (which used CartSession directly) with
the v3 design that accepts a CartDriver contract via constructor injection.
Removes validateConfig(), replaces $this->session with $this->driver, adds
getDriver()/extend() helpers, serializes items/conditions through the driver,
and drops the unused setDecimals() method.
This commit is contained in:
Joel Male
2026-05-27 21:06:22 +10:00
parent 90ea8c44e4
commit e0103aadaa
+163 -426
View File
@@ -1,33 +1,33 @@
<?php <?php
declare(strict_types=1);
namespace Wearepixel\Cart; namespace Wearepixel\Cart;
use Closure;
use Wearepixel\Cart\Helpers\Helpers; use Wearepixel\Cart\Helpers\Helpers;
use Wearepixel\Cart\Validators\CartItemValidator; use Wearepixel\Cart\Validators\CartItemValidator;
use Wearepixel\Cart\Exceptions\InvalidItemException; use Wearepixel\Cart\Exceptions\InvalidItemException;
use Wearepixel\Cart\Exceptions\UnknownModelException; use Wearepixel\Cart\Exceptions\UnknownModelException;
use Wearepixel\Cart\Exceptions\InvalidConditionException; use Wearepixel\Cart\Exceptions\InvalidConditionException;
use Wearepixel\Cart\Drivers\Contracts\CartDriver;
class Cart class Cart
{ {
protected $session; protected CartDriver $driver;
protected $events; protected $events;
protected $instanceName; protected string $instanceName;
protected $config; protected array $config;
protected $currentItemId; protected mixed $currentItemId;
protected $decimals; public function __construct(CartDriver $driver, $events, string $instanceName, array $config)
protected $decPoint;
public function __construct($sessionStorage, $events, $instanceName, $sessionKey, $config)
{ {
$this->validateConfig($config); $this->driver = $driver;
$this->events = $events; $this->events = $events;
$this->session = new CartSession($sessionStorage, $sessionKey, $config);
$this->instanceName = $instanceName; $this->instanceName = $instanceName;
$this->config = $config; $this->config = $config;
$this->currentItemId = null; $this->currentItemId = null;
@@ -35,71 +35,41 @@ public function __construct($sessionStorage, $events, $instanceName, $sessionKey
$this->fireEvent('Created'); $this->fireEvent('Created');
} }
private function validateConfig($config) public static function extend(string $name, Closure $resolver): void
{ {
if ($config['driver'] == 'database') { app('cart.manager')->extend($name, fn($app) => $resolver($app['session']->getId(), config('cart')));
if (! isset($config['storage']['database']['model'])) { }
throw new \Exception('You need to set a model for the database driver in the cart configuration.');
}
if (! isset($config['storage']['database']['id'])) { public function getDriver(): CartDriver
throw new \Exception('You need to set an id (for the session) for the database driver in the cart configuration.'); {
} return $this->driver;
if (! isset($config['storage']['database']['items'])) {
throw new \Exception('You need to set an items key for the database driver in the cart configuration.');
}
if (! isset($config['storage']['database']['conditions'])) {
throw new \Exception('You need to set a conditions key for the database driver in the cart configuration.');
}
}
} }
public function getSessionKey(): string public function getSessionKey(): string
{ {
return $this->session->getSessionKey(); return $this->driver->getSessionKey();
} }
public function setSessionKey(string $sessionKey): void public function setSessionKey(string $sessionKey): void
{ {
$this->session->setSessionKey($sessionKey); $this->driver->setSessionKey($sessionKey);
} }
/** public function getInstanceName(): string
* get instance name of the cart
*
* @return string
*/
public function getInstanceName()
{ {
return $this->instanceName; return $this->instanceName;
} }
/**
* get an item on a cart by item ID
*/
public function get($itemId): ?ItemCollection public function get($itemId): ?ItemCollection
{ {
return $this->getContent()->get($itemId); return $this->getContent()->get($itemId);
} }
/**
* check if we have this item in the cart by item ID
*/
public function has($itemId): bool public function has($itemId): bool
{ {
return $this->getContent()->has($itemId); return $this->getContent()->has($itemId);
} }
/**
* add item to the cart, it can be an array or multi dimensional array
*
* @param string|array $id
* @return $this
*
* @throws InvalidItemException
*/
public function add( public function add(
string|int|array $id, string|int|array $id,
?string $name = null, ?string $name = null,
@@ -109,15 +79,13 @@ public function add(
array|CartCondition $conditions = [], array|CartCondition $conditions = [],
?string $associatedModel = null ?string $associatedModel = null
): self { ): self {
// check if we are adding an array of items
if (is_array($id)) { if (is_array($id)) {
// check if we are adding a multi dimensional array
if (Helpers::isMultiArray($id)) { if (Helpers::isMultiArray($id)) {
foreach ($id as $item) { foreach ($id as $item) {
$this->add( $this->add(
$item['id'], $item['id'],
$item['name'], $item['name'],
isset($item['price']) ? $item['price'] : null, $item['price'] ?? null,
$item['quantity'], $item['quantity'],
Helpers::issetAndHasValueOrAssignDefault($item['attributes'], []), Helpers::issetAndHasValueOrAssignDefault($item['attributes'], []),
Helpers::issetAndHasValueOrAssignDefault($item['conditions'], []), Helpers::issetAndHasValueOrAssignDefault($item['conditions'], []),
@@ -128,7 +96,7 @@ public function add(
$this->add( $this->add(
$id['id'], $id['id'],
$id['name'], $id['name'],
isset($id['price']) ? $id['price'] : null, $id['price'] ?? null,
$id['quantity'], $id['quantity'],
Helpers::issetAndHasValueOrAssignDefault($id['attributes'], []), Helpers::issetAndHasValueOrAssignDefault($id['attributes'], []),
Helpers::issetAndHasValueOrAssignDefault($id['conditions'], []), Helpers::issetAndHasValueOrAssignDefault($id['conditions'], []),
@@ -139,24 +107,21 @@ public function add(
return $this; return $this;
} }
// if we are here, we are adding a single item
$data = [ $data = [
'id' => $id, 'id' => $id,
'name' => $name, 'name' => $name,
'price' => Helpers::normalizePrice($price), 'price' => Helpers::normalizePrice($price),
'quantity' => $quantity, 'quantity' => $quantity,
'attributes' => new ItemAttributeCollection($attributes), 'attributes' => new ItemAttributeCollection($attributes),
'conditions' => $conditions, 'conditions' => $conditions,
]; ];
if (isset($associatedModel) && $associatedModel != '') { if (isset($associatedModel) && $associatedModel !== '') {
$data['associatedModel'] = $associatedModel; $data['associatedModel'] = $associatedModel;
} }
// validate data
$item = $this->validate($data); $item = $this->validate($data);
// if the item is already in the cart we will just update it
if ($this->get($id)) { if ($this->get($id)) {
$this->update($id, $item); $this->update($id, $item);
} else { } else {
@@ -164,25 +129,15 @@ public function add(
} }
$this->currentItemId = $id; $this->currentItemId = $id;
// clean up any incomplete items
$this->removeInvalidItems(); $this->removeInvalidItems();
return $this; return $this;
} }
/**
* Remove any incomplete items
*/
public function removeInvalidItems(): bool public function removeInvalidItems(): bool
{ {
$carts = $this->getContent(); foreach ($this->getContent() as $index => $cart) {
if (! isset($cart['id'], $cart['name'], $cart['quantity'])) {
foreach ($carts as $index => $cart) {
if (! (isset($cart['id'], $cart['name'], $cart['quantity']))) {
// remove item
$this->remove($index); $this->remove($index);
} }
} }
@@ -190,9 +145,6 @@ public function removeInvalidItems(): bool
return true; return true;
} }
/**
* Update a cart item with whatever data is passed in
*/
public function update(int|string $id, array $data): bool public function update(int|string $id, array $data): bool
{ {
if ($this->fireEvent('Updating', 'item', $data) === false) { if ($this->fireEvent('Updating', 'item', $data) === false) {
@@ -200,67 +152,44 @@ public function update(int|string $id, array $data): bool
} }
$cart = $this->getContent(); $cart = $this->getContent();
$item = $cart->get($id); $item = $cart->get($id);
foreach ($data as $key => $value) { foreach ($data as $key => $value) {
if ($key == 'quantity') { if ($key === 'quantity') {
if (is_array($value)) { if (is_array($value)) {
if (isset($value['relative'])) { if (isset($value['relative']) && $value['relative'] === true) {
if (isset($value['relative']) && $value['relative'] === true) { $item = $this->updateQuantityRelative($item, $key, $value['value']);
$item = $this->updateQuantityRelative($item, $key, $value['value']); } else {
} else { $item = $this->updateQuantityNotRelative($item, $key, $value['value']);
$item = $this->updateQuantityNotRelative($item, $key, $value['value']);
}
} }
} else { } else {
$item = $this->updateQuantityRelative($item, $key, $value); $item = $this->updateQuantityRelative($item, $key, $value);
} }
} elseif ($key == 'attributes') { } elseif ($key === 'attributes') {
$item[$key] = new ItemAttributeCollection($value); $item[$key] = new ItemAttributeCollection($value);
} else { } else {
$item[$key] = $value; $item[$key] = $value;
} }
} }
// update the item in the cart
$cart->put($id, $item); $cart->put($id, $item);
$this->save($cart); $this->save($cart);
$this->fireEvent('Updated', 'item', $item); $this->fireEvent('Updated', 'item', $item);
return true; return true;
} }
/** public function setConfig(array $config): void
* Set the config
*
* @param array $config
* @return void
*/
public function setConfig($config)
{ {
$this->config = $config; $this->config = $config;
} }
/** public function addItemCondition($productId, $itemCondition): self
* add condition on an existing item on the cart
*
* @param int|string $productId
* @param CartCondition $itemCondition
* @return $this
*/
public function addItemCondition($productId, $itemCondition)
{ {
if ($product = $this->get($productId)) { if ($product = $this->get($productId)) {
$conditionInstance = '\\Wearepixel\\Cart\\CartCondition'; $conditionInstance = CartCondition::class;
if ($itemCondition instanceof $conditionInstance) { if ($itemCondition instanceof $conditionInstance) {
// we need to copy first to a temporary variable to hold the conditions
// to avoid hitting this error "Indirect modification of overloaded element of Wearepixel\Cart\ItemCollection has no effect"
// this is due to laravel Collection instance that implements Array Access
// // see link for more info: http://stackoverflow.com/questions/20053269/indirect-modification-of-overloaded-element-of-splfixedarray-has-no-effect
$itemConditionTempHolder = $product['conditions']; $itemConditionTempHolder = $product['conditions'];
if (is_array($itemConditionTempHolder)) { if (is_array($itemConditionTempHolder)) {
@@ -269,21 +198,14 @@ public function addItemCondition($productId, $itemCondition)
$itemConditionTempHolder = $itemCondition; $itemConditionTempHolder = $itemCondition;
} }
$this->update($productId, [ $this->update($productId, ['conditions' => $itemConditionTempHolder]);
'conditions' => $itemConditionTempHolder, // the newly updated conditions
]);
} }
} }
return $this; return $this;
} }
/** public function remove($id): bool
* removes an item on cart by item ID
*
* @return bool
*/
public function remove($id)
{ {
$cart = $this->getContent(); $cart = $this->getContent();
@@ -292,48 +214,36 @@ public function remove($id)
} }
$cart->forget($id); $cart->forget($id);
$this->save($cart); $this->save($cart);
$this->fireEvent('Removed', 'item', $id); $this->fireEvent('Removed', 'item', $id);
return true; return true;
} }
public function clear() public function clear(): bool
{ {
if ($this->fireEvent('Clearing') === false) { if ($this->fireEvent('Clearing') === false) {
return false; return false;
} }
$this->session->clear(); $this->driver->flush();
$this->fireEvent('Cleared'); $this->fireEvent('Cleared');
return true; return true;
} }
public function clearItems() public function clearItems(): bool
{ {
if ($this->fireEvent('Clearing') === false) { if ($this->fireEvent('Clearing') === false) {
return false; return false;
} }
$this->session->clearItems(); $this->driver->clearItems();
$this->fireEvent('Cleared'); $this->fireEvent('Cleared');
return true; return true;
} }
/**
* Adds a condition to the cart
*/
/**
* Adds a condition to the cart
*
* @throws InvalidConditionException
*/
public function condition(array|CartCondition $condition): self public function condition(array|CartCondition $condition): self
{ {
if (is_array($condition)) { if (is_array($condition)) {
@@ -350,309 +260,184 @@ public function condition(array|CartCondition $condition): self
$conditions = $this->getConditions(); $conditions = $this->getConditions();
// Check if order has been applied if ($condition->getOrder() === 0) {
if ($condition->getOrder() == 0) {
$last = $conditions->last(); $last = $conditions->last();
$condition->setOrder(! is_null($last) ? $last->getOrder() + 1 : 1); $condition->setOrder(! is_null($last) ? $last->getOrder() + 1 : 1);
} }
$conditions->put($condition->getName(), $condition); $conditions->put($condition->getName(), $condition);
$conditions = $conditions->reject(function ($condition) { $conditions = $conditions->reject(fn($c) => empty($c))
return empty($condition); ->sortBy(fn($c) => $c->getOrder());
})->sortBy(function ($condition, $key) {
return $condition->getOrder();
});
$this->saveConditions($conditions); $this->saveConditions($conditions);
return $this; return $this;
} }
/**
* get conditions applied on the cart
*
* @param bool $active - If true, only conditions actually applied on the cart are returned
*/
public function getConditions(bool $array = false, bool $active = false): CartConditionCollection|array public function getConditions(bool $array = false, bool $active = false): CartConditionCollection|array
{ {
$conditions = new CartConditionCollection($this->session->getConditions()); $conditions = new CartConditionCollection($this->driver->getConditions());
$conditions = $conditions->reject(function ($condition) { $conditions = $conditions->reject(fn($c) => empty($c))
return empty($condition); ->transform(fn($c) => $c instanceof CartCondition ? $c : new CartCondition($c));
})
->transform(function ($condition) {
return $condition instanceof CartCondition ? $condition : new CartCondition($condition);
});
if ($active) { if ($active) {
return $conditions->filter(function (CartCondition $condition) { return $conditions
$amount = $condition->getTarget() == 'subtotal' ? $this->getSubTotal(false) : $this->getTotal(); ->filter(function (CartCondition $condition) {
$amount = $condition->getTarget() === 'subtotal' ? $this->getSubTotal(false) : $this->getTotal();
return $condition->getMinimum() === null || $condition->getMinimum() <= $amount; return $condition->getMinimum() === null || $condition->getMinimum() <= $amount;
})->filter(function (CartCondition $condition) { })
$amount = $condition->getTarget() == 'subtotal' ? $this->getSubTotal(false) : $this->getTotal(); ->filter(function (CartCondition $condition) {
$amount = $condition->getTarget() === 'subtotal' ? $this->getSubTotal(false) : $this->getTotal();
return $condition->getMaximum() === null || $condition->getMaximum() >= $amount; return $condition->getMaximum() === null || $condition->getMaximum() >= $amount;
}); });
} }
return $array ? $conditions->map(function (CartCondition $condition) { return $array
return $condition->toArray(); ? $conditions->map(fn(CartCondition $c) => $c->toArray())->toArray()
})->toArray() : $conditions; : $conditions;
} }
/** public function getCondition($conditionName): ?CartCondition
* get condition applied on the cart by its name
*
* @return CartCondition
*/
public function getCondition($conditionName)
{ {
return $this->getConditions()->get($conditionName); return $this->getConditions()->get($conditionName);
} }
/** public function getConditionsByType(string $type): CartConditionCollection
* Get all the condition filtered by Type
* Please Note that this will only return condition added on cart bases, not those conditions added
* specifically on an per item bases
*
* @return CartConditionCollection
*/
public function getConditionsByType($type)
{ {
return $this->getConditions()->filter(function (CartCondition $condition) use ($type) { return $this->getConditions()->filter(fn(CartCondition $c) => $c->getType() === $type);
return $condition->getType() == $type;
});
} }
/** public function removeConditionsByType(string $type): void
* Remove all the condition with the $type specified
*/
public function removeConditionsByType(string $type)
{ {
$this->getConditionsByType($type)->each(function ($condition) { $this->getConditionsByType($type)->each(fn($c) => $this->removeCartCondition($c->getName()));
$this->removeCartCondition($condition->getName());
});
} }
/** public function removeCartCondition($conditionName): void
* Remove a condition from the cart
*/
public function removeCartCondition($conditionName)
{ {
$conditions = $this->getConditions(); $conditions = $this->getConditions();
$conditions->pull($conditionName); $conditions->pull($conditionName);
$this->saveConditions($conditions); $this->saveConditions($conditions);
} }
/** public function removeItemCondition($itemId, $conditionName): bool
* remove a condition that has been applied on an item that is already on the cart
*
* @return bool
*/
public function removeItemCondition($itemId, $conditionName)
{ {
if (! $item = $this->getContent()->get($itemId)) { if (! $item = $this->getContent()->get($itemId)) {
return false; return false;
} }
if ($this->itemHasConditions($item)) { if ($this->itemHasConditions($item)) {
// NOTE:
// we do it this way, we get first conditions and store
// it in a temp variable $originalConditions, then we will modify the array there
// and after modification we will store it again on $item['conditions']
// This is because of ArrayAccess implementation
// see link for more info: http://stackoverflow.com/questions/20053269/indirect-modification-of-overloaded-element-of-splfixedarray-has-no-effect
$tempConditionsHolder = $item['conditions']; $tempConditionsHolder = $item['conditions'];
// if the item's conditions is in array format
// we will iterate through all of it and check if the name matches
// to the given name the user wants to remove, if so, remove it
if (is_array($tempConditionsHolder)) { if (is_array($tempConditionsHolder)) {
foreach ($tempConditionsHolder as $k => $condition) { foreach ($tempConditionsHolder as $k => $condition) {
if ($condition->getName() == $conditionName) { if ($condition->getName() === $conditionName) {
unset($tempConditionsHolder[$k]); unset($tempConditionsHolder[$k]);
} }
} }
$item['conditions'] = $tempConditionsHolder; $item['conditions'] = $tempConditionsHolder;
} } else {
if ($item['conditions'] instanceof CartCondition) {
// if the item condition is not an array, we will check if it is if ($tempConditionsHolder->getName() === $conditionName) {
// an instance of a Condition, if so, we will check if the name matches
// on the given condition name the user wants to remove, if so,
// lets just make $item['conditions'] an empty array as there's just 1 condition on it anyway
else {
$conditionInstance = 'Wearepixel\\Cart\\CartCondition';
if ($item['conditions'] instanceof $conditionInstance) {
if ($tempConditionsHolder->getName() == $conditionName) {
$item['conditions'] = []; $item['conditions'] = [];
} }
} }
} }
} }
$this->update($itemId, [ $this->update($itemId, ['conditions' => $item['conditions']]);
'conditions' => $item['conditions'],
]);
return true; return true;
} }
/** public function clearItemConditions($itemId): bool
* remove all conditions that has been applied on an item that is already on the cart
*
* @return bool
*/
public function clearItemConditions($itemId)
{ {
if (! $item = $this->getContent()->get($itemId)) { if (! $this->getContent()->get($itemId)) {
return false; return false;
} }
$this->update($itemId, [ $this->update($itemId, ['conditions' => []]);
'conditions' => [],
]);
return true; return true;
} }
/**
* Clear cart conditions (this does not clear item conditions)
*/
public function clearCartConditions(): void public function clearCartConditions(): void
{ {
$this->session->putConditions([]); $this->driver->putConditions([]);
} }
/**
* Clear all conditions from all items and the cart
*/
public function clearAllConditions(): void public function clearAllConditions(): void
{ {
$cart = $this->getContent(); $this->getContent()->each(fn($item) => $this->clearItemConditions($item->id));
$cart->each(function ($item) {
$this->clearItemConditions($item->id);
});
$this->clearCartConditions(); $this->clearCartConditions();
} }
/** public function getSubTotalWithoutConditions(bool $formatted = true): int|float|string
* get cart sub total without conditions
*
* @param bool $formatted
* @return float
*/
public function getSubTotalWithoutConditions($formatted = true)
{ {
$cart = $this->getContent(); $sum = $this->getContent()->sum(fn($item) => $item->getPriceSum());
$sum = $cart->sum(function ($item) {
return $item->getPriceSum();
});
return Helpers::formatValue(floatval($sum), $formatted, $this->config); return Helpers::formatValue(floatval($sum), $formatted, $this->config);
} }
public function getSubTotal($formatted = true): int|float|string public function getSubTotal(bool $formatted = true): int|float|string
{ {
$subTotal = 0.00; $subTotal = 0.00;
// add all the items together with conditions applied $subTotalSum = $this->getContent()->sum(fn(ItemCollection $item) => $item->getPriceSumWithConditions(false));
$subTotalSum = $this->getContent()->sum(function (ItemCollection $item) {
return $item->getPriceSumWithConditions(false);
});
// get the conditions that are meant to be applied
// on the subtotal and apply it here before returning the subtotal
$conditionsForSubtotal = $this->getConditions() $conditionsForSubtotal = $this->getConditions()
->filter(function (CartCondition $condition) { ->filter(fn(CartCondition $c) => $c->getTarget() === 'subtotal')
return $condition->getTarget() === 'subtotal'; ->filter(fn(CartCondition $c) => $c->getMinimum() === null || $c->getMinimum() <= $subTotalSum)
}) ->filter(fn(CartCondition $c) => $c->getMaximum() === null || $c->getMaximum() >= $subTotalSum)
->filter(function (CartCondition $condition) use ($subTotalSum) { ->sortBy(fn(CartCondition $c) => $c->getOrder());
return $condition->getMinimum() === null || $condition->getMinimum() <= $subTotalSum;
})
->filter(function (CartCondition $condition) use ($subTotalSum) {
return $condition->getMaximum() === null || $condition->getMaximum() >= $subTotalSum;
})
->sortBy(function (CartCondition $condition) {
return $condition->getOrder();
});
if ($conditionsForSubtotal->isEmpty()) { if ($conditionsForSubtotal->isEmpty()) {
return Helpers::formatValue($subTotalSum, $formatted, $this->config); return Helpers::formatValue($subTotalSum, $formatted, $this->config);
} }
$index = 0; $index = 0;
$conditionsForSubtotal->each(function (CartCondition $condition) use ($subTotalSum, &$subTotal, &$index) { $conditionsForSubtotal->each(function (CartCondition $condition) use ($subTotalSum, &$subTotal, &$index) {
$toBeCalculated = $index > 0 ? $subTotal : $subTotalSum; $toBeCalculated = $index > 0 ? $subTotal : $subTotalSum;
$subTotal = $condition->applyCondition($toBeCalculated); $subTotal = $condition->applyCondition($toBeCalculated);
$index++; $index++;
}); });
return Helpers::formatValue($subTotal, $formatted, $this->config); return Helpers::formatValue($subTotal, $formatted, $this->config);
} }
/**
* Get the total of the cart with conditions applied
*/
public function getTotal(): int|float public function getTotal(): int|float
{ {
$total = 0.00; $total = 0.00;
$subTotal = $this->getSubTotal(false); $subTotal = $this->getSubTotal(false);
$conditionsForTotal = $this->getConditions() $conditionsForTotal = $this->getConditions()
->filter(function (CartCondition $condition) { ->filter(fn(CartCondition $c) => $c->getTarget() === 'total')
return $condition->getTarget() === 'total'; ->filter(fn(CartCondition $c) => $c->getMinimum() === null || $c->getMinimum() <= $subTotal)
}) ->filter(fn(CartCondition $c) => $c->getMaximum() === null || $c->getMaximum() >= $subTotal)
->filter(function (CartCondition $condition) use ($subTotal) { ->sortBy(fn(CartCondition $c) => $c->getOrder());
return $condition->getMinimum() === null || $condition->getMinimum() <= $subTotal;
})
->filter(function (CartCondition $condition) use ($subTotal) {
return $condition->getMaximum() === null || $condition->getMaximum() >= $subTotal;
})
->sortBy(function (CartCondition $condition) {
return $condition->getOrder();
});
// if no conditions were added, just return the sub total
if (! $conditionsForTotal->count()) { if (! $conditionsForTotal->count()) {
return Helpers::formatValue($subTotal, $this->config['format_numbers'], $this->config); return Helpers::formatValue($subTotal, $this->config['format_numbers'], $this->config);
} }
$index = 0; $index = 0;
$conditionsForTotal->each(function (CartCondition $condition) use ($subTotal, &$total, &$index) { $conditionsForTotal->each(function (CartCondition $condition) use ($subTotal, &$total, &$index) {
$toBeCalculated = ($index > 0) ? $total : $subTotal; $toBeCalculated = $index > 0 ? $total : $subTotal;
$total = $condition->applyCondition($toBeCalculated); $total = $condition->applyCondition($toBeCalculated);
$index++; $index++;
}); });
return Helpers::formatValue($total, $this->config['format_numbers'], $this->config); return Helpers::formatValue($total, $this->config['format_numbers'], $this->config);
} }
/**
* Get the calculated value for a condition by it's name
*/
public function getCalculatedValueForCondition(string $conditionName): int|float public function getCalculatedValueForCondition(string $conditionName): int|float
{ {
$conditions = $this->getConditions();
$subTotal = $this->getSubTotalWithoutConditions(false); $subTotal = $this->getSubTotalWithoutConditions(false);
foreach ($conditions as $condition) { foreach ($this->getConditions() as $condition) {
$conditionValue = $condition->getCalculatedValue($subTotal); $conditionValue = $condition->getCalculatedValue($subTotal);
if ($condition->getName() === $conditionName) { if ($condition->getName() === $conditionName) {
@@ -665,12 +450,7 @@ public function getCalculatedValueForCondition(string $conditionName): int|float
return 0; return 0;
} }
/** public function getTotalQuantity(): int|float
* get total quantity of items in the cart
*
* @return int
*/
public function getTotalQuantity()
{ {
$items = $this->getContent(); $items = $this->getContent();
@@ -678,39 +458,41 @@ public function getTotalQuantity()
return 0; return 0;
} }
$count = $items->sum(function ($item) { return $items->sum(fn($item) => $item['quantity']);
return $item['quantity'];
});
return $count;
} }
public function getContent(): CartCollection public function getContent(): CartCollection
{ {
return (new CartCollection($this->session->getItems()))->transform(function ($item) { return (new CartCollection($this->driver->getItems()))
return $item instanceof ItemCollection ? $item : new ItemCollection($item, $this->config); ->transform(fn($item) => $item instanceof ItemCollection ? $item : new ItemCollection($item, $this->config))
})->reject(function ($item) { ->reject(fn($item) => ! ($item instanceof ItemCollection));
return ! ($item instanceof ItemCollection);
});
} }
public function isEmpty($test = null) public function isEmpty(): bool
{ {
return $this->getContent()->isEmpty(); return $this->getContent()->isEmpty();
} }
/** public function associate(mixed $model): self
* validate Item data {
* if (is_string($model) && ! class_exists($model)) {
* @return array $item; throw new UnknownModelException("The supplied model {$model} does not exist.");
* }
* @throws InvalidItemException
*/ $cart = $this->getContent();
protected function validate($item) $item = $cart->pull($this->currentItemId);
$item['associatedModel'] = $model;
$cart->put($this->currentItemId, new ItemCollection($item, $this->config));
$this->save($cart);
return $this;
}
protected function validate(array $item): array
{ {
$rules = [ $rules = [
'id' => 'required', 'id' => 'required',
'name' => 'required', 'name' => 'required',
'quantity' => 'required|numeric|min:0.1', 'quantity' => 'required|numeric|min:0.1',
]; ];
@@ -720,11 +502,9 @@ protected function validate($item)
if ($validator->errors()->first('id') === 'validation.required') { if ($validator->errors()->first('id') === 'validation.required') {
throw new InvalidItemException('The id field is required.'); throw new InvalidItemException('The id field is required.');
} }
if ($validator->errors()->first('name') === 'validation.required') { if ($validator->errors()->first('name') === 'validation.required') {
throw new InvalidItemException('The name field is required.'); throw new InvalidItemException('The name field is required.');
} }
if ($validator->errors()->first('quantity') === 'validation.min.numeric') { if ($validator->errors()->first('quantity') === 'validation.min.numeric') {
throw new InvalidItemException('The quantity must be at least 0.1.'); throw new InvalidItemException('The quantity must be at least 0.1.');
} }
@@ -733,52 +513,62 @@ protected function validate($item)
return $item; return $item;
} }
/** protected function addItem(int|string $id, array $item): bool
* add row to cart collection
*
* @return bool
*/
protected function addItem($id, $item)
{ {
if ($this->fireEvent('Adding', 'item', $item) === false) { if ($this->fireEvent('Adding', 'item', $item) === false) {
return false; return false;
} }
$cart = $this->getContent(); $cart = $this->getContent();
$cart->put($id, new ItemCollection($item, $this->config)); $cart->put($id, new ItemCollection($item, $this->config));
$this->save($cart); $this->save($cart);
$this->fireEvent('Added', 'item', $item); $this->fireEvent('Added', 'item', $item);
return true; return true;
} }
/** protected function save(CartCollection $cart): void
* save the cart
*
* @param $cart CartCollection
*/
protected function save($cart)
{ {
$this->session->putItems($cart); $this->driver->putItems($this->serializeItems($cart));
} }
/** protected function saveConditions(CartConditionCollection $conditions): void
* save the cart conditions
*/
protected function saveConditions($conditions)
{ {
$this->session->putConditions($conditions); $this->driver->putConditions($this->serializeConditions($conditions));
} }
/** private function serializeItems(CartCollection $cart): array
* check if an item has condition {
* return $cart->map(function (ItemCollection $item) {
* @return bool $data = $item->toArray();
*/
protected function itemHasConditions($item) $conditions = $item['conditions'] ?? [];
if ($conditions instanceof CartCondition) {
$data['conditions'] = [$conditions->toArray()];
} elseif (is_array($conditions) || $conditions instanceof \Traversable) {
$data['conditions'] = collect($conditions)
->map(fn($c) => $c instanceof CartCondition ? $c->toArray() : $c)
->values()
->toArray();
} else {
$data['conditions'] = [];
}
if ($item['attributes'] instanceof ItemAttributeCollection) {
$data['attributes'] = $item['attributes']->toArray();
}
return $data;
})->toArray();
}
private function serializeConditions(CartConditionCollection $conditions): array
{
return $conditions->map(fn(CartCondition $c) => $c->toArray())->toArray();
}
protected function itemHasConditions(ItemCollection $item): bool
{ {
if (! isset($item['conditions'])) { if (! isset($item['conditions'])) {
return false; return false;
@@ -788,31 +578,17 @@ protected function itemHasConditions($item)
return count($item['conditions']) > 0; return count($item['conditions']) > 0;
} }
$conditionInstance = 'Wearepixel\\Cart\\CartCondition'; return $item['conditions'] instanceof CartCondition;
if ($item['conditions'] instanceof $conditionInstance) {
return true;
}
return false;
} }
/** protected function updateQuantityRelative(ItemCollection $item, string $key, mixed $value): ItemCollection
* update a cart item quantity relative to its current quantity
*
* @return mixed
*/
protected function updateQuantityRelative($item, $key, $value)
{ {
if (preg_match('/\-/', $value) == 1) { if (preg_match('/\-/', $value) === 1) {
$value = (float) str_replace('-', '', $value); $value = (float) str_replace('-', '', $value);
// we will not allowed to reduced quantity to 0, so if the given value
// would result to item quantity of 0, we will not do it.
if (($item[$key] - $value) > 0) { if (($item[$key] - $value) > 0) {
$item[$key] -= $value; $item[$key] -= $value;
} }
} elseif (preg_match('/\+/', $value) == 1) { } elseif (preg_match('/\+/', $value) === 1) {
$item[$key] += (float) str_replace('+', '', $value); $item[$key] += (float) str_replace('+', '', $value);
} else { } else {
$item[$key] += (float) $value; $item[$key] += (float) $value;
@@ -821,32 +597,19 @@ protected function updateQuantityRelative($item, $key, $value)
return $item; return $item;
} }
/** protected function updateQuantityNotRelative(ItemCollection $item, string $key, mixed $value): ItemCollection
* update cart item quantity not relative to its current quantity value
*
* @return mixed
*/
protected function updateQuantityNotRelative($item, $key, $value)
{ {
$item[$key] = (float) $value; $item[$key] = (float) $value;
return $item; return $item;
} }
/** protected function fireEvent(string $name, ?string $type = null, mixed $data = null): mixed
* Setter for decimals. Change value on demand.
*/
public function setDecimals($decimals)
{
$this->decimals = $decimals;
}
protected function fireEvent($name, $type = null, $data = null)
{ {
$eventData = [ $eventData = [
'session_key' => $this->session->sessionKey, 'session_key' => $this->driver->getSessionKey(),
'session_driver' => $this->session->driver, 'session_driver' => $this->driver->getDriverName(),
'session_model' => $this->session->getSessionModel(), 'session_model' => $this->driver->getSessionModel(),
]; ];
if ($type) { if ($type) {
@@ -855,30 +618,4 @@ protected function fireEvent($name, $type = null, $data = null)
return $this->events->dispatch('LaravelCart.' . $name, array_values([$eventData, $this]), true); return $this->events->dispatch('LaravelCart.' . $name, array_values([$eventData, $this]), true);
} }
/**
* Associate the cart item with the given id with the given model.
*
* @param string $id
* @param mixed $model
* @return void
*/
public function associate($model)
{
if (is_string($model) && ! class_exists($model)) {
throw new UnknownModelException("The supplied model {$model} does not exist.");
}
$cart = $this->getContent();
$item = $cart->pull($this->currentItemId);
$item['associatedModel'] = $model;
$cart->put($this->currentItemId, new ItemCollection($item, $this->config));
$this->save($cart);
return $this;
}
} }