Setting::getValueAttribute()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
eloc 1
c 0
b 0
f 0
dl 0
loc 3
ccs 2
cts 2
cp 1
rs 10
cc 1
nc 1
nop 1
crap 1
1
<?php
2
3
namespace App\Models;
4
5
use Illuminate\Database\Eloquent\Model;
6
7
/**
8
 * @property string $key
9
 * @property mixed  $value
10
 *
11
 * @method static self find(string $key)
12
 * @method static self updateOrCreate(array $where, array $params)
13
 */
14
class Setting extends Model
15
{
16
    protected $primaryKey = 'key';
17
18
    public $timestamps = false;
19
20
    protected $guarded = [];
21
22
    /**
23
     * Get a setting value.
24
     *
25
     * @param string $key
26
     *
27
     * @return mixed|string
28
     */
29 3
    public static function get(string $key)
30
    {
31 3
        if ($record = self::find($key)) {
32 3
            return $record->value;
33
        }
34
35
        return '';
36
    }
37
38
    /**
39
     * Set a setting (no pun) value.
40
     *
41
     * @param string|array $key   The key of the setting, or an associative array of settings,
42
     *                            in which case $value will be discarded.
43
     * @param mixed        $value
44
     */
45 132
    public static function set($key, $value = null): void
46
    {
47 132
        if (is_array($key)) {
48 1
            foreach ($key as $k => $v) {
49 1
                self::set($k, $v);
50
            }
51
52 1
            return;
53
        }
54
55 132
        self::updateOrCreate(compact('key'), compact('value'));
56 132
    }
57
58
    /**
59
     * Serialize the setting value before saving into the database.
60
     * This makes settings more flexible.
61
     *
62
     * @param mixed $value
63
     */
64 132
    public function setValueAttribute($value): void
65
    {
66 132
        $this->attributes['value'] = serialize($value);
67 132
    }
68
69
    /**
70
     * Get the unserialized setting value.
71
     *
72
     * @param mixed $value
73
     *
74
     * @return mixed
75
     */
76 3
    public function getValueAttribute($value)
77
    {
78 3
        return unserialize($value);
79
    }
80
}
81