Completed
Push — 16146-settings-to-admin ( e90069 )
by Shawn
05:56
created

Setting::set()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 5
rs 9.4285
cc 1
eloc 3
nc 1
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
     * @return string
24
     */
25
    public static function get(string $key, string $default = null)
26
    {
27
        if (Cache::has($key)) {
28
            return Cache::get($key);
29
        }
30
31
        $dbValue = Setting::where('key', $key)->first();
32
        $value = isset($dbValue) ? json_decode($dbValue->value) : $default;
33
        Cache::forever($key, $value);
34
35
        return $value;
36
    }
37
38
    /**
39
     * Get all data in settings as an array.
40
     * @return array
41
     */
42
    public static function getAll()
43
    {
44
        $array = array();
45
        $settings = Setting::all();
46
        foreach ($settings as $setting){
47
            $array[$setting->key] = json_decode($setting->value);
48
        };
49
        return $array;
50
    }
51
52
    /**
53
     * Set a setting value. If no value is provided, it is stored as null.
54
     *
55
     * @param string $key
56
     * @param string|null $value
57
     */
58
    public static function set(string $key, $value = null)
59
    {
60
        Setting::updateOrCreate(['key' => $key], ['value' => json_encode($value)]);
1 ignored issue
show
Bug introduced by
The method updateOrCreate() does not exist on SET\Setting. Did you maybe mean create()?

This check marks calls to methods that do not seem to exist on an object.

This is most likely the result of a method being renamed without all references to it being renamed likewise.

Loading history...
61
        Cache::forever($key, $value);
62
    }
63
}
64