Compare commits

..
35 Commits
Author SHA1 Message Date
Joel Male 2196f58f01 Merge pull request #1 from joelwmale/feature/laravel-12.x-support
Laravel 12.x Support
2025-02-25 08:57:01 +10:00
Joel Male ed4d112665 Laravel 12.x Support 2025-02-25 08:54:04 +10:00
Joel Male f60bf92157 1.0.12 2024-11-28 13:11:23 +10:00
Joel Male a231ed8c43 1.0.12 2024-11-28 13:06:30 +10:00
Joel Male 599051631c wip: rename package to joelwmale 2024-11-28 13:06:24 +10:00
Joel Male b3ef4c38fc 1.0.11 2024-09-23 07:48:27 +10:00
Joel Male a45121ca63 Merge pull request #20 from wearepixel/task/fix-subtotal-always-being-used-if-the-total-is-$0
Task: Fix subtotal always being used when cart conditions on the total bring it to $0
2024-09-23 07:48:06 +10:00
Joel Male 5505f121c7 fix subtotal always being used 2024-09-23 07:45:59 +10:00
Joel Male 472d505041 wip: fix issue with conditions not being properly removed 2024-09-18 15:56:12 +10:00
Joel Male c6c4240c5f 1.0.9 2024-09-08 18:27:44 +10:00
Joel Male 54d7c8a54f Merge pull request #17 from wearepixel/feature/livewire-support-for-nested-collections
Better Livewire Support
2024-09-08 12:23:22 +10:00
Joel Male a8d743eb9b remove php formatting 2024-09-08 12:22:03 +10:00
Pixel Tech b7381573e8 Apply Laravel Pint
Signed-off-by: Pixel Tech <tech@wearepixel.com.au>
2024-09-08 02:21:01 +00:00
Joel Male d4d4df7d58 pint fixes 2024-09-08 12:20:36 +10:00
Pixel Tech 6ea2cb3b8b Apply Laravel Pint
Signed-off-by: Pixel Tech <tech@wearepixel.com.au>
2024-09-07 22:36:00 +00:00
Joel Male 7a2c41e02d add better livewire support
- and reset collection indexes properly
2024-09-08 08:32:51 +10:00
Joel Male 9a59857825 Merge pull request #12 from wearepixel/feature/targets-to-activate-cart-conditions
Feature: Add targets to cart conditions
2024-09-04 09:38:34 +10:00
Joel Male 43238b6f2e revert php 8.0 support 2024-09-04 09:33:49 +10:00
Joel Male c0f0fcd2f0 fix 8.0 tests 2024-09-04 09:30:28 +10:00
Joel Male 185c4572ae fix tests 2024-09-04 09:26:50 +10:00
Pixel Tech c111cda3aa Apply Laravel Pint
Signed-off-by: Pixel Tech <tech@wearepixel.com.au>
2024-09-03 23:16:53 +00:00
Joel Male ab9eb6c873 fix tests 2024-09-04 09:16:15 +10:00
Joel Male 7ee26add8d undo extra changes 2024-09-04 09:14:23 +10:00
Joel Male 05318b7b13 working on deprecations and code cleanup 2024-09-03 21:41:45 +10:00
Joel Male 4d2efcdeae fix tests for cart conditions 2024-09-03 21:07:58 +10:00
Joel Male a269c188e4 initial functionality 2024-09-03 20:22:03 +10:00
Joel Male 2ccba20119 1.0.8 2024-08-30 10:08:47 +10:00
Joel Male 313a4f7aa2 Revert "1.0.7"
This reverts commit 4a312a37e2.
2024-08-30 10:08:27 +10:00
Joel Male 4a312a37e2 1.0.7 2024-08-30 09:44:40 +10:00
github-actions[bot] 274a8504af Merge pull request #10 from wearepixel/dependabot/composer/master/pestphp/pest-2.35.1
Bump pestphp/pest from 2.35.0 to 2.35.1
2024-08-26 12:56:01 +00:00
dependabot[bot] 4f22672ca5 Bump pestphp/pest from 2.35.0 to 2.35.1
Bumps [pestphp/pest](https://github.com/pestphp/pest) from 2.35.0 to 2.35.1.
- [Release notes](https://github.com/pestphp/pest/releases)
- [Changelog](https://github.com/pestphp/pest/blob/2.x/RELEASE.md)
- [Commits](https://github.com/pestphp/pest/compare/v2.35.0...v2.35.1)

---
updated-dependencies:
- dependency-name: pestphp/pest
  dependency-type: direct:development
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
2024-08-26 12:55:45 +00:00
Joel Male 61475a7060 1.0.6 2024-08-26 10:58:14 +10:00
Joel Male 6604cf984d fix tests & validation errors 2024-08-26 10:57:02 +10:00
Joel Male 7d955d722c Merge pull request #9 from wearepixel/task/add-items-with-no-price
Add items with no price
2024-08-26 10:49:47 +10:00
Joel Male 54d94d8d12 Add items with no price 2024-08-26 10:38:20 +10:00
29 changed files with 1626 additions and 1328 deletions
-25
View File
@@ -1,25 +0,0 @@
name: PHP Formatting
on: pull_request
jobs:
php-formatting:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: "Run Pint"
uses: aglipanci/laravel-pint-action@latest
with:
verboseMode: true
configPath: "pint.json"
pintVersion: 1.17.2
- name: Commit changes
uses: stefanzweifel/git-auto-commit-action@v5
with:
commit_message: "Apply Laravel Pint"
commit_options: '--no-verify --signoff'
file_pattern: "*.php"
commit_user_name: "Pixel Tech"
commit_user_email: "tech@wearepixel.com.au"
commit_author: "Pixel Tech<tech@wearepixel.com.au>"
+1 -1
View File
@@ -13,7 +13,7 @@ jobs:
strategy:
fail-fast: true
matrix:
php: ['8.1','8.2', '8.3']
php: ['8.2', '8.3', '8.4']
stability: [prefer-stable]
steps:
+1 -1
View File
@@ -1,6 +1,6 @@
The MIT License (MIT)
Copyright (c) Pixel Digital Pty Ltd <hello@wearepixel.com.au>
Copyright (c) Joel Male <joel@joelmale.com>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
+126 -21
View File
@@ -1,11 +1,13 @@
[![Latest Version on Packagist](https://img.shields.io/packagist/v/wearepixel/laravel-cart.svg?style=flat-square)](https://packagist.org/packages/wearepixel/laravel-cart)
[![GitHub Tests Action Status](https://img.shields.io/github/actions/workflow/status/wearepixel/laravel-cart/tests.yml?branch=master&label=Tests)](https://github.com/wearepixel/laravel-cart/actions?query=workflow%3ATests+branch%3Amaster)
[![Total Downloads](https://img.shields.io/packagist/dt/wearepixel/laravel-cart.svg?style=flat-square)](https://packagist.org/packages/wearepixel/laravel-cart)
[![License](https://poser.pugx.org/wearepixel/laravel-cart/license.svg)](https://packagist.org/packages/wearepixel/laravel-cart)
[![Latest Version on Packagist](https://img.shields.io/packagist/v/joelwmale/laravel-cart.svg?style=flat-square)](https://packagist.org/packages/joelwmale/laravel-cart)
[![GitHub Tests Action Status](https://img.shields.io/github/actions/workflow/status/joelwmale/laravel-cart/tests.yml?branch=master&label=Tests)](https://github.com/joelwmale/laravel-cart/actions?query=workflow%3ATests+branch%3Amaster)
[![Total Downloads](https://img.shields.io/packagist/dt/joelwmale/laravel-cart.svg?style=flat-square)](https://packagist.org/packages/joelwmale/laravel-cart)
[![License](https://poser.pugx.org/joelwmale/laravel-cart/license.svg)](https://packagist.org/packages/joelwmale/laravel-cart)
A Cart Implementation for Laravel.
Supported Laravel Versions: 9, 10, 11
Supported Laravel Versions: 10, 11, and 12.
For Laravel 9.0 and below, please use version [1.0](https://github.com/joelwmale/laravel-cart/releases/tag/1.0.12)
## Quick Demo
@@ -33,14 +35,14 @@ ## Installing
Install the package through [Composer](http://getcomposer.org/).
`composer require "wearepixel/laravel-cart"`
`composer require "joelwmale/laravel-cart"`
## Configuration
You can publish the configuration file to customize various options.
```php
php artisan vendor:publish --provider="Wearepixel\Cart\CartServiceProvider" --tag="config"
php artisan vendor:publish --provider="Joelwmale\Cart\CartServiceProvider" --tag="config"
```
### Formatting Numbers
@@ -76,9 +78,9 @@ ### Round Mode
'round_mode' => env('LARAVEL_CART_ROUND_MODE', 'down'),
```
## HOW TO USE
## Usage
- [Usage](#usage)
- [Basic Usage](#basic-usage)
- [Conditions](#conditions)
- [Items](#items)
- [Associating Models](#associating-models)
@@ -288,12 +290,14 @@ ### Clearing the Cart: **Cart::clear()**
## Conditions
Conditions are very useful in terms for adding things like discounts, taxes, shipping costs, etc.
Conditions are very useful for adding things like discounts, taxes, shipping, etc.
Conditions can be added on the entire cart or on individual items.
Conditions can be added on the entire cart or on individual items, and can even be applied only at certain cart values.
Conditions on a cart level should always have a `target` of `subtotal` or `total`. This tells the cart which value to apply the condition to.
You can provide an optional `minimum` value which should be the dollar value in which the target (subtotal or total) needs to be for the condition to be active and impact the cart.
You can also provide an `order` to cart conditions which tells the cart in what order to apply the conditions. Item level conditions do not support the `order` parameter.
### Conditions on the cart
@@ -302,7 +306,7 @@ #### Adding a condition to the cart: **Cart::condition()**
```php
// Add a single condition to the cart
$condition = new \Wearepixel\Cart\CartCondition([
$condition = new \Joelwmale\Cart\CartCondition([
'name' => 'Tax: 10%',
'type' => 'tax',
'target' => 'subtotal', // this condition will be applied to cart's subtotal when getSubTotal() is called.
@@ -315,7 +319,7 @@ #### Adding a condition to the cart: **Cart::condition()**
Cart::condition($condition);
// Add multiple conditions
$tax = new \Wearepixel\Cart\CartCondition([
$tax = new \Joelwmale\Cart\CartCondition([
'name' => 'Tax: 10%',
'type' => 'tax',
'target' => 'subtotal', // this condition will be applied to cart's subtotal when getSubTotal() is called.
@@ -323,7 +327,7 @@ #### Adding a condition to the cart: **Cart::condition()**
'order' => 2
]);
$shipping = new \Wearepixel\Cart\CartCondition([
$shipping = new \Joelwmale\Cart\CartCondition([
'name' => 'Shipping: $15',
'type' => 'shipping',
'target' => 'subtotal', // this condition will be applied to cart's subtotal when getSubTotal() is called.
@@ -338,7 +342,7 @@ #### Adding a condition to the cart: **Cart::condition()**
Cart::condition([$tax, $shipping]);
// add condition to only apply on totals, not in subtotal
$shipping = new \Wearepixel\Cart\CartCondition([
$shipping = new \Joelwmale\Cart\CartCondition([
'name' => 'Express Shipping $15',
'type' => 'shipping',
'target' => 'total',
@@ -362,18 +366,81 @@ #### Getting conditions on the cart: **Cart::getConditions()**
$condition->getType(); // the type
$condition->getValue(); // the value of the condition
$condition->getOrder(); // the order of the condition
$condition->getMinimum(); // the minimum dollar amount of the target, needed to activate the condition
$condition->getMaximum(); // the maximum dollar amount of the target, needed to keep the condition active
$condition->getAttributes(); // the attributes of the condition, returns an empty [] if no attributes added
}
```
#### Getting conditions on the cart as an array: **Cart::getConditions(array: true)**
You can get all cart conditions in array format by passing "array: true". This is useful if you want to store the carts conditions on a Livewire component since by default we have collections inside collections for conditions which Livewire does not support.
```php
$cartConditions = Cart::getConditions(true);
$cartConditions = Cart::getConditions(active: true);
foreach ($cartConditions as $condition) {
$condition['name']; // the name of the condition
$condition['type']; // the type
$condition['value']; // the value of the condition
$condition['order']; // the order of the condition
$condition['minimum']; // the minimum dollar amount of the target, needed to activate the condition
$condition['maximum']; // the maximum dollar amount of the target, needed to keep the condition active
$condition['attributes']; // the attributes of the condition, returns an empty [] if no attributes added
}
```
#### Getting conditions by name: **Cart::getCondition($conditionName)**
```php
$condition = Cart::getCondition('GST');
// You can also get a condition that has been applied on the cart by using its name:
$condition = Cart::getCondition('Tax: 10%');
$condition->getTarget(); // the target of which the condition was applied
$condition->getName(); // the name of the condition
$condition->getType(); // the type
$condition->getValue(); // the value of the condition
$condition->getMinimum(); // the minimum dollar amount of the target, needed to activate the condition
$condition->getMaximum(); // the maximum dollar amount of the target, needed to keep the condition active
$condition->getAttributes(); // the attributes of the condition, returns an empty [] if no attributes added
```
#### Getting active conditions on the cart: **Cart::getConditions(active: true)**
You can get only active conditions by passsing `active: true` to the `getConditions()` method.
This will return conditions that are actively being applied to the cart (i.e if they meet their minimum or maximum value)
```php
$tenPercentOff = new CartCondition([
'name' => '10% Off',
'type' => 'discount',
'target' => 'subtotal',
'value' => '-10%',
'minimum' => 120,
'order' => 1,
]);
Cart::getConditions(active: true);
// will return "10% Off" if the subtotal of the cart is $200.
// will return no conditions if the subtotal is $100.
$shipping = new CartCondition([
'name' => 'Shipping',
'type' => 'discount',
'target' => 'subtotal',
'value' => '10',
'maximum' => 200,
'order' => 1,
]);
Cart::getConditions(active: true);
// will return "Shipping" if the subtotal of the cart is less than or equal 200
// will return no conditions if the subtotal is $210
```
### Calculating condition value
There are 2 ways to calculate the value of a condition:
@@ -385,7 +452,7 @@ #### Using the `getCalculatedValue` method on the condition instance
```php
$subTotal = Cart::getSubTotal();
$condition = Cart::getCondition('VAT 12.5%');
$condition = Cart::getCondition('10% GST');
$conditionCalculatedValue = $condition->getCalculatedValue($subTotal);
```
@@ -422,6 +489,44 @@ #### Using the `getCalculatedValueForCondition` method on the cart instance
Cart::getCalculatedValueForCondition('Gift Card'); // returns 0 as the coupon discount is applied first and brings the subtotal to 0
```
### Adding conditions that activate once a minimum value is met
You can add a `minimum` amount required for a condition to activate.
This is useful for applying discounts only after certain cart values, i.e: 10% off for any purchases over $120.
```php
$tenPercentOff = new CartCondition([
'name' => '10% Off',
'type' => 'discount',
'target' => 'subtotal',
'value' => '-10%',
'minimum' => 120,
'order' => 1,
]);
Cart::condition($tenPercentOff)
```
### Adding conditions that only activate up to a maximum value
You can add a `maximum` amount required for a condition to activate.
This is useful for applying discounts up until amounts, i.e shipping for anything below $200, and free shipping above.
```php
$shipping = new CartCondition([
'name' => 'Shipping',
'type' => 'discount',
'target' => 'subtotal',
'value' => '12',
'maximum' => 200,
'order' => 1,
]);
Cart::condition($shipping)
```
### Condition on items
Item conditions are useful if you have discounts to be applied specifically on an item and not on the whole cart value.
@@ -429,7 +534,7 @@ ### Condition on items
```php
// lets create first our condition instance
$saleCondition = new \Wearepixel\Cart\CartCondition([
$saleCondition = new \Joelwmale\Cart\CartCondition([
'name' => '50% Off',
'type' => 'tax',
'value' => '-50%',
@@ -449,7 +554,7 @@ ### Condition on items
Cart::add($product);
// You can of course also do multiple conditions on an item
$saleCondition = new \Wearepixel\Cart\CartCondition([
$saleCondition = new \Joelwmale\Cart\CartCondition([
'name' => 'SALE 5%',
'type' => 'sale',
'value' => '-5%',
@@ -483,7 +588,7 @@ ### Condition on items
$cartSubTotal = Cart::getSubTotal();
```
#### Add condition to existing Item on the cart: **Cart::addItemCondition($productId, $itemCondition)**
#### Add a condition to an existing item on the cart: **Cart::addItemCondition($productId, $itemCondition)**
Adding Condition to an existing Item on the cart is simple as well.
+12 -13
View File
@@ -1,6 +1,6 @@
{
"name": "wearepixel/laravel-cart",
"version": "1.0.4",
"name": "joelwmale/laravel-cart",
"version": "1.1.0",
"description": "A cart implementation for Laravel",
"keywords": [
"laravel",
@@ -15,34 +15,33 @@
},
{
"name": "Joel Male",
"email": "joel@wearepixel.com.au"
"email": "joel@joelmale.com"
}
],
"require": {
"php": ">=8.1",
"illuminate/support": "^9.0|^10.0|^11.0",
"illuminate/validation": "^9.0|^10.0|^11.0",
"illuminate/translation": "^9.0|^10.0|^11.0"
"php": ">=8.2",
"illuminate/support": "^10.0|^11.0|^12.0",
"illuminate/validation": "^10.0|^11.0|^12.0",
"illuminate/translation": "^10.0|^11.0|^12.0"
},
"require-dev": {
"mockery/mockery": "^1.4.2",
"laravel/pint": "dev-main",
"pestphp/pest": "2.35.0",
"larapack/dd": "dev-master"
"laravel/pint": "^1.21",
"pestphp/pest": "^3.0"
},
"autoload": {
"psr-4": {
"Wearepixel\\Cart\\": "src/"
"Joelwmale\\Cart\\": "src/"
}
},
"minimum-stability": "dev",
"extra": {
"laravel": {
"providers": [
"Wearepixel\\Cart\\CartServiceProvider"
"Joelwmale\\Cart\\CartServiceProvider"
],
"aliases": {
"Cart": "Wearepixel\\Cart\\Facades\\CartFacade"
"Cart": "Joelwmale\\Cart\\Facades\\CartFacade"
}
}
},
Generated
+876 -939
View File
File diff suppressed because it is too large Load Diff
+81 -84
View File
@@ -1,68 +1,31 @@
<?php
namespace Wearepixel\Cart;
namespace Joelwmale\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;
use Joelwmale\Cart\Helpers\Helpers;
use Joelwmale\Cart\Validators\CartItemValidator;
use Joelwmale\Cart\Exceptions\InvalidItemException;
use Joelwmale\Cart\Exceptions\UnknownModelException;
use Joelwmale\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;
@@ -73,6 +36,7 @@ public function __construct($session, $events, $instanceName, $session_key, $con
$this->sessionKeyCartConditions = $this->sessionKey . '_cart_conditions';
$this->config = $config;
$this->currentItemId = null;
$this->fireEvent('created');
}
@@ -109,20 +73,16 @@ public function getInstanceName()
/**
* get an item on a cart by item ID
*
* @return mixed
*/
public function get($itemId)
public function get($itemId): ?ItemCollection
{
return $this->getContent()->get($itemId);
}
/**
* check if an item exists by item ID
*
* @return bool
* check if we have this item in the cart by item ID
*/
public function has($itemId)
public function has($itemId): bool
{
return $this->getContent()->has($itemId);
}
@@ -144,16 +104,15 @@ public function add(
array|CartCondition $conditions = [],
?string $associatedModel = null
): self {
// check if its an array of items
// check if we are adding an array of items
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
// check if we are adding a multi dimensional array
if (Helpers::isMultiArray($id)) {
foreach ($id as $item) {
$this->add(
$item['id'],
$item['name'],
$item['price'],
isset($item['price']) ? $item['price'] : null,
$item['quantity'],
Helpers::issetAndHasValueOrAssignDefault($item['attributes'], []),
Helpers::issetAndHasValueOrAssignDefault($item['conditions'], []),
@@ -164,7 +123,7 @@ public function add(
$this->add(
$id['id'],
$id['name'],
$id['price'],
isset($id['price']) ? $id['price'] : null,
$id['quantity'],
Helpers::issetAndHasValueOrAssignDefault($id['attributes'], []),
Helpers::issetAndHasValueOrAssignDefault($id['conditions'], []),
@@ -175,6 +134,7 @@ public function add(
return $this;
}
// if we are here, we are adding a single item
$data = [
'id' => $id,
'name' => $name,
@@ -191,11 +151,8 @@ public function add(
// validate data
$item = $this->validate($data);
// get the cart
$inCart = $this->get($id);
// if the item is already in the cart we will just update it
if ($inCart) {
if ($this->get($id)) {
$this->update($id, $item);
} else {
$this->addItem($id, $item);
@@ -270,11 +227,11 @@ public function setConfig($config)
public function addItemCondition($productId, $itemCondition)
{
if ($product = $this->get($productId)) {
$conditionInstance = '\\Wearepixel\\Cart\\CartCondition';
$conditionInstance = '\\Joelwmale\\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"
// to avoid hitting this error "Indirect modification of overloaded element of Joelwmale\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'];
@@ -337,6 +294,9 @@ public function clear()
return true;
}
/**
* Adds a condition to the cart
*/
/**
* Adds a condition to the cart
*
@@ -353,7 +313,7 @@ public function condition(array|CartCondition $condition): self
}
if (! $condition instanceof CartCondition) {
throw new InvalidConditionException('Argument 1 must be an instance of \'Wearepixel\Cart\CartCondition\'');
throw new InvalidConditionException('Argument 1 must be an instance of \'Joelwmale\Cart\CartCondition\'');
}
$conditions = $this->getConditions();
@@ -378,11 +338,29 @@ public function condition(array|CartCondition $condition): self
/**
* get conditions applied on the cart
*
* @return CartConditionCollection
* @param bool $active - If true, only conditions actually applied on the cart are returned
*/
public function getConditions()
public function getConditions(bool $array = false, bool $active = false): CartConditionCollection|array
{
return new CartConditionCollection($this->session->get($this->sessionKeyCartConditions));
$conditions = new CartConditionCollection(
$this->session->get($this->sessionKeyCartConditions)
);
if ($active) {
return $conditions->filter(function (CartCondition $condition) {
$amount = $condition->getTarget() == 'subtotal' ? $this->getSubTotal(false) : $this->getTotal();
return $condition->getMinimum() === null || $condition->getMinimum() <= $amount;
})->filter(function (CartCondition $condition) {
$amount = $condition->getTarget() == 'subtotal' ? $this->getSubTotal(false) : $this->getTotal();
return $condition->getMaximum() === null || $condition->getMaximum() >= $amount;
});
}
return $array ? $conditions->map(function (CartCondition $condition) {
return $condition->toArray();
})->toArray() : $conditions;
}
/**
@@ -411,12 +389,8 @@ public function getConditionsByType($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)
public function removeConditionsByType(string $type)
{
$this->getConditionsByType($type)->each(function ($condition) {
$this->removeCartCondition($condition->getName());
@@ -424,12 +398,7 @@ public function removeConditionsByType($type)
}
/**
* 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
* Remove a condition from the cart
*/
public function removeCartCondition($conditionName)
{
@@ -479,7 +448,7 @@ public function removeItemCondition($itemId, $conditionName)
// 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';
$conditionInstance = 'Joelwmale\\Cart\\CartCondition';
if ($item['conditions'] instanceof $conditionInstance) {
if ($tempConditionsHolder->getName() == $conditionName) {
@@ -575,6 +544,12 @@ public function getSubTotal($formatted = true): int|float|string
->filter(function (CartCondition $condition) {
return $condition->getTarget() === 'subtotal';
})
->filter(function (CartCondition $condition) use ($subTotalSum) {
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();
});
@@ -607,6 +582,15 @@ public function getTotal(): int|float
$conditionsForTotal = $this->getConditions()
->filter(function (CartCondition $condition) {
return $condition->getTarget() === 'total';
})
->filter(function (CartCondition $condition) use ($subTotal) {
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
@@ -614,10 +598,14 @@ public function getTotal(): int|float
return Helpers::formatValue($subTotal, $this->config['format_numbers'], $this->config);
}
$conditionsForTotal->each(function (CartCondition $condition) use ($subTotal, &$total) {
$toBeCalculated = $total > 0 ? $total : $subTotal;
$index = 0;
$conditionsForTotal->each(function (CartCondition $condition) use ($subTotal, &$total, &$index) {
$toBeCalculated = ($index > 0) ? $total : $subTotal;
$total = $condition->applyCondition($toBeCalculated);
$index++;
});
return Helpers::formatValue($total, $this->config['format_numbers'], $this->config);
@@ -698,15 +686,24 @@ protected function validate($item)
{
$rules = [
'id' => 'required',
'price' => 'required|numeric',
'quantity' => 'required|numeric|min:0.1',
'name' => 'required',
'quantity' => 'required|numeric|min:0.1',
];
$validator = CartItemValidator::make($item, $rules);
if ($validator->fails()) {
throw new InvalidItemException($validator->messages()->first());
if ($validator->errors()->first('id') === 'validation.required') {
throw new InvalidItemException('The id field is required.');
}
if ($validator->errors()->first('name') === 'validation.required') {
throw new InvalidItemException('The name field is required.');
}
if ($validator->errors()->first('quantity') === 'validation.min.numeric') {
throw new InvalidItemException('The quantity must be at least 0.1.');
}
}
return $item;
@@ -737,7 +734,7 @@ protected function addItem($id, $item)
/**
* save the cart
*
* @param $cart CartCollection
* @param $cart CartCollection
*/
protected function save($cart)
{
@@ -767,7 +764,7 @@ protected function itemHasConditions($item)
return count($item['conditions']) > 0;
}
$conditionInstance = 'Wearepixel\\Cart\\CartCondition';
$conditionInstance = 'Joelwmale\\Cart\\CartCondition';
if ($item['conditions'] instanceof $conditionInstance) {
return true;
+1 -1
View File
@@ -1,6 +1,6 @@
<?php
namespace Wearepixel\Cart;
namespace Joelwmale\Cart;
use Illuminate\Support\Collection;
+26 -8
View File
@@ -1,22 +1,19 @@
<?php
namespace Wearepixel\Cart;
namespace Joelwmale\Cart;
use Wearepixel\Cart\Helpers\Helpers;
use Wearepixel\Cart\Validators\CartConditionValidator;
use Wearepixel\Cart\Exceptions\InvalidConditionException;
use Joelwmale\Cart\Helpers\Helpers;
use Joelwmale\Cart\Validators\CartConditionValidator;
use Joelwmale\Cart\Exceptions\InvalidConditionException;
class CartCondition
{
/**
* @var array
*/
private $args;
/**
* the parsed raw value of the condition
*/
public $parsedRawValue = 0;
private $parsedRawValue = 0;
/**
* @param array $args (name, type, target, value)
@@ -65,6 +62,22 @@ public function getType()
return $this->args['type'];
}
/**
* Get the minimum value of this condition
*/
public function getMinimum(): int|float|null
{
return $this->args['minimum'] ?? null;
}
/**
* Get the maximum value of this condition
*/
public function getMaximum(): int|float|null
{
return $this->args['maximum'] ?? null;
}
/**
* get the additional attributes of a condition
*
@@ -253,4 +266,9 @@ protected function validate($args)
throw new InvalidConditionException($validator->messages()->first());
}
}
public function toArray(): array
{
return $this->args;
}
}
+1 -1
View File
@@ -1,6 +1,6 @@
<?php
namespace Wearepixel\Cart;
namespace Joelwmale\Cart;
use Illuminate\Support\Collection;
+1 -1
View File
@@ -1,6 +1,6 @@
<?php
namespace Wearepixel\Cart;
namespace Joelwmale\Cart;
use Illuminate\Support\ServiceProvider;
+1 -1
View File
@@ -1,5 +1,5 @@
<?php
namespace Wearepixel\Cart\Exceptions;
namespace Joelwmale\Cart\Exceptions;
class InvalidConditionException extends \Exception {}
+1 -1
View File
@@ -1,5 +1,5 @@
<?php
namespace Wearepixel\Cart\Exceptions;
namespace Joelwmale\Cart\Exceptions;
class InvalidItemException extends \Exception {}
+1 -1
View File
@@ -1,5 +1,5 @@
<?php
namespace Wearepixel\Cart\Exceptions;
namespace Joelwmale\Cart\Exceptions;
class UnknownModelException extends \Exception {}
+1 -1
View File
@@ -1,6 +1,6 @@
<?php
namespace Wearepixel\Cart\Facades;
namespace Joelwmale\Cart\Facades;
use Illuminate\Support\Facades\Facade;
+2 -2
View File
@@ -1,13 +1,13 @@
<?php
namespace Wearepixel\Cart\Helpers;
namespace Joelwmale\Cart\Helpers;
class Helpers
{
/**
* Normalize prices
*/
public static function normalizePrice($price): float
public static function normalizePrice($price): ?float
{
return (is_string($price)) ? floatval($price) : $price;
}
+1 -1
View File
@@ -1,6 +1,6 @@
<?php
namespace Wearepixel\Cart;
namespace Joelwmale\Cart;
use Illuminate\Support\Collection;
+3 -3
View File
@@ -1,9 +1,9 @@
<?php
namespace Wearepixel\Cart;
namespace Joelwmale\Cart;
use Illuminate\Support\Collection;
use Wearepixel\Cart\Helpers\Helpers;
use Joelwmale\Cart\Helpers\Helpers;
class ItemCollection extends Collection
{
@@ -72,7 +72,7 @@ public function hasConditions()
if (is_array($this['conditions'])) {
return count($this['conditions']) > 0;
}
$conditionInstance = 'Wearepixel\\Cart\\CartCondition';
$conditionInstance = 'Joelwmale\\Cart\\CartCondition';
if ($this['conditions'] instanceof $conditionInstance) {
return true;
}
+1 -1
View File
@@ -1,5 +1,5 @@
<?php
namespace Wearepixel\Cart\Validators;
namespace Joelwmale\Cart\Validators;
class CartConditionValidator extends Validator {}
+1 -1
View File
@@ -1,5 +1,5 @@
<?php
namespace Wearepixel\Cart\Validators;
namespace Joelwmale\Cart\Validators;
class CartItemValidator extends Validator {}
+1 -1
View File
@@ -1,6 +1,6 @@
<?php
namespace Wearepixel\Cart\Validators;
namespace Joelwmale\Cart\Validators;
use Illuminate\Validation\Factory;
use Illuminate\Filesystem\Filesystem;
+1 -1
View File
@@ -1,6 +1,6 @@
<?php
namespace Wearepixel\Cart\Tests\Helpers;
namespace Joelwmale\Cart\Tests\Helpers;
use Illuminate\Contracts\Database\ModelIdentifier;
+1 -1
View File
@@ -1,6 +1,6 @@
<?php
namespace Wearepixel\Cart\Tests\Helpers;
namespace Joelwmale\Cart\Tests\Helpers;
class SessionMock
{
+435 -184
View File
@@ -1,19 +1,20 @@
<?php
use Wearepixel\Cart\Cart;
use Wearepixel\Cart\CartCondition;
use Wearepixel\Cart\Tests\Helpers\SessionMock;
use Joelwmale\Cart\Cart;
use Joelwmale\Cart\CartCondition;
use Joelwmale\Cart\CartConditionCollection;
use Joelwmale\Cart\Tests\Helpers\SessionMock;
beforeEach(function () {
$events = Mockery::mock('Illuminate\Contracts\Events\Dispatcher');
$events->shouldReceive('dispatch');
$this->cart = new Cart(
new SessionMock,
new SessionMock(),
$events,
'cart',
'SAMPLESESSIONKEY',
require (__DIR__ . '/../Helpers/ConfigConditionsMock.php')
require(__DIR__ . '/../Helpers/ConfigConditionsMock.php')
);
});
@@ -21,7 +22,168 @@
Mockery::close();
});
describe('conditions', function () {
test('can be completely cleared', function () {
$siteWideDiscount = new CartCondition([
'name' => 'Site Wide Discount',
'type' => 'discount',
'target' => 'total',
'value' => '-5%',
]);
$giftCard = new CartCondition([
'name' => 'Gift Card',
'type' => 'gift_card',
'target' => 'total',
'value' => '-25',
]);
$itemCondition = new CartCondition([
'name' => 'Item Discount',
'type' => 'discount',
'value' => '-5%',
]);
$item = [
'id' => 1,
'name' => 'Backpack',
'price' => 168.72,
'quantity' => 1,
'attributes' => [],
'conditions' => [$itemCondition],
];
$this->cart->add($item);
$this->cart->condition([$siteWideDiscount, $giftCard]);
expect($this->cart->getConditions()->count())->toEqual(2, 'Cart should have two conditions');
expect($this->cart->get(1)['conditions'])->toHaveCount(1, 'Cart should have one condition');
$this->cart->clearAllConditions();
expect($this->cart->getConditions()->count())->toEqual(0, 'Cart should have no conditions now');
expect($this->cart->get(1)['conditions'])->toHaveCount(0, 'Cart items should have no conditions now');
});
test('can be converted to array', function () {
$condition = new CartCondition([
'name' => 'Site Wide Discount',
'type' => 'discount',
'target' => 'total',
'value' => '-5%',
]);
$this->cart->condition($condition);
$conditions = $this->cart->getConditions(true);
expect($conditions)->toHaveCount(1, 'Cart should have one condition');
expect($conditions['Site Wide Discount'])->toEqual([
'name' => 'Site Wide Discount',
'type' => 'discount',
'target' => 'total',
'value' => '-5%',
'order' => 1,
]);
});
test('can be removed by name', function () {
$conditionOne = new CartCondition([
'name' => '5% Site Wide Sale',
'type' => 'sale',
'value' => '-5%',
]);
$conditionTwo = new CartCondition([
'name' => 'Mother\'s Day Gift Pack',
'type' => 'promo',
'value' => '-25',
]);
$this->cart->add([
'id' => 1,
'name' => 'Body Scrub Kit',
'price' => 100,
'quantity' => 1,
'attributes' => [],
]);
$this->cart->condition([$conditionOne, $conditionTwo]);
// let's very first the item has 2 conditions in it
expect($this->cart->getConditions())->toHaveCount(2, 'The item should have two conditions');
// now let's remove a condition on that item using the condition name
$this->cart->removeCartCondition('5% Site Wide Sale');
// now we should have only 1 condition left on that item
expect($this->cart->getConditions())->toHaveCount(1, 'Item should have one condition left');
expect($this->cart->getConditions()->first()->getName())->toEqual('Mother\'s Day Gift Pack');
});
});
describe('cart level conditions', function () {
test('can get conditions', function () {
$this->cart->add([
'id' => 456,
'name' => 'Leather Shoes',
'price' => 129.99,
'quantity' => 1,
]);
$condition = new CartCondition([
'name' => '$5 Discount',
'type' => 'tax',
'target' => 'subtotal',
'value' => '-5',
]);
$this->cart->condition($condition);
$conditions = $this->cart->getConditions();
expect($conditions)->toHaveCount(1, 'Cart should have one condition');
expect($conditions)->toBeInstanceOf(CartConditionCollection::class);
});
test('can get conditions by name', function () {
$this->cart->add([
'id' => 456,
'name' => 'Leather Shoes',
'price' => 129.99,
'quantity' => 1,
]);
$conditionOne = new CartCondition([
'name' => '$5 Discount',
'type' => 'tax',
'target' => 'subtotal',
'value' => '-5',
]);
$conditionTwo = new CartCondition([
'name' => '5% Off',
'type' => 'tax',
'target' => 'subtotal',
'value' => '-5%',
]);
$this->cart->condition($conditionOne);
$this->cart->condition($conditionTwo);
$conditions = $this->cart->getConditions();
expect($conditions)->toHaveCount(2, 'Cart should have two conditions');
expect($conditions)->toBeInstanceOf(CartConditionCollection::class);
$condition = $this->cart->getCondition('5% Off');
expect($condition)->toBeInstanceOf(CartCondition::class);
expect($condition->getName())->toEqual('5% Off');
expect($condition->getValue())->toEqual('-5%');
});
test('can discount the subtotal by dollar amount', function () {
$this->cart->add([
'id' => 456,
@@ -792,40 +954,6 @@
expect($giftCard->getCalculatedValue())->toEqual(0, 'Gift Card value should be 0');
});
test('can be cleared', function () {
$siteWideDiscount = new CartCondition([
'name' => 'Site Wide Discount',
'type' => 'discount',
'target' => 'total',
'value' => '-5%',
]);
$giftCard = new CartCondition([
'name' => 'Gift Card',
'type' => 'gift_card',
'target' => 'total',
'value' => '-25',
]);
$item = [
'id' => 1,
'name' => 'Backpack',
'price' => 168.72,
'quantity' => 1,
'attributes' => [],
];
$this->cart->add($item);
$this->cart->condition([$siteWideDiscount, $giftCard]);
expect($this->cart->getConditions()->count())->toEqual(2, 'Cart should have two conditions');
$this->cart->clearCartConditions();
expect($this->cart->getConditions()->count())->toEqual(0, 'Cart should have no conditions now');
});
test('calculate the subtotal correctly when one condition makes it $0, and the other adds $10', function () {
$this->cart->add([
[
@@ -915,10 +1043,218 @@
expect($this->cart->getSubTotal())->toEqual(10.00, 'Cart should have sub total of 10.00');
expect($this->cart->getTotal())->toEqual(10.00, 'Cart should have a total of 10.00');
});
test('can activate a dollar discount when a minimum amount is met', function () {
$condition = new CartCondition([
'name' => 'Get $10 off when you spend $100',
'type' => 'target',
'target' => 'total',
'value' => '-10',
'minimum' => '100',
]);
$this->cart->add([
'id' => 1,
'name' => 'Apple iPhone 15',
'price' => 90,
'quantity' => 1,
'attributes' => [],
]);
$this->cart->condition($condition);
expect($this->cart->getTotal())->toEqual(90, 'Cart should have total of 90');
$this->cart->clear();
$this->cart->add([
'id' => 1,
'name' => 'Apple iPhone 15',
'price' => 90,
'quantity' => 2,
'attributes' => [],
]);
expect($this->cart->getTotal())->toEqual(170, 'Cart should have total of 170');
});
test('can activate a percentage discount when a minimum amount is met', function () {
$condition = new CartCondition([
'name' => 'Get 10% off when you spend $100',
'type' => 'target',
'target' => 'total',
'value' => '-10%',
'minimum' => '100',
]);
$this->cart->add([
'id' => 1,
'name' => 'Apple iPhone 15',
'price' => 90,
'quantity' => 1,
'attributes' => [],
]);
$this->cart->condition($condition);
expect($this->cart->getTotal())->toEqual(90, 'Cart should have total of 90');
$this->cart->clear();
$this->cart->add([
'id' => 1,
'name' => 'Apple iPhone 15',
'price' => 90,
'quantity' => 2,
'attributes' => [],
]);
expect($this->cart->getTotal())->toEqual(162, 'Cart should have total of 162');
});
test('can remove a dollar value condition when a maximum is met', function () {
$condition = new CartCondition([
'name' => 'Shipping',
'type' => 'target',
'target' => 'total',
'value' => '18',
'maximum' => '160',
]);
$this->cart->add([
'id' => 1,
'name' => 'Apple iPhone 15',
'price' => 90,
'quantity' => 1,
'attributes' => [],
]);
$this->cart->condition($condition);
expect($this->cart->getTotal())->toEqual(108, 'Cart should have total of 108');
$this->cart->clear();
$this->cart->add([
'id' => 1,
'name' => 'Apple iPhone 15',
'price' => 90,
'quantity' => 2,
'attributes' => [],
]);
expect($this->cart->getTotal())->toEqual(180, 'Cart should have total of 180');
});
test('can remove a percentage condition when a maximum is met', function () {
$condition = new CartCondition([
'name' => 'Low Cart Tax',
'type' => 'target',
'target' => 'total',
'value' => '10%',
'maximum' => '140',
]);
$this->cart->add([
'id' => 1,
'name' => 'Apple iPhone 15',
'price' => 90,
'quantity' => 1,
'attributes' => [],
]);
$this->cart->condition($condition);
expect($this->cart->getTotal())->toEqual(99, 'Cart should have total of 99');
$this->cart->clear();
$this->cart->add([
'id' => 1,
'name' => 'Apple iPhone 15',
'price' => 90,
'quantity' => 2,
'attributes' => [],
]);
expect($this->cart->getTotal())->toEqual(180, 'Cart should have total of 180');
});
test('return cart conditions only when they are active', function () {
$condition = new CartCondition([
'name' => 'Get $10 off when you spend $100',
'type' => 'target',
'target' => 'total',
'value' => '-10',
'minimum' => '100',
]);
$this->cart->add([
'id' => 1,
'name' => 'Apple iPhone 15',
'price' => 90,
'quantity' => 1,
'attributes' => [],
]);
$this->cart->condition($condition);
expect($this->cart->getConditions(active: true))->toHaveCount(0, 'Cart should have 0 conditions');
$this->cart->clear();
$this->cart->add([
'id' => 1,
'name' => 'Apple iPhone 15',
'price' => 90,
'quantity' => 2,
'attributes' => [],
]);
expect($this->cart->getConditions(active: true))->toHaveCount(1, 'Cart should have 1 condition');
});
test('can be removed by condition name', function () {
$shipping = new CartCondition([
'name' => 'Shipping',
'type' => 'shipping',
'target' => 'total',
'value' => '12',
]);
$tax = new CartCondition([
'name' => 'Tax',
'type' => 'tax',
'target' => 'total',
'value' => '2.50',
]);
$item = [
'id' => 456,
'name' => 'Sample Item 1',
'price' => 100,
'quantity' => 1,
'attributes' => [],
];
$this->cart->add($item);
$this->cart->condition([$shipping, $tax]);
// let's prove first we have now two conditions in the cart
expect($this->cart->getConditions()->count())->toEqual(2, 'Cart should have two conditions');
// now let's remove a specific condition by condition name
$this->cart->removeCartCondition('Tax');
// cart should have now only 1 condition
expect($this->cart->getConditions()->count())->toEqual(1, 'Cart should have one condition');
expect($this->cart->getConditions()->first()->getName())->toEqual('Shipping');
});
});
describe('item level conditions', function () {
test('can add an item with a condition', function () {
test('can be added to an item', function () {
$saleCondition = new CartCondition([
'name' => '5% Discount',
'type' => 'sale',
@@ -942,6 +1278,41 @@
expect($this->cart->getTotal())->toEqual(18, 'Cart should have total of 18');
});
test('can be removed by name', function () {
$itemCondition1 = new CartCondition([
'name' => '5% Site Wide Sale',
'type' => 'sale',
'value' => '-5%',
]);
$itemCondition2 = new CartCondition([
'name' => 'Mother\'s Day Gift Pack',
'type' => 'promo',
'value' => '-25',
]);
$item = [
'id' => 1,
'name' => 'Body Scrub Kit',
'price' => 100,
'quantity' => 1,
'attributes' => [],
'conditions' => [$itemCondition1, $itemCondition2],
];
$this->cart->add($item);
// let's very first the item has 2 conditions in it
expect($this->cart->get(1)['conditions'])->toHaveCount(2, 'The item should have two conditions');
// now let's remove a condition on that item using the condition name
$this->cart->removeItemCondition(1, '5% Site Wide Sale');
// now we should have only 1 condition left on that item
expect($this->cart->get(1)['conditions'])->toHaveCount(1, 'Item should have one condition left');
expect($this->cart->get(1)['conditions'][1]->getName())->toEqual('Mother\'s Day Gift Pack');
});
test('can add item with multiple negative item conditions', function () {
$saleCondition = new CartCondition([
'name' => '5% Sale',
@@ -1082,110 +1453,36 @@
expect($this->cart->get(1)->getPriceSumWithConditions())->toEqual(0.00, "The item's price should be prevented from going below zero.");
});
// test('get cart condition by condition name', function () {
// $itemCondition1 = new CartCondition([
// 'name' => 'SALE 5%',
// 'type' => 'sale',
// 'target' => 'total',
// 'value' => '-5%',
// ]);
// $itemCondition2 = new CartCondition([
// 'name' => 'Item Gift Pack 25.00',
// 'type' => 'promo',
// 'target' => 'total',
// 'value' => '-25',
// ]);
test('can be removed by condition name', function () {
$heavyItemSurcharge = new CartCondition([
'name' => 'Heavy Item Surcharge',
'type' => 'surcharge',
'value' => '10',
]);
// $item = [
// 'id' => 456,
// 'name' => 'Sample Item 1',
// 'price' => 100,
// 'quantity' => 1,
// 'attributes' => [],
// ];
$tax = new CartCondition([
'name' => 'Tax',
'type' => 'tax',
'value' => '10%',
]);
// $this->cart->add($item);
$item = [
'id' => 12,
'name' => 'Beer (1 box)',
'price' => 410.60,
'quantity' => 1,
'attributes' => [],
'conditions' => [$heavyItemSurcharge, $tax],
];
// $this->cart->condition([$itemCondition1, $itemCondition2]);
$this->cart->add($item);
// // get a condition applied on cart by condition name
// $condition = $this->cart->getCondition($itemCondition1->getName());
expect($this->cart->get(12)['conditions'])->toHaveCount(2, 'Item should have two conditions');
// expect('SALE 5%')->toEqual($condition->getName());
// expect('total')->toEqual($condition->getTarget());
// expect('sale')->toEqual($condition->getType());
// expect('-5%')->toEqual($condition->getValue());
// });
$this->cart->removeItemCondition(12, 'Tax');
// test('remove cart condition by condition name', function () {
// $itemCondition1 = new CartCondition([
// 'name' => 'SALE 5%',
// 'type' => 'sale',
// 'target' => 'total',
// 'value' => '-5%',
// ]);
// $itemCondition2 = new CartCondition([
// 'name' => 'Item Gift Pack 25.00',
// 'type' => 'promo',
// 'target' => 'total',
// 'value' => '-25',
// ]);
// $item = [
// 'id' => 456,
// 'name' => 'Sample Item 1',
// 'price' => 100,
// 'quantity' => 1,
// 'attributes' => [],
// ];
// $this->cart->add($item);
// $this->cart->condition([$itemCondition1, $itemCondition2]);
// // let's prove first we have now two conditions in the cart
// expect($this->cart->getConditions()->count())->toEqual(2, 'Cart should have two conditions');
// // now let's remove a specific condition by condition name
// $this->cart->removeCartCondition('SALE 5%');
// // cart should have now only 1 condition
// expect($this->cart->getConditions()->count())->toEqual(1, 'Cart should have one condition');
// expect($this->cart->getConditions()->first()->getName())->toEqual('Item Gift Pack 25.00');
// });
// test('remove item condition by condition name', function () {
// $itemCondition1 = new CartCondition([
// 'name' => 'SALE 5%',
// 'type' => 'sale',
// 'value' => '-5%',
// ]);
// $itemCondition2 = new CartCondition([
// 'name' => 'Item Gift Pack 25.00',
// 'type' => 'promo',
// 'value' => '-25',
// ]);
// $item = [
// 'id' => 456,
// 'name' => 'Sample Item 1',
// 'price' => 100,
// 'quantity' => 1,
// 'attributes' => [],
// 'conditions' => [$itemCondition1, $itemCondition2],
// ];
// $this->cart->add($item);
// // let's very first the item has 2 conditions in it
// expect($this->cart->get(456)['conditions'])->toHaveCount(2, 'Item should have two conditions');
// // now let's remove a condition on that item using the condition name
// $this->cart->removeItemCondition(456, 'SALE 5%');
// // now we should have only 1 condition left on that item
// expect($this->cart->get(456)['conditions'])->toHaveCount(1, 'Item should have one condition left');
// });
expect($this->cart->get(12)['conditions'])->toHaveCount(1, 'Item should have one condition');
});
// test('remove item condition by condition name scenario two', function () {
// // NOTE: in this scenario, we will add the conditions not in array format
@@ -1556,50 +1853,4 @@
// expect($this->cart->getConditions()->first()->getName())->toEqual('Item Gift Pack 20');
// expect($this->cart->getConditions()->last()->getName())->toEqual('TAX');
// });
});
describe('conditions', function () {
test('can be completely cleared', function () {
$siteWideDiscount = new CartCondition([
'name' => 'Site Wide Discount',
'type' => 'discount',
'target' => 'total',
'value' => '-5%',
]);
$giftCard = new CartCondition([
'name' => 'Gift Card',
'type' => 'gift_card',
'target' => 'total',
'value' => '-25',
]);
$itemCondition = new CartCondition([
'name' => 'Item Discount',
'type' => 'discount',
'value' => '-5%',
]);
$item = [
'id' => 1,
'name' => 'Backpack',
'price' => 168.72,
'quantity' => 1,
'attributes' => [],
'conditions' => [$itemCondition],
];
$this->cart->add($item);
$this->cart->condition([$siteWideDiscount, $giftCard]);
expect($this->cart->getConditions()->count())->toEqual(2, 'Cart should have two conditions');
expect($this->cart->get(1)['conditions'])->toHaveCount(1, 'Cart should have one condition');
$this->cart->clearAllConditions();
expect($this->cart->getConditions()->count())->toEqual(0, 'Cart should have no conditions now');
expect($this->cart->get(1)['conditions'])->toHaveCount(0, 'Cart items should have no conditions now');
});
});
+38 -22
View File
@@ -1,8 +1,8 @@
<?php
use Wearepixel\Cart\Cart;
use Wearepixel\Cart\Tests\Helpers\MockProduct;
use Wearepixel\Cart\Tests\Helpers\SessionMock;
use Joelwmale\Cart\Cart;
use Joelwmale\Cart\Tests\Helpers\MockProduct;
use Joelwmale\Cart\Tests\Helpers\SessionMock;
beforeEach(function () {
$events = Mockery::mock('Illuminate\Contracts\Events\Dispatcher');
@@ -49,6 +49,19 @@
expect($this->cart->getTotal())->toEqual(0, 'Total should be 0');
});
test('can add an item an array with no price', function () {
$this->cart->add([
'id' => 455,
'name' => 'Sample Item',
'quantity' => 2,
]);
expect($this->cart->isEmpty())->toBeFalse('Cart should not be empty');
expect($this->cart->getContent()->count())->toEqual(1, 'Cart content should be 1');
expect($this->cart->getContent()->first()['id'])->toEqual(455, 'Item added has ID of 455 so first content ID should be 455');
expect($this->cart->getTotal())->toEqual(0, 'Total should be 0');
});
test('can add an item without attributes', function () {
$item = [
'id' => 1,
@@ -136,7 +149,7 @@
$item = $this->cart->get(1);
expect($item->attributes)->toBeInstanceOf('Wearepixel\\Cart\\ItemAttributeCollection');
expect($item->attributes)->toBeInstanceOf('Joelwmale\\Cart\\ItemAttributeCollection');
// now lets update the item with its new attributes
// when we get that item from cart, it should still be an instance of ItemAttributeCollection
@@ -149,7 +162,7 @@
$this->cart->update(1, $updatedItem);
expect($item->attributes)->toBeInstanceOf('Wearepixel\\Cart\\ItemAttributeCollection');
expect($item->attributes)->toBeInstanceOf('Joelwmale\\Cart\\ItemAttributeCollection');
});
test('item orders are preserved by the order they are added', function () {
@@ -283,6 +296,24 @@
expect($item['quantity'])->toEqual(9.9, 'Item quantity should be 9.9');
});
test('should throw an exception when no quantity is provided', function () {
$this->expectException('Joelwmale\Cart\Exceptions\InvalidItemException');
$this->expectExceptionMessage('The quantity must be at least 0.1.');
$this->cart->add(455, 'Sample Item', 100.99, 0, []);
});
test('should throw an exception when no id is provided', function () {
$this->expectException('Joelwmale\Cart\Exceptions\InvalidItemException');
$this->expectExceptionMessage('The id field is required.');
$this->cart->add('', 'Sample Item', 100.99, 2, []);
});
test('should throw an exception when no name is provided', function () {
$this->expectException('Joelwmale\Cart\Exceptions\InvalidItemException');
$this->expectExceptionMessage('The name field is required.');
$this->cart->add(523, '', 100.99, 2, []);
});
});
test('cart items attributes', function () {
@@ -542,21 +573,6 @@
expect($item['quantity'])->toEqual(3, 'Item quantity of with item ID of 456 should now be reduced to 2');
});
test('should throw exception when provided invalid values scenario one', function () {
$this->expectException('Wearepixel\Cart\Exceptions\InvalidItemException');
$this->cart->add(455, 'Sample Item', 100.99, 0, []);
});
test('should throw exception when provided invalid values scenario two', function () {
$this->expectException('Wearepixel\Cart\Exceptions\InvalidItemException');
$this->cart->add('', 'Sample Item', 100.99, 2, []);
});
test('should throw exception when provided invalid values scenario three', function () {
$this->expectException('Wearepixel\Cart\Exceptions\InvalidItemException');
$this->cart->add(523, '', 100.99, 2, []);
});
test('clearing cart', function () {
$items = [
[
@@ -630,7 +646,7 @@
expect($this->cart->getContent()->count())->toEqual(1, 'Cart should have 1 item on it');
expect($this->cart->getContent()->first()['id'])->toEqual(456, 'The first content must have ID of 456');
expect($this->cart->getContent()->first()['name'])->toEqual('Sample Item', 'The first content must have name of "Sample Item"');
expect($addedItem->model)->toBeInstanceOf('Wearepixel\Cart\Tests\Helpers\MockProduct');
expect($addedItem->model)->toBeInstanceOf('Joelwmale\Cart\Tests\Helpers\MockProduct');
});
test('cart can add items with multidimensional array with associated model', function () {
@@ -665,7 +681,7 @@
$content = $this->cart->getContent();
foreach ($content as $item) {
expect($item->model)->toBeInstanceOf('Wearepixel\Cart\Tests\Helpers\MockProduct');
expect($item->model)->toBeInstanceOf('Joelwmale\Cart\Tests\Helpers\MockProduct');
}
expect($this->cart->isEmpty())->toBeFalse('Cart should not be empty');
+2 -2
View File
@@ -1,7 +1,7 @@
<?php
use Wearepixel\Cart\Cart;
use Wearepixel\Cart\Tests\Helpers\SessionMock;
use Joelwmale\Cart\Cart;
use Joelwmale\Cart\Tests\Helpers\SessionMock;
beforeEach(function () {});
+2 -2
View File
@@ -1,7 +1,7 @@
<?php
use Wearepixel\Cart\Cart;
use Wearepixel\Cart\Tests\Helpers\SessionMock;
use Joelwmale\Cart\Cart;
use Joelwmale\Cart\Tests\Helpers\SessionMock;
beforeEach(function () {
$events = Mockery::mock('Illuminate\Contracts\Events\Dispatcher');
+6 -6
View File
@@ -1,9 +1,9 @@
<?php
use Wearepixel\Cart\Cart;
use Wearepixel\Cart\CartCondition;
use Wearepixel\Cart\Tests\Helpers\MockProduct;
use Wearepixel\Cart\Tests\Helpers\SessionMock;
use Joelwmale\Cart\Cart;
use Joelwmale\Cart\CartCondition;
use Joelwmale\Cart\Tests\Helpers\MockProduct;
use Joelwmale\Cart\Tests\Helpers\SessionMock;
beforeEach(function () {
$events = Mockery::mock('Illuminate\Contracts\Events\Dispatcher');
@@ -47,7 +47,7 @@
});
test('item get conditions with conditions', function () {
$itemCondition1 = new \Wearepixel\Cart\CartCondition([
$itemCondition1 = new \Joelwmale\Cart\CartCondition([
'name' => 'SALE 5%',
'type' => 'sale',
'target' => 'item',
@@ -77,7 +77,7 @@
});
test('it will throw an exception when a non existing model is being associated', function () {
$this->expectException(\Wearepixel\Cart\Exceptions\UnknownModelException::class);
$this->expectException(\Joelwmale\Cart\Exceptions\UnknownModelException::class);
$this->expectExceptionMessage('The supplied model SomeModel does not exist.');
$this->cart->add(1, 'Test item', 1, 10.00)->associate('SomeModel');
+2 -2
View File
@@ -1,7 +1,7 @@
<?php
use Wearepixel\Cart\Cart;
use Wearepixel\Cart\Tests\Helpers\SessionMock;
use Joelwmale\Cart\Cart;
use Joelwmale\Cart\Tests\Helpers\SessionMock;
beforeEach(function () {
$events = Mockery::mock('Illuminate\Contracts\Events\Dispatcher');