SettingRepository::update()   B
last analyzed

Complexity

Conditions 8
Paths 11

Size

Total Lines 41
Code Lines 23

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
cc 8
eloc 23
nc 11
nop 2
dl 0
loc 41
rs 8.4444
c 2
b 0
f 0
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Xetaravel\Models\Repositories;
6
7
use Xetaravel\Models\Setting;
8
use Xetaravel\Settings\Settings;
9
10
class SettingRepository
11
{
12
    /**
13
     * Update settings.
14
     *
15
     * @param Settings $settingClass
16
     * @param array $settings The settings to update.
17
     *
18
     * @return bool
19
     */
20
    public static function update(Settings $settingClass, array $settings): bool
21
    {
22
        if (empty($settings)) {
23
            return true;
24
        }
25
26
        foreach ($settings as $key => $value) {
27
            $setting = Setting::where('key', $key)
28
                ->whereNull('model_type')
29
                ->whereNull('model_id')
30
                ->first();
31
32
            if (is_null($setting)) {
33
                continue;
34
            }
35
36
            // Cast the value the same as the old value to not change the type
37
            if (is_bool($setting->value)) {
38
                $value = (bool)$value;
39
            } elseif (is_int($setting->value)) {
40
                $value = (int)$value;
41
            } elseif (is_float($setting->value)) {
42
                $value = (float)$value;
43
            } else {
44
                $value = (string)$value;
45
            }
46
47
            // Assign the new value dans save it.
48
            $setting->value = $value;
49
            $saved = $setting->save();
50
51
            // If the save fails, return directly.
52
            if ($saved === false) {
53
                return false;
54
            }
55
56
            // Delete the cache related to the setting
57
            $settingClass->withoutContext()->remove($key);
58
        }
59
60
        return true;
61
    }
62
}
63