Passed
Push — master ( 6a8dbb...031595 )
by Koen
07:27
created

HasTranslations::resolveRouteBinding()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 1
nc 1
nop 1
dl 0
loc 3
rs 10
c 0
b 0
f 0
1
<?php
2
3
namespace KoenHoeijmakers\LaravelTranslatable;
4
5
use Illuminate\Database\Eloquent\Builder;
6
use Illuminate\Support\Arr;
7
use KoenHoeijmakers\LaravelTranslatable\Exceptions\MissingTranslationsException;
8
use KoenHoeijmakers\LaravelTranslatable\Scopes\JoinTranslationScope;
9
use KoenHoeijmakers\LaravelTranslatable\Services\TranslationSavingService;
10
11
/**
12
 * Trait HasTranslations
13
 *
14
 * @mixin \Illuminate\Database\Eloquent\Model
15
 */
16
trait HasTranslations
17
{
18
    /**
19
     * The current locale, used to handle internal states.
20
     *
21
     * @var string|null
22
     */
23
    protected $currentLocale = null;
24
25
    /**
26
     * Boot the translatable trait.
27
     *
28
     * @return void
29
     */
30
    public static function bootHasTranslations()
31
    {
32
        if (config('translatable.use_saving_service', true)) {
33
            static::saving(function (self $model) {
34
                app(TranslationSavingService::class)->rememberTranslationForModel($model);
0 ignored issues
show
Bug introduced by
$model of type KoenHoeijmakers\LaravelT...latable\HasTranslations is incompatible with the type Illuminate\Database\Eloquent\Model expected by parameter $model of KoenHoeijmakers\LaravelT...erTranslationForModel(). ( Ignorable by Annotation )

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

34
                app(TranslationSavingService::class)->rememberTranslationForModel(/** @scrutinizer ignore-type */ $model);
Loading history...
35
            });
36
37
            static::saved(function (self $model) {
38
                app(TranslationSavingService::class)->storeTranslationOnModel($model);
0 ignored issues
show
Bug introduced by
$model of type KoenHoeijmakers\LaravelT...latable\HasTranslations is incompatible with the type Illuminate\Database\Eloquent\Model expected by parameter $model of KoenHoeijmakers\LaravelT...oreTranslationOnModel(). ( Ignorable by Annotation )

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

38
                app(TranslationSavingService::class)->storeTranslationOnModel(/** @scrutinizer ignore-type */ $model);
Loading history...
39
40
                $model->refreshTranslation();
41
            });
42
        }
43
44
        static::deleting(function (self $model) {
45
            $model->purgeTranslations();
46
        });
47
48
        static::addGlobalScope(new JoinTranslationScope());
49
    }
50
51
    /**
52
     * @return \Illuminate\Database\Eloquent\Relations\HasMany
53
     */
54
    public function translations()
55
    {
56
        return $this->hasMany($this->getTranslationModel(), $this->getTranslationForeignKey());
0 ignored issues
show
Bug introduced by
It seems like hasMany() must be provided by classes using this trait. How about adding it as abstract method to this trait? ( Ignorable by Annotation )

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

56
        return $this->/** @scrutinizer ignore-call */ hasMany($this->getTranslationModel(), $this->getTranslationForeignKey());
Loading history...
57
    }
58
59
    /**
60
     * Check if the translation by the given locale exists.
61
     *
62
     * @param string $locale
63
     * @return bool
64
     */
65
    public function translationExists(string $locale): bool
66
    {
67
        return $this->translations()->where($this->getLocaleKeyName(), $locale)->exists();
68
    }
69
70
    /**
71
     * Purge the translations.
72
     *
73
     * @return mixed
74
     */
75
    public function purgeTranslations()
76
    {
77
        return $this->translations()->delete();
78
    }
79
80
    /**
81
     * Get the translation model.
82
     *
83
     * @return string
84
     */
85
    public function getTranslationModel(): string
86
    {
87
        if (isset($this->translationModel)) {
88
            return $this->translationModel;
89
        }
90
91
        return get_class($this) . $this->getTranslationModelSuffix();
92
    }
93
94
    /**
95
     * Get the translation model suffix.
96
     *
97
     * @return string
98
     */
99
    protected function getTranslationModelSuffix(): string
100
    {
101
        return 'Translation';
102
    }
103
104
    /**
105
     * Get the translation table.
106
     *
107
     * @return string
108
     */
109
    public function getTranslationTable(): string
110
    {
111
        $model = $this->getTranslationModel();
112
113
        return (new $model())->getTable();
114
    }
115
116
    /**
117
     * Get the translation foreign key.
118
     *
119
     * @return string
120
     */
121
    public function getTranslationForeignKey()
122
    {
123
        if (isset($this->translationForeignKey)) {
124
            return $this->translationForeignKey;
125
        }
126
127
        return $this->getForeignKey();
0 ignored issues
show
Bug introduced by
It seems like getForeignKey() must be provided by classes using this trait. How about adding it as abstract method to this trait? ( Ignorable by Annotation )

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

127
        return $this->/** @scrutinizer ignore-call */ getForeignKey();
Loading history...
128
    }
129
130
    /**
131
     * Get the translatable.
132
     *
133
     * @return array
134
     * @throws \KoenHoeijmakers\LaravelTranslatable\Exceptions\MissingTranslationsException
135
     */
136
    public function getTranslatable(): array
137
    {
138
        if (!isset($this->translatable)) {
139
            throw new MissingTranslationsException('Model "' . static::class . '" is missing translations');
140
        }
141
142
        return $this->translatable;
143
    }
144
145
    /**
146
     * Get the translatable attributes.
147
     *
148
     * @return array
149
     */
150
    public function getTranslatableAttributes(): array
151
    {
152
        return Arr::only($this->getAttributes(), $this->translatable);
0 ignored issues
show
Bug introduced by
It seems like getAttributes() must be provided by classes using this trait. How about adding it as abstract method to this trait? ( Ignorable by Annotation )

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

152
        return Arr::only($this->/** @scrutinizer ignore-call */ getAttributes(), $this->translatable);
Loading history...
153
    }
154
155
    /**
156
     * @param string $locale
157
     * @param array<string, mixed> $attributes
158
     * @return \Illuminate\Database\Eloquent\Model
159
     */
160
    public function storeTranslation(string $locale, array $attributes = [])
161
    {
162
        if (!is_null($model = $this->translations()->where($this->getLocaleKeyName(), $locale)->first())) {
163
            $model->update($attributes);
164
165
            return $model;
166
        }
167
168
        $model = $this->translations()->make($attributes);
169
        $model->setAttribute($this->getLocaleKeyName(), $locale);
170
        $model->save();
171
172
        return $model;
173
    }
174
175
    /**
176
     * Store many translations at once.
177
     *
178
     * @param array<string, array> $translations
179
     * @return $this
180
     */
181
    public function storeTranslations(array $translations)
182
    {
183
        foreach ($translations as $locale => $translation) {
184
            $this->storeTranslation($locale, $translation);
185
        }
186
187
        return $this;
188
    }
189
190
    /**
191
     * @param string $locale
192
     * @return \Illuminate\Database\Eloquent\Model|self
193
     */
194
    public function getTranslation(string $locale)
195
    {
196
        return $this->translations()->where($this->getLocaleKeyName(), $locale)->first();
197
    }
198
199
    /**
200
     * The locale key name.
201
     *
202
     * @return string
203
     */
204
    public function getLocaleKeyName(): string
205
    {
206
        return $this->localeKeyName ?? config('translatable.locale_key_name', 'locale');
207
    }
208
209
    /**
210
     * Get the locale.
211
     *
212
     * @return string
213
     */
214
    public function getLocale(): string
215
    {
216
        return $this->currentLocale ?? app()->getLocale();
0 ignored issues
show
introduced by
The method getLocale() does not exist on Illuminate\Container\Container. Are you sure you never get this type here, but always one of the subclasses? ( Ignorable by Annotation )

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

216
        return $this->currentLocale ?? app()->/** @scrutinizer ignore-call */ getLocale();
Loading history...
217
    }
218
219
    /**
220
     * Refresh the translation (in the current locale).
221
     *
222
     * @return \Illuminate\Database\Eloquent\Model|null
223
     */
224
    public function refreshTranslation()
225
    {
226
        if (!$this->exists) {
227
            return null;
228
        }
229
230
        $attributes = Arr::only(
231
            static::findOrFail($this->getKey())->attributes, $this->getTranslatable()
0 ignored issues
show
Bug introduced by
It seems like getKey() must be provided by classes using this trait. How about adding it as abstract method to this trait? ( Ignorable by Annotation )

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

231
            static::findOrFail($this->/** @scrutinizer ignore-call */ getKey())->attributes, $this->getTranslatable()
Loading history...
232
        );
233
234
        foreach ($attributes as $key => $value) {
235
            $this->setAttribute($key, $value);
0 ignored issues
show
Bug introduced by
It seems like setAttribute() must be provided by classes using this trait. How about adding it as abstract method to this trait? ( Ignorable by Annotation )

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

235
            $this->/** @scrutinizer ignore-call */ 
236
                   setAttribute($key, $value);
Loading history...
236
        }
237
238
        $this->syncOriginal();
0 ignored issues
show
Bug introduced by
It seems like syncOriginal() must be provided by classes using this trait. How about adding it as abstract method to this trait? ( Ignorable by Annotation )

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

238
        $this->/** @scrutinizer ignore-call */ 
239
               syncOriginal();
Loading history...
239
240
        return $this;
0 ignored issues
show
Bug Best Practice introduced by
The expression return $this returns the type KoenHoeijmakers\LaravelT...latable\HasTranslations which is incompatible with the documented return type null|Illuminate\Database\Eloquent\Model.
Loading history...
241
    }
242
243
    /**
244
     * Translate the model to the given locale.
245
     *
246
     * @param string $locale
247
     * @return \Illuminate\Database\Eloquent\Model|null
248
     */
249
    public function translate(string $locale)
250
    {
251
        if (!$this->exists) {
252
            return null;
253
        }
254
255
        $this->currentLocale = $locale;
256
257
        return $this->refreshTranslation();
258
    }
259
260
    /**
261
     * Get a new query builder that doesn't have any global scopes (except the JoinTranslationScope).
262
     *
263
     * @return \Illuminate\Database\Eloquent\Builder
264
     */
265
    public function newQueryWithoutScopes(): Builder
266
    {
267
        return parent::newQueryWithoutScopes()
268
            ->withGlobalScope(JoinTranslationScope::class, new JoinTranslationScope());
269
    }
270
271
    /**
272
     * Retrieve the model for a bound value.
273
     *
274
     * @param  mixed  $value
275
     * @return \Illuminate\Database\Eloquent\Model|null
276
     */
277
    public function resolveRouteBinding($value)
278
    {
279
        return $this->where($this->getTable() . '.' . $this->getRouteKeyName(), $value)->first();
0 ignored issues
show
Bug introduced by
It seems like getTable() must be provided by classes using this trait. How about adding it as abstract method to this trait? ( Ignorable by Annotation )

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

279
        return $this->where($this->/** @scrutinizer ignore-call */ getTable() . '.' . $this->getRouteKeyName(), $value)->first();
Loading history...
Bug introduced by
It seems like where() must be provided by classes using this trait. How about adding it as abstract method to this trait? ( Ignorable by Annotation )

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

279
        return $this->/** @scrutinizer ignore-call */ where($this->getTable() . '.' . $this->getRouteKeyName(), $value)->first();
Loading history...
Bug introduced by
It seems like getRouteKeyName() must be provided by classes using this trait. How about adding it as abstract method to this trait? ( Ignorable by Annotation )

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

279
        return $this->where($this->getTable() . '.' . $this->/** @scrutinizer ignore-call */ getRouteKeyName(), $value)->first();
Loading history...
280
    }
281
}
282