Completed
Push — master ( 2bd499...c45ce7 )
by Nazmus
01:14
created

DbConfig::cacheKey()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 4
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 0
1
<?php
2
3
namespace Nzsakib\DbConfig;
4
5
use Illuminate\Support\Arr;
6
use InvalidArgumentException;
7
use Illuminate\Support\Facades\Cache;
8
use Illuminate\Database\Eloquent\Builder;
9
use Nzsakib\DbConfig\Models\Configuration;
10
use Illuminate\Database\Eloquent\Collection;
11
12
class DbConfig
13
{
14
    /**
15
     * Get the configuration key value pairs from database to merge with config
16
     *
17
     * @return array
18
     */
19
    public function get(): array
20
    {
21
        return Configuration::query()
0 ignored issues
show
Bug introduced by
The method select() does not exist on Illuminate\Database\Eloquent\Builder. Did you maybe mean createSelectWithConstraint()?

This check marks calls to methods that do not seem to exist on an object.

This is most likely the result of a method being renamed without all references to it being renamed likewise.

Loading history...
22
                ->select('name', 'value')
23
                ->get()
24
                ->keyBy('name')
25
                ->transform(function ($config) {
26
                    return $config->value;
27
                })
28
                ->toArray();
29
    }
30
31
    /**
32
     * Get all custom config from database
33
     *
34
     * @return \Illuminate\Database\Eloquent\Collection
35
     */
36
    public function getCollection(): Collection
37
    {
38
        return Configuration::all();
39
    }
40
41
    /**
42
     * Get Eloquent query to operate on from controller
43
     *
44
     * @return \Illuminate\Database\Eloquent\Builder
45
     */
46
    public function getQuery(): Builder
47
    {
48
        return Configuration::query();
49
    }
50
51
    /**
52
     * Get flattened array of config files
53
     *
54
     * @return array
55
     */
56
    public function getCachedData(): array
57
    {
58
        if (config('db-config.use_cache') && $config = Cache::get($this->cacheKey())) {
59
            return $config;
60
        }
61
62
        $configs = $this->get();
63
        $flatted = Arr::dot($configs);
64
65
        if (config('db-config.use_cache')) {
66
            Cache::forever($this->cacheKey(), $flatted);
67
        }
68
69
        return $flatted;
70
    }
71
72
    /**
73
     * Set a new config to db
74
     *
75
     * @param string $name
76
     * @param mixed $value
77
     * @return \Nzsakib\DbConfig\Models\Configuration
78
     * @throws InvalidArgumentException
79
     */
80
    public function set(string $name, $value): Configuration
81
    {
82
        $this->mustBeAssociativeArrayWhenMerging($name, $value);
83
84
        $this->checkExistingDefaultKeys($name, $value);
85
86
        if (Configuration::where('name', $name)->exists()) {
87
            throw new InvalidArgumentException('Same name configuration exists. Please edit existing config or give it a new name.');
88
        }
89
90
        $newConfig = Configuration::create([
91
            'name' => $name,
92
            'value' => $value,
93
        ]);
94
95
        $this->invalidateCache();
96
97
        return $newConfig;
98
    }
99
100
    /**
101
     * Update a config by its primary key `id`
102
     *
103
     * @param integer $id
104
     * @param string $name
105
     * @param mixed $newValue
106
     * @return \Nzsakib\DbConfig\Models\Configuration
107
     * @throws \Illuminate\Database\Eloquent\ModelNotFoundException
108
     */
109
    public function updateById($id, string $name, $newValue)
110
    {
111
        $config = Configuration::findOrFail($id);
112
113
        $config->name = $name;
114
        $config->value = $newValue;
115
        $config->save();
116
117
        $this->invalidateCache();
118
119
        return $config;
120
    }
121
122
    /**
123
     * Update configuration by config name
124
     *
125
     * @param string $name
126
     * @param mixed $value
127
     * @return \Nzsakib\DbConfig\Models\Configuration
128
     * @throws \Illuminate\Database\Eloquent\ModelNotFoundException
129
     */
130
    public function updateByName(string $name, $value)
131
    {
132
        $config = Configuration::where('name', $name)->firstOrFail();
133
134
        $config->value = $value;
135
        $config->save();
136
137
        $this->invalidateCache();
138
139
        return $config;
140
    }
141
142
    /**
143
     * Delete a config from db by name
144
     *
145
     * @param string $name
146
     * @return \Nzsakib\DbConfig\Models\Configuration
147
     * @throws \Illuminate\Database\Eloquent\ModelNotFoundException
148
     */
149
    public function deleteByName(string $name): Configuration
150
    {
151
        $config = Configuration::where('name', $name)->firstOrFail();
152
153
        $config->delete();
154
155
        $this->invalidateCache();
156
157
        return $config;
158
    }
159
160
    /**
161
     * Delete db config by its primary key `id`
162
     *
163
     * @param int $id
164
     * @return Configuration
165
     */
166
    public function deleteById($id): Configuration
167
    {
168
        $config = Configuration::findOrFail($id);
169
170
        $config->delete();
171
172
        $this->invalidateCache();
173
174
        return $config;
175
    }
176
177
    /**
178
     * we dont merge if same key exists in default
179
     * Check each array key if existing configuration exists with same key
180
     *
181
     * @param string $name
182
     * @param string|array $value
183
     * @return void
184
     * @throws InvalidArgumentException
185
     */
186
    protected function checkExistingDefaultKeys(string $name, $value)
187
    {
188
        if (config($name) && is_array($value)) {
189
            $dotArray = Arr::dot($value);
190
191
            foreach ($dotArray as $key => $arrValue) {
192
                $configName = "{$name}.{$key}";
193
                if (config($configName)) {
194
                    throw new InvalidArgumentException('There is an existing config found with name: ' . $configName);
195
                }
196
            }
197
        }
198
    }
199
200
    /**
201
     * we allow merging with existing config keys
202
     * 2nd argument must be an associative array when merging with existing config
203
     *
204
     * @param string $name
205
     * @param string|array $value
206
     * @return void
207
     * @throws InvalidArgumentException
208
     */
209
    protected function mustBeAssociativeArrayWhenMerging(string $name, $value)
210
    {
211
        if (config($name) && !is_array($value) || (is_array($value) && !Arr::isAssoc($value))) {
212
            throw new InvalidArgumentException('Value should be an associative array when merging with existing config.');
213
        }
214
    }
215
216
    /**
217
     * Get Cache key name to store in cache
218
     *
219
     * @return string
220
     */
221
    protected function cacheKey(): string
222
    {
223
        return config('db-config.cache_key', 'app_config');
224
    }
225
226
    /**
227
     * Invalidate the config cache
228
     *
229
     * @return boolean
230
     */
231
    protected function invalidateCache(): bool
232
    {
233
        return cache()->forget($this->cacheKey());
234
    }
235
}
236