db->get_results($this->db->prepare('SELECT * FROM %i WHERE order_item_id = %d ORDER BY unit_index', Schema::unitsTable(), $orderItemId), ARRAY_A) ?: []; return array_map([CoveredUnit::class, 'fromRow'], $rows); } /** @return list */ public function findByOrder(int $orderId): array { $rows = $this->db->get_results($this->db->prepare('SELECT * FROM %i WHERE order_id = %d ORDER BY order_item_id, unit_index', Schema::unitsTable(), $orderId), ARRAY_A) ?: []; return array_map([CoveredUnit::class, 'fromRow'], $rows); } public function get(int $id): ?CoveredUnit { $row = $this->db->get_row($this->db->prepare('SELECT * FROM %i WHERE id = %d', Schema::unitsTable(), $id), ARRAY_A); return $row ? CoveredUnit::fromRow($row) : null; } public function insert(CoveredUnit $unit): void { $data = self::columns($unit->toRow()); unset($data['id']); $data['created_at'] = EventWriter::now(); $data['updated_at'] = $data['created_at']; $suppress = $this->db->suppress_errors(true); $ok = $this->db->insert(Schema::unitsTable(), $data); $this->db->suppress_errors($suppress); if (false === $ok) { if (str_contains($this->db->last_error, 'Duplicate entry')) { // Another request tracked the same line at the same moment. throw new DomainError('abcreate_wd_duplicate_unit', 'The unit was tracked meanwhile. Try again.', 409); } throw new \RuntimeException('Could not insert unit: ' . esc_html($this->db->last_error)); } $unit->assignId((int) $this->db->insert_id); $this->events->append(WarrantyEvent::SUBJECT_UNIT, (int) $unit->id(), $unit->pullEvents()); } public function save(CoveredUnit $unit): void { if ($unit->version() === $unit->loadedVersion()) { return; // Nothing changed. } $id = (int) $unit->id(); $data = self::columns($unit->toRow()); unset($data['id']); $data['updated_at'] = EventWriter::now(); $affected = $this->db->update(Schema::unitsTable(), $data, ['id' => $id, 'version' => $unit->loadedVersion()]); if (false === $affected) { throw new \RuntimeException('Could not update unit: ' . esc_html($this->db->last_error)); } if (0 === $affected) { $current = $this->db->get_row($this->db->prepare('SELECT open_claim_id, version FROM %i WHERE id = %d', Schema::unitsTable(), $id), ARRAY_A); $held = null === ($current['open_claim_id'] ?? null) ? null : (int) $current['open_claim_id']; $next = $unit->openClaimId(); // Rule 1 first: the clear error for two claims racing on a unit (G07). if (null !== $held && null !== $next && $held !== $next) { throw DomainError::unitBusy((int) $id, (int) $held); } throw DomainError::versionConflict((int) $unit->loadedVersion(), (int) ($current['version'] ?? 0)); } $this->events->append(WarrantyEvent::SUBJECT_UNIT, $id, $unit->pullEvents()); } /** * @param array $row * @return array */ private static function columns(array $row): array { foreach ($row as $key => $value) { if (is_bool($value)) { $row[$key] = $value ? 1 : 0; } } return $row; } }