*/ public array $items = []; private int $nextId = 1; public function findById(int $id): ?Product { return isset($this->items[$id]) ? clone $this->items[$id] : null; } public function save(Product $product): Product { $id = $product->id() ?? $this->nextId++; $this->items[$id] = Product::reconstitute( $id, $product->name(), $product->unit(), $product->price(), $product->vatRateId(), $product->isConsumerProduct(), $product->duration(), $product->workTypeId(), $product->isActive(), $product->sortOrder(), ); return clone $this->items[$id]; } public function isNameTaken(string $name, ?int $exceptId = null): bool { foreach ($this->items as $id => $product) { if ($id !== $exceptId && mb_strtolower($product->name()->value) === mb_strtolower($name)) { return true; } } return false; } public function nextSortOrder(): int { return array_reduce($this->items, fn (int $max, Product $product): int => max($max, $product->sortOrder()), 0) + 1; } public function neighbour(Product $product, MoveDirection $direction): ?Product { $candidates = array_values(array_filter($this->items, fn (Product $other): bool => $direction === MoveDirection::Up ? $other->sortOrder() < $product->sortOrder() : $other->sortOrder() > $product->sortOrder())); usort($candidates, fn (Product $a, Product $b): int => $direction === MoveDirection::Up ? $b->sortOrder() <=> $a->sortOrder() : $a->sortOrder() <=> $b->sortOrder()); return isset($candidates[0]) ? clone $candidates[0] : null; } }