cookidoo-shopping-advanced/src/Models/ShoppingList.php

120 lines
3.0 KiB
PHP

<?php
namespace CookidooShoppingAdvanced\Models;
class ShoppingList implements \ArrayAccess, \Iterator {
/** @var Ingredient[] */
private array $ingredients = [];
private int $index = 0;
public function add(Ingredient $ingredient) {
$this->ingredients[] = $ingredient;
}
public function remove(Ingredient $ingredientToRemove): void {
$result = [];
foreach($this->ingredients as $ingredient) {
if ($ingredient->getId() === $ingredientToRemove->getId()) {
continue;
}
$result[] = $ingredient;
}
$this->ingredients = $result;
}
public function update(Ingredient $ingredientToUpdate): void {
foreach($this->ingredients as $key => $ingredient) {
if ($ingredient->getId() === $ingredientToUpdate->getId()) {
$this->ingredients[$key] = $ingredientToUpdate;
return;
}
}
}
public function get(): array {
return $this->ingredients;
}
public function getByCategory(): array {
$result = [];
foreach($this->ingredients as $ingredient) {
if (!isset($result[$ingredient->getCategory()->getName()])) {
$result[$ingredient->getCategory()->getName()] = [];
}
$result[$ingredient->getCategory()->getName()][] = $ingredient;
}
return $result;
}
public function isEmpty(): bool {
return empty($this->ingredients);
}
public function rewind() {
$this->index = 0;
}
public function current() {
return $this->ingredients[$this->index];
}
public function key() {
return $this->index;
}
public function next() {
++$this->index;
}
public function valid(): bool {
return isset($this->ingredients[$this->index]);
}
public function offsetSet($offset, $value) {
if (is_null($offset)) {
$this->ingredients[] = $value;
} else {
$this->ingredients[$offset] = $value;
}
}
public function offsetExists($offset) {
return isset($this->ingredients[$offset]);
}
public function offsetUnset($offset) {
unset($this->ingredients[$offset]);
}
public function offsetGet($offset) {
return isset($this->ingredients[$offset]) ? $this->ingredients[$offset] : null;
}
public function toJson(): string {
return json_encode($this->ingredients);
}
public static function fromJson(string $json): self {
$list = new self();
if (empty($json)) {
return $list;
}
$data = json_decode($json);
foreach($data as $entry) {
$ingredient = new Ingredient(
new Category($entry->category->name),
$entry->name,
$entry->amount,
$entry->unit,
);
$list->add($ingredient);
}
return $list;
}
}