ModelOverride::saveToJson()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 9
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 2

Importance

Changes 0
Metric Value
cc 2
eloc 5
c 0
b 0
f 0
nc 2
nop 0
dl 0
loc 9
ccs 5
cts 5
cp 1
crap 2
rs 10
1
<?php
2
3
namespace Okipa\LaravelModelJsonStorage;
4
5
use Exception;
6
use File;
7
use Illuminate\Support\Collection;
8
9
trait ModelOverride
10
{
11
    /**
12
     * Get all of the models from the json file.
13
     *
14
     * @param array $columns
15
     *
16
     * @return Collection
17
     */
18 22
    public static function all($columns = ['*'])
19
    {
20 22
        return (new static)->get($columns);
21
    }
22
23
    /**
24
     * Add a "where not in" clause to the query.
25
     *
26
     * @param string $column
27
     * @param array  $values
28
     *
29
     * @return $this
30
     */
31
    abstract public function whereNotIn(string $column, array $values);
32
    
33
    
34
35
    /**
36
     * Get the class name of the parent model.
37
     *
38
     * @return string
39
     */
40
    abstract public function getMorphClass();
41
42
    /**
43
     * Load all of the models from the json file in the "modelsFromJson" variable.
44
     *
45
     * @return Collection
46
     */
47
    abstract protected function loadModelsFromJson();
48
49
    /**
50
     * Execute the query as a "select" statement.
51
     *
52
     * @param  array $columns
53
     *
54
     * @return Collection
55
     */
56
    abstract public function get(array $columns = ['*']);
57
58
    /**
59
     * Fill the model with an array of attributes.
60
     *
61
     * @param  array $attributes
62
     *
63
     * @return $this
64
     * @throws \Illuminate\Database\Eloquent\MassAssignmentException
65
     */
66
    abstract public function fill(array $attributes);
67
68
    /**
69
     * Determine if the model uses timestamps.
70
     *
71
     * @return bool
72
     */
73
    abstract public function usesTimestamps();
74
75
    /**
76
     * Get a fresh timestamp for the model.
77
     *
78
     * @return string
79
     */
80
    abstract public function freshTimestampString();
81
82
    /**
83
     * Set the value of the "created at" attribute.
84
     *
85
     * @param  mixed $value
86
     *
87
     * @return $this
88
     */
89
    abstract public function setCreatedAt($value);
90
91
    /**
92
     * Set the value of the "updated at" attribute.
93
     *
94
     * @param  mixed $value
95
     *
96
     * @return $this
97
     */
98
    abstract public function setUpdatedAt($value);
99
100
    /**
101
     * Get an attribute from the model.
102
     *
103
     * @param  string $key
104
     *
105
     * @return mixed
106
     */
107
    abstract public function getAttribute($key);
108
109
    /**
110
     * Get all of the current attributes on the model.
111
     *
112
     * @return array
113
     */
114
    abstract public function getAttributes();
115
116
    /**
117
     * Make the given, typically hidden, attributes visible.
118
     *
119
     * @param  array|string $attributes
120
     *
121
     * @return $this
122
     */
123
    abstract public function makeVisible($attributes);
124
125
    /**
126
     * Set the array of model attributes. No checking is done.
127
     *
128
     * @param  array $attributes
129
     * @param  bool  $sync
130
     *
131
     * @return $this
132
     */
133
    abstract public function setRawAttributes(array $attributes, $sync = false);
134
135
    /**
136
     * Get the hidden attributes for the model.
137
     *
138
     * @return array
139
     */
140
    abstract public function getHidden();
141
142
    /**
143
     * Get the primary key for the model.
144
     *
145
     * @return string
146
     */
147
    abstract public function getKeyName();
148
149
    /**
150
     * Save the model to the json file.
151
     *
152
     * @param  array $options
153
     *
154
     * @return bool
155
     */
156 22
    public function save(array $options = [])
0 ignored issues
show
Unused Code introduced by
The parameter $options is not used and could be removed. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-unused  annotation

156
    public function save(/** @scrutinizer ignore-unused */ array $options = [])

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
157
    {
158 22
        return $this->saveToJson();
159
    }
160
161
    /**
162
     * Save the model to the json file.
163
     *
164
     * @return bool
165
     */
166 22
    protected function saveToJson()
167
    {
168 22
        if ($this->{$this->getKeyName()}) {
169 2
            $this->updateModelInJson();
170
        } else {
171 22
            $this->createModelInJson();
172
        }
173
174 22
        return true;
175
    }
176
177
    /**
178
     * Update the model in the json file.
179
     *
180
     * @return void
181
     */
182 2
    protected function updateModelInJson()
183
    {
184 2
        if ($this->usesTimestamps()) {
185 2
            $this->setTimestampFields(true);
186
        }
187 2
        $withoutCurrentModel = $this->whereNotIn(
188 2
            $this->getKeyName(),
189 2
            [$this->getAttribute($this->getKeyName())]
190 2
        )->get();
191 2
        $models = $withoutCurrentModel->push($this->makeVisible($this->getHidden()))->sortBy($this->getKeyName());
192 2
        File::put($this->getJsonStoragePath(), $models->toJson());
193 2
    }
194
195
    /**
196
     * Set the model timestamp field
197
     *
198
     * @param bool $update
199
     *
200
     * @return void
201
     */
202 22
    protected function setTimestampFields($update = false)
203
    {
204 22
        $now = $this->freshTimestampString();
205 22
        $this->setUpdatedAt($now);
206 22
        if (! $update) {
207 22
            $this->setCreatedAt($now);
208
        }
209 22
    }
210
211
    /**
212
     * Get the storage path for the model json file.
213
     *
214
     * @return string
215
     */
216 23
    public function getJsonStoragePath()
217
    {
218 23
        $modelName = str_slug(last(explode('\\', $this->getMorphClass())));
219 23
        $configStoragePath = storage_path(config('model-json-storage.storage_path'));
220 23
        if (! is_dir($configStoragePath)) {
221 23
            mkdir($configStoragePath, 0777, true);
222
        }
223 23
        $jsonStoragePath = $configStoragePath . '/' . $modelName . '.json';
224
225 23
        return $jsonStoragePath;
226
    }
227
228
    /**
229
     * Save a new model in the json file.
230
     *
231
     * @return void
232
     */
233 22
    protected function createModelInJson()
234
    {
235 22
        if ($this->usesTimestamps()) {
236 22
            $this->setTimestampFields();
237
        }
238 22
        $this->setModelPrimaryKeyValue();
239 22
        $models = $this->all()->push($this->makeVisible($this->getHidden()));
240 22
        File::put($this->getJsonStoragePath(), $models->toJson());
241 22
    }
242
243
    /**
244
     * Set the model primary key by incrementing from the bigger id found in the json file.
245
     *
246
     * @return void
247
     */
248 22
    protected function setModelPrimaryKeyValue()
249
    {
250 22
        $modelPrimaryKeyValue = 1;
251 22
        $modelsCollection = $this->loadModelsFromJson();
252 22
        if (! $modelsCollection->isEmpty()) {
253 19
            $lastModelId = $modelsCollection->sortBy('id')->last()->getAttribute($this->getKeyName());
254 19
            $modelPrimaryKeyValue = $lastModelId + 1;
255
        }
256 22
        $this->setRawAttributes(array_merge(['id' => $modelPrimaryKeyValue], $this->getAttributes()));
257 22
    }
258
259
    /**
260
     * Update the model in the json file.
261
     *
262
     * @param array $attributes
263
     * @param array $options
264
     *
265
     * @return mixed
266
     */
267 1
    public function update(array $attributes = [], array $options = [])
268
    {
269 1
        return $this->fill($attributes)->save($options);
270
    }
271
272
    /**
273
     * Delete the model from the json file.
274
     *
275
     * @return bool|null
276
     * @throws Exception
277
     */
278 2
    public function delete()
279
    {
280 2
        if (is_null($this->getKeyName())) {
0 ignored issues
show
introduced by
The condition is_null($this->getKeyName()) is always false.
Loading history...
281 1
            throw new Exception('No primary key defined on model.');
282
        }
283 1
        $this->deleteModelFromJson();
284
285 1
        return true;
286
    }
287
288
    /**
289
     * Delete the model from the json file.
290
     *
291
     * @return void
292
     */
293 1
    protected function deleteModelFromJson()
294
    {
295 1
        $withoutCurrentModel = $this->whereNotIn(
296 1
            $this->getKeyName(),
297 1
            [$this->getAttribute($this->getKeyName())]
298 1
        )->get();
299 1
        File::put($this->getJsonStoragePath(), $withoutCurrentModel->values()->toJson());
300 1
    }
301
}
302