Passed
Push — master ( ead992...bbe860 )
by Бабичев
03:02
created

WritableService::setSettingString()   A

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 1
Bugs 0 Features 1
Metric Value
cc 1
eloc 1
c 1
b 0
f 1
nc 1
nop 3
dl 0
loc 3
ccs 2
cts 2
cp 1
crap 1
rs 10
1
<?php
2
3
namespace Bavix\Settings\Services;
4
5
use Bavix\Settings\Models\Setting;
6
use Bavix\Settings\Traits\HasSettings;
7
use Illuminate\Database\Eloquent\Model;
8
9
class WritableService
10
{
11
12
    /**
13
     * @param Model $model
14
     * @param string $key
15
     * @param int|null $value
16
     * @return Setting
17
     */
18 4
    public function setSettingInt(Model $model, string $key, ?int $value = null): Setting
19
    {
20 4
        return $this->setSetting($model, $key, 'int', $value);
21
    }
22
23
    /**
24
     * @param Model $model
25
     * @param string $key
26
     * @param float|null $value
27
     * @return float|null
28
     */
29 2
    public function setSettingFloat(Model $model, string $key, ?float $value = null): Setting
30
    {
31 2
        return $this->setSetting($model, $key, 'float', $value);
32
    }
33
34
    /**
35
     * @param Model $model
36
     * @param string $key
37
     * @param bool|null $value
38
     * @return bool|null
39
     */
40 2
    public function setSettingBool(Model $model, string $key, ?bool $value = null): Setting
41
    {
42 2
        return $this->setSetting($model, $key, 'bool', $value);
43
    }
44
45
    /**
46
     * @param Model $model
47
     * @param string $key
48
     * @param string|null $value
49
     * @return string|null
50
     */
51 2
    public function setSettingString(Model $model, string $key, ?string $value = null): Setting
52
    {
53 2
        return $this->setSetting($model, $key, 'string', $value);
54
    }
55
56
    /**
57
     * @param Model $model
58
     * @param string $key
59
     * @param array|null $value
60
     * @return array|null
61
     */
62 2
    public function setSettingArray(Model $model, string $key, ?array $value = null): Setting
63
    {
64 2
        return $this->setSetting($model, $key, 'array', $value);
65
    }
66
67
    /**
68
     * @param Model $model
69
     * @param string $key
70
     * @param string $cast
71
     * @param mixed $value
72
     * @return Setting
73
     */
74 12
    protected function setSetting(Model $model, string $key, string $cast, $value): Setting
75
    {
76 12
        $setting = app(ReadableService::class)
77 12
            ->getSetting($model, $key);
78
79
        // refresh
80 12
        $model->unsetRelation('settings');
81
82 12
        if (!$setting) {
83 12
            return app(SettingService::class)
84 12
                ->create($model, $key, $cast, $value);
85
        }
86
87 6
        $setting->update(compact('cast', 'value'));
88 6
        return $setting;
89
    }
90
91
}
92