|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace UniMan\Drivers\Redis; |
|
4
|
|
|
|
|
5
|
|
|
use Exception; |
|
6
|
|
|
use Nette\Localization\ITranslator; |
|
7
|
|
|
use Phar; |
|
8
|
|
|
|
|
9
|
|
|
class RedisDatabaseAliasStorage |
|
10
|
|
|
{ |
|
11
|
|
|
private $translator; |
|
12
|
|
|
|
|
13
|
|
|
private $baseDirname; |
|
14
|
|
|
|
|
15
|
|
|
private $savesDirname = 'uniman_saves'; |
|
16
|
|
|
|
|
17
|
|
|
private $filename = 'redis_aliases.json'; |
|
18
|
|
|
|
|
19
|
2 |
|
public function __construct($dir, ITranslator $translator) |
|
20
|
|
|
{ |
|
21
|
2 |
|
$this->translator = $translator; |
|
22
|
2 |
|
$pharFile = Phar::running(false); |
|
23
|
2 |
|
$dirname = $pharFile ? dirname($pharFile) : $dir; |
|
24
|
2 |
|
$this->baseDirname = realpath($dirname); |
|
25
|
2 |
|
} |
|
26
|
|
|
|
|
27
|
|
|
public function loadAll() |
|
28
|
|
|
{ |
|
29
|
|
|
$filename = $this->createFilename(); |
|
30
|
|
|
$content = file_exists($filename) ? file_get_contents($filename) : null; |
|
31
|
|
|
return $content ? json_decode($content, true) : []; |
|
32
|
|
|
} |
|
33
|
|
|
|
|
34
|
|
|
public function load($database) |
|
35
|
|
|
{ |
|
36
|
|
|
$aliases = $this->loadAll(); |
|
37
|
|
|
return isset($aliases[$database]) ? $aliases[$database] : null; |
|
38
|
|
|
} |
|
39
|
|
|
|
|
40
|
|
|
public function check() |
|
41
|
|
|
{ |
|
42
|
|
View Code Duplication |
if (!is_writeable($this->baseDirname)) { |
|
|
|
|
|
|
43
|
|
|
throw new Exception($this->translator->translate('redis.alias_storage_not_writable', ['directory' => $this->baseDirname])); |
|
44
|
|
|
} |
|
45
|
|
|
$dirname = $this->baseDirname . '/' . $this->savesDirname; |
|
46
|
|
|
if (!file_exists($dirname)) { |
|
47
|
|
|
mkdir($dirname, 0777, true); |
|
48
|
|
|
} |
|
49
|
|
View Code Duplication |
if (!file_exists($dirname)) { |
|
|
|
|
|
|
50
|
|
|
throw new Exception($this->translator->translate('redis.alias_storage_not_writable', ['directory' => $this->baseDirname])); |
|
51
|
|
|
} |
|
52
|
|
|
return true; |
|
53
|
|
|
} |
|
54
|
|
|
|
|
55
|
|
|
public function save(array $aliases) |
|
56
|
|
|
{ |
|
57
|
|
|
ksort($aliases); |
|
58
|
|
|
$filename = $this->createFilename(); |
|
59
|
|
|
return (bool) file_put_contents($filename, json_encode($aliases)); |
|
60
|
|
|
} |
|
61
|
|
|
|
|
62
|
|
|
private function createFilename() |
|
63
|
|
|
{ |
|
64
|
|
|
return $this->baseDirname . '/' . $this->savesDirname . '/' . $this->filename; |
|
65
|
|
|
} |
|
66
|
|
|
} |
|
67
|
|
|
|
Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.
You can also find more detailed suggestions in the “Code” section of your repository.