Passed
Push — ft/urls ( 560a84...fa7ece )
by Ben
23:24 queued 11s
created

UrlRecord::replace()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 12
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 9
CRAP Score 1

Importance

Changes 0
Metric Value
eloc 8
dl 0
loc 12
ccs 9
cts 9
cp 1
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 1
crap 1
1
<?php
2
3
namespace Thinktomorrow\Chief\Urls;
4
5
use Illuminate\Database\Eloquent\Model;
6
7
class UrlRecord extends Model
8
{
9
    public $table = 'chief_urls';
10
11
    public $guarded = [];
12
13
    /**
14
     * Find matching url record for passed slug and locale. The locale parameter will try
15
     * to match specific given locales first and records without locale as fallback.
16
     *
17
     * @param string $slug
18
     * @param string $locale
19
     * @return UrlRecord
20
     * @throws UrlRecordNotFound
21
     */
22 24
    public static function findBySlug(string $slug, string $locale): UrlRecord
23
    {
24
        // Clear the input from any trailing slashes.
25 24
        if ($slug != '/') {
26 23
            $slug = trim($slug, '/');
27
        }
28
29 24
        $record = static::where('slug', $slug)
30 24
                        ->where('locale', $locale)
31 24
                        ->orderBy('redirect_id', 'ASC')
32 24
                        ->first();
33
34 24
        if (!$record) {
35 4
            throw new UrlRecordNotFound('No url record found by slug ['.$slug.'] for locale ['.$locale.'].');
36
        }
37
38 20
        return $record;
39
    }
40
41
    /**
42
     * Find matching url record for passed slug and locale. The locale parameter will try
43
     * to match specific given locales first and records without locale as fallback.
44
     *
45
     * @param Model $model
46
     * @param string $locale
47
     * @return UrlRecord
48
     * @throws UrlRecordNotFound
49
     */
50 49
    public static function findByModel(Model $model, string $locale = null): UrlRecord
51
    {
52 49
        $record = static::where('model_type', $model->getMorphClass())
53 49
            ->where('model_id', $model->id)
54 49
            ->where('locale', $locale)
55 49
            ->orderBy('redirect_id', 'ASC')
56 49
            ->first();
57
58 49
        if (!$record) {
59 18
            throw new UrlRecordNotFound('No url record found for model ['.$model->getMorphClass().'@'.$model->id.'] for locale ['.$locale.'].');
0 ignored issues
show
Coding Style introduced by
This line exceeds maximum limit of 120 characters; contains 144 characters

Overly long lines are hard to read on any screen. Most code styles therefor impose a maximum limit on the number of characters in a line.

Loading history...
60
        }
61
62 33
        return $record;
63
    }
64
65 65
    public static function getByModel(Model $model)
66
    {
67 65
        return static::where('model_type', $model->getMorphClass())
68 65
                     ->where('model_id', $model->id)
69 65
                     ->get();
70
    }
71
72 13
    public function replaceAndRedirect(array $values): UrlRecord
73
    {
74 13
        $newRecord = static::create(array_merge([
75 13
            'locale'              => $this->locale,
76 13
            'model_type'          => $this->model_type,
77 13
            'model_id'            => $this->model_id,
78 13
        ], $values));
79
80 13
        $this->redirectTo($newRecord);
81
82 13
        return $newRecord;
83
    }
84
85 13
    public function redirectTo(self $record = null): ?UrlRecord
86
    {
87 13
        if (!$record) {
88 1
            return $this->isRedirect() ? static::find($this->redirect_id) : null;
89
        }
90
91 13
        $this->redirect_id = $record->id;
92 13
        $this->save();
93
94 13
        return null;
95
    }
96
97 26
    public function isRedirect(): bool
98
    {
99 26
        return !!($this->redirect_id);
100
    }
101
102 57
    public static function existsIgnoringRedirects($slug, string $locale = null, Model $ignoredModel = null): bool
103
    {
104 57
        return static::exists($slug, $locale, $ignoredModel, false);
105
    }
106
107 57
    public static function exists($slug, string $locale = null, Model $ignoredModel = null, bool $includeRedirects = true): bool
0 ignored issues
show
Coding Style introduced by
This line exceeds maximum limit of 120 characters; contains 128 characters

Overly long lines are hard to read on any screen. Most code styles therefor impose a maximum limit on the number of characters in a line.

Loading history...
108
    {
109 57
        $builder = static::where('slug', $slug);
110
111 57
        if ($locale) {
112 57
            $builder->where('locale', $locale);
113
        }
114
115 57
        if (! $includeRedirects) {
116 57
            $builder->whereNull('redirect_id');
117
        }
118
119 57
        if ($ignoredModel) {
120
            $builder->whereNotIn('id', function ($query) use ($ignoredModel) {
121 43
                $query->select('id')
122 43
                      ->from('chief_urls')
123 43
                      ->where('model_type', '=', $ignoredModel->getMorphClass())
124 43
                      ->where('model_id', '=', $ignoredModel->id);
125 43
            });
126
        }
127
128 57
        return ($builder->count() > 0);
129
    }
130
}
131