mirror of
https://github.com/wearepixel/laravel-cart.git
synced 2026-11-14 13:51:44 +00:00
init commit :rocket
This commit is contained in:
+856
@@ -0,0 +1,856 @@
|
||||
<?php
|
||||
|
||||
namespace Wearepixel\Cart;
|
||||
|
||||
use Wearepixel\Cart\Helpers\Helpers;
|
||||
use Wearepixel\Cart\Validators\CartItemValidator;
|
||||
use Wearepixel\Cart\Exceptions\InvalidItemException;
|
||||
use Wearepixel\Cart\Exceptions\UnknownModelException;
|
||||
use Wearepixel\Cart\Exceptions\InvalidConditionException;
|
||||
|
||||
class Cart
|
||||
{
|
||||
/**
|
||||
* the item storage
|
||||
*/
|
||||
protected $session;
|
||||
|
||||
/**
|
||||
* the event dispatcher
|
||||
*/
|
||||
protected $events;
|
||||
|
||||
/**
|
||||
* the cart session key
|
||||
*/
|
||||
protected $instanceName;
|
||||
|
||||
/**
|
||||
* the session key use for the cart
|
||||
*/
|
||||
protected $sessionKey;
|
||||
|
||||
/**
|
||||
* the session key use to persist cart items
|
||||
*/
|
||||
protected $sessionKeyCartItems;
|
||||
|
||||
/**
|
||||
* the session key use to persist cart conditions
|
||||
*/
|
||||
protected $sessionKeyCartConditions;
|
||||
|
||||
/**
|
||||
* Configuration to pass to ItemCollection
|
||||
*/
|
||||
protected $config;
|
||||
|
||||
/**
|
||||
* This holds the currently added item id in cart for association
|
||||
*/
|
||||
protected $currentItemId;
|
||||
|
||||
/**
|
||||
* The number of decimals to use when formatting prices
|
||||
*/
|
||||
protected $decimals;
|
||||
|
||||
/**
|
||||
* The decimal point character
|
||||
*/
|
||||
protected $decPoint;
|
||||
|
||||
/**
|
||||
* our object constructor
|
||||
*/
|
||||
public function __construct($session, $events, $instanceName, $session_key, $config)
|
||||
{
|
||||
$this->events = $events;
|
||||
$this->session = $session;
|
||||
$this->instanceName = $instanceName;
|
||||
$this->sessionKey = $session_key;
|
||||
$this->sessionKeyCartItems = $this->sessionKey . '_cart_items';
|
||||
$this->sessionKeyCartConditions = $this->sessionKey . '_cart_conditions';
|
||||
$this->config = $config;
|
||||
$this->currentItemId = null;
|
||||
$this->fireEvent('created');
|
||||
}
|
||||
|
||||
/**
|
||||
* sets the session key
|
||||
*
|
||||
* @param string $sessionKey the session key or identifier
|
||||
* @return $this|bool
|
||||
*
|
||||
* @throws \Exception
|
||||
*/
|
||||
public function session($sessionKey)
|
||||
{
|
||||
if (! $sessionKey) {
|
||||
throw new \Exception('Session key is required.');
|
||||
}
|
||||
|
||||
$this->sessionKey = $sessionKey;
|
||||
$this->sessionKeyCartItems = $this->sessionKey . '_cart_items';
|
||||
$this->sessionKeyCartConditions = $this->sessionKey . '_cart_conditions';
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* get instance name of the cart
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
public function getInstanceName()
|
||||
{
|
||||
return $this->instanceName;
|
||||
}
|
||||
|
||||
/**
|
||||
* get an item on a cart by item ID
|
||||
*
|
||||
* @return mixed
|
||||
*/
|
||||
public function get($itemId)
|
||||
{
|
||||
return $this->getContent()->get($itemId);
|
||||
}
|
||||
|
||||
/**
|
||||
* check if an item exists by item ID
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
public function 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
|
||||
* @param string $name
|
||||
* @param float $price
|
||||
* @param int $quantity
|
||||
* @param array $attributes
|
||||
* @param CartCondition|array $conditions
|
||||
* @param string $associatedModel
|
||||
* @return $this
|
||||
*
|
||||
* @throws InvalidItemException
|
||||
*/
|
||||
public function add($id, $name = null, $price = null, $quantity = null, $attributes = [], $conditions = [], $associatedModel = null)
|
||||
{
|
||||
// if the first argument is an array,
|
||||
// we will need to call add again
|
||||
if (is_array($id)) {
|
||||
// the first argument is an array, now we will need to check if it is a multi dimensional
|
||||
// array, if so, we will iterate through each item and call add again
|
||||
if (Helpers::isMultiArray($id)) {
|
||||
foreach ($id as $item) {
|
||||
$this->add(
|
||||
$item['id'],
|
||||
$item['name'],
|
||||
$item['price'],
|
||||
$item['quantity'],
|
||||
Helpers::issetAndHasValueOrAssignDefault($item['attributes'], []),
|
||||
Helpers::issetAndHasValueOrAssignDefault($item['conditions'], []),
|
||||
Helpers::issetAndHasValueOrAssignDefault($item['associatedModel'], null)
|
||||
);
|
||||
}
|
||||
} else {
|
||||
$this->add(
|
||||
$id['id'],
|
||||
$id['name'],
|
||||
$id['price'],
|
||||
$id['quantity'],
|
||||
Helpers::issetAndHasValueOrAssignDefault($id['attributes'], []),
|
||||
Helpers::issetAndHasValueOrAssignDefault($id['conditions'], []),
|
||||
Helpers::issetAndHasValueOrAssignDefault($id['associatedModel'], null)
|
||||
);
|
||||
}
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
$data = [
|
||||
'id' => $id,
|
||||
'name' => $name,
|
||||
'price' => Helpers::normalizePrice($price),
|
||||
'quantity' => $quantity,
|
||||
'attributes' => new ItemAttributeCollection($attributes),
|
||||
'conditions' => $conditions,
|
||||
];
|
||||
|
||||
if (isset($associatedModel) && $associatedModel != '') {
|
||||
$data['associatedModel'] = $associatedModel;
|
||||
}
|
||||
|
||||
// validate data
|
||||
$item = $this->validate($data);
|
||||
|
||||
// get the cart
|
||||
$cart = $this->getContent();
|
||||
|
||||
// if the item is already in the cart we will just update it
|
||||
if ($cart->has($id)) {
|
||||
|
||||
$this->update($id, $item);
|
||||
} else {
|
||||
|
||||
$this->addRow($id, $item);
|
||||
}
|
||||
|
||||
$this->currentItemId = $id;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* update a cart
|
||||
*
|
||||
* @param array $data
|
||||
*
|
||||
* the $data will be an associative array, you don't need to pass all the data, only the key value
|
||||
* of the item you want to update on it
|
||||
* @return bool
|
||||
*/
|
||||
public function update($id, $data)
|
||||
{
|
||||
if ($this->fireEvent('updating', $data) === false) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$cart = $this->getContent();
|
||||
|
||||
$item = $cart->pull($id);
|
||||
|
||||
foreach ($data as $key => $value) {
|
||||
// if the key is currently "quantity" we will need to check if an arithmetic
|
||||
// symbol is present so we can decide if the update of quantity is being added
|
||||
// or being reduced.
|
||||
if ($key == 'quantity') {
|
||||
// we will check if quantity value provided is array,
|
||||
// if it is, we will need to check if a key "relative" is set
|
||||
// and we will evaluate its value if true or false,
|
||||
// this tells us how to treat the quantity value if it should be updated
|
||||
// relatively to its current quantity value or just totally replace the value
|
||||
if (is_array($value)) {
|
||||
if (isset($value['relative'])) {
|
||||
if ((bool) $value['relative']) {
|
||||
$item = $this->updateQuantityRelative($item, $key, $value['value']);
|
||||
} else {
|
||||
$item = $this->updateQuantityNotRelative($item, $key, $value['value']);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
$item = $this->updateQuantityRelative($item, $key, $value);
|
||||
}
|
||||
} elseif ($key == 'attributes') {
|
||||
$item[$key] = new ItemAttributeCollection($value);
|
||||
} else {
|
||||
$item[$key] = $value;
|
||||
}
|
||||
}
|
||||
|
||||
$cart->put($id, $item);
|
||||
|
||||
$this->save($cart);
|
||||
|
||||
$this->fireEvent('updated', $item);
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the config
|
||||
*
|
||||
* @param array $config
|
||||
* @return void
|
||||
*/
|
||||
public function setConfig($config)
|
||||
{
|
||||
$this->config = $config;
|
||||
}
|
||||
|
||||
/**
|
||||
* 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)) {
|
||||
$conditionInstance = '\\Wearepixel\\Cart\\CartCondition';
|
||||
|
||||
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'];
|
||||
|
||||
if (is_array($itemConditionTempHolder)) {
|
||||
array_push($itemConditionTempHolder, $itemCondition);
|
||||
} else {
|
||||
$itemConditionTempHolder = $itemCondition;
|
||||
}
|
||||
|
||||
$this->update($productId, [
|
||||
'conditions' => $itemConditionTempHolder, // the newly updated conditions
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* removes an item on cart by item ID
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
public function remove($id)
|
||||
{
|
||||
$cart = $this->getContent();
|
||||
|
||||
if ($this->fireEvent('removing', $id) === false) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$cart->forget($id);
|
||||
|
||||
$this->save($cart);
|
||||
|
||||
$this->fireEvent('removed', $id);
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* clear cart
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
public function clear()
|
||||
{
|
||||
if ($this->fireEvent('clearing') === false) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$this->session->put(
|
||||
$this->sessionKeyCartItems,
|
||||
[]
|
||||
);
|
||||
|
||||
$this->fireEvent('cleared');
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* add a condition on the cart
|
||||
*
|
||||
* @param CartCondition|array $condition
|
||||
* @return $this
|
||||
*
|
||||
* @throws InvalidConditionException
|
||||
*/
|
||||
public function condition($condition)
|
||||
{
|
||||
if (is_array($condition)) {
|
||||
foreach ($condition as $c) {
|
||||
$this->condition($c);
|
||||
}
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
if (! $condition instanceof CartCondition) {
|
||||
throw new InvalidConditionException('Argument 1 must be an instance of \'Wearepixel\Cart\CartCondition\'');
|
||||
}
|
||||
|
||||
$conditions = $this->getConditions();
|
||||
|
||||
// Check if order has been applied
|
||||
if ($condition->getOrder() == 0) {
|
||||
$last = $conditions->last();
|
||||
$condition->setOrder(! is_null($last) ? $last->getOrder() + 1 : 1);
|
||||
}
|
||||
|
||||
$conditions->put($condition->getName(), $condition);
|
||||
|
||||
$conditions = $conditions->sortBy(function ($condition, $key) {
|
||||
return $condition->getOrder();
|
||||
});
|
||||
|
||||
$this->saveConditions($conditions);
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* get conditions applied on the cart
|
||||
*
|
||||
* @return CartConditionCollection
|
||||
*/
|
||||
public function getConditions()
|
||||
{
|
||||
return new CartConditionCollection($this->session->get($this->sessionKeyCartConditions));
|
||||
}
|
||||
|
||||
/**
|
||||
* get condition applied on the cart by its name
|
||||
*
|
||||
* @return CartCondition
|
||||
*/
|
||||
public function getCondition($conditionName)
|
||||
{
|
||||
return $this->getConditions()->get($conditionName);
|
||||
}
|
||||
|
||||
/**
|
||||
* 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 $condition->getType() == $type;
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove all the condition with the $type specified
|
||||
* Please Note that this will only remove condition added on cart bases, not those conditions added
|
||||
* specifically on an per item bases
|
||||
*
|
||||
* @return $this
|
||||
*/
|
||||
public function removeConditionsByType($type)
|
||||
{
|
||||
$this->getConditionsByType($type)->each(function ($condition) {
|
||||
$this->removeCartCondition($condition->getName());
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* removes a condition on a cart by condition name,
|
||||
* this can only remove conditions that are added on cart bases not conditions that are added on an item/product.
|
||||
* If you wish to remove a condition that has been added for a specific item/product, you may
|
||||
* use the removeItemCondition(itemId, conditionName) method instead.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function removeCartCondition($conditionName)
|
||||
{
|
||||
$conditions = $this->getConditions();
|
||||
|
||||
$conditions->pull($conditionName);
|
||||
|
||||
$this->saveConditions($conditions);
|
||||
}
|
||||
|
||||
/**
|
||||
* 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)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
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'];
|
||||
|
||||
// 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)) {
|
||||
foreach ($tempConditionsHolder as $k => $condition) {
|
||||
if ($condition->getName() == $conditionName) {
|
||||
unset($tempConditionsHolder[$k]);
|
||||
}
|
||||
}
|
||||
|
||||
$item['conditions'] = $tempConditionsHolder;
|
||||
}
|
||||
|
||||
// if the item condition is not an array, we will check if it is
|
||||
// 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'] = [];
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
$this->update($itemId, [
|
||||
'conditions' => $item['conditions'],
|
||||
]);
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* 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)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$this->update($itemId, [
|
||||
'conditions' => [],
|
||||
]);
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* clears all conditions on a cart,
|
||||
* this does not remove conditions that has been added specifically to an item/product.
|
||||
* If you wish to remove a specific condition to a product, you may use the method: removeItemCondition($itemId, $conditionName)
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function clearCartConditions()
|
||||
{
|
||||
$this->session->put(
|
||||
$this->sessionKeyCartConditions,
|
||||
[]
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* get cart sub total without conditions
|
||||
*
|
||||
* @param bool $formatted
|
||||
* @return float
|
||||
*/
|
||||
public function getSubTotalWithoutConditions($formatted = true)
|
||||
{
|
||||
$cart = $this->getContent();
|
||||
|
||||
$sum = $cart->sum(function ($item) {
|
||||
return $item->getPriceSum();
|
||||
});
|
||||
|
||||
return Helpers::formatValue(floatval($sum), $formatted, $this->config);
|
||||
}
|
||||
|
||||
/**
|
||||
* get cart sub total
|
||||
*
|
||||
* @param bool $formatted
|
||||
* @return float
|
||||
*/
|
||||
public function getSubTotal($formatted = true)
|
||||
{
|
||||
$cart = $this->getContent();
|
||||
|
||||
$sum = $cart->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
|
||||
$conditions = $this
|
||||
->getConditions()
|
||||
->filter(function (CartCondition $cond) {
|
||||
return $cond->getTarget() === 'subtotal';
|
||||
});
|
||||
|
||||
// if there is no conditions, lets just return the sum
|
||||
if (! $conditions->count()) {
|
||||
return Helpers::formatValue($sum, $formatted, $this->config);
|
||||
}
|
||||
|
||||
// there are conditions, lets apply it
|
||||
$newTotal = 0.00;
|
||||
$process = 0;
|
||||
|
||||
$conditions->each(function (CartCondition $cond) use ($sum, &$newTotal, &$process) {
|
||||
|
||||
// if this is the first iteration, the toBeCalculated
|
||||
// should be the sum as initial point of value.
|
||||
$toBeCalculated = ($process > 0) ? $newTotal : $sum;
|
||||
|
||||
$newTotal = $cond->applyCondition($toBeCalculated);
|
||||
|
||||
$process++;
|
||||
});
|
||||
|
||||
return Helpers::formatValue((float) $newTotal, $formatted, $this->config);
|
||||
}
|
||||
|
||||
/**
|
||||
* the new total in which conditions are already applied
|
||||
*
|
||||
* @return float
|
||||
*/
|
||||
public function getTotal()
|
||||
{
|
||||
$subTotal = $this->getSubTotal(false);
|
||||
|
||||
$newTotal = 0.00;
|
||||
|
||||
$process = 0;
|
||||
|
||||
$conditions = $this
|
||||
->getConditions()
|
||||
->filter(function (CartCondition $cond) {
|
||||
return $cond->getTarget() === 'total';
|
||||
});
|
||||
|
||||
// if no conditions were added, just return the sub total
|
||||
if (! $conditions->count()) {
|
||||
return Helpers::formatValue($subTotal, $this->config['format_numbers'], $this->config);
|
||||
}
|
||||
|
||||
$conditions
|
||||
->each(function (CartCondition $cond) use ($subTotal, &$newTotal, &$process) {
|
||||
$toBeCalculated = ($process > 0) ? $newTotal : $subTotal;
|
||||
|
||||
$newTotal = $cond->applyCondition($toBeCalculated);
|
||||
|
||||
$process++;
|
||||
});
|
||||
|
||||
return Helpers::formatValue($newTotal, $this->config['format_numbers'], $this->config);
|
||||
}
|
||||
|
||||
/**
|
||||
* get total quantity of items in the cart
|
||||
*
|
||||
* @return int
|
||||
*/
|
||||
public function getTotalQuantity()
|
||||
{
|
||||
$items = $this->getContent();
|
||||
|
||||
if ($items->isEmpty()) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
$count = $items->sum(function ($item) {
|
||||
return $item['quantity'];
|
||||
});
|
||||
|
||||
return $count;
|
||||
}
|
||||
|
||||
/**
|
||||
* get the cart
|
||||
*
|
||||
* @return CartCollection
|
||||
*/
|
||||
public function getContent()
|
||||
{
|
||||
return (new CartCollection($this->session->get($this->sessionKeyCartItems)))->reject(function ($item) {
|
||||
return ! ($item instanceof ItemCollection);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* check if cart is empty
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
public function isEmpty()
|
||||
{
|
||||
return $this->getContent()->isEmpty();
|
||||
}
|
||||
|
||||
/**
|
||||
* validate Item data
|
||||
*
|
||||
* @return array $item;
|
||||
*
|
||||
* @throws InvalidItemException
|
||||
*/
|
||||
protected function validate($item)
|
||||
{
|
||||
$rules = [
|
||||
'id' => 'required',
|
||||
'price' => 'required|numeric',
|
||||
'quantity' => 'required|numeric|min:0.1',
|
||||
'name' => 'required',
|
||||
];
|
||||
|
||||
$validator = CartItemValidator::make($item, $rules);
|
||||
|
||||
if ($validator->fails()) {
|
||||
throw new InvalidItemException($validator->messages()->first());
|
||||
}
|
||||
|
||||
return $item;
|
||||
}
|
||||
|
||||
/**
|
||||
* add row to cart collection
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
protected function addRow($id, $item)
|
||||
{
|
||||
if ($this->fireEvent('adding', $item) === false) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$cart = $this->getContent();
|
||||
|
||||
$cart->put($id, new ItemCollection($item, $this->config));
|
||||
|
||||
$this->save($cart);
|
||||
|
||||
$this->fireEvent('added', $item);
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* save the cart
|
||||
*
|
||||
* @param $cart CartCollection
|
||||
*/
|
||||
protected function save($cart)
|
||||
{
|
||||
$this->session->put($this->sessionKeyCartItems, $cart);
|
||||
}
|
||||
|
||||
/**
|
||||
* save the cart conditions
|
||||
*/
|
||||
protected function saveConditions($conditions)
|
||||
{
|
||||
$this->session->put($this->sessionKeyCartConditions, $conditions);
|
||||
}
|
||||
|
||||
/**
|
||||
* check if an item has condition
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
protected function itemHasConditions($item)
|
||||
{
|
||||
if (! isset($item['conditions'])) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (is_array($item['conditions'])) {
|
||||
return count($item['conditions']) > 0;
|
||||
}
|
||||
|
||||
$conditionInstance = 'Wearepixel\\Cart\\CartCondition';
|
||||
|
||||
if ($item['conditions'] instanceof $conditionInstance) {
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* update a cart item quantity relative to its current quantity
|
||||
*
|
||||
* @return mixed
|
||||
*/
|
||||
protected function updateQuantityRelative($item, $key, $value)
|
||||
{
|
||||
if (preg_match('/\-/', $value) == 1) {
|
||||
$value = (int) 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) {
|
||||
$item[$key] -= $value;
|
||||
}
|
||||
} elseif (preg_match('/\+/', $value) == 1) {
|
||||
$item[$key] += (int) str_replace('+', '', $value);
|
||||
} else {
|
||||
$item[$key] += (int) $value;
|
||||
}
|
||||
|
||||
return $item;
|
||||
}
|
||||
|
||||
/**
|
||||
* update cart item quantity not relative to its current quantity value
|
||||
*
|
||||
* @return mixed
|
||||
*/
|
||||
protected function updateQuantityNotRelative($item, $key, $value)
|
||||
{
|
||||
$item[$key] = (int) $value;
|
||||
|
||||
return $item;
|
||||
}
|
||||
|
||||
/**
|
||||
* Setter for decimals. Change value on demand.
|
||||
*/
|
||||
public function setDecimals($decimals)
|
||||
{
|
||||
$this->decimals = $decimals;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return mixed
|
||||
*/
|
||||
protected function fireEvent($name, $value = [])
|
||||
{
|
||||
return $this->events->dispatch($this->getInstanceName() . '.' . $name, array_values([$value, $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;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
<?php
|
||||
|
||||
namespace Wearepixel\Cart;
|
||||
|
||||
use Illuminate\Support\Collection;
|
||||
|
||||
class CartCollection extends Collection
|
||||
{
|
||||
}
|
||||
@@ -0,0 +1,248 @@
|
||||
<?php
|
||||
|
||||
namespace Wearepixel\Cart;
|
||||
|
||||
use Wearepixel\Cart\Helpers\Helpers;
|
||||
use Wearepixel\Cart\Validators\CartConditionValidator;
|
||||
use Wearepixel\Cart\Exceptions\InvalidConditionException;
|
||||
|
||||
class CartCondition
|
||||
{
|
||||
/**
|
||||
* @var array
|
||||
*/
|
||||
private $args;
|
||||
|
||||
/**
|
||||
* the parsed raw value of the condition
|
||||
*/
|
||||
public $parsedRawValue;
|
||||
|
||||
/**
|
||||
* @param array $args (name, type, target, value)
|
||||
*
|
||||
* @throws InvalidConditionException
|
||||
*/
|
||||
public function __construct(array $args)
|
||||
{
|
||||
$this->args = $args;
|
||||
|
||||
if (Helpers::isMultiArray($args)) {
|
||||
throw new InvalidConditionException('Multi dimensional array is not supported.');
|
||||
} else {
|
||||
$this->validate($this->args);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* the target of where the condition is applied.
|
||||
* NOTE: On conditions added to per item bases, target is not needed.
|
||||
*
|
||||
* @return mixed
|
||||
*/
|
||||
public function getTarget()
|
||||
{
|
||||
return (isset($this->args['target'])) ? $this->args['target'] : '';
|
||||
}
|
||||
|
||||
/**
|
||||
* the name of the condition
|
||||
*
|
||||
* @return mixed
|
||||
*/
|
||||
public function getName()
|
||||
{
|
||||
return $this->args['name'];
|
||||
}
|
||||
|
||||
/**
|
||||
* the type of the condition
|
||||
*
|
||||
* @return mixed
|
||||
*/
|
||||
public function getType()
|
||||
{
|
||||
return $this->args['type'];
|
||||
}
|
||||
|
||||
/**
|
||||
* get the additional attributes of a condition
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
public function getAttributes()
|
||||
{
|
||||
return (isset($this->args['attributes'])) ? $this->args['attributes'] : [];
|
||||
}
|
||||
|
||||
/**
|
||||
* the value of this the condition
|
||||
*
|
||||
* @return mixed
|
||||
*/
|
||||
public function getValue()
|
||||
{
|
||||
return $this->args['value'];
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the order to apply this condition. If no argument order is applied we return 0 as
|
||||
* indicator that no assignment has been made
|
||||
*
|
||||
* @param int $order
|
||||
* @return int
|
||||
*/
|
||||
public function setOrder($order = 1)
|
||||
{
|
||||
$this->args['order'] = $order;
|
||||
}
|
||||
|
||||
/**
|
||||
* the order to apply this condition. If no argument order is applied we return 0 as
|
||||
* indicator that no assignment has been made
|
||||
*
|
||||
* @return int
|
||||
*/
|
||||
public function getOrder()
|
||||
{
|
||||
return isset($this->args['order']) && is_numeric($this->args['order']) ? (int) $this->args['order'] : 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* apply condition to total or subtotal
|
||||
*
|
||||
* @return float
|
||||
*/
|
||||
public function applyCondition($totalOrSubTotalOrPrice)
|
||||
{
|
||||
return $this->apply($totalOrSubTotalOrPrice, $this->getValue());
|
||||
}
|
||||
|
||||
/**
|
||||
* get the calculated value of this condition supplied by the subtotal|price
|
||||
*
|
||||
* @return mixed
|
||||
*/
|
||||
public function getCalculatedValue($totalOrSubTotalOrPrice)
|
||||
{
|
||||
$this->apply($totalOrSubTotalOrPrice, $this->getValue());
|
||||
|
||||
return $this->parsedRawValue;
|
||||
}
|
||||
|
||||
/**
|
||||
* apply condition
|
||||
*
|
||||
* @return float
|
||||
*/
|
||||
protected function apply($totalOrSubTotalOrPrice, $conditionValue)
|
||||
{
|
||||
// if value has a percentage sign on it, we will get first
|
||||
// its percentage then we will evaluate again if the value
|
||||
// has a minus or plus sign so we can decide what to do with the
|
||||
// percentage, whether to add or subtract it to the total/subtotal/price
|
||||
// if we can't find any plus/minus sign, we will assume it as plus sign
|
||||
if ($this->valueIsPercentage($conditionValue)) {
|
||||
if ($this->valueIsToBeSubtracted($conditionValue)) {
|
||||
$value = Helpers::normalizePrice($this->cleanValue($conditionValue));
|
||||
|
||||
$this->parsedRawValue = $totalOrSubTotalOrPrice * ($value / 100);
|
||||
|
||||
$result = floatval($totalOrSubTotalOrPrice - $this->parsedRawValue);
|
||||
} elseif ($this->valueIsToBeAdded($conditionValue)) {
|
||||
$value = Helpers::normalizePrice($this->cleanValue($conditionValue));
|
||||
|
||||
$this->parsedRawValue = $totalOrSubTotalOrPrice * ($value / 100);
|
||||
|
||||
$result = floatval($totalOrSubTotalOrPrice + $this->parsedRawValue);
|
||||
} else {
|
||||
$value = Helpers::normalizePrice($conditionValue);
|
||||
|
||||
$this->parsedRawValue = $totalOrSubTotalOrPrice * ($value / 100);
|
||||
|
||||
$result = floatval($totalOrSubTotalOrPrice + $this->parsedRawValue);
|
||||
}
|
||||
}
|
||||
|
||||
// if the value has no percent sign on it, the operation will not be a percentage
|
||||
// next is we will check if it has a minus/plus sign so then we can just deduct it to total/subtotal/price
|
||||
else {
|
||||
if ($this->valueIsToBeSubtracted($conditionValue)) {
|
||||
$this->parsedRawValue = Helpers::normalizePrice($this->cleanValue($conditionValue));
|
||||
|
||||
$result = floatval($totalOrSubTotalOrPrice - $this->parsedRawValue);
|
||||
} elseif ($this->valueIsToBeAdded($conditionValue)) {
|
||||
$this->parsedRawValue = Helpers::normalizePrice($this->cleanValue($conditionValue));
|
||||
|
||||
$result = floatval($totalOrSubTotalOrPrice + $this->parsedRawValue);
|
||||
} else {
|
||||
$this->parsedRawValue = Helpers::normalizePrice($conditionValue);
|
||||
|
||||
$result = floatval($totalOrSubTotalOrPrice + $this->parsedRawValue);
|
||||
}
|
||||
}
|
||||
|
||||
// Do not allow items with negative prices.
|
||||
return $result < 0 ? 0.00 : $result;
|
||||
}
|
||||
|
||||
/**
|
||||
* check if value is a percentage
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
protected function valueIsPercentage($value)
|
||||
{
|
||||
return preg_match('/%/', $value) == 1;
|
||||
}
|
||||
|
||||
/**
|
||||
* check if value is a subtract
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
protected function valueIsToBeSubtracted($value)
|
||||
{
|
||||
return preg_match('/\-/', $value) == 1;
|
||||
}
|
||||
|
||||
/**
|
||||
* check if value is to be added
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
protected function valueIsToBeAdded($value)
|
||||
{
|
||||
return preg_match('/\+/', $value) == 1;
|
||||
}
|
||||
|
||||
/**
|
||||
* removes some arithmetic signs (%,+,-) only
|
||||
*
|
||||
* @return mixed
|
||||
*/
|
||||
protected function cleanValue($value)
|
||||
{
|
||||
return str_replace(['%', '-', '+'], '', $value);
|
||||
}
|
||||
|
||||
/**
|
||||
* validates condition arguments
|
||||
*
|
||||
* @throws InvalidConditionException
|
||||
*/
|
||||
protected function validate($args)
|
||||
{
|
||||
$rules = [
|
||||
'name' => 'required',
|
||||
'type' => 'required',
|
||||
'value' => 'required',
|
||||
];
|
||||
|
||||
$validator = CartConditionValidator::make($args, $rules);
|
||||
|
||||
if ($validator->fails()) {
|
||||
throw new InvalidConditionException($validator->messages()->first());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
<?php
|
||||
|
||||
namespace Wearepixel\Cart;
|
||||
|
||||
use Illuminate\Support\Collection;
|
||||
|
||||
class CartConditionCollection extends Collection {}
|
||||
@@ -0,0 +1,69 @@
|
||||
<?php
|
||||
|
||||
namespace Wearepixel\Cart;
|
||||
|
||||
use Illuminate\Support\ServiceProvider;
|
||||
|
||||
class CartServiceProvider extends ServiceProvider
|
||||
{
|
||||
/**
|
||||
* Indicates if loading of the provider is deferred.
|
||||
*
|
||||
* @var bool
|
||||
*/
|
||||
protected $defer = false;
|
||||
|
||||
/**
|
||||
* Boot the service provider.
|
||||
*/
|
||||
public function boot()
|
||||
{
|
||||
if ($this->app->runningInConsole()) {
|
||||
$this->publishes([
|
||||
__DIR__ . '/../config/config.php' => config_path('cart.php'),
|
||||
], 'config');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Register the service provider.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function register()
|
||||
{
|
||||
$this->mergeConfigFrom(__DIR__ . '/../config/config.php', 'cart');
|
||||
|
||||
$this->app->singleton('cart', function ($app) {
|
||||
$storageClass = config('cart.storage');
|
||||
$eventsClass = config('cart.events');
|
||||
|
||||
$storage = $storageClass ? new $storageClass : $app['session'];
|
||||
$events = $eventsClass ? new $eventsClass : $app['events'];
|
||||
$instanceName = 'cart';
|
||||
|
||||
// default session or cart identifier. This will be overridden when calling Cart::session($sessionKey)->add() etc..
|
||||
// like when adding a cart for a specific user name. Session Key can be string or maybe a unique identifier to bind a cart
|
||||
// to a specific user, this can also be a user ID
|
||||
$session_key = '4yTlTDKu3oJOfzD';
|
||||
|
||||
return new Cart(
|
||||
$storage,
|
||||
$events,
|
||||
$instanceName,
|
||||
$session_key,
|
||||
config('cart')
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the services provided by the provider.
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
public function provides()
|
||||
{
|
||||
return [];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
<?php
|
||||
|
||||
namespace Wearepixel\Cart\Exceptions;
|
||||
|
||||
class InvalidConditionException extends \Exception {}
|
||||
@@ -0,0 +1,5 @@
|
||||
<?php
|
||||
|
||||
namespace Wearepixel\Cart\Exceptions;
|
||||
|
||||
class InvalidItemException extends \Exception {}
|
||||
@@ -0,0 +1,7 @@
|
||||
<?php
|
||||
|
||||
namespace Wearepixel\Cart\Exceptions;
|
||||
|
||||
class UnknownModelException extends \Exception
|
||||
{
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
<?php
|
||||
|
||||
namespace Wearepixel\Cart\Facades;
|
||||
|
||||
use Illuminate\Support\Facades\Facade;
|
||||
|
||||
class CartFacade extends Facade
|
||||
{
|
||||
protected static function getFacadeAccessor()
|
||||
{
|
||||
return 'cart';
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
<?php
|
||||
|
||||
namespace Wearepixel\Cart\Helpers;
|
||||
|
||||
class Helpers
|
||||
{
|
||||
/**
|
||||
* normalize price
|
||||
*
|
||||
* @return float
|
||||
*/
|
||||
public static function normalizePrice($price)
|
||||
{
|
||||
return (is_string($price)) ? floatval($price) : $price;
|
||||
}
|
||||
|
||||
/**
|
||||
* check if array is multi dimensional array
|
||||
* This will only check the first element of the array if it is still an array
|
||||
* to decide that it is a multi dimensional, if you want to check the array strictly
|
||||
* with all on its element, flag the second argument as true
|
||||
*
|
||||
* @param bool $recursive
|
||||
* @return bool
|
||||
*/
|
||||
public static function isMultiArray($array, $recursive = false)
|
||||
{
|
||||
if ($recursive) {
|
||||
return (count($array) == count($array, COUNT_RECURSIVE)) ? false : true;
|
||||
} else {
|
||||
foreach ($array as $k => $v) {
|
||||
if (is_array($v)) {
|
||||
return true;
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* check if variable is set and has value, return a default value
|
||||
*
|
||||
* @param bool|mixed $default
|
||||
* @return bool|mixed
|
||||
*/
|
||||
public static function issetAndHasValueOrAssignDefault(&$var, $default = false)
|
||||
{
|
||||
if ((isset($var)) && ($var != '')) {
|
||||
return $var;
|
||||
}
|
||||
|
||||
return $default;
|
||||
}
|
||||
|
||||
public static function formatValue($value, $formatNumber, $config)
|
||||
{
|
||||
if ($formatNumber || $config['format_numbers']) {
|
||||
return floatval(number_format($value, $config['decimals'], $config['dec_point'], $config['thousands_sep']));
|
||||
} else {
|
||||
return $value;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
<?php
|
||||
|
||||
namespace Wearepixel\Cart;
|
||||
|
||||
use Illuminate\Support\Collection;
|
||||
|
||||
class ItemAttributeCollection extends Collection
|
||||
{
|
||||
public function __get($name)
|
||||
{
|
||||
if ($this->has($name)) {
|
||||
return $this->get($name);
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,137 @@
|
||||
<?php
|
||||
|
||||
namespace Wearepixel\Cart;
|
||||
|
||||
use Illuminate\Support\Collection;
|
||||
use Wearepixel\Cart\Helpers\Helpers;
|
||||
|
||||
class ItemCollection extends Collection
|
||||
{
|
||||
/**
|
||||
* Sets the config parameters.
|
||||
*/
|
||||
protected $config;
|
||||
|
||||
/**
|
||||
* ItemCollection constructor.
|
||||
*
|
||||
* @param array|mixed $items
|
||||
*/
|
||||
public function __construct($items, $config = [])
|
||||
{
|
||||
parent::__construct($items);
|
||||
|
||||
$this->config = $config;
|
||||
}
|
||||
|
||||
/**
|
||||
* get the sum of price
|
||||
*
|
||||
* @return mixed|null
|
||||
*/
|
||||
public function getPriceSum()
|
||||
{
|
||||
return Helpers::formatValue($this->price * $this->quantity, $this->config['format_numbers'], $this->config);
|
||||
}
|
||||
|
||||
public function __get($name)
|
||||
{
|
||||
if ($this->has($name) || $name == 'model') {
|
||||
return ! is_null($this->get($name)) ? $this->get($name) : $this->getAssociatedModel();
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* return the associated model of an item
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
protected function getAssociatedModel()
|
||||
{
|
||||
if (! $this->has('associatedModel')) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$associatedModel = $this->get('associatedModel');
|
||||
|
||||
return with(new $associatedModel)->find($this->get('id'));
|
||||
}
|
||||
|
||||
/**
|
||||
* check if item has conditions
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
public function hasConditions()
|
||||
{
|
||||
if (! isset($this['conditions'])) {
|
||||
return false;
|
||||
}
|
||||
if (is_array($this['conditions'])) {
|
||||
return count($this['conditions']) > 0;
|
||||
}
|
||||
$conditionInstance = 'Wearepixel\\Cart\\CartCondition';
|
||||
if ($this['conditions'] instanceof $conditionInstance) {
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* check if item has conditions
|
||||
*
|
||||
* @return mixed|null
|
||||
*/
|
||||
public function getConditions()
|
||||
{
|
||||
if (! $this->hasConditions()) {
|
||||
return [];
|
||||
}
|
||||
|
||||
return $this['conditions'];
|
||||
}
|
||||
|
||||
/**
|
||||
* get the single price in which conditions are already applied
|
||||
*
|
||||
* @param bool $formatted
|
||||
* @return mixed|null
|
||||
*/
|
||||
public function getPriceWithConditions($formatted = true)
|
||||
{
|
||||
$originalPrice = $this->price;
|
||||
|
||||
$newPrice = 0.00;
|
||||
$processed = 0;
|
||||
|
||||
if ($this->hasConditions()) {
|
||||
if (is_array($this->conditions)) {
|
||||
foreach ($this->conditions as $condition) {
|
||||
($processed > 0) ? $toBeCalculated = $newPrice : $toBeCalculated = $originalPrice;
|
||||
$newPrice = $condition->applyCondition($toBeCalculated);
|
||||
$processed++;
|
||||
}
|
||||
} else {
|
||||
$newPrice = $this['conditions']->applyCondition($originalPrice);
|
||||
}
|
||||
|
||||
return Helpers::formatValue($newPrice, $formatted, $this->config);
|
||||
}
|
||||
|
||||
return Helpers::formatValue($originalPrice, $formatted, $this->config);
|
||||
}
|
||||
|
||||
/**
|
||||
* get the sum of price in which conditions are already applied
|
||||
*
|
||||
* @param bool $formatted
|
||||
* @return mixed|null
|
||||
*/
|
||||
public function getPriceSumWithConditions($formatted = true)
|
||||
{
|
||||
return Helpers::formatValue($this->getPriceWithConditions(false) * $this->quantity, $formatted, $this->config);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
<?php
|
||||
|
||||
namespace Wearepixel\Cart\Validators;
|
||||
|
||||
class CartConditionValidator extends Validator {}
|
||||
@@ -0,0 +1,5 @@
|
||||
<?php
|
||||
|
||||
namespace Wearepixel\Cart\Validators;
|
||||
|
||||
class CartItemValidator extends Validator {}
|
||||
@@ -0,0 +1,53 @@
|
||||
<?php
|
||||
|
||||
namespace Wearepixel\Cart\Validators;
|
||||
|
||||
use Illuminate\Validation\Factory;
|
||||
use Illuminate\Filesystem\Filesystem;
|
||||
use Illuminate\Translation\FileLoader;
|
||||
use Illuminate\Translation\Translator;
|
||||
|
||||
abstract class Validator
|
||||
{
|
||||
protected static $factory;
|
||||
|
||||
public static function instance()
|
||||
{
|
||||
if (! static::$factory) {
|
||||
$loader = new FileLoader(
|
||||
new Filesystem,
|
||||
'/Translations'
|
||||
);
|
||||
|
||||
$translator = new Translator($loader, 'en');
|
||||
static::$factory = new Factory($translator);
|
||||
}
|
||||
|
||||
return static::$factory;
|
||||
}
|
||||
|
||||
public static function __callStatic($method, $args)
|
||||
{
|
||||
$instance = static::instance();
|
||||
|
||||
switch (count($args)) {
|
||||
case 0:
|
||||
return $instance->$method();
|
||||
|
||||
case 1:
|
||||
return $instance->$method($args[0]);
|
||||
|
||||
case 2:
|
||||
return $instance->$method($args[0], $args[1]);
|
||||
|
||||
case 3:
|
||||
return $instance->$method($args[0], $args[1], $args[2]);
|
||||
|
||||
case 4:
|
||||
return $instance->$method($args[0], $args[1], $args[2], $args[3]);
|
||||
|
||||
default:
|
||||
return call_user_func_array([$instance, $method], $args);
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user