Advertisement
Guest User

Untitled

a guest
Sep 22nd, 2019
97
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.24 KB | None | 0 0
  1. <?php
  2. declare(strict_types=1);
  3.  
  4. namespace Src\PackItems;
  5.  
  6. final class Item
  7. {
  8. /**
  9. * @var int
  10. */
  11. private $price;
  12. /**
  13. * @var int
  14. */
  15. private $quantity;
  16. /**
  17. * @var array
  18. */
  19. private $packPrice;
  20. /**
  21. * @var string
  22. */
  23. private $code;
  24.  
  25. private function __construct(string $code, int $price, int $quantity, array $packPrice)
  26. {
  27. $this->code = $code;
  28. $this->price = $price;
  29. $this->quantity = $quantity;
  30. $this->packPrice = $packPrice;
  31. }
  32.  
  33. /**
  34. * @param string $code
  35. * @param int $price
  36. *
  37. * @return Item
  38. */
  39. public static function fromBasic(string $code, int $price)
  40. {
  41. return new static($code, $price, 1, []);
  42. }
  43.  
  44. /**
  45. * @return int
  46. */
  47. public function getQuantity(): int
  48. {
  49. return $this->quantity;
  50. }
  51.  
  52. /**
  53. * @param Item $item
  54. *
  55. * @return bool
  56. */
  57. public function equals(Item $item): bool
  58. {
  59. return $this->code === $item->getCode();
  60. }
  61.  
  62. /**
  63. * @return float
  64. */
  65. public function getTotal(): float
  66. {
  67. if (!count($this->packPrice)) {
  68. return $this->quantity * $this->price;
  69. }
  70. $packs = array_keys($this->packPrice);
  71. $minPack = min($packs);
  72. if ($this->quantity < $minPack) {
  73. return $this->quantity * $this->price;
  74. }
  75. $totalPrice = 0;
  76. $quantity = $this->quantity;
  77. foreach ($this->packPrice as $packQuantity => $packPrice) {
  78. if ($quantity < $packQuantity) {
  79. break;
  80. }
  81. $totalPrice += $packQuantity * $packPrice;
  82. $quantity -= $packQuantity;
  83. }
  84. $totalPrice += $quantity * $this->price;
  85.  
  86. return $totalPrice;
  87. }
  88.  
  89. /**
  90. * @return string
  91. */
  92. public function getCode(): string
  93. {
  94. return $this->code;
  95. }
  96.  
  97. /**
  98. * @param int $quantity
  99. */
  100. public function setQuantity(int $quantity): void
  101. {
  102. $this->quantity = $quantity;
  103. }
  104.  
  105. /**
  106. * @param array $packPrice
  107. *
  108. * @return Item
  109. */
  110. public function withPackPrice(array $packPrice): Item
  111. {
  112. $this->packPrice = $packPrice;
  113.  
  114. return $this;
  115. }
  116. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement