$row The row from the database */ public static function fromDatabase(array $row): self { return new self( $row["id"], $row["user_id"], $row["name"] ); } public static function fetch(string $id = "", string $userId = ""): ?self { if (! empty($id) && empty($userId)) { throw new \InvalidArgumentException("Can't fetch device without user id."); } $row = []; if (! empty($userId)) { if (! empty($id)) { $row = Database::getInstance()->query( << $id, "user_id" => $userId, ] )->fetch(); } else { $row = Database::getInstance()->query( << $userId, ] )->fetch(); } } if (empty($row)) { return null; } return self::fromDatabase($row); } public static function fetchAll(string $userId = ""): array { if (empty($userId)) { throw new \InvalidArgumentException("missing user id"); } $devices = []; $rows = Database::getInstance()->query( << $userId, ] )->fetchAll(); foreach ($rows as $row) { $devices[] = Device::fromDatabase($row); } return $devices; } public static function new(string $userId, string $deviceId = "", string $initialDisplayName = ""): self { $deviceId = $deviceId ?: md5($userId . random_bytes(512)); $initialDisplayName = $initialDisplayName ?: "capybara"; return new self( $deviceId, $userId, $initialDisplayName, ); } public function insert(): bool { return !! Database::getInstance()->query( << $this->id, "user_id" => $this->userId, "name" => $this->name, ] ); } public function update(): bool {} public function delete(): bool {} public function getId(): string { return $this->id; } public function getName(): string { return $this->name; } }