|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
declare(strict_types=1); |
|
4
|
|
|
|
|
5
|
|
|
namespace Damax\Bundle\ApiAuthBundle\Key\Storage; |
|
6
|
|
|
|
|
7
|
|
|
use Damax\Bundle\ApiAuthBundle\Key\Key; |
|
8
|
|
|
use Doctrine\DBAL\Connection; |
|
9
|
|
|
use Doctrine\DBAL\FetchMode; |
|
10
|
|
|
|
|
11
|
|
|
final class DoctrineStorage implements Storage |
|
12
|
|
|
{ |
|
13
|
|
|
private const FIELD_KEY = 'key'; |
|
14
|
|
|
private const FIELD_TTL = 'ttl'; |
|
15
|
|
|
private const FIELD_IDENTITY = 'identity'; |
|
16
|
|
|
|
|
17
|
|
|
private $db; |
|
18
|
|
|
private $tableName; |
|
19
|
|
|
private $fields = [ |
|
20
|
|
|
self::FIELD_KEY => self::FIELD_KEY, |
|
21
|
|
|
self::FIELD_TTL => self::FIELD_TTL, |
|
22
|
|
|
self::FIELD_IDENTITY => self::FIELD_IDENTITY, |
|
23
|
|
|
]; |
|
24
|
|
|
|
|
25
|
|
|
public function __construct(Connection $db, string $tableName, array $fields = []) |
|
26
|
|
|
{ |
|
27
|
|
|
$this->db = $db; |
|
28
|
|
|
$this->tableName = $tableName; |
|
29
|
|
|
$this->fields = array_replace($this->fields, $fields); |
|
30
|
|
|
} |
|
31
|
|
|
|
|
32
|
|
|
public function has(string $key): bool |
|
33
|
|
|
{ |
|
34
|
|
|
$sql = sprintf('SELECT 1 FROM %s WHERE %s = ?', $this->tableName, $this->fields[self::FIELD_KEY]); |
|
35
|
|
|
|
|
36
|
|
|
return (bool) $this->db->executeQuery($sql, [$key])->fetchColumn(); |
|
37
|
|
|
} |
|
38
|
|
|
|
|
39
|
|
|
public function remove(string $key): void |
|
40
|
|
|
{ |
|
41
|
|
|
$sql = sprintf('DELETE FROM %s WHERE %s = ?', $this->tableName, $this->fields[self::FIELD_KEY]); |
|
42
|
|
|
|
|
43
|
|
|
$this->db->executeQuery($sql, [$key])->execute(); |
|
44
|
|
|
} |
|
45
|
|
|
|
|
46
|
|
|
public function add(Key $key): void |
|
47
|
|
|
{ |
|
48
|
|
|
$this->db->insert($this->tableName, [ |
|
49
|
|
|
$this->fields[self::FIELD_KEY] => (string) $key, |
|
50
|
|
|
$this->fields[self::FIELD_IDENTITY] => $key->identity(), |
|
51
|
|
|
$this->fields[self::FIELD_TTL] => time() + $key->ttl(), |
|
52
|
|
|
]); |
|
53
|
|
|
} |
|
54
|
|
|
|
|
55
|
|
|
public function get(string $key): Key |
|
56
|
|
|
{ |
|
57
|
|
|
$fields = $this->fields[self::FIELD_IDENTITY] . ', ' . $this->fields[self::FIELD_TTL]; |
|
58
|
|
|
|
|
59
|
|
|
$sql = sprintf('SELECT %s FROM %s WHERE %s = ?', $fields, $this->tableName, $this->fields[self::FIELD_KEY]); |
|
60
|
|
|
|
|
61
|
|
|
if (false === $row = $this->db->executeQuery($sql, [$key])->fetch(FetchMode::ASSOCIATIVE)) { |
|
62
|
|
|
throw new KeyNotFound(); |
|
63
|
|
|
} |
|
64
|
|
|
|
|
65
|
|
|
return new Key($key, $row[$this->fields[self::FIELD_IDENTITY]], $row[$this->fields[self::FIELD_TTL]] - time()); |
|
66
|
|
|
} |
|
67
|
|
|
} |
|
68
|
|
|
|