parse($data); $unitIds = $this->allowedUnits($data->serviceUnitIds, []); return $this->transactions->run(function () use ($data, $name, $type, $counters, $unitIds): int { if ($this->machines->isNameTaken($name->value)) { throw new MachineNameTaken; } $machine = Machine::create($name, $type, $data->description, $unitIds, $data->responsibleUserId, $counters); return (int) $this->machines->save($machine)->id(); }); } /** * @throws MachineNotFound * @throws InvalidMachineName * @throws InvalidCounter * @throws MachineNameTaken * @throws MachineNeedsServiceUnit */ public function update(int $machineId, MachineData $data): void { [$name, $type, $counters] = $this->parse($data); $this->transactions->run(function () use ($machineId, $data, $name, $type, $counters): void { $machine = $this->machines->findById($machineId) ?? throw new MachineNotFound; if ($this->machines->isNameTaken($name->value, $machineId)) { throw new MachineNameTaken; } $machine->change($name, $type, $data->description, $this->allowedUnits($data->serviceUnitIds, $machine->serviceUnitIds()), $data->responsibleUserId, $counters); $this->machines->save($machine); }); } /** * @throws MachineNotFound */ public function setActive(int $machineId, bool $active): void { $this->transactions->run(function () use ($machineId, $active): void { $machine = $this->machines->findById($machineId) ?? throw new MachineNotFound; $active ? $machine->activate() : $machine->deactivate(); $this->machines->save($machine); }); } /** * @return array{0: MachineName, 1: MachineType, 2: list} * * @throws InvalidMachineName * @throws InvalidCounter */ private function parse(MachineData $data): array { $counters = []; foreach ($data->counters as $counter) { $unit = CounterUnit::tryFrom($counter['unit']) ?? throw new InvalidCounter; $counters[] = new MachineCounter($counter['id'], $counter['name'], $unit); } return [new MachineName($data->name), MachineType::tryFrom($data->type) ?? MachineType::Other, $counters]; } /** * @param list $requested * @param list $current * @return list */ private function allowedUnits(array $requested, array $current): array { $stockUnitIds = $this->catalog->stockServiceUnitIds(); return array_values(array_filter( array_unique($requested), fn (int $id): bool => in_array($id, $stockUnitIds, true) || in_array($id, $current, true), )); } }