--- /dev/null
+<?php
+require_once 'Profile.php';
+
+/**
+ * Functions to work with player profiles
+ */
+class ProfileDb
+{
+ protected PDO $db;
+
+ public function __construct()
+ {
+ $dbFile = dirname(__FILE__, 2) . '/data/profiles.sqlite3';
+ $this->db = new PDO(
+ 'sqlite:' . $dbFile,
+ '', '',
+ [
+ PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
+ PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
+ ]
+ );
+ $this->createTablesIfNeeded();
+ }
+
+ public function getProfileByHardwareId(string $hwId): ?Profile
+ {
+ $stmt = $this->db->prepare('SELECT * FROM gamesticks WHERE hwId = :id');
+ $stmt->setFetchMode(PDO::FETCH_CLASS, 'Profile');
+ $stmt->execute([':id' => $hwId]);
+ $row = $stmt->fetch();
+ return $row === false ? null : $row;
+ }
+
+ public function getProfileBySessionId(string $sessionId): ?Profile
+ {
+ $stmt = $this->db->prepare('SELECT * FROM gamesticks WHERE sessionId = :id');
+ $stmt->setFetchMode(PDO::FETCH_CLASS, 'Profile');
+ $stmt->execute([':id' => $sessionId]);
+ $row = $stmt->fetch();
+ return $row === false ? null : $row;
+ }
+
+ public function createProfile(string $hwId): Profile
+ {
+ $stmt = $this->db->prepare(
+ <<<SQL
+ INSERT INTO gamesticks
+ (hwId, sessionId, verificationCode)
+ VALUES (:hwId, :sessionId, :verificationCode)
+SQL
+ );
+ $stmt->execute(
+ [
+ ':hwId' => $hwId,
+ ':sessionId' => 's' . str_replace(':', '', $hwId),
+ ':verificationCode' => date('His'),
+ ]
+ );
+ return $this->getProfileByHardwareId($hwId);
+ }
+
+ protected function createTablesIfNeeded()
+ {
+ $res = $this->db->query(
+ 'SELECT name FROM sqlite_master WHERE type = "table" AND name = "gamesticks"'
+ )->fetch();
+ if ($res !== false) {
+ return;
+ }
+
+ $this->db->exec(
+ <<<SQL
+ CREATE TABLE gamesticks (
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
+ hwId TEXT NOT NULL,
+ sessionId TEXT,
+ verificationCode TEXT DEFAULT NULL,
+ gamerTag TEXT DEFAULT NULL,
+ founderFlag INTEGER DEFAULT 0 NOT NULL,
+ founderName TEXT DEFAULT NULL,
+ minAge INTEGER DEFAULT 3 NOT NULL,
+ avatar TEXT DEFAULT NULL,
+
+ created_at TEXT DEFAULT CURRENT_TIMESTAMP
+ )
+SQL
+ );
+ }
+}
+?>