1
|
|
|
<?php declare(strict_types=1); |
2
|
|
|
|
3
|
|
|
namespace Smr; |
4
|
|
|
|
5
|
|
|
class DatabaseRecord { |
6
|
|
|
|
7
|
|
|
/** |
8
|
|
|
* @param array $dbRecord A record from a DatabaseResult. |
9
|
|
|
*/ |
10
|
|
|
public function __construct( |
11
|
|
|
private array $dbRecord |
12
|
|
|
) {} |
13
|
|
|
|
14
|
|
|
public function hasField(string $name) : bool { |
15
|
|
|
return isset($this->dbRecord[$name]); |
16
|
|
|
} |
17
|
|
|
|
18
|
|
|
public function getField(string $name) : ?string { |
19
|
|
|
return $this->dbRecord[$name]; |
20
|
|
|
} |
21
|
|
|
|
22
|
|
|
/** |
23
|
|
|
* Get a string-only field from the database record. |
24
|
|
|
* If the field can be null, use `getField` instead. |
25
|
|
|
*/ |
26
|
|
|
public function getString(string $name) : string { |
27
|
|
|
return $this->dbRecord[$name]; |
28
|
|
|
} |
29
|
|
|
|
30
|
|
|
public function getBoolean(string $name) : bool { |
31
|
|
|
return match($this->dbRecord[$name]) { |
32
|
|
|
'TRUE' => true, |
33
|
|
|
'FALSE' => false, |
34
|
|
|
}; |
35
|
|
|
} |
36
|
|
|
|
37
|
|
|
public function getInt(string $name) : int { |
38
|
|
|
return (int)$this->dbRecord[$name]; |
39
|
|
|
} |
40
|
|
|
|
41
|
|
|
public function getFloat(string $name) : float { |
42
|
|
|
return (float)$this->dbRecord[$name]; |
43
|
|
|
} |
44
|
|
|
|
45
|
|
|
public function getMicrotime(string $name) : string { |
46
|
|
|
// All digits of precision are stored in a MySQL bigint |
47
|
|
|
$data = $this->dbRecord[$name]; |
48
|
|
|
return sprintf('%f', $data / 1E6); |
49
|
|
|
} |
50
|
|
|
|
51
|
|
|
public function getObject(string $name, bool $compressed = false, bool $nullable = false) : mixed { |
52
|
|
|
$object = $this->getField($name); |
53
|
|
|
if ($nullable === true && $object === null) { |
54
|
|
|
return null; |
55
|
|
|
} |
56
|
|
|
if ($compressed === true) { |
57
|
|
|
$object = gzuncompress($object); |
|
|
|
|
58
|
|
|
} |
59
|
|
|
return unserialize($object); |
|
|
|
|
60
|
|
|
} |
61
|
|
|
|
62
|
|
|
public function getRow() : array { |
63
|
|
|
return $this->dbRecord; |
64
|
|
|
} |
65
|
|
|
|
66
|
|
|
} |
67
|
|
|
|