Completed
Pull Request — master (#48)
by Shawn
05:13 queued 02:49
created

Setting::get()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 12
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 12
rs 9.4285
cc 3
eloc 7
nc 3
nop 2
1
<?php
2
3
namespace SET;
4
5
use Illuminate\Database\Eloquent\Model;
6
use Illuminate\Support\Facades\Cache;
7
8
/**
9
 * Class Setting.
10
 */
11
class Setting extends Model
12
{
13
    /**
14
     * @var array
15
     */
16
    protected $fillable = ['key', 'value'];
17
18
    /**
19
     * Get a single setting value. If no value is set, return null.
20
     *
21
     * @param string      $key
22
     * @param string|null $default
23
     *
24
     * @return string
25
     */
26
    public static function get(string $key, string $default = null)
27
    {
28
        if (Cache::has($key)) {
29
            return Cache::get($key);
30
        }
31
32
        $dbValue = self::where('key', $key)->first();
33
        $value = isset($dbValue) ? json_decode($dbValue->value) : $default;
34
        Cache::forever($key, $value);
35
36
        return $value;
37
    }
38
39
    /**
40
     * Get all data in settings as an array.
41
     *
42
     * @return array
43
     */
44
    public static function getAll()
45
    {
46
        $array = [];
47
        $settings = self::all();
48
        foreach ($settings as $setting) {
49
            $array[$setting->key] = json_decode($setting->value);
50
        }
51
52
        return $array;
53
    }
54
55
    /**
56
     * Set a setting value. If no value is provided, it is stored as null.
57
     *
58
     * @param string      $key
59
     * @param mixed $value
60
     */
61
    public static function set(string $key, $value = null)
62
    {
63
        self::updateOrCreate(['key' => $key], ['value' => json_encode($value)]);
64
        Cache::forever($key, $value);
65
    }
66
}
67