Skip to content

Instantly share code, notes, and snippets.

@olrandir
Last active October 19, 2021 09:10
Show Gist options
  • Save olrandir/db60f1c6c11662da8dd8238beea6e288 to your computer and use it in GitHub Desktop.
Save olrandir/db60f1c6c11662da8dd8238beea6e288 to your computer and use it in GitHub Desktop.
<?php
class Order
{
/** @var OrderItem[] */
private $orderItems;
/** @var int */
private $countItems;
/** @var int */
private $maxPrice;
/** @var int */
private $sumPrice;
public function __construct(?array $orderItems)
{
$this->orderItems = $orderItems;
$this->calculateTotals();
}
/**
* @return OrderItem[]
*/
public function getOrderItems(): array
{
return $this->orderItems;
}
/**
* @param OrderItem $orderItem
*/
public function addOrderItem(OrderItem $orderItem): void
{
$this->orderItems[] = $orderItem;
}
public function removeOrderItem(OrderItem $orderItem): void
{
if (($key = array_search($orderItem, $this->orderItems)) !== false) {
unset($this->orderItems[$key]);
}
}
/**
* @return int
*/
public function getCountItems(): int
{
return $this->countItems;
}
/**
* @return int
*/
public function getMaxPrice(): int
{
return $this->maxPrice;
}
/**
* @return int
*/
public function getSumPrice(): int
{
return $this->sumPrice;
}
private function calculateTotals(): void
{
$this->countItems = count($this->orderItems);
$this->sumPrice = 0;
foreach ($this->orderItems as &$curOrderItem) {
$this->sumPrice += $curOrderItem->getPrice();
}
$this->maxPrice = reset($this->orderItems)->getPrice();
foreach ($this->orderItems as $curOrderItem) {
if ($curOrderItem->getPrice() > $this->maxPrice) {
$this->maxPrice = $curOrderItem->getPrice();
}
}
}
}
class OrderItem {
/** @var int */
private $price;
public function __construct($price) {
$this->price = $price;
}
public function getPrice() {
return $this->price;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment