2023-06-11 12:14:03 +00:00
|
|
|
<?php
|
|
|
|
|
|
|
|
namespace Modules\Cart;
|
|
|
|
|
|
|
|
use JsonSerializable;
|
|
|
|
use Modules\Support\Money;
|
|
|
|
|
|
|
|
class CartTax implements JsonSerializable
|
|
|
|
{
|
|
|
|
private $cart;
|
|
|
|
private $taxRate;
|
|
|
|
private $taxCondition;
|
|
|
|
|
2023-12-03 14:07:47 +00:00
|
|
|
|
2023-06-11 12:14:03 +00:00
|
|
|
public function __construct($cart, $taxRate, $taxCondition)
|
|
|
|
{
|
|
|
|
$this->cart = $cart;
|
|
|
|
$this->taxRate = $taxRate;
|
|
|
|
$this->taxCondition = $taxCondition;
|
|
|
|
}
|
|
|
|
|
2023-12-03 14:07:47 +00:00
|
|
|
|
2023-06-11 12:14:03 +00:00
|
|
|
public function id()
|
|
|
|
{
|
|
|
|
return $this->taxRate->id;
|
|
|
|
}
|
|
|
|
|
2023-12-03 14:07:47 +00:00
|
|
|
|
|
|
|
public function __toString()
|
|
|
|
{
|
|
|
|
return json_encode($this->jsonSerialize());
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
public function jsonSerialize()
|
|
|
|
{
|
|
|
|
return $this->toArray();
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
public function toArray(): array
|
|
|
|
{
|
|
|
|
return [
|
|
|
|
'name' => $this->name(),
|
|
|
|
'amount' => $this->amount(),
|
|
|
|
];
|
|
|
|
}
|
|
|
|
|
|
|
|
|
2023-06-11 12:14:03 +00:00
|
|
|
public function name()
|
|
|
|
{
|
|
|
|
return $this->taxRate->name;
|
|
|
|
}
|
|
|
|
|
2023-12-03 14:07:47 +00:00
|
|
|
|
|
|
|
public function amount(): Money
|
2023-06-11 12:14:03 +00:00
|
|
|
{
|
|
|
|
return Money::inDefaultCurrency($this->calculate());
|
|
|
|
}
|
|
|
|
|
2023-12-03 14:07:47 +00:00
|
|
|
|
2023-06-11 12:14:03 +00:00
|
|
|
private function calculate()
|
|
|
|
{
|
2023-12-03 14:07:47 +00:00
|
|
|
return $this->taxCondition->getCalculatedValue($this->taxApplicableProductsTotalPrice());
|
2023-06-11 12:14:03 +00:00
|
|
|
}
|
|
|
|
|
2023-12-03 14:07:47 +00:00
|
|
|
|
|
|
|
private function taxApplicableProductsTotalPrice()
|
2023-06-11 12:14:03 +00:00
|
|
|
{
|
|
|
|
return $this->taxApplicableProducts()->sum(function ($cartItem) {
|
2023-12-03 14:07:47 +00:00
|
|
|
return $cartItem->totalPrice()->amount();
|
2023-06-11 12:14:03 +00:00
|
|
|
});
|
|
|
|
}
|
|
|
|
|
2023-12-03 14:07:47 +00:00
|
|
|
|
2023-06-11 12:14:03 +00:00
|
|
|
private function taxApplicableProducts()
|
|
|
|
{
|
|
|
|
return $this->cart->items()->filter(function ($cartItem) {
|
|
|
|
return $this->hasMatchingTaxClass($cartItem);
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
|
|
|
|
2023-12-03 14:07:47 +00:00
|
|
|
private function hasMatchingTaxClass($cartItem): bool
|
2023-06-11 12:14:03 +00:00
|
|
|
{
|
2023-12-03 14:07:47 +00:00
|
|
|
return $cartItem->product->tax_class_id === $this->taxRate->tax_class_id;
|
2023-06-11 12:14:03 +00:00
|
|
|
}
|
|
|
|
}
|