-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathKeySet.php
93 lines (76 loc) · 2.03 KB
/
KeySet.php
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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
<?php
namespace clentfort\LaravelFindJsLocalizations;
use Illuminate\Filesystem\Filesystem;
use Illuminate\Support\Arr;
use Illuminate\Support\Collection;
use clentfort\LaravelFindJsLocalizations\Exceptions\RuntimeException;
class KeySet
{
/**
* @var string
*/
const FILE_TEMPLATE = <<<PHP
<?php
return %s;
PHP;
/**
* @var Filesystem
*/
private $filesystem;
/**
* @var string
*/
protected $directory;
public function __construct(Filesystem $filesystem, $directory)
{
$this->filesystem = $filesystem;
$this->directory = $directory;
if (!$this->filesystem->exists($this->directory)) {
throw new RuntimeException(
"Directory \"$this->directory\" does not exists."
);
}
if (!$this->filesystem->isDirectory($this->directory)) {
throw new RuntimeException(
"\"$this->directory\" is not a directory."
);
}
}
public function getKeysWithPrefix($prefix)
{
$prefixFilePath = $this->getFilePath($prefix);
if ($this->filesystem->isFile($prefixFilePath)) {
$keys = $this->filesystem->getRequire($prefixFilePath);
if (is_array($keys)) {
$keys = Arr::dot($keys);
ksort($keys);
return new Collection($keys);
}
}
return new Collection();
}
public function setKeysWithPrefix($prefix, $keys)
{
$prefixFilePath = $this->getFilePath($prefix);
return $this->filesystem->put(
$prefixFilePath,
static::exportKeys($keys)
);
}
/**
* @return string
*/
protected static function exportKeys($keys)
{
$keys = Arr::dot($keys);
ksort($keys);
return sprintf(static::FILE_TEMPLATE, var_export($keys, true));
}
protected function getFilePath($prefix)
{
return PathHelper::join(
$this->directory,
"$prefix.php"
);
}
}