mirror of
https://github.com/wearepixel/laravel-cart.git
synced 2026-11-14 13:51:44 +00:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f60bf92157 | ||
|
|
a231ed8c43 | ||
|
|
599051631c | ||
|
|
b3ef4c38fc | ||
|
|
a45121ca63 | ||
|
|
5505f121c7 | ||
|
|
472d505041 | ||
|
|
c6c4240c5f | ||
|
|
54d7c8a54f | ||
|
|
a8d743eb9b | ||
|
|
b7381573e8 | ||
|
|
d4d4df7d58 | ||
|
|
6ea2cb3b8b | ||
|
|
7a2c41e02d | ||
|
|
9a59857825 | ||
|
|
43238b6f2e | ||
|
|
c0f0fcd2f0 | ||
|
|
185c4572ae | ||
|
|
c111cda3aa | ||
|
|
ab9eb6c873 | ||
|
|
7ee26add8d | ||
|
|
05318b7b13 | ||
|
|
4d2efcdeae | ||
|
|
a269c188e4 | ||
|
|
2ccba20119 | ||
|
|
313a4f7aa2 | ||
|
|
4a312a37e2 | ||
|
|
274a8504af | ||
|
|
4f22672ca5 | ||
|
|
61475a7060 | ||
|
|
6604cf984d | ||
|
|
7d955d722c | ||
|
|
54d94d8d12 | ||
|
|
e49ebe02e0 | ||
|
|
28b451583d | ||
|
|
3673f360b7 | ||
|
|
f6447ad4d9 | ||
|
|
b102dd2356 | ||
|
|
25fc662c05 | ||
|
|
57328c2f64 | ||
|
|
4d19211f2c | ||
|
|
8cee4f6208 | ||
|
|
0ec0668bcf | ||
|
|
9a4b5382bd | ||
|
|
95054f41a4 | ||
|
|
0a9bcc2832 | ||
|
|
8c8c90c170 | ||
|
|
18c753f39b | ||
|
|
d12a566366 | ||
|
|
66fd4c9099 | ||
|
|
d48f54cf16 | ||
|
|
24f64e712c | ||
|
|
85ae0c30c5 |
@@ -3,15 +3,15 @@ version: 2
|
||||
updates:
|
||||
- package-ecosystem: "github-actions"
|
||||
directory: "/"
|
||||
target-branch: "develop"
|
||||
target-branch: "master"
|
||||
schedule:
|
||||
interval: "weekly"
|
||||
labels:
|
||||
- "dependencies"
|
||||
- "deps"
|
||||
- package-ecosystem: "composer"
|
||||
directory: "/"
|
||||
target-branch: "develop"
|
||||
target-branch: "master"
|
||||
schedule:
|
||||
interval: "weekly"
|
||||
labels:
|
||||
- "dependencies"
|
||||
- "deps"
|
||||
|
||||
@@ -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>"
|
||||
@@ -13,7 +13,7 @@ jobs:
|
||||
strategy:
|
||||
fail-fast: true
|
||||
matrix:
|
||||
php: ['8.1','8.2', '8.3']
|
||||
php: ['8.1', '8.2', '8.3']
|
||||
stability: [prefer-stable]
|
||||
|
||||
steps:
|
||||
|
||||
+2
-1
@@ -2,4 +2,5 @@
|
||||
.DS_Store
|
||||
.idea
|
||||
.phpunit.result.cache
|
||||
READMETODO.md
|
||||
READMETODO.md
|
||||
build
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
The MIT License (MIT)
|
||||
|
||||
Copyright (c) Pixel <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
|
||||
|
||||
@@ -1,11 +1,11 @@
|
||||
[](https://packagist.org/packages/wearepixel/laravel-cart)
|
||||
[](https://github.com/wearepixel/laravel-cart/actions?query=workflow%3ATests+branch%3Amaster)
|
||||
[](https://packagist.org/packages/wearepixel/laravel-cart)
|
||||
[](https://packagist.org/packages/wearepixel/laravel-cart)
|
||||
[](https://packagist.org/packages/joelwmale/laravel-cart)
|
||||
[](https://github.com/joelwmale/laravel-cart/actions?query=workflow%3ATests+branch%3Amaster)
|
||||
[](https://packagist.org/packages/joelwmale/laravel-cart)
|
||||
[](https://packagist.org/packages/joelwmale/laravel-cart)
|
||||
|
||||
A Cart Implementation for Laravel.
|
||||
|
||||
Supported Laravel Versions: 9, 10, 11
|
||||
Supported Laravel Versions: 9, 10, and 11
|
||||
|
||||
## Quick Demo
|
||||
|
||||
@@ -33,19 +33,52 @@ ## 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"
|
||||
```
|
||||
|
||||
## HOW TO USE
|
||||
### Formatting Numbers
|
||||
|
||||
- [Usage](#usage)
|
||||
The package by default does not use round to format numbers, and instead returns the number using floatval().
|
||||
|
||||
If you'd prefer this number to be rounded, you can customize the formatting in the configuration file.
|
||||
|
||||
Defaults to false.
|
||||
|
||||
```php
|
||||
'format_numbers' => env('LARAVEL_CART_FORMAT_VALUES', false),
|
||||
'round_mode' => env('LARAVEL_CART_ROUND_MODE', 'down'),
|
||||
```
|
||||
|
||||
### Decimals
|
||||
|
||||
You can customize the number of decimals in the configuration file.
|
||||
|
||||
Defaults to 2.
|
||||
|
||||
```php
|
||||
'decimals' => env('LARAVEL_CART_DECIMALS', 2),
|
||||
```
|
||||
|
||||
### Round Mode
|
||||
|
||||
The package uses the `round` function to round the prices. You can customize the rounding mode in the configuration file.
|
||||
|
||||
Defaults to `down`.
|
||||
|
||||
```php
|
||||
'round_mode' => env('LARAVEL_CART_ROUND_MODE', 'down'),
|
||||
```
|
||||
|
||||
## Usage
|
||||
|
||||
- [Basic Usage](#basic-usage)
|
||||
- [Conditions](#conditions)
|
||||
- [Items](#items)
|
||||
- [Associating Models](#associating-models)
|
||||
@@ -255,12 +288,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
|
||||
@@ -269,7 +304,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.
|
||||
@@ -282,7 +317,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.
|
||||
@@ -290,7 +325,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.
|
||||
@@ -305,7 +340,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',
|
||||
@@ -329,26 +364,167 @@ #### 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
|
||||
```
|
||||
|
||||
### Calculating condition value: **Cart::getCondition('Tax: 10%')->getCalculatedValue($subTotal)**
|
||||
#### 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:
|
||||
|
||||
1. Using the `getCalculatedValue` method on the condition instance
|
||||
2. Using the `getCalculatedValueForCondition` method on the cart instance and passing the condition name
|
||||
|
||||
#### 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);
|
||||
```
|
||||
|
||||
#### Using the `getCalculatedValueForCondition` method on the cart instance
|
||||
|
||||
This method automatically calculates the value of a condition by it's name based on the order of the conditions.
|
||||
|
||||
```php
|
||||
Cart::add([
|
||||
'id' => 1,
|
||||
'name' => 'Apple iPhone 15',
|
||||
'price' => 200,
|
||||
'quantity' => 1,
|
||||
'attributes' => [],
|
||||
]);
|
||||
|
||||
$couponDiscount = new CartCondition([
|
||||
'name' => 'Coupon Discount',
|
||||
'type' => 'discount',
|
||||
'target' => 'subtotal',
|
||||
'value' => '-200',
|
||||
'order' => 1,
|
||||
]);
|
||||
|
||||
$giftCard = new CartCondition([
|
||||
'name' => 'Gift Card',
|
||||
'type' => 'discount',
|
||||
'target' => 'subtotal',
|
||||
'value' => '-200',
|
||||
'order' => 2,
|
||||
]);
|
||||
|
||||
Cart::getCalculatedValueForCondition('Coupon Discount'); // returns 200
|
||||
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.
|
||||
@@ -356,7 +532,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%',
|
||||
@@ -376,7 +552,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%',
|
||||
@@ -410,7 +586,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.
|
||||
|
||||
@@ -426,10 +602,18 @@ #### Add condition to existing Item on the cart: **Cart::addItemCondition($produ
|
||||
|
||||
### Clearing Cart Conditions: **Cart::clearCartConditions()**
|
||||
|
||||
This clears all cart level conditions, and does not affect item level conditions.
|
||||
|
||||
```php
|
||||
Cart::clearCartConditions()
|
||||
```
|
||||
|
||||
If you wish to clear all conditions from all items and the cart, use **Cart::clearAllConditions()**
|
||||
|
||||
```php
|
||||
Cart::clearAllConditions()
|
||||
```
|
||||
|
||||
### Remove a specific cart condtion: **Cart::removeCartCondition($conditionName)**
|
||||
|
||||
```php
|
||||
|
||||
+10
-9
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "wearepixel/laravel-cart",
|
||||
"version": "1.0.0",
|
||||
"name": "joelwmale/laravel-cart",
|
||||
"version": "1.0.12",
|
||||
"description": "A cart implementation for Laravel",
|
||||
"keywords": [
|
||||
"laravel",
|
||||
@@ -15,33 +15,34 @@
|
||||
},
|
||||
{
|
||||
"name": "Joel Male",
|
||||
"email": "joel@wearepixel.com.au"
|
||||
"email": "joel@joelmale.com"
|
||||
}
|
||||
],
|
||||
"require": {
|
||||
"php": ">=8.0",
|
||||
"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"
|
||||
},
|
||||
"require-dev": {
|
||||
"mockery/mockery": "^1.4.2",
|
||||
"laravel/pint": "dev-main",
|
||||
"pestphp/pest": "2.34.4"
|
||||
"laravel/pint": "^1.17",
|
||||
"pestphp/pest": "2.35.1",
|
||||
"larapack/dd": "1.1"
|
||||
},
|
||||
"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
+578
-530
File diff suppressed because it is too large
Load Diff
+7
-15
@@ -3,34 +3,26 @@
|
||||
return [
|
||||
/*
|
||||
* ---------------------------------------------------------------
|
||||
* formatting
|
||||
* Formatting
|
||||
* ---------------------------------------------------------------
|
||||
*
|
||||
* the formatting of shopping cart values
|
||||
*/
|
||||
'format_numbers' => env('SHOPPING_FORMAT_VALUES', false),
|
||||
'format_numbers' => env('LARAVEL_CART_FORMAT_VALUES', false),
|
||||
|
||||
'decimals' => env('SHOPPING_DECIMALS', 0),
|
||||
'decimals' => env('LARAVEL_CART_DECIMALS', 0),
|
||||
|
||||
'dec_point' => env('SHOPPING_DEC_POINT', '.'),
|
||||
|
||||
'thousands_sep' => env('SHOPPING_THOUSANDS_SEP', ','),
|
||||
'round_mode' => env('LARAVEL_CART_ROUND_MODE', 'down'),
|
||||
|
||||
/*
|
||||
* ---------------------------------------------------------------
|
||||
* persistence
|
||||
* Persistence
|
||||
* ---------------------------------------------------------------
|
||||
*
|
||||
* the configuration for persisting cart
|
||||
*/
|
||||
'storage' => null,
|
||||
|
||||
/*
|
||||
* ---------------------------------------------------------------
|
||||
* events
|
||||
* Events
|
||||
* ---------------------------------------------------------------
|
||||
*
|
||||
* the configuration for cart events
|
||||
*/
|
||||
'events' => null,
|
||||
];
|
||||
];
|
||||
|
||||
@@ -1,17 +1,17 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<phpunit xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:noNamespaceSchemaLocation="./vendor/phpunit/phpunit/phpunit.xsd"
|
||||
bootstrap="vendor/autoload.php"
|
||||
colors="true"
|
||||
xsi:noNamespaceSchemaLocation="https://schema.phpunit.de/10.4/phpunit.xsd"
|
||||
>
|
||||
<testsuites>
|
||||
<testsuite name="Unit">
|
||||
<directory suffix="Test.php">./tests/Unit</directory>
|
||||
</testsuite>
|
||||
</testsuites>
|
||||
<source>
|
||||
<source>
|
||||
<include>
|
||||
<directory suffix=".php">./src</directory>
|
||||
</include>
|
||||
</source>
|
||||
<testsuites>
|
||||
<testsuite name="Laravel Cart Test Suite">
|
||||
<directory>tests</directory>
|
||||
</testsuite>
|
||||
</testsuites>
|
||||
</phpunit>
|
||||
@@ -1,12 +1,12 @@
|
||||
{
|
||||
"preset": "laravel",
|
||||
"rules": {
|
||||
"concat_space": {
|
||||
"spacing": "one"
|
||||
},
|
||||
"class_attributes_separation": false,
|
||||
"ordered_imports": {
|
||||
"sort_algorithm": "length"
|
||||
}
|
||||
"preset": "laravel",
|
||||
"rules": {
|
||||
"concat_space": {
|
||||
"spacing": "one"
|
||||
},
|
||||
"class_attributes_separation": false,
|
||||
"ordered_imports": {
|
||||
"sort_algorithm": "length"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+168
-171
@@ -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);
|
||||
}
|
||||
@@ -131,29 +91,28 @@ public function 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
|
||||
public function add(
|
||||
string|int|array $id,
|
||||
?string $name = null,
|
||||
?float $price = null,
|
||||
int|float|null $quantity = null,
|
||||
array $attributes = [],
|
||||
array|CartCondition $conditions = [],
|
||||
?string $associatedModel = null
|
||||
): self {
|
||||
// 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($id, $name = null, $price = null, $quantity = null, $attribu
|
||||
$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($id, $name = null, $price = null, $quantity = null, $attribu
|
||||
return $this;
|
||||
}
|
||||
|
||||
// if we are here, we are adding a single item
|
||||
$data = [
|
||||
'id' => $id,
|
||||
'name' => $name,
|
||||
@@ -191,16 +151,11 @@ public function add($id, $name = null, $price = null, $quantity = null, $attribu
|
||||
// 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)) {
|
||||
|
||||
if ($this->get($id)) {
|
||||
$this->update($id, $item);
|
||||
} else {
|
||||
|
||||
$this->addRow($id, $item);
|
||||
$this->addItem($id, $item);
|
||||
}
|
||||
|
||||
$this->currentItemId = $id;
|
||||
@@ -209,15 +164,9 @@ public function add($id, $name = null, $price = null, $quantity = null, $attribu
|
||||
}
|
||||
|
||||
/**
|
||||
* 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
|
||||
* Update a cart item with whatever data is passed in
|
||||
*/
|
||||
public function update($id, $data)
|
||||
public function update(int|string $id, array $data): bool
|
||||
{
|
||||
if ($this->fireEvent('updating', $data) === false) {
|
||||
return false;
|
||||
@@ -225,21 +174,13 @@ public function update($id, $data)
|
||||
|
||||
$cart = $this->getContent();
|
||||
|
||||
$item = $cart->pull($id);
|
||||
$item = $cart->get($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']) {
|
||||
if (isset($value['relative']) && $value['relative'] === true) {
|
||||
$item = $this->updateQuantityRelative($item, $key, $value['value']);
|
||||
} else {
|
||||
$item = $this->updateQuantityNotRelative($item, $key, $value['value']);
|
||||
@@ -255,6 +196,7 @@ public function update($id, $data)
|
||||
}
|
||||
}
|
||||
|
||||
// update the item in the cart
|
||||
$cart->put($id, $item);
|
||||
|
||||
$this->save($cart);
|
||||
@@ -285,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'];
|
||||
@@ -353,14 +295,14 @@ public function clear()
|
||||
}
|
||||
|
||||
/**
|
||||
* add a condition on the cart
|
||||
*
|
||||
* @param CartCondition|array $condition
|
||||
* @return $this
|
||||
* Adds a condition to the cart
|
||||
*/
|
||||
/**
|
||||
* Adds a condition to the cart
|
||||
*
|
||||
* @throws InvalidConditionException
|
||||
*/
|
||||
public function condition($condition)
|
||||
public function condition(array|CartCondition $condition): self
|
||||
{
|
||||
if (is_array($condition)) {
|
||||
foreach ($condition as $c) {
|
||||
@@ -371,7 +313,7 @@ public function condition($condition)
|
||||
}
|
||||
|
||||
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();
|
||||
@@ -396,11 +338,29 @@ public function condition($condition)
|
||||
/**
|
||||
* 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;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -429,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());
|
||||
@@ -442,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)
|
||||
{
|
||||
@@ -497,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) {
|
||||
@@ -533,13 +484,9 @@ public function clearItemConditions($itemId)
|
||||
}
|
||||
|
||||
/**
|
||||
* 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
|
||||
* Clear cart conditions (this does not clear item conditions)
|
||||
*/
|
||||
public function clearCartConditions()
|
||||
public function clearCartConditions(): void
|
||||
{
|
||||
$this->session->put(
|
||||
$this->sessionKeyCartConditions,
|
||||
@@ -547,6 +494,20 @@ public function clearCartConditions()
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Clear all conditions from all items and the cart
|
||||
*/
|
||||
public function clearAllConditions(): void
|
||||
{
|
||||
$cart = $this->getContent();
|
||||
|
||||
$cart->each(function ($item) {
|
||||
$this->clearItemConditions($item->id);
|
||||
});
|
||||
|
||||
$this->clearCartConditions();
|
||||
}
|
||||
|
||||
/**
|
||||
* get cart sub total without conditions
|
||||
*
|
||||
@@ -568,81 +529,108 @@ public function getSubTotalWithoutConditions($formatted = true)
|
||||
* get cart sub total
|
||||
*
|
||||
* @param bool $formatted
|
||||
* @return float
|
||||
*/
|
||||
public function getSubTotal($formatted = true)
|
||||
public function getSubTotal($formatted = true): int|float|string
|
||||
{
|
||||
$cart = $this->getContent();
|
||||
|
||||
$sum = $cart->sum(function (ItemCollection $item) {
|
||||
$subTotal = 0.00;
|
||||
// add all the items together with conditions applied
|
||||
$subTotalSum = $this->getContent()->sum(function (ItemCollection $item) {
|
||||
return $item->getPriceSumWithConditions(false);
|
||||
});
|
||||
|
||||
// get the conditions that are meant to be applied
|
||||
// on the subtotal and apply it here before returning the subtotal
|
||||
$conditions = $this
|
||||
->getConditions()
|
||||
->filter(function (CartCondition $cond) {
|
||||
return $cond->getTarget() === 'subtotal';
|
||||
$conditionsForSubtotal = $this->getConditions()
|
||||
->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();
|
||||
});
|
||||
|
||||
// if there is no conditions, lets just return the sum
|
||||
if (! $conditions->count()) {
|
||||
return Helpers::formatValue($sum, $formatted, $this->config);
|
||||
if ($conditionsForSubtotal->isEmpty()) {
|
||||
return Helpers::formatValue($subTotalSum, $formatted, $this->config);
|
||||
}
|
||||
|
||||
// there are conditions, lets apply it
|
||||
$newTotal = 0.00;
|
||||
$process = 0;
|
||||
$index = 0;
|
||||
|
||||
$conditions->each(function (CartCondition $cond) use ($sum, &$newTotal, &$process) {
|
||||
$conditionsForSubtotal->each(function (CartCondition $condition) use ($subTotalSum, &$subTotal, &$index) {
|
||||
$toBeCalculated = $index > 0 ? $subTotal : $subTotalSum;
|
||||
|
||||
// if this is the first iteration, the toBeCalculated
|
||||
// should be the sum as initial point of value.
|
||||
$toBeCalculated = ($process > 0) ? $newTotal : $sum;
|
||||
$subTotal = $condition->applyCondition($toBeCalculated);
|
||||
|
||||
$newTotal = $cond->applyCondition($toBeCalculated);
|
||||
|
||||
$process++;
|
||||
$index++;
|
||||
});
|
||||
|
||||
return Helpers::formatValue((float) $newTotal, $formatted, $this->config);
|
||||
return Helpers::formatValue($subTotal, $formatted, $this->config);
|
||||
}
|
||||
|
||||
/**
|
||||
* the new total in which conditions are already applied
|
||||
*
|
||||
* @return float
|
||||
* Get the total of the cart with conditions applied
|
||||
*/
|
||||
public function getTotal()
|
||||
public function getTotal(): int|float
|
||||
{
|
||||
$total = 0.00;
|
||||
$subTotal = $this->getSubTotal(false);
|
||||
|
||||
$newTotal = 0.00;
|
||||
|
||||
$process = 0;
|
||||
|
||||
$conditions = $this
|
||||
->getConditions()
|
||||
->filter(function (CartCondition $cond) {
|
||||
return $cond->getTarget() === 'total';
|
||||
$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
|
||||
if (! $conditions->count()) {
|
||||
if (! $conditionsForTotal->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;
|
||||
$index = 0;
|
||||
|
||||
$newTotal = $cond->applyCondition($toBeCalculated);
|
||||
$conditionsForTotal->each(function (CartCondition $condition) use ($subTotal, &$total, &$index) {
|
||||
$toBeCalculated = ($index > 0) ? $total : $subTotal;
|
||||
|
||||
$process++;
|
||||
});
|
||||
$total = $condition->applyCondition($toBeCalculated);
|
||||
|
||||
return Helpers::formatValue($newTotal, $this->config['format_numbers'], $this->config);
|
||||
$index++;
|
||||
});
|
||||
|
||||
return Helpers::formatValue($total, $this->config['format_numbers'], $this->config);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the calculated value for a condition by it's name
|
||||
*/
|
||||
public function getCalculatedValueForCondition(string $conditionName): int|float
|
||||
{
|
||||
$conditions = $this->getConditions();
|
||||
|
||||
$subTotal = $this->getSubTotalWithoutConditions(false);
|
||||
|
||||
foreach ($conditions as $condition) {
|
||||
$conditionValue = $condition->getCalculatedValue($subTotal);
|
||||
|
||||
if ($condition->getName() === $conditionName) {
|
||||
return $conditionValue;
|
||||
}
|
||||
|
||||
$subTotal -= $conditionValue;
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -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;
|
||||
@@ -717,7 +714,7 @@ protected function validate($item)
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
protected function addRow($id, $item)
|
||||
protected function addItem($id, $item)
|
||||
{
|
||||
if ($this->fireEvent('adding', $item) === false) {
|
||||
return false;
|
||||
@@ -737,7 +734,7 @@ protected function addRow($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;
|
||||
@@ -784,7 +781,7 @@ protected function itemHasConditions($item)
|
||||
protected function updateQuantityRelative($item, $key, $value)
|
||||
{
|
||||
if (preg_match('/\-/', $value) == 1) {
|
||||
$value = (int) str_replace('-', '', $value);
|
||||
$value = (float) str_replace('-', '', $value);
|
||||
|
||||
// we will not allowed to reduced quantity to 0, so if the given value
|
||||
// would result to item quantity of 0, we will not do it.
|
||||
@@ -792,9 +789,9 @@ protected function updateQuantityRelative($item, $key, $value)
|
||||
$item[$key] -= $value;
|
||||
}
|
||||
} elseif (preg_match('/\+/', $value) == 1) {
|
||||
$item[$key] += (int) str_replace('+', '', $value);
|
||||
$item[$key] += (float) str_replace('+', '', $value);
|
||||
} else {
|
||||
$item[$key] += (int) $value;
|
||||
$item[$key] += (float) $value;
|
||||
}
|
||||
|
||||
return $item;
|
||||
@@ -807,7 +804,7 @@ protected function updateQuantityRelative($item, $key, $value)
|
||||
*/
|
||||
protected function updateQuantityNotRelative($item, $key, $value)
|
||||
{
|
||||
$item[$key] = (int) $value;
|
||||
$item[$key] = (float) $value;
|
||||
|
||||
return $item;
|
||||
}
|
||||
|
||||
@@ -1,9 +1,7 @@
|
||||
<?php
|
||||
|
||||
namespace Wearepixel\Cart;
|
||||
namespace Joelwmale\Cart;
|
||||
|
||||
use Illuminate\Support\Collection;
|
||||
|
||||
class CartCollection extends Collection
|
||||
{
|
||||
}
|
||||
class CartCollection extends Collection {}
|
||||
|
||||
+39
-13
@@ -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;
|
||||
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
|
||||
*
|
||||
@@ -77,14 +90,20 @@ public function getAttributes()
|
||||
|
||||
/**
|
||||
* the value of this the condition
|
||||
*
|
||||
* @return mixed
|
||||
*/
|
||||
public function getValue()
|
||||
public function getValue(): int|float|string
|
||||
{
|
||||
return $this->args['value'];
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the value of this condition
|
||||
*/
|
||||
public function setValue($value): void
|
||||
{
|
||||
$this->args['value'] = $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
|
||||
@@ -123,9 +142,11 @@ public function applyCondition($totalOrSubTotalOrPrice)
|
||||
*
|
||||
* @return mixed
|
||||
*/
|
||||
public function getCalculatedValue($totalOrSubTotalOrPrice)
|
||||
public function getCalculatedValue($totalOrSubTotalOrPrice = null): int|float
|
||||
{
|
||||
$this->apply($totalOrSubTotalOrPrice, $this->getValue());
|
||||
if ($totalOrSubTotalOrPrice) {
|
||||
$this->apply($totalOrSubTotalOrPrice, $this->getValue());
|
||||
}
|
||||
|
||||
return $this->parsedRawValue;
|
||||
}
|
||||
@@ -245,4 +266,9 @@ protected function validate($args)
|
||||
throw new InvalidConditionException($validator->messages()->first());
|
||||
}
|
||||
}
|
||||
|
||||
public function toArray(): array
|
||||
{
|
||||
return $this->args;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
<?php
|
||||
|
||||
namespace Wearepixel\Cart;
|
||||
namespace Joelwmale\Cart;
|
||||
|
||||
use Illuminate\Support\Collection;
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
<?php
|
||||
|
||||
namespace Wearepixel\Cart;
|
||||
namespace Joelwmale\Cart;
|
||||
|
||||
use Illuminate\Support\ServiceProvider;
|
||||
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
<?php
|
||||
|
||||
namespace Wearepixel\Cart\Exceptions;
|
||||
namespace Joelwmale\Cart\Exceptions;
|
||||
|
||||
class InvalidConditionException extends \Exception {}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
<?php
|
||||
|
||||
namespace Wearepixel\Cart\Exceptions;
|
||||
namespace Joelwmale\Cart\Exceptions;
|
||||
|
||||
class InvalidItemException extends \Exception {}
|
||||
|
||||
@@ -1,7 +1,5 @@
|
||||
<?php
|
||||
|
||||
namespace Wearepixel\Cart\Exceptions;
|
||||
namespace Joelwmale\Cart\Exceptions;
|
||||
|
||||
class UnknownModelException extends \Exception
|
||||
{
|
||||
}
|
||||
class UnknownModelException extends \Exception {}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
<?php
|
||||
|
||||
namespace Wearepixel\Cart\Facades;
|
||||
namespace Joelwmale\Cart\Facades;
|
||||
|
||||
use Illuminate\Support\Facades\Facade;
|
||||
|
||||
|
||||
+26
-16
@@ -1,29 +1,34 @@
|
||||
<?php
|
||||
|
||||
namespace Wearepixel\Cart\Helpers;
|
||||
namespace Joelwmale\Cart\Helpers;
|
||||
|
||||
class Helpers
|
||||
{
|
||||
/**
|
||||
* normalize price
|
||||
*
|
||||
* @return float
|
||||
* Normalize prices
|
||||
*/
|
||||
public static function normalizePrice($price)
|
||||
public static function normalizePrice($price): ?float
|
||||
{
|
||||
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
|
||||
* Get the rounding mode
|
||||
*/
|
||||
public static function isMultiArray($array, $recursive = false)
|
||||
public static function roundMode($config): int
|
||||
{
|
||||
if (isset($config['round_mode']) && $config['round_mode'] == 'up') {
|
||||
return PHP_ROUND_HALF_UP;
|
||||
}
|
||||
|
||||
return PHP_ROUND_HALF_DOWN;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if array is multi dimensional array
|
||||
* This will only check if the first element of the array is an array
|
||||
*/
|
||||
public static function isMultiArray(array $array, bool $recursive = false): bool
|
||||
{
|
||||
if ($recursive) {
|
||||
return (count($array) == count($array, COUNT_RECURSIVE)) ? false : true;
|
||||
@@ -35,8 +40,9 @@ public static function isMultiArray($array, $recursive = false)
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -56,10 +62,14 @@ public static function issetAndHasValueOrAssignDefault(&$var, $default = false)
|
||||
|
||||
public static function formatValue($value, $formatNumber, $config)
|
||||
{
|
||||
if (! $value) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
if ($formatNumber || $config['format_numbers']) {
|
||||
return floatval(number_format($value, $config['decimals'], $config['dec_point'], $config['thousands_sep']));
|
||||
return round($value, $config['decimals'], self::roundMode($config));
|
||||
} else {
|
||||
return $value;
|
||||
return floatval($value);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
<?php
|
||||
|
||||
namespace Wearepixel\Cart;
|
||||
namespace Joelwmale\Cart;
|
||||
|
||||
use Illuminate\Support\Collection;
|
||||
|
||||
|
||||
@@ -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,5 +1,5 @@
|
||||
<?php
|
||||
|
||||
namespace Wearepixel\Cart\Validators;
|
||||
namespace Joelwmale\Cart\Validators;
|
||||
|
||||
class CartConditionValidator extends Validator {}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
<?php
|
||||
|
||||
namespace Wearepixel\Cart\Validators;
|
||||
namespace Joelwmale\Cart\Validators;
|
||||
|
||||
class CartItemValidator extends Validator {}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
<?php
|
||||
|
||||
namespace Wearepixel\Cart\Validators;
|
||||
namespace Joelwmale\Cart\Validators;
|
||||
|
||||
use Illuminate\Validation\Factory;
|
||||
use Illuminate\Filesystem\Filesystem;
|
||||
|
||||
@@ -0,0 +1,9 @@
|
||||
<?php
|
||||
|
||||
return [
|
||||
'format_numbers' => true,
|
||||
'decimals' => 2,
|
||||
'dec_point' => '.',
|
||||
'thousands_sep' => ',',
|
||||
'use_cents' => false,
|
||||
];
|
||||
@@ -1,8 +1,7 @@
|
||||
<?php
|
||||
|
||||
return [
|
||||
'format_numbers' => false,
|
||||
'format_numbers' => true,
|
||||
'decimals' => 2,
|
||||
'dec_point' => '.',
|
||||
'thousands_sep' => ',',
|
||||
'round_mode' => 'up',
|
||||
];
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
<?php
|
||||
|
||||
namespace Wearepixel\Cart\Tests\Helpers;
|
||||
namespace Joelwmale\Cart\Tests\Helpers;
|
||||
|
||||
use Illuminate\Contracts\Database\ModelIdentifier;
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
<?php
|
||||
|
||||
namespace Wearepixel\Cart\Tests\Helpers;
|
||||
namespace Joelwmale\Cart\Tests\Helpers;
|
||||
|
||||
class SessionMock
|
||||
{
|
||||
|
||||
@@ -27,43 +27,3 @@
|
||||
expect()->extend('toBeOne', function () {
|
||||
return $this->toBe(1);
|
||||
});
|
||||
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| Functions
|
||||
|--------------------------------------------------------------------------
|
||||
|
|
||||
| While Pest is very powerful out-of-the-box, you may have some testing code specific to your
|
||||
| project that you don't want to repeat in every file. Here you can also expose helpers as
|
||||
| global functions to help you to reduce the number of lines of code in your test files.
|
||||
|
|
||||
*/
|
||||
|
||||
function fillCart()
|
||||
{
|
||||
$items = [
|
||||
[
|
||||
'id' => 456,
|
||||
'name' => 'Sample Item 1',
|
||||
'price' => 67.99,
|
||||
'quantity' => 1,
|
||||
'attributes' => [],
|
||||
],
|
||||
[
|
||||
'id' => 568,
|
||||
'name' => 'Sample Item 2',
|
||||
'price' => 69.25,
|
||||
'quantity' => 1,
|
||||
'attributes' => [],
|
||||
],
|
||||
[
|
||||
'id' => 856,
|
||||
'name' => 'Sample Item 3',
|
||||
'price' => 50.25,
|
||||
'quantity' => 1,
|
||||
'attributes' => [],
|
||||
],
|
||||
];
|
||||
|
||||
$this->cart->add($items);
|
||||
}
|
||||
|
||||
+1823
-829
File diff suppressed because it is too large
Load Diff
+276
-116
@@ -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');
|
||||
@@ -21,115 +21,299 @@
|
||||
Mockery::close();
|
||||
});
|
||||
|
||||
test('cart can add item', function () {
|
||||
$this->cart->add(455, 'Sample Item', 100.99, 2, []);
|
||||
describe('cart', function () {
|
||||
test('can add an item', function () {
|
||||
$this->cart->add(1, 'Sample Item', 100.99, 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->getContent()->first()['price'])->toEqual(100.99, 'Item added has price of 100.99 so first content price should be 100.99');
|
||||
});
|
||||
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(1, 'Item added has ID of 1 so first content ID should be 1');
|
||||
expect($this->cart->getContent()->first()['price'])->toEqual(100.99, 'Item added has price of 100.99 so first content price should be 100.99');
|
||||
});
|
||||
|
||||
test('cart can add item with no price', function () {
|
||||
$this->cart->add(455, 'Sample Item', 0, 2, []);
|
||||
test('can add an item in cents', function () {
|
||||
$this->cart->add(1, 'Sample Item', 10099, 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');
|
||||
});
|
||||
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(1, 'Item added has ID of 1 so first content ID should be 1');
|
||||
expect($this->cart->getContent()->first()['price'])->toEqual(10099, 'Item added has price of 100.99 so first content price should be 100.99');
|
||||
});
|
||||
|
||||
test('cart can add items as array', function () {
|
||||
$item = [
|
||||
'id' => 456,
|
||||
'name' => 'Sample Item',
|
||||
'price' => 67.99,
|
||||
'quantity' => 4,
|
||||
'attributes' => [],
|
||||
];
|
||||
test('can add an item with no price', function () {
|
||||
$this->cart->add(455, 'Sample Item', 0, 2, []);
|
||||
|
||||
$this->cart->add($item);
|
||||
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');
|
||||
});
|
||||
|
||||
expect($this->cart->isEmpty())->toBeFalse('Cart should not be empty');
|
||||
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"');
|
||||
});
|
||||
test('can add an item an array with no price', function () {
|
||||
$this->cart->add([
|
||||
'id' => 455,
|
||||
'name' => 'Sample Item',
|
||||
'quantity' => 2,
|
||||
]);
|
||||
|
||||
test('cart can add items with multidimensional array', function () {
|
||||
$items = [
|
||||
[
|
||||
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,
|
||||
'name' => 'Pocket Shorts',
|
||||
'price' => 67.99,
|
||||
'quantity' => 2,
|
||||
];
|
||||
|
||||
$this->cart->add($item);
|
||||
|
||||
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->getTotal())->toEqual(135.98, 'Cart total should be 135.98');
|
||||
});
|
||||
|
||||
test('can add items as array', function () {
|
||||
$item = [
|
||||
'id' => 456,
|
||||
'name' => 'Sample Item 1',
|
||||
'name' => 'Sample Item',
|
||||
'price' => 67.99,
|
||||
'quantity' => 4,
|
||||
'attributes' => [],
|
||||
],
|
||||
[
|
||||
'id' => 568,
|
||||
'name' => 'Sample Item 2',
|
||||
'price' => 69.25,
|
||||
];
|
||||
|
||||
$this->cart->add($item);
|
||||
|
||||
expect($this->cart->isEmpty())->toBeFalse('Cart should not be empty');
|
||||
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"');
|
||||
});
|
||||
|
||||
test('can add multiple items with an array', function () {
|
||||
$items = [
|
||||
[
|
||||
'id' => 1,
|
||||
'name' => 'Half Button Open Collar',
|
||||
'price' => 71.99,
|
||||
'quantity' => 1,
|
||||
'attributes' => [],
|
||||
],
|
||||
[
|
||||
'id' => 2,
|
||||
'name' => 'Oli Crew Neck',
|
||||
'price' => 59.99,
|
||||
'quantity' => 1,
|
||||
'attributes' => [],
|
||||
],
|
||||
[
|
||||
'id' => 3,
|
||||
'name' => 'Denim Shorts',
|
||||
'price' => 69.99,
|
||||
'quantity' => 3,
|
||||
'attributes' => [],
|
||||
],
|
||||
];
|
||||
|
||||
$this->cart->add($items);
|
||||
|
||||
expect($this->cart->isEmpty())->toBeFalse('Cart should not be empty');
|
||||
expect($this->cart->getContent()->toArray())->toHaveCount(3, 'Cart should have 3 items');
|
||||
expect($this->cart->getTotal())->toEqual(341.95, 'Cart should have a total of 341.95');
|
||||
});
|
||||
|
||||
test('cart item prices should be normalized when added to cart', function () {
|
||||
// add a price in a string format should be converted to float
|
||||
$this->cart->add(1, 'Book of Languages Item', '100.99', 2, []);
|
||||
|
||||
expect($this->cart->getContent()->first()['price'])->toBeFloat('Cart price should be a float');
|
||||
});
|
||||
|
||||
test('can update a cart item with new attributes and it should be still instance of item attribute collection', function () {
|
||||
$item = [
|
||||
'id' => 1,
|
||||
'name' => 'Leather Shows',
|
||||
'price' => 67.99,
|
||||
'quantity' => 4,
|
||||
'attributes' => [],
|
||||
],
|
||||
[
|
||||
'id' => 856,
|
||||
'name' => 'Sample Item 3',
|
||||
'price' => 50.25,
|
||||
'quantity' => 4,
|
||||
'attributes' => [],
|
||||
],
|
||||
];
|
||||
'attributes' => [
|
||||
'product_id' => '145',
|
||||
'color' => 'red',
|
||||
],
|
||||
];
|
||||
|
||||
$this->cart->add($items);
|
||||
$this->cart->add($item);
|
||||
|
||||
expect($this->cart->isEmpty())->toBeFalse('Cart should not be empty');
|
||||
expect($this->cart->getContent()->toArray())->toHaveCount(3, 'Cart should have 3 items');
|
||||
});
|
||||
$item = $this->cart->get(1);
|
||||
|
||||
test('cart can add item without attributes', function () {
|
||||
$item = [
|
||||
'id' => 456,
|
||||
'name' => 'Sample Item 1',
|
||||
'price' => 67.99,
|
||||
'quantity' => 4,
|
||||
];
|
||||
expect($item->attributes)->toBeInstanceOf('Joelwmale\\Cart\\ItemAttributeCollection');
|
||||
|
||||
$this->cart->add($item);
|
||||
// now lets update the item with its new attributes
|
||||
// when we get that item from cart, it should still be an instance of ItemAttributeCollection
|
||||
$updatedItem = [
|
||||
'attributes' => [
|
||||
'product_id' => '145',
|
||||
'color' => 'red',
|
||||
],
|
||||
];
|
||||
|
||||
expect($this->cart->isEmpty())->toBeFalse('Cart should not be empty');
|
||||
});
|
||||
$this->cart->update(1, $updatedItem);
|
||||
|
||||
test('cart update with attribute then attributes should be still instance of item attribute collection', function () {
|
||||
$item = [
|
||||
'id' => 456,
|
||||
'name' => 'Sample Item 1',
|
||||
'price' => 67.99,
|
||||
'quantity' => 4,
|
||||
'attributes' => [
|
||||
'product_id' => '145',
|
||||
'color' => 'red',
|
||||
],
|
||||
];
|
||||
$this->cart->add($item);
|
||||
expect($item->attributes)->toBeInstanceOf('Joelwmale\\Cart\\ItemAttributeCollection');
|
||||
});
|
||||
|
||||
// lets get the attribute and prove first its an instance of
|
||||
// ItemAttributeCollection
|
||||
$item = $this->cart->get(456);
|
||||
test('item orders are preserved by the order they are added', function () {
|
||||
$items = [
|
||||
[
|
||||
'id' => 50,
|
||||
'name' => 'Leather Shows',
|
||||
'price' => 67.99,
|
||||
'quantity' => 4,
|
||||
'attributes' => [
|
||||
'product_id' => '145',
|
||||
'color' => 'red',
|
||||
],
|
||||
],
|
||||
[
|
||||
'id' => 2,
|
||||
'name' => 'Oli Crew Neck',
|
||||
'price' => 59.99,
|
||||
'quantity' => 1,
|
||||
'attributes' => [],
|
||||
],
|
||||
];
|
||||
|
||||
expect($item->attributes)->toBeInstanceOf('Wearepixel\Cart\ItemAttributeCollection');
|
||||
$this->cart->add($items);
|
||||
|
||||
// now lets update the item with its new attributes
|
||||
// when we get that item from cart, it should still be an instance of ItemAttributeCollection
|
||||
$updatedItem = [
|
||||
'attributes' => [
|
||||
'product_id' => '145',
|
||||
'color' => 'red',
|
||||
],
|
||||
];
|
||||
$this->cart->update(456, $updatedItem);
|
||||
$items = $this->cart->getContent();
|
||||
|
||||
expect($item->attributes)->toBeInstanceOf('Wearepixel\Cart\ItemAttributeCollection');
|
||||
expect($items->toArray())->toHaveCount(2, 'Cart should have 2 items');
|
||||
expect($items->first()->id)->toEqual(50, 'First item should have ID of 1');
|
||||
expect($items->last()->id)->toEqual(2, 'Last item should have ID of 2');
|
||||
});
|
||||
|
||||
test('item orders are preserved by the order they are added even when items are updated', function () {
|
||||
$items = [
|
||||
[
|
||||
'id' => 50,
|
||||
'name' => 'Leather Shows',
|
||||
'price' => 67.99,
|
||||
'quantity' => 4,
|
||||
'attributes' => [
|
||||
'product_id' => '145',
|
||||
'color' => 'red',
|
||||
],
|
||||
],
|
||||
[
|
||||
'id' => 2,
|
||||
'name' => 'Oli Crew Neck',
|
||||
'price' => 59.99,
|
||||
'quantity' => 1,
|
||||
'attributes' => [],
|
||||
],
|
||||
];
|
||||
|
||||
$this->cart->add($items);
|
||||
|
||||
$this->cart->update(50, ['name' => 'Updated Name']);
|
||||
|
||||
$items = $this->cart->getContent();
|
||||
|
||||
expect($items->toArray())->toHaveCount(2, 'Cart should have 2 items');
|
||||
expect($items->first()->id)->toEqual(50, 'First item should have ID of 1');
|
||||
expect($items->last()->id)->toEqual(2, 'Last item should have ID of 2');
|
||||
});
|
||||
|
||||
test('can update existing items', function () {
|
||||
$items = [
|
||||
[
|
||||
'id' => 1,
|
||||
'name' => 'Magic The Gathering Card Pack',
|
||||
'price' => 12.99,
|
||||
'quantity' => 3,
|
||||
'attributes' => [],
|
||||
],
|
||||
[
|
||||
'id' => 2,
|
||||
'name' => 'Magic The Gathering Card Case',
|
||||
'price' => 39.99,
|
||||
'quantity' => 1,
|
||||
'attributes' => [],
|
||||
],
|
||||
];
|
||||
|
||||
$this->cart->add($items);
|
||||
|
||||
$item = $this->cart->get(1);
|
||||
|
||||
expect($item['name'])->toEqual('Magic The Gathering Card Pack', 'Item name should be "Magic The Gathering Card Pack"');
|
||||
expect($item['price'])->toEqual(12.99, 'Item price should be "12.99"');
|
||||
expect($item['quantity'])->toEqual(3, 'Item quantity should be 3');
|
||||
|
||||
// when cart's item quantity is updated, the subtotal should be updated as well
|
||||
$this->cart->update(1, [
|
||||
'name' => 'Magic The Gathering Card Packs',
|
||||
'quantity' => 2,
|
||||
'price' => 10.20,
|
||||
]);
|
||||
|
||||
$item = $this->cart->get(1);
|
||||
|
||||
expect($item['name'])->toEqual('Magic The Gathering Card Packs', 'Item name should be "Magic The Gathering Card Packs"');
|
||||
expect($item['price'])->toEqual(10.20, 'Item price should be 10.20');
|
||||
expect($item['quantity'])->toEqual(5, 'Item quantity should be 2');
|
||||
});
|
||||
|
||||
test('can update existing item quanties with decimals', function () {
|
||||
$items = [
|
||||
'id' => 1,
|
||||
'name' => 'Fertilizer',
|
||||
'price' => 30,
|
||||
'quantity' => 7.8,
|
||||
'attributes' => [
|
||||
'unit' => 'kilogram',
|
||||
],
|
||||
];
|
||||
|
||||
$this->cart->add($items);
|
||||
|
||||
$item = $this->cart->get(1);
|
||||
|
||||
expect($item['quantity'])->toEqual(7.8, 'Item quantity should be 7.8');
|
||||
|
||||
// when cart's item quantity is updated, the subtotal should be updated as well
|
||||
$this->cart->update(1, [
|
||||
'quantity' => [
|
||||
'relative' => true,
|
||||
'value' => 2.1,
|
||||
],
|
||||
]);
|
||||
|
||||
$item = $this->cart->get(1);
|
||||
|
||||
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 () {
|
||||
@@ -222,13 +406,6 @@
|
||||
expect($item['quantity'])->toEqual(5, 'Item quantity should be 5');
|
||||
});
|
||||
|
||||
test('item price should be normalized when added to cart', function () {
|
||||
// add a price in a string format should be converted to float
|
||||
$this->cart->add(455, 'Sample Item', '100.99', 2, []);
|
||||
|
||||
expect($this->cart->getContent()->first()['price'])->toBeFloat('Cart price should be a float');
|
||||
});
|
||||
|
||||
test('it removes an item on cart by item id', function () {
|
||||
$items = [
|
||||
[
|
||||
@@ -331,8 +508,6 @@
|
||||
});
|
||||
|
||||
test('sub total when item quantity is updated by reduced', function () {
|
||||
// $this->cart->setConfig(['format_numbers' => true, 'decimals' => 2, 'dec_point' => '.', 'thousands_sep' => ',']);
|
||||
|
||||
$items = [
|
||||
[
|
||||
'id' => 456,
|
||||
@@ -398,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 = [
|
||||
[
|
||||
@@ -486,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 () {
|
||||
@@ -521,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');
|
||||
|
||||
@@ -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 () {});
|
||||
|
||||
|
||||
@@ -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');
|
||||
|
||||
@@ -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');
|
||||
|
||||
@@ -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');
|
||||
|
||||
Reference in New Issue
Block a user