Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- declare(strict_types=1);
- namespace Src\PackItems;
- final class Item
- {
- /**
- * @var int
- */
- private $price;
- /**
- * @var int
- */
- private $quantity;
- /**
- * @var array
- */
- private $packPrice;
- /**
- * @var string
- */
- private $code;
- private function __construct(string $code, int $price, int $quantity, array $packPrice)
- {
- $this->code = $code;
- $this->price = $price;
- $this->quantity = $quantity;
- $this->packPrice = $packPrice;
- }
- /**
- * @param string $code
- * @param int $price
- *
- * @return Item
- */
- public static function fromBasic(string $code, int $price)
- {
- return new static($code, $price, 1, []);
- }
- /**
- * @return int
- */
- public function getQuantity(): int
- {
- return $this->quantity;
- }
- /**
- * @param Item $item
- *
- * @return bool
- */
- public function equals(Item $item): bool
- {
- return $this->code === $item->getCode();
- }
- /**
- * @return float
- */
- public function getTotal(): float
- {
- if (!count($this->packPrice)) {
- return $this->quantity * $this->price;
- }
- $packs = array_keys($this->packPrice);
- $minPack = min($packs);
- if ($this->quantity < $minPack) {
- return $this->quantity * $this->price;
- }
- $totalPrice = 0;
- $quantity = $this->quantity;
- foreach ($this->packPrice as $packQuantity => $packPrice) {
- if ($quantity < $packQuantity) {
- break;
- }
- $totalPrice += $packQuantity * $packPrice;
- $quantity -= $packQuantity;
- }
- $totalPrice += $quantity * $this->price;
- return $totalPrice;
- }
- /**
- * @return string
- */
- public function getCode(): string
- {
- return $this->code;
- }
- /**
- * @param int $quantity
- */
- public function setQuantity(int $quantity): void
- {
- $this->quantity = $quantity;
- }
- /**
- * @param array $packPrice
- *
- * @return Item
- */
- public function withPackPrice(array $packPrice): Item
- {
- $this->packPrice = $packPrice;
- return $this;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement