Passed
Pull Request — master (#95)
by Fèvre
22:54 queued 17:29
created

Settings::getCacheKey()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 9
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 4
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 BDS\Models\Setting;
0 ignored issues
show
Bug introduced by
The type BDS\Models\Setting was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

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