Completed
Pull Request — master (#4)
by Amr
01:26
created

HasSettings::getSettings()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 12
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 3

Importance

Changes 1
Bugs 0 Features 1
Metric Value
c 1
b 0
f 1
dl 0
loc 12
ccs 6
cts 6
cp 1
rs 9.4285
cc 3
eloc 6
nc 3
nop 2
crap 3
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 14
    public function settingsCacheKey($key)
13
    {
14 14
        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
        Setting::updateOrCreate(['key' => $key, 'owner_id' => $this->getKey()], ['value' => $value,]);
25 20
    }
26
27 6
    public function getSettings($key, $default = null)
28
    {
29 6
        $cache_key = $this->settingsCacheKey($key);
30
31 6
        if (Cache::has($cache_key)) {
32 4
            return Cache::get($cache_key);
33
        }
34
35 2
        $value = Setting::where('key', $key)->where('owner_id', $this->getKey())->pluck('value')->first();
36
37 2
        return $value ? $value : $default;
38
    }
39
40 2
    public function forgetSettings($key)
41
    {
42 2
        Setting::where('key', $key)->where('owner_id', $this->getKey())->first()->delete();
43 2
    }
44
45
    public function flushSettings()
46
    {
47 2
        Setting::where('owner_id', $this->getKey())->each(function ($item) {
48 2
            $item->delete();
49 2
        });
50 2
    }
51
}
52