|
1
|
|
|
<?php |
|
2
|
|
|
/** |
|
3
|
|
|
* This file is part of the Rate Limit package. |
|
4
|
|
|
* |
|
5
|
|
|
* Copyright (c) Nikola Posa |
|
6
|
|
|
* |
|
7
|
|
|
* For full copyright and license information, please refer to the LICENSE file, |
|
8
|
|
|
* located at the package root folder. |
|
9
|
|
|
*/ |
|
10
|
|
|
|
|
11
|
|
|
declare(strict_types=1); |
|
12
|
|
|
|
|
13
|
|
|
namespace RateLimit\Storage; |
|
14
|
|
|
|
|
15
|
|
|
use RateLimit\Exception\StorageRecordNotExistException; |
|
16
|
|
|
|
|
17
|
|
|
/** |
|
18
|
|
|
* @author Nikola Posa <[email protected]> |
|
19
|
|
|
*/ |
|
20
|
|
|
final class FilesystemStorage implements StorageInterface |
|
21
|
|
|
{ |
|
22
|
|
|
/** |
|
23
|
|
|
* @var string |
|
24
|
|
|
*/ |
|
25
|
|
|
private $directory; |
|
26
|
|
|
|
|
27
|
2 |
|
public function __construct(string $directory) |
|
28
|
|
|
{ |
|
29
|
2 |
|
$this->directory = rtrim($directory, DIRECTORY_SEPARATOR); |
|
30
|
2 |
|
} |
|
31
|
|
|
|
|
32
|
|
|
/** |
|
33
|
|
|
* {@inheritdoc} |
|
34
|
|
|
*/ |
|
35
|
1 |
|
public function get(string $key) |
|
36
|
|
|
{ |
|
37
|
1 |
|
$filePath = $this->buildFilePath($key); |
|
38
|
|
|
|
|
39
|
1 |
|
if (!is_file($filePath)) { |
|
40
|
|
|
throw StorageRecordNotExistException::forKey($key); |
|
41
|
|
|
} |
|
42
|
|
|
|
|
43
|
1 |
|
$contents = file_get_contents($filePath); |
|
44
|
|
|
|
|
45
|
1 |
|
return unserialize($contents); |
|
46
|
|
|
} |
|
47
|
|
|
|
|
48
|
|
|
/** |
|
49
|
|
|
* {@inheritdoc} |
|
50
|
|
|
*/ |
|
51
|
2 |
|
public function set(string $key, $data) |
|
52
|
|
|
{ |
|
53
|
2 |
|
if (!is_dir($this->directory)) { |
|
54
|
2 |
|
mkdir($this->directory, 0777, true); |
|
55
|
|
|
} |
|
56
|
|
|
|
|
57
|
2 |
|
$filePath = $this->buildFilePath($key); |
|
58
|
|
|
|
|
59
|
2 |
|
$contents = serialize($data); |
|
60
|
|
|
|
|
61
|
2 |
|
file_put_contents($filePath, $contents, FILE_APPEND | LOCK_EX); |
|
62
|
2 |
|
} |
|
63
|
|
|
|
|
64
|
2 |
|
private function buildFilePath(string $key) |
|
65
|
|
|
{ |
|
66
|
2 |
|
return $this->directory . DIRECTORY_SEPARATOR . md5($key); |
|
67
|
|
|
} |
|
68
|
|
|
} |
|
69
|
|
|
|