Settings::normalizeKey()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 9
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 5
nc 1
nop 1
dl 0
loc 9
rs 10
c 1
b 0
f 0
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Xetaravel\Settings;
6
7
use Illuminate\Contracts\Cache\Repository as Cache;
8
use Illuminate\Database\Eloquent\Model;
9
use Illuminate\Support\Str;
10
use Xetaravel\Models\Setting;
11
12
class Settings
13
{
14
    protected null|array $context = [
15
        'model_type' => null,
16
        'model_id' => null
17
    ];
18
19
    public function __construct(
20
        protected Cache $cache,
21
    ) {
22
    }
23
24
    /**
25
     * Generate the key used by the cache driver to store the value.
26
     *
27
     * @param string $key
28
     *
29
     * @return string
30
     */
31
    protected function getCacheKey(string $key): string
32
    {
33
        $cacheKey = $this->normalizeKey($key);
34
35
        // Add context to the cache key.
36
        $context = serialize($this->context);
37
        $cacheKey .= "::c::{$context}";
38
39
        return $cacheKey;
40
    }
41
42
    protected function normalizeKey(string $key): string
43
    {
44
        // We want to preserve period characters in the key, however everything else is fair game
45
        // to convert to a slug.
46
        return Str::of($key)
47
            ->replace('.', '-dot-')
48
            ->slug()
49
            ->replace('-dot-', '.')
50
            ->__toString();
51
    }
52
53
    /**
54
     * Get the value for the given key, siteId and context fromm the cache or from the database if no cache key.
55
     *
56
     * @param string $key
57
     *
58
     * @return mixed
59
     */
60
    public function get(string $key): mixed
61
    {
62
        $cacheKey = $this->getCacheKey(key: $key);
63
64
        $value = $this->cache->rememberForever($cacheKey, function () use ($key) {
65
            $query = Setting::query()
66
                ->where('key', $key)
67
                ->where('model_type', $this->context['model_type'])
68
                ->where('model_id', $this->context['model_id']);
69
70
            return serialize($query->value('value'));
71
        });
72
73
        return $value ? unserialize($value) : null;
0 ignored issues
show
introduced by
$value is of type Illuminate\Cache\TCacheValue, thus it always evaluated to true.
Loading history...
74
    }
75
76
    /**
77
     * Remove the specified key.
78
     *
79
     * @param string $key The key to flush.
80
     *
81
     * @return bool
82
     */
83
    public function remove(string $key): bool
84
    {
85
        $cacheKey = $this->getCacheKey(key: $key);
86
87
        return $this->cache->forget($cacheKey);
88
    }
89
90
    /**
91
     * Set the context to the setting.
92
     *
93
     *
94
     *
95
     * @param Model|array|null $context
96
     * Pattern :
97
     *  [
98
     *      'type' => 'Xetaravel\Models\User',
99
     *      'id' => 1
100
     *  ]
101
     *
102
     * @return $this
103
     */
104
    public function setContext(Model|array|null $context = null): self
105
    {
106
        if ($context instanceof Model) {
107
            $this->context['model_type'] = get_class($context);
108
            $this->context['model_id'] = $context->getKey();
109
110
            return $this;
111
        }
112
        $this->context = [
113
            'model_type' => $context['type'] ?? null,
114
            'model_id' => $context['id'] ?? null
115
        ];
116
117
        return $this;
118
    }
119
120
    /**
121
     * Reset the context.
122
     *
123
     * @return $this
124
     */
125
    public function withoutContext(): self
126
    {
127
        $this->context = [
128
            'model_type' => null,
129
            'model_id' => null
130
        ];
131
132
        return $this;
133
    }
134
135
}
136