Passed
Push — master ( c36ed8...8867a0 )
by Quentin
13:25 queued 05:48
created

ModuleRepository::afterRestore()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 3

Importance

Changes 0
Metric Value
cc 3
eloc 3
nc 3
nop 1
dl 0
loc 5
ccs 4
cts 4
cp 1
crap 3
rs 10
c 0
b 0
f 0
1
<?php
2
3
namespace A17\Twill\Repositories;
4
5
use A17\Twill\Models\Behaviors\HasMedias;
6
use A17\Twill\Models\Behaviors\Sortable;
7
use A17\Twill\Repositories\Behaviors\HandleDates;
8
use A17\Twill\Repositories\Behaviors\HandleBrowsers;
9
use A17\Twill\Repositories\Behaviors\HandleFieldsGroups;
10
use Illuminate\Support\Arr;
11
use Illuminate\Support\Collection;
12
use Illuminate\Support\Facades\App;
13
use Illuminate\Support\Facades\Config;
14
use Illuminate\Support\Facades\DB;
15
use Illuminate\Support\Facades\Log;
16
use Illuminate\Support\Str;
17
use PDO;
18
19
abstract class ModuleRepository
20
{
21
    use HandleDates, HandleBrowsers, HandleFieldsGroups;
0 ignored issues
show
introduced by
The trait A17\Twill\Repositories\Behaviors\HandleBrowsers requires some properties which are not provided by A17\Twill\Repositories\ModuleRepository: $titleInBrowser, $id, $adminEditUrl, $browsers, $title
Loading history...
22
  
23
    /**
24
     * @var \A17\Twill\Models\Model
25
     */
26
    protected $model;
27
28
    /**
29
     * @var string[]
30
     */
31
    protected $ignoreFieldsBeforeSave = [];
32
33
    /**
34
     * @var array
35
     */
36
    protected $countScope = [];
37
38
    /**
39
     * @var array
40
     */
41
    protected $fieldsGroups = [];
42
43
    /**
44
     * @param array $with
45
     * @param array $scopes
46
     * @param array $orders
47
     * @param int $perPage
48
     * @param bool $forcePagination
49
     * @return \Illuminate\Database\Eloquent\Collection
50
     */
51 12
    public function get($with = [], $scopes = [], $orders = [], $perPage = 20, $forcePagination = false)
52
    {
53 12
        $query = $this->model->with($with);
54
55 12
        $query = $this->filter($query, $scopes);
0 ignored issues
show
Bug introduced by
$query of type Illuminate\Database\Eloquent\Builder is incompatible with the type Illuminate\Database\Query\Builder expected by parameter $query of A17\Twill\Repositories\ModuleRepository::filter(). ( Ignorable by Annotation )

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

55
        $query = $this->filter(/** @scrutinizer ignore-type */ $query, $scopes);
Loading history...
56 12
        $query = $this->order($query, $orders);
57
58 12
        if (!$forcePagination && $this->model instanceof Sortable) {
59 3
            return $query->ordered()->get();
60
        }
61
62 10
        if ($perPage == -1) {
63
            return $query->get();
64
        }
65
66 10
        return $query->paginate($perPage);
67
    }
68
69
    /**
70
     * @param string $slug
71
     * @param array $scope
72
     * @return int
73
     */
74 6
    public function getCountByStatusSlug($slug, $scope = [])
75
    {
76 6
        $this->countScope = $scope;
77
78 6
        switch ($slug) {
79 6
            case 'all':
80 5
                return $this->getCountForAll();
81 6
            case 'published':
82 6
                return $this->getCountForPublished();
83 6
            case 'draft':
84 6
                return $this->getCountForDraft();
85 6
            case 'trash':
86 6
                return $this->getCountForTrash();
87
        }
88
89 5
        foreach (class_uses_recursive(get_called_class()) as $trait) {
90 5
            if (method_exists(get_called_class(), $method = 'getCountByStatusSlug' . class_basename($trait))) {
91 5
                if (($count = $this->$method($slug)) !== false) {
92 5
                    return $count;
93
                }
94
            }
95
        }
96
97
        return 0;
98
    }
99
100
    /**
101
     * @return int
102
     */
103 5
    public function getCountForAll()
104
    {
105 5
        $query = $this->model->newQuery();
106 5
        return $this->filter($query, $this->countScope)->count();
0 ignored issues
show
Bug introduced by
$query of type Illuminate\Database\Eloquent\Builder is incompatible with the type Illuminate\Database\Query\Builder expected by parameter $query of A17\Twill\Repositories\ModuleRepository::filter(). ( Ignorable by Annotation )

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

106
        return $this->filter(/** @scrutinizer ignore-type */ $query, $this->countScope)->count();
Loading history...
107
    }
108
109
    /**
110
     * @return int
111
     */
112 5
    public function getCountForPublished()
113
    {
114 5
        $query = $this->model->newQuery();
115 5
        return $this->filter($query, $this->countScope)->published()->count();
0 ignored issues
show
Bug introduced by
$query of type Illuminate\Database\Eloquent\Builder is incompatible with the type Illuminate\Database\Query\Builder expected by parameter $query of A17\Twill\Repositories\ModuleRepository::filter(). ( Ignorable by Annotation )

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

115
        return $this->filter(/** @scrutinizer ignore-type */ $query, $this->countScope)->published()->count();
Loading history...
116
    }
117
118
    /**
119
     * @return int
120
     */
121 5
    public function getCountForDraft()
122
    {
123 5
        $query = $this->model->newQuery();
124 5
        return $this->filter($query, $this->countScope)->draft()->count();
0 ignored issues
show
Bug introduced by
$query of type Illuminate\Database\Eloquent\Builder is incompatible with the type Illuminate\Database\Query\Builder expected by parameter $query of A17\Twill\Repositories\ModuleRepository::filter(). ( Ignorable by Annotation )

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

124
        return $this->filter(/** @scrutinizer ignore-type */ $query, $this->countScope)->draft()->count();
Loading history...
125
    }
126
127
    /**
128
     * @return int
129
     */
130 5
    public function getCountForTrash()
131
    {
132 5
        $query = $this->model->newQuery();
133 5
        return $this->filter($query, $this->countScope)->onlyTrashed()->count();
0 ignored issues
show
Bug introduced by
$query of type Illuminate\Database\Eloquent\Builder is incompatible with the type Illuminate\Database\Query\Builder expected by parameter $query of A17\Twill\Repositories\ModuleRepository::filter(). ( Ignorable by Annotation )

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

133
        return $this->filter(/** @scrutinizer ignore-type */ $query, $this->countScope)->onlyTrashed()->count();
Loading history...
134
    }
135
136
    /**
137
     * @param $id
138
     * @param array $with
139
     * @param array $withCount
140
     * @return \A17\Twill\Models\Model
141
     * @throws \Illuminate\Database\Eloquent\ModelNotFoundException
142
     */
143 17
    public function getById($id, $with = [], $withCount = [])
144
    {
145 17
        return $this->model->with($with)->withCount($withCount)->findOrFail($id);
146
    }
147
148
    /**
149
     * @param string $column
150
     * @param array $orders
151
     * @param null $exceptId
0 ignored issues
show
Documentation Bug introduced by
Are you sure the doc-type for parameter $exceptId is correct as it would always require null to be passed?
Loading history...
152
     * @return \Illuminate\Support\Collection
153
     */
154
    public function listAll($column = 'title', $orders = [], $exceptId = null)
155
    {
156
        $query = $this->model->newQuery();
157
158
        if ($exceptId) {
0 ignored issues
show
introduced by
$exceptId is of type null, thus it always evaluated to false.
Loading history...
159
            $query = $query->where($this->model->getTable() . '.id', '<>', $exceptId);
160
        }
161
162
        if ($this->model instanceof Sortable) {
163
            $query = $query->ordered();
164
        } elseif (!empty($orders)) {
165
            $query = $this->order($query, $orders);
0 ignored issues
show
Bug introduced by
$query of type Illuminate\Database\Eloquent\Builder is incompatible with the type Illuminate\Database\Query\Builder expected by parameter $query of A17\Twill\Repositories\ModuleRepository::order(). ( Ignorable by Annotation )

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

165
            $query = $this->order(/** @scrutinizer ignore-type */ $query, $orders);
Loading history...
166
        }
167
168
        if (property_exists($this->model, 'translatedAttributes')) {
169
            $query = $query->withTranslation();
170
        }
171
172
        return $query->get()->pluck($column, 'id');
173
    }
174
175
    /**
176
     * @param $search
177
     * @param array $fields
178
     * @return \Illuminate\Database\Eloquent\Collection
179
     */
180
    public function cmsSearch($search, $fields = [])
181
    {
182
        $query = $this->model->latest();
183
184
        $translatedAttributes = $this->model->translatedAttributes ?? [];
0 ignored issues
show
Bug introduced by
The property translatedAttributes does not seem to exist on A17\Twill\Models\Model. Are you sure there is no database migration missing?

Checks if undeclared accessed properties appear in database migrations and if the creating migration is correct.

Loading history...
185
186
        foreach ($fields as $field) {
187
            if (in_array($field, $translatedAttributes)) {
188
                $query->orWhereHas('translations', function ($q) use ($field, $search) {
189
                    $q->where($field, $this->getLikeOperator(), "%{$search}%");
190
                });
191
            } else {
192
                $query->orWhere($field, $this->getLikeOperator(), "%{$search}%");
193
            }
194
        }
195
196
        return $query->get();
197
    }
198
199
    /**
200
     * @param $attributes
201
     * @param $fields
202
     * @return \A17\Twill\Models\Model
203
     */
204
    public function firstOrCreate($attributes, $fields)
205
    {
206
        return $this->model->where($attributes)->first() ?? $this->create($fields);
207
    }
208
209
    /**
210
     * @param string[] $fields
211
     * @return \A17\Twill\Models\Model
212
     */
213 27
    public function create($fields)
214
    {
215
        return DB::transaction(function () use ($fields) {
216 27
            $original_fields = $fields;
217
218 27
            $fields = $this->prepareFieldsBeforeCreate($fields);
219
220 27
            $object = $this->model->create(Arr::except($fields, $this->getReservedFields()));
221
222 27
            $this->beforeSave($object, $original_fields);
223
224 27
            $fields = $this->prepareFieldsBeforeSave($object, $fields);
225
226 27
            $object->save();
227
228 27
            $this->afterSave($object, $fields);
229
230 27
            return $object;
231 27
        }, 3);
232
    }
233
234
    /**
235
     * @param array $fields
236
     * @return \A17\Twill\Models\Model
237
     */
238 2
    public function createForPreview($fields)
239
    {
240 2
        $fields = $this->prepareFieldsBeforeCreate($fields);
241
242 2
        $object = $this->model->newInstance(Arr::except($fields, $this->getReservedFields()));
243
244 2
        return $this->hydrate($object, $fields);
245
    }
246
247
    /**
248
     * @param array $attributes
249
     * @param array $fields
250
     * @return \A17\Twill\Models\Model
251
     */
252
    public function updateOrCreate($attributes, $fields)
253
    {
254
        $object = $this->model->where($attributes)->first();
255
256
        if (!$object) {
257
            return $this->create($fields);
258
        }
259
260
        $this->update($object->id, $fields);
261
    }
262
263
    /**
264
     * @param mixed $id
265
     * @param array $fields
266
     * @return void
267
     */
268 11
    public function update($id, $fields)
269
    {
270
        DB::transaction(function () use ($id, $fields) {
271 11
            $object = $this->model->findOrFail($id);
272
273 11
            $this->beforeSave($object, $fields);
274
275 11
            $fields = $this->prepareFieldsBeforeSave($object, $fields);
276
277 11
            $object->fill(Arr::except($fields, $this->getReservedFields()));
278
279 11
            $object->save();
280
281 11
            $this->afterSave($object, $fields);
282 11
        }, 3);
283 11
    }
284
285
    /**
286
     * @param mixed $id
287
     * @param array $values
288
     * @param array $scopes
289
     * @return mixed
290
     */
291 4
    public function updateBasic($id, $values, $scopes = [])
292
    {
293
        return DB::transaction(function () use ($id, $values, $scopes) {
294
            // apply scopes if no id provided
295 4
            if (is_null($id)) {
296 1
                $query = $this->model->query();
297
298 1
                foreach ($scopes as $column => $value) {
299
                    $query->where($column, $value);
300
                }
301
302 1
                $query->update($values);
303
304
                $query->get()->each(function ($object) use ($values) {
305
                    $this->afterUpdateBasic($object, $values);
306 1
                });
307
308 1
                return true;
309
            }
310
311
            // apply to all ids if array of ids provided
312 3
            if (is_array($id)) {
313
                $query = $this->model->whereIn('id', $id);
314
                $query->update($values);
315
316
                $query->get()->each(function ($object) use ($values) {
317
                    $this->afterUpdateBasic($object, $values);
318
                });
319
320
                return true;
321
            }
322
323 3
            if (($object = $this->model->find($id)) != null) {
324 2
                $object->update($values);
325 2
                $this->afterUpdateBasic($object, $values);
326 2
                return true;
327
            }
328
329 1
            return false;
330 4
        }, 3);
331
    }
332
333
    /**
334
     * @param array $ids
335
     * @return void
336
     */
337 2
    public function setNewOrder($ids)
338
    {
339
        DB::transaction(function () use ($ids) {
340 2
            $this->model->setNewOrder($ids);
341 2
        }, 3);
342 1
    }
343
344
    /**
345
     * @param mixed $id
346
     * @return mixed
347
     */
348 2
    public function delete($id)
349
    {
350
        return DB::transaction(function () use ($id) {
351 2
            if (($object = $this->model->find($id)) === null) {
352
                return false;
353
            }
354
355 2
            if (!method_exists($object, 'canDeleteSafely') || $object->canDeleteSafely()) {
356 2
                $object->delete();
357 2
                $this->afterDelete($object);
358 2
                return true;
359
            }
360
            return false;
361 2
        }, 3);
362
    }
363
364
    /**
365
     * @param array $ids
366
     * @return mixed
367
     */
368 17
    public function bulkDelete($ids)
369
    {
370
        return DB::transaction(function () use ($ids) {
371
            try {
372
                Collection::make($ids)->each(function ($id) {
373
                    $this->delete($id);
374 17
                });
375
            } catch (\Exception $e) {
376
                Log::error($e);
377
                return false;
378
            }
379
380 17
            return true;
381 17
        }, 3);
382
    }
383
384
    /**
385
     * @param mixed $id
386
     * @return mixed
387
     */
388 2
    public function restore($id)
389
    {
390
        return DB::transaction(function () use ($id) {
391 2
            if (($object = $this->model->withTrashed()->find($id)) != null) {
392 1
                $object->restore();
393 1
                $this->afterRestore($object);
394 1
                return true;
395
            }
396
397 1
            return false;
398 2
        }, 3);
399
    }
400
401
    /**
402
     * @param array $ids
403
     * @return mixed
404
     */
405
    public function bulkRestore($ids)
406
    {
407
        return DB::transaction(function () use ($ids) {
408
            try {
409
                $query = $this->model->withTrashed()->whereIn('id', $ids);
410
                $objects = $query->get();
411
412
                $query->restore();
413
414
                $objects->each(function ($object) {
415
                    $this->afterRestore($object);
416
                });
417
            } catch (\Exception $e) {
418
                Log::error($e);
419
                return false;
420
            }
421
422
            return true;
423
        }, 3);
424
    }
425
426
    /**
427
     * @param \A17\Twill\Models\Model $object
428
     * @param array $fields
429
     * @return array
430
     */
431 28
    public function cleanupFields($object, $fields)
432
    {
433 28
        if (property_exists($this->model, 'checkboxes')) {
434 21
            foreach ($this->model->checkboxes as $field) {
0 ignored issues
show
Bug introduced by
The property checkboxes does not seem to exist on A17\Twill\Models\Model. Are you sure there is no database migration missing?

Checks if undeclared accessed properties appear in database migrations and if the creating migration is correct.

Loading history...
435 21
                if (!$this->shouldIgnoreFieldBeforeSave($field)) {
436 21
                    if (!isset($fields[$field])) {
437 5
                        $fields[$field] = false;
438
                    } else {
439 21
                        $fields[$field] = !empty($fields[$field]);
440
                    }
441
                }
442
            }
443
        }
444
445 28
        if (property_exists($this->model, 'nullable')) {
446
            foreach ($this->model->nullable as $field) {
0 ignored issues
show
Bug introduced by
The property nullable does not seem to exist on A17\Twill\Models\Model. Are you sure there is no database migration missing?

Checks if undeclared accessed properties appear in database migrations and if the creating migration is correct.

Loading history...
447
                if (!isset($fields[$field]) && !$this->shouldIgnoreFieldBeforeSave($field)) {
448
                    $fields[$field] = null;
449
                }
450
            }
451
        }
452
453 28
        foreach ($fields as $key => $value) {
454 28
            if (!$this->shouldIgnoreFieldBeforeSave($key)) {
455 28
                if (is_array($value) && empty($value)) {
456 7
                    $fields[$key] = null;
457
                }
458 28
                if ($value === '') {
459
                    $fields[$key] = null;
460
                }
461
            }
462
        }
463
464 28
        return $fields;
465
    }
466
467
    /**
468
     * @param array $fields
469
     * @return array
470
     */
471 22
    public function prepareFieldsBeforeCreate($fields)
472
    {
473 22
        $fields = $this->cleanupFields(null, $fields);
474
475 22
        foreach (class_uses_recursive(get_called_class()) as $trait) {
476 22
            if (method_exists(get_called_class(), $method = 'prepareFieldsBeforeCreate' . class_basename($trait))) {
477 22
                $fields = $this->$method($fields);
478
            }
479
        }
480
481 22
        return $fields;
482
    }
483
484
    /**
485
     * @param \A17\Twill\Models\Model $object
486
     * @param array $fields
487
     * @return string[]
488
     */
489 27
    public function prepareFieldsBeforeSave($object, $fields)
490
    {
491 27
        $fields = $this->cleanupFields($object, $fields);
492
493 27
        foreach (class_uses_recursive(get_called_class()) as $trait) {
494 27
            if (method_exists(get_called_class(), $method = 'prepareFieldsBeforeSave' . class_basename($trait))) {
495 27
                $fields = $this->$method($object, $fields);
496
            }
497
        }
498
499 27
        return $fields;
500
    }
501
502
    /**
503
     * @param \A17\Twill\Models\Model $object
504
     * @param array $fields
505
     * @return void
506
     */
507 2
    public function afterUpdateBasic($object, $fields)
508
    {
509 2
        foreach (class_uses_recursive(get_called_class()) as $trait) {
510 2
            if (method_exists(get_called_class(), $method = 'afterUpdateBasic' . class_basename($trait))) {
511
                $this->$method($object, $fields);
512
            }
513
        }
514 2
    }
515
516
    /**
517
     * @param \A17\Twill\Models\Model $object
518
     * @param array $fields
519
     * @return void
520
     */
521 27
    public function beforeSave($object, $fields)
522
    {
523 27
        foreach (class_uses_recursive(get_called_class()) as $trait) {
524 27
            if (method_exists(get_called_class(), $method = 'beforeSave' . class_basename($trait))) {
525 17
                $this->$method($object, $fields);
526
            }
527
        }
528 27
    }
529
530
    /**
531
     * @param \A17\Twill\Models\Model $object
532
     * @param array $fields
533
     * @return void
534
     */
535 27
    public function afterSave($object, $fields)
536
    {
537 27
        foreach (class_uses_recursive(get_called_class()) as $trait) {
538 27
            if (method_exists(get_called_class(), $method = 'afterSave' . class_basename($trait))) {
539 27
                $this->$method($object, $fields);
540
            }
541
        }
542 27
    }
543
544
    /**
545
     * @param \A17\Twill\Models\Model $object
546
     * @return void
547
     */
548 2
    public function afterDelete($object)
549
    {
550 2
        foreach (class_uses_recursive(get_called_class()) as $trait) {
551 2
            if (method_exists(get_called_class(), $method = 'afterDelete' . class_basename($trait))) {
552 2
                $this->$method($object);
553
            }
554
        }
555 2
    }
556
557
    /**
558
     * @param \A17\Twill\Models\Model $object
559
     * @return void
560
     */
561 1
    public function afterRestore($object)
562
    {
563 1
        foreach (class_uses_recursive(get_called_class()) as $trait) {
564 1
            if (method_exists(get_called_class(), $method = 'afterRestore' . class_basename($trait))) {
565 1
                $this->$method($object);
566
            }
567
        }
568 1
    }
569
570
    /**
571
     * @param \A17\Twill\Models\Model $object
572
     * @param array $fields
573
     * @return \A17\Twill\Models\Model
574
     */
575 3
    public function hydrate($object, $fields)
576
    {
577 3
        foreach (class_uses_recursive(get_called_class()) as $trait) {
578 3
            if (method_exists(get_called_class(), $method = 'hydrate' . class_basename($trait))) {
579 3
                $object = $this->$method($object, $fields);
580
            }
581
        }
582
583 3
        return $object;
584
    }
585
586
    /**
587
     * @param \A17\Twill\Models\Model $object
588
     * @return array
589
     */
590 5
    public function getFormFields($object)
591
    {
592 5
        $fields = $object->attributesToArray();
593
594 5
        foreach (class_uses_recursive(get_called_class()) as $trait) {
595 5
            if (method_exists(get_called_class(), $method = 'getFormFields' . class_basename($trait))) {
596 5
                $fields = $this->$method($object, $fields);
597
            }
598
        }
599
600 5
        return $fields;
601
    }
602
603
    /**
604
     * @param \Illuminate\Database\Query\Builder $query
605
     * @param array $scopes
606
     * @return \Illuminate\Database\Query\Builder
607
     */
608 12
    public function filter($query, array $scopes = [])
609
    {
610 12
        $likeOperator = $this->getLikeOperator();
611
612 12
        foreach (class_uses_recursive(get_called_class()) as $trait) {
613 12
            if (method_exists(get_called_class(), $method = 'filter' . class_basename($trait))) {
614 11
                $this->$method($query, $scopes);
615
            }
616
        }
617
618 12
        unset($scopes['search']);
619
620 12
        if (isset($scopes['exceptIds'])) {
621 2
            $query->whereNotIn($this->model->getTable() . '.id', $scopes['exceptIds']);
622 2
            unset($scopes['exceptIds']);
623
        }
624
625 12
        foreach ($scopes as $column => $value) {
626 5
            if (method_exists($this->model, 'scope' . ucfirst($column))) {
627 1
                $query->$column();
628
            } else {
629 4
                if (is_array($value)) {
630 2
                    $query->whereIn($column, $value);
631 2
                } elseif ($column[0] == '%') {
632
                    $value && ($value[0] == '!') ? $query->where(substr($column, 1), "not $likeOperator", '%' . substr($value, 1) . '%') : $query->where(substr($column, 1), $likeOperator, '%' . $value . '%');
633 2
                } elseif (isset($value[0]) && $value[0] == '!') {
634
                    $query->where($column, '<>', substr($value, 1));
635 2
                } elseif ($value !== '') {
636 2
                    $query->where($column, $value);
637
                }
638
            }
639
        }
640
641 12
        return $query;
642
    }
643
644
    /**
645
     * @param \Illuminate\Database\Query\Builder $query
646
     * @param array $orders
647
     * @return \Illuminate\Database\Query\Builder
648
     */
649 12
    public function order($query, array $orders = [])
650
    {
651 12
        foreach (class_uses_recursive(get_called_class()) as $trait) {
652 12
            if (method_exists(get_called_class(), $method = 'order' . class_basename($trait))) {
653 7
                $this->$method($query, $orders);
654
            }
655
        }
656
657 12
        foreach ($orders as $column => $direction) {
658 5
            $query->orderBy($column, $direction);
659
        }
660
661 12
        return $query;
662
    }
663
664
    /**
665
     * @param \A17\Twill\Models\Model $object
666
     * @param array $fields
667
     * @param string $relationship
668
     * @param string $formField
669
     * @param string $attribute
670
     * @return void
671
     */
672
    public function updateOneToMany($object, $fields, $relationship, $formField, $attribute)
673
    {
674
        if (isset($fields[$formField])) {
675
            foreach ($fields[$formField] as $id) {
676
                $object->$relationship()->updateOrCreate([$attribute => $id]);
677
            }
678
679
            foreach ($object->$relationship as $relationshipObject) {
680
                if (!in_array($relationshipObject->$attribute, $fields[$formField])) {
681
                    $relationshipObject->delete();
682
                }
683
            }
684
        } else {
685
            $object->$relationship()->delete();
686
        }
687
    }
688
689
    /**
690
     * @param \A17\Twill\Models\Model $object
691
     * @param array $fields
692
     * @param string $relationship
693
     * @return void
694
     */
695
    public function updateMultiSelect($object, $fields, $relationship)
696
    {
697
        $object->$relationship()->sync($fields[$relationship] ?? []);
698
    }
699
700
    /**
701
     * @param \Illuminate\Database\Query\Builder $query
702
     * @param array $scopes
703
     * @param string $scopeField
704
     * @param string $scopeRelation
705
     * @return void
706
     */
707 9
    public function addRelationFilterScope($query, &$scopes, $scopeField, $scopeRelation)
708
    {
709 9
        if (isset($scopes[$scopeField])) {
710
            $id = $scopes[$scopeField];
711
            $query->whereHas($scopeRelation, function ($query) use ($id, $scopeField) {
712
                $query->where($scopeField, $id);
713
            });
714
            unset($scopes[$scopeField]);
715
        }
716 9
    }
717
718
    /**
719
     * @param \Illuminate\Database\Query\Builder $query
720
     * @param array $scopes
721
     * @param string $scopeField
722
     * @return void
723
     */
724
    public function addLikeFilterScope($query, &$scopes, $scopeField)
725
    {
726
        if (isset($scopes[$scopeField]) && is_string($scopes[$scopeField])) {
727
            $query->where($scopeField, $this->getLikeOperator(), '%' . $scopes[$scopeField] . '%');
728
            unset($scopes[$scopeField]);
729
        }
730
    }
731
732
    /**
733
     * @param \Illuminate\Database\Query\Builder $query
734
     * @param array $scopes
735
     * @param string $scopeField
736
     * @param string[] $orFields
737
     */
738 5
    public function searchIn($query, &$scopes, $scopeField, $orFields = [])
739
    {
740
741 5
        if (isset($scopes[$scopeField]) && is_string($scopes[$scopeField])) {
742
            $query->where(function ($query) use (&$scopes, $scopeField, $orFields) {
743 2
                foreach ($orFields as $field) {
744 2
                    $query->orWhere($field, $this->getLikeOperator(), '%' . $scopes[$scopeField] . '%');
745 2
                    unset($scopes[$field]);
746
                }
747 2
            });
748
        }
749 5
    }
750
751
    /**
752
     * @return bool
753
     */
754 2
    public function isUniqueFeature()
755
    {
756 2
        return false;
757
    }
758
759
    /**
760
     * @param array $ignore
761
     * @return void
762
     */
763
    public function addIgnoreFieldsBeforeSave($ignore = [])
764
    {
765
        $this->ignoreFieldsBeforeSave = is_array($ignore)
0 ignored issues
show
introduced by
The condition is_array($ignore) is always true.
Loading history...
766
        ? array_merge($this->ignoreFieldsBeforeSave, $ignore)
767
        : array_merge($this->ignoreFieldsBeforeSave, [$ignore]);
768
    }
769
770
    /**
771
     * @param string $ignore
772
     * @return bool
773
     */
774 28
    public function shouldIgnoreFieldBeforeSave($ignore)
775
    {
776 28
        return in_array($ignore, $this->ignoreFieldsBeforeSave);
777
    }
778
779
    /**
780
     * @return string[]
781
     */
782 28
    public function getReservedFields()
783
    {
784
        return [
785 28
            'medias',
786
            'browsers',
787
            'repeaters',
788
            'blocks',
789
        ];
790
    }
791
792
    /**
793
     * @param string $relation
794
     * @param \A17\Twill\Models\Model|null $model
795
     * @return mixed
796
     */
797
    protected function getModelRepository($relation, $model = null)
798
    {
799
        if (!$model) {
800
            $model = ucfirst(Str::singular($relation));
801
        }
802
803
        return App::make(Config::get('twill.namespace') . "\\Repositories\\" . ucfirst($model) . "Repository");
804
    }
805
806
    /**
807
     * @return string
808
     */
809 12
    private function getLikeOperator()
810
    {
811 12
        if (DB::connection()->getPDO()->getAttribute(PDO::ATTR_DRIVER_NAME) === 'pgsql') {
812
            return 'ILIKE';
813
        }
814
815 12
        return 'LIKE';
816
    }
817
818
    /**
819
     * @param string $method
820
     * @param array $parameters
821
     * @return mixed
822
     */
823 2
    public function __call($method, $parameters)
824
    {
825 2
        return $this->model->$method(...$parameters);
826
    }
827
}
828