<?php/** * Cart Model * * @author Vincent van Waasbergen <v.vanwaasbergen@visualmedia.nl> */namespace VisualMedia\OrderBundle\Model;use Doctrine\Common\Collections\ArrayCollection;use VisualMedia\OrderBundle\Entity\BaseOrderItem;/** * Cart Model */class CartModel{ /** * Items * @var ArrayCollection */ protected $items; /** * Amount * @var float */ protected $amount; /** * Subtotal * @var float */ protected $subtotal; /** * Shipping * @var float */ protected $shipping; /** * Payment * @var float */ protected $payment; /** * Total * @var float */ protected $total; /** * Constructor */ public function __construct() { $this->items = new ArrayCollection(); } /** * Get Items * * @return ArrayCollection */ public function getItems(): ArrayCollection { return $this->items; } /** * Set Items * * @param ArrayCollection $items * * @return void */ public function setItems(ArrayCollection $items): void { $this->items = $items; } /** * Add * * @param BaseOrderItem $item * * @return void */ public function add(BaseOrderItem $item): void { if (null === $existing = $this->contains($item)) { $this->items->add($item); } else { $existing->setAmount($existing->getAmount() + 1); } } /** * Contains * * @param BaseOrderItem $new * * @return BaseOrderItem */ public function contains(BaseOrderItem $new): ?BaseOrderItem { $newHash = $new->getItemHash(); foreach ($this->getItems() as $existing) { if ($newHash === $existingHash = $existing->getItemHash()) { return $existing; } } return null; } /** * Update Item Amount * * @param string $hash * @param int $amount * * @return void */ public function updateItemAmount(string $hash, int $amount): void { foreach ($this->getItems() as $item) { if ($item->getItemHash() === $hash) { $item->setAmount($amount); } } } /** * Remove Item * * @param string $hash * * @return void */ public function removeItem(string $hash): void { foreach ($this->getItems() as $item) { if ($item->getItemHash() === $hash) { $this->getItems()->removeElement($item); } } } /** * Getc Item By Hash * * @param string $hash * * @return BaseOrderItem|null */ public function getItemByHash(string $hash): ?BaseOrderItem { foreach ($this->getItems() as $item) { if ($item->getItemHash() === $hash) { return $item; } } return null; } /** * Get Amount * * @return int */ public function getAmount(): int { $amount = 0; foreach ($this->getItems() as $item) { $amount += $item->getAmount(); } return $amount; } /** * @return float */ public function getSubtotal(): float { $this->subtotal = 0; foreach ($this->getItems() as $item) { if ($item->isFree()) { continue; } $this->subtotal += $item->getTotal(); } return $this->subtotal; }}