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
|
|
|
use Doctrine\DBAL\ParameterType; |
11
|
|
|
|
12
|
|
|
class DoctrineStorage implements Storage |
13
|
|
|
{ |
14
|
|
|
private const FIELD_USERNAME = 'username'; |
15
|
|
|
private const FIELD_EXPIRES = 'expires'; |
16
|
|
|
|
17
|
|
|
private $db; |
18
|
|
|
private $tableName; |
19
|
|
|
private $fields; |
20
|
|
|
|
21
|
|
|
public function __construct(Connection $db, string $tableName, array $fields = []) |
|
|
|
|
22
|
|
|
{ |
23
|
|
|
$this->db = $db; |
24
|
|
|
$this->tableName = $tableName; |
25
|
|
|
$this->fields[self::FIELD_USERNAME] = $this->fields[self::FIELD_USERNAME] ?? self::FIELD_USERNAME; |
26
|
|
|
$this->fields[self::FIELD_EXPIRES] = $this->fields[self::FIELD_EXPIRES] ?? self::FIELD_EXPIRES; |
27
|
|
|
} |
28
|
|
|
|
29
|
|
|
public function has(string $key): bool |
30
|
|
|
{ |
31
|
|
|
$sql = sprintf('SELECT 1 FROM %s WHERE id = ?', $this->tableName); |
32
|
|
|
|
33
|
|
|
return (bool) $this->db->executeQuery($sql, [$key], [ParameterType::STRING])->fetchColumn(); |
34
|
|
|
} |
35
|
|
|
|
36
|
|
|
public function remove(string $key): void |
37
|
|
|
{ |
38
|
|
|
$sql = sprintf('DELETE FROM %s WHERE id = ?', $this->tableName); |
39
|
|
|
|
40
|
|
|
$this->db->executeQuery($sql, [$key], [ParameterType::STRING])->execute(); |
41
|
|
|
} |
42
|
|
|
|
43
|
|
|
public function get(string $key): Key |
44
|
|
|
{ |
45
|
|
|
$sql = sprintf('SELECT * FROM %s WHERE id = ?', $this->tableName); |
46
|
|
|
|
47
|
|
|
if (false === $row = $this->db->executeQuery($sql, [$key], [ParameterType::STRING])->fetch(FetchMode::ASSOCIATIVE)) { |
48
|
|
|
throw new KeyNotFoundException(); |
49
|
|
|
} |
50
|
|
|
|
51
|
|
|
return new Key($key, $row[self::FIELD_USERNAME], time() - $row[self::FIELD_EXPIRES]); |
52
|
|
|
} |
53
|
|
|
|
54
|
|
|
public function add(Key $key): void |
55
|
|
|
{ |
56
|
|
|
$this->db->insert($this->tableName, [ |
57
|
|
|
'id' => (string) $key, |
58
|
|
|
self::FIELD_USERNAME => $key->username(), |
59
|
|
|
self::FIELD_EXPIRES => time() + $key->ttl(), |
60
|
|
|
]); |
61
|
|
|
} |
62
|
|
|
} |
63
|
|
|
|
This check looks for parameters that have been defined for a function or method, but which are not used in the method body.