Completed
Pull Request — master (#79)
by Sebastian
04:18
created

Repository::save()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 10
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 5
nc 2
nop 1
dl 0
loc 10
rs 9.4285
c 0
b 0
f 0
1
<?php
2
3
namespace App\Foundation\Repositories;
4
5
use Illuminate\Database\Eloquent\Model;
6
use Illuminate\Support\Collection;
7
8
abstract class Repository
9
{
10
    public function save(Model $model): bool
11
    {
12
        $saved = $model->save();
13
14
        if ($saved) {
15
            app('cache')->flush();
16
        }
17
18
        return $saved;
19
    }
20
21
    public function delete(Model $model): bool
22
    {
23
        $deleted = $model->delete();
24
25
        if ($deleted) {
26
            app('cache')->flush();
27
        }
28
29
        return $deleted;
30
    }
31
32
    public function getAll(): Collection
33
    {
34
        return $this->query()->get();
35
    }
36
37
    /**
38
     * @return \Illuminate\Database\Eloquent\Model|null
39
     */
40
    public function find(int $id)
41
    {
42
        return $this->query()->find($id);
43
    }
44
45
    /**
46
     * @return \Illuminate\Database\Eloquent\Model|null
47
     */
48
    public function findOnline(int $id)
49
    {
50
        return $this->query()->online()->find($id);
51
    }
52
53
    public function getAllOnline(): Collection
54
    {
55
        return $this->query()
56
            ->online()
57
            ->get();
58
    }
59
60
    /**
61
     * @param string $url
62
     * @param array  $with
63
     *
64
     * @return \Illuminate\Database\Eloquent\Model|null
65
     */
66
    public function findByUrl(string $url, $with = [])
67
    {
68
        $model = static::MODEL;
69
70
        $locale = content_locale();
71
72
        if (!isset((new $model())->translatedAttributes)) {
73
            return $this->query()
74
                ->online()
75
                ->where('url', 'regexp', "\"{$locale}\"\s*:\s*\"{$url}\"")
76
                ->first();
77
        }
78
79
        return $this->query()
80
            ->with($with)
81
            ->online()
82
            ->whereTranslation('url', $url, $locale)
83
            ->first();
84
    }
85
86
    protected function query()
87
    {
88
        return call_user_func(static::MODEL.'::query');
89
    }
90
}
91