Update CartModel.php

This commit is contained in:
Patrick
2022-02-09 00:06:27 +01:00
committed by GitHub
parent efbacd16f3
commit 978319d4c6

View File

@@ -34,4 +34,107 @@ class CartModel extends Model
{
return $this->hasMany(CartItem::class);
}
/**
* This will is the price of the CartItem as Money
*/
public function price(): Attribute
{
return new Attribute(
get: fn (): Money => {
$sum = new Money(0, 'USD');
foreach (this->items as $item) {
$sum->add($item->price_all);
}
return $sum;
},
);
}
/**
* This is the discount granted for this CartItem. It is based on the given price and, in case
* discount is a float, multiplied or, in case it is an absolute Money, subtracted. It will return
* a minimum value of 0.
*/
public function discount(): Attribute
{
return new Attribute(
get: fn (): Money => {
$sum = new Money(0, 'USD');
foreach (this->items as $item) {
$sum->add($item->discount);
}
return $sum;
},
);
}
/**
* This is the final price of the CartItem but without any tax applied. This does on the
* other hand include any discounts.
*/
public function subtotal(): Attribute
{
return new Attribute(
get: fn (): Money => {
$sum = new Money(0, 'USD');
foreach (this->items as $item) {
$sum->add($item->subtotal);
}
return $sum;
},
);
}
/**
* This is the tax, based on the subtotal (all previous calculations) and set tax rate.
*/
public function tax(): Attribute
{
return new Attribute(
get: fn (): Money => {
$sum = new Money(0, 'USD');
foreach (this->items as $item) {
$sum->add($item->tax);
}
return $sum;
},
);
}
/**
* This is the total price, consisting of the subtotal and tax applied.
*/
public function total(): Attribute
{
return new Attribute(
get: fn (): Money => {
$sum = new Money(0, 'USD');
foreach (this->items as $item) {
$sum->add($item->total);
}
return $sum;
},
);
}
/**
* This is the total price, consisting of the subtotal and tax applied.
*/
public function weight(): Attribute
{
return new Attribute(
get: fn () => $this->qty * $this->weight,
);
}
}