1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Fomvasss\Variable; |
4
|
|
|
|
5
|
|
|
/** |
6
|
|
|
* Class VariableManager |
7
|
|
|
* |
8
|
|
|
* @package \Fomvasss\Variable |
9
|
|
|
*/ |
10
|
|
|
class VariableManager implements VariableManagerContract |
11
|
|
|
{ |
12
|
|
|
protected $app; |
13
|
|
|
|
14
|
|
|
protected $variableModel; |
15
|
|
|
|
16
|
|
|
protected $cacheRepository; |
17
|
|
|
|
18
|
|
|
protected $locale = null; |
19
|
|
|
|
20
|
|
|
protected $variables = null; |
21
|
|
|
|
22
|
|
|
/** |
23
|
|
|
* VariableManager constructor. |
24
|
|
|
* @param $cacheRepository |
25
|
|
|
* @param null $app |
|
|
|
|
26
|
|
|
*/ |
27
|
|
|
public function __construct($variableModel, $cacheRepository, $app = null) |
28
|
|
|
{ |
29
|
|
|
if (! $app) { |
|
|
|
|
30
|
|
|
$app = app(); //Fallback when $app is not given |
|
|
|
|
31
|
|
|
} |
32
|
|
|
$this->app = $app; |
33
|
|
|
|
34
|
|
|
$this->config = $this->app['config']->get('variables'); |
|
|
|
|
35
|
|
|
|
36
|
|
|
$this->variableModel = $variableModel; |
37
|
|
|
|
38
|
|
|
$this->cacheRepository = $cacheRepository; |
39
|
|
|
} |
40
|
|
|
|
41
|
|
|
/** |
42
|
|
|
* @param string $key |
43
|
|
|
* @param null $default |
|
|
|
|
44
|
|
|
* @return mixed|null |
45
|
|
|
*/ |
46
|
|
|
public function get(string $key, $default = null) |
47
|
|
|
{ |
48
|
|
|
if (isset($this->all()[$key])) { |
49
|
|
|
return $this->all()[$key]; |
50
|
|
|
} |
51
|
|
|
|
52
|
|
|
return $default; |
53
|
|
|
|
54
|
|
|
} |
55
|
|
|
|
56
|
|
|
/** |
57
|
|
|
* @return array |
58
|
|
|
*/ |
59
|
|
|
public function all(): array |
60
|
|
|
{ |
61
|
|
|
if ($this->variables === null) { |
62
|
|
|
|
63
|
|
|
$all = $this->cacheRepository->remember($this->config['cache']['name'], $this->config['cache']['time'], function () { |
64
|
|
|
return $this->getCollection(); |
65
|
|
|
}); |
66
|
|
|
|
67
|
|
|
if ($all) { |
68
|
|
|
$allByLocale = $this->locale ? $all->where('locale', $this->locale) : $all; |
69
|
|
|
$this->variables = $allByLocale->pluck('value', 'key')->toArray(); |
70
|
|
|
} else { |
71
|
|
|
$this->variables = []; |
72
|
|
|
} |
73
|
|
|
|
74
|
|
|
} |
75
|
|
|
|
76
|
|
|
return $this->variables; |
77
|
|
|
} |
78
|
|
|
|
79
|
|
|
/** |
80
|
|
|
* @param string $locale |
81
|
|
|
* @return $this |
82
|
|
|
*/ |
83
|
|
|
public function locale(string $locale = null) |
84
|
|
|
{ |
85
|
|
|
$this->locale = $locale; |
86
|
|
|
|
87
|
|
|
return $this; |
88
|
|
|
} |
89
|
|
|
|
90
|
|
|
/** |
91
|
|
|
* @return \Illuminate\Support\Collection | null |
92
|
|
|
*/ |
93
|
|
|
protected function getCollection() |
94
|
|
|
{ |
95
|
|
|
try { |
96
|
|
|
return $this->variableModel->select('key', 'value', 'locale')->get(); |
97
|
|
|
} catch (\Exception $exception) { |
98
|
|
|
$this->app['log']->info(__CLASS__ . ' - ' . $exception->getMessage()); |
99
|
|
|
|
100
|
|
|
return null; |
101
|
|
|
} |
102
|
|
|
} |
103
|
|
|
} |
104
|
|
|
|