Completed
Push — dev ( cb6296...2e3e2f )
by Amr
03:50
created

HasSettings   A

Complexity

Total Complexity 8

Size/Duplication

Total Lines 48
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 0

Test Coverage

Coverage 100%

Importance

Changes 2
Bugs 0 Features 1
Metric Value
wmc 8
c 2
b 0
f 1
lcom 1
cbo 0
dl 0
loc 48
ccs 23
cts 23
cp 1
rs 10

7 Methods

Rating   Name   Duplication   Size   Complexity  
getKey() 0 1 ?
A settingsCacheKey() 0 4 1
A allSettings() 0 4 1
A setSettings() 0 8 1
A getSettings() 0 12 3
A forgetSettings() 0 4 1
A flushSettings() 0 6 1
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