-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSqliteStorage.php
More file actions
67 lines (57 loc) · 1.85 KB
/
SqliteStorage.php
File metadata and controls
67 lines (57 loc) · 1.85 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
<?php
namespace Slowmove\SimplePhpQueue\Storage\Adapters;
use Slowmove\SimplePhpQueue\Helpers\FileUtils;
use Slowmove\SimplePhpQueue\Storage\StorageInterface;
class SqliteStorage implements StorageInterface
{
private string $queueFile;
private \SQLite3 $connection;
public function __construct(
string $storagePath,
string $storageName = 'queue',
) {
if (empty($storagePath)) {
$storagePath = ".";
}
$this->queueFile = FileUtils::isFilePath($storagePath)
? $storagePath
: rtrim($storagePath, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR . $storageName . '.db';
FileUtils::createFile($this->queueFile);
$this->connection = new \SQLite3($this->queueFile);
$this->connection->query("CREATE TABLE IF NOT EXISTS queue (id INTEGER PRIMARY KEY AUTOINCREMENT, data TEXT)");
}
public function enqueue(string $data): bool
{
$stmt = $this->connection->prepare("INSERT INTO queue (data) VALUES (:data)");
$stmt->bindValue(':data', $data);
$result = $stmt->execute();
return !!$result;
}
public function dequeue(): ?string
{
$result = $this->connection->querySingle("SELECT * FROM queue ORDER BY id asc LIMIT 1", true);
if ($result) {
extract($result);
$this->connection->query("DELETE FROM queue WHERE id = $id");
}
return $data ?? null;
}
public function exist(string $value): bool
{
$result = $this->connection->querySingle("SELECT COUNT(*) FROM queue WHERE data = '$value'");
return !!$result;
}
public function length(): int
{
return $this->connection->querySingle("SELECT COUNT(*) FROM queue");
}
public function content(): array
{
$result = $this->connection->query("SELECT data FROM queue ORDER BY id asc");
$data = [];
while ($row = $result->fetchArray(SQLITE3_ASSOC)) {
$data[] = $row["data"];
}
return $data;
}
}