Verify session ID; introduce player profile database
[gamestick-pjgsapi.git] / src / ProfileDb.php
1 <?php
2 require_once 'Profile.php';
3
4 /**
5  * Functions to work with player profiles
6  */
7 class ProfileDb
8 {
9     protected PDO $db;
10
11     public function __construct()
12     {
13         $dbFile = dirname(__FILE__, 2) . '/data/profiles.sqlite3';
14         $this->db = new PDO(
15             'sqlite:' . $dbFile,
16             '', '',
17             [
18                 PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
19                 PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
20             ]
21         );
22         $this->createTablesIfNeeded();
23     }
24
25     public function getProfileByHardwareId(string $hwId): ?Profile
26     {
27         $stmt = $this->db->prepare('SELECT * FROM gamesticks WHERE hwId = :id');
28         $stmt->setFetchMode(PDO::FETCH_CLASS, 'Profile');
29         $stmt->execute([':id' => $hwId]);
30         $row = $stmt->fetch();
31         return $row === false ? null : $row;
32     }
33
34     public function getProfileBySessionId(string $sessionId): ?Profile
35     {
36         $stmt = $this->db->prepare('SELECT * FROM gamesticks WHERE sessionId = :id');
37         $stmt->setFetchMode(PDO::FETCH_CLASS, 'Profile');
38         $stmt->execute([':id' => $sessionId]);
39         $row = $stmt->fetch();
40         return $row === false ? null : $row;
41     }
42
43     public function createProfile(string $hwId): Profile
44     {
45         $stmt = $this->db->prepare(
46             <<<SQL
47             INSERT INTO gamesticks
48             (hwId, sessionId, verificationCode)
49             VALUES (:hwId, :sessionId, :verificationCode)
50 SQL
51         );
52         $stmt->execute(
53             [
54                 ':hwId'             => $hwId,
55                 ':sessionId'        => 's' . str_replace(':', '', $hwId),
56                 ':verificationCode' => date('His'),
57             ]
58         );
59         return $this->getProfileByHardwareId($hwId);
60     }
61
62     protected function createTablesIfNeeded()
63     {
64         $res = $this->db->query(
65             'SELECT name FROM sqlite_master WHERE type = "table" AND name = "gamesticks"'
66         )->fetch();
67         if ($res !== false) {
68             return;
69         }
70
71         $this->db->exec(
72             <<<SQL
73         CREATE TABLE gamesticks (
74             id INTEGER PRIMARY KEY AUTOINCREMENT,
75             hwId TEXT NOT NULL,
76             sessionId TEXT,
77             verificationCode TEXT DEFAULT NULL,
78             gamerTag TEXT DEFAULT NULL,
79             founderFlag INTEGER DEFAULT 0 NOT NULL,
80             founderName TEXT DEFAULT NULL,
81             minAge INTEGER DEFAULT 3 NOT NULL,
82             avatar TEXT DEFAULT NULL,
83
84             created_at TEXT DEFAULT CURRENT_TIMESTAMP
85         )
86 SQL
87         );
88     }
89 }
90 ?>