1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Merodiro\Settings; |
4
|
|
|
|
5
|
|
|
use Illuminate\Support\Facades\Cache; |
6
|
|
|
use Merodiro\Settings\Models\Setting; |
7
|
|
|
|
8
|
|
|
trait HasSettings |
9
|
|
|
{ |
10
|
|
|
abstract public function getKey(); |
11
|
|
|
|
12
|
22 |
|
public function settingsCacheKey($key) |
13
|
|
|
{ |
14
|
22 |
|
return config('settings.cache_prefix') . $key . '_' . $this->getKey(); |
15
|
|
|
} |
16
|
|
|
|
17
|
8 |
|
public function allSettings() |
18
|
|
|
{ |
19
|
8 |
|
return Setting::where('owner_id', $this->getKey())->pluck('value', 'key'); |
20
|
|
|
} |
21
|
|
|
|
22
|
20 |
|
public function setSettings($key, $value) |
23
|
|
|
{ |
24
|
20 |
|
$cache_key = $this->settingsCacheKey($key); |
25
|
20 |
|
$duration = config('settings.cache_duration'); |
26
|
|
|
|
27
|
20 |
|
Setting::updateOrCreate(['key' => $key, 'owner_id' => $this->getKey()], ['value' => $value,]); |
28
|
20 |
|
Cache::put($cache_key, $value, $duration); |
29
|
20 |
|
} |
30
|
|
|
|
31
|
6 |
|
public function getSettings($key, $default = null) |
32
|
|
|
{ |
33
|
6 |
|
$cache_key = $this->settingsCacheKey($key); |
34
|
|
|
|
35
|
6 |
|
if (Cache::has($cache_key)) { |
36
|
4 |
|
return Cache::get($cache_key); |
37
|
|
|
} |
38
|
|
|
|
39
|
2 |
|
$value = Setting::where('key', $key)->where('owner_id', $this->getKey())->pluck('value')->first(); |
40
|
|
|
|
41
|
2 |
|
return $value ? $value : $default; |
42
|
|
|
} |
43
|
|
|
|
44
|
2 |
|
public function forgetSettings($key) |
45
|
|
|
{ |
46
|
2 |
|
Setting::where('key', $key)->where('owner_id', $this->getKey())->first()->delete(); |
47
|
2 |
|
} |
48
|
|
|
|
49
|
|
|
public function flushSettings() |
50
|
|
|
{ |
51
|
2 |
|
Setting::where('owner_id', $this->getKey())->each(function ($item) { |
52
|
2 |
|
$item->delete(); |
53
|
2 |
|
}); |
54
|
2 |
|
} |
55
|
|
|
} |
56
|
|
|
|