Completed
Push — master ( 5507e8...b08fe5 )
by
unknown
50:15
created

Translatable::scopeLocale()   A

Complexity

Conditions 3
Paths 4

Size

Total Lines 19

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 19
rs 9.6333
c 0
b 0
f 0
cc 3
nc 4
nop 2
1
<?php
2
3
namespace BBSLab\NovaTranslation\Models\Traits;
4
5
use BBSLab\NovaTranslation\Models\Locale;
6
use BBSLab\NovaTranslation\Models\Translation;
7
use Exception;
8
use Illuminate\Database\Eloquent\Builder;
9
10
/**
11
 * @property \Illuminate\Database\Eloquent\Collection $translations
12
 */
13
trait Translatable
14
{
15
    /**
16
     * {@inheritdoc}
17
     */
18
    public static function bootTranslatable()
19
    {
20
        static::deleted(function ($model) {
21
            Translation::query()
22
                ->where('translatable_id', '=', $model->getKey())
23
                ->where('translatable_type', '=', get_class($model))
24
                ->delete();
25
        });
26
    }
27
28
    /**
29
     * Initialize a translatable model.
30
     *
31
     * @return void
32
     */
33
    public function initializeTranslatable()
34
    {
35
        if (! isset($this->nonTranslatable)) {
36
            $this->nonTranslatable = [];
0 ignored issues
show
Bug introduced by
The property nonTranslatable does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
37
        }
38
    }
39
40
    /**
41
     * Get the list of non translatable fields.
42
     *
43
     * @return array
44
     */
45
    public function getNonTranslatable()
46
    {
47
        return $this->nonTranslatable;
48
    }
49
50
    /**
51
     * Translations relationship.
52
     *
53
     * @return \Illuminate\Database\Eloquent\Relations\MorphMany
54
     */
55
    public function translations(): MorphMany
56
    {
57
        return $this->morphMany(Translation::class, 'translatable')->withPivot(['locale_id', 'translation_id']);
0 ignored issues
show
Bug introduced by
It seems like morphMany() must be provided by classes using this trait. How about adding it as abstract method to this trait?

This check looks for methods that are used by a trait but not required by it.

To illustrate, let’s look at the following code example

trait Idable {
    public function equalIds(Idable $other) {
        return $this->getId() === $other->getId();
    }
}

The trait Idable provides a method equalsId that in turn relies on the method getId(). If this method does not exist on a class mixing in this trait, the method will fail.

Adding the getId() as an abstract method to the trait will make sure it is available.

Loading history...
58
    }
59
60
    /**
61
     * Create and return a translation entry for given locale ID.
62
     *
63
     * @param  int  $localeId
64
     * @return \BBS\Nova\Translation\Models\Translation
65
     */
66
    public function upsertTranslationEntry(int $localeId, int $translationId = 0)
67
    {
68
        $data = [
69
            'locale_id' => $localeId,
70
            'translation_id' => ! empty($translationId) ? $translationId : static::freshTranslationId(),
71
            'translatable_id' => $this->getKey(),
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?

This check looks for methods that are used by a trait but not required by it.

To illustrate, let’s look at the following code example

trait Idable {
    public function equalIds(Idable $other) {
        return $this->getId() === $other->getId();
    }
}

The trait Idable provides a method equalsId that in turn relies on the method getId(). If this method does not exist on a class mixing in this trait, the method will fail.

Adding the getId() as an abstract method to the trait will make sure it is available.

Loading history...
72
            'translatable_type' => get_class($this),
73
        ];
74
75
        $translation = Translation::query()->where($data)->first();
76
        if (empty($translation)) {
77
            Translation::query()->create($data);
78
        }
79
    }
80
81
    /**
82
     * Return next fresh translation ID.
83
     *
84
     * @return int
85
     */
86
    public function freshTranslationId()
87
    {
88
        /** @var \BBSLab\NovaTranslation\Models\Translation $lastTranslation */
89
        $lastTranslation = Translation::query()
0 ignored issues
show
Bug introduced by
The method select() does not exist on Illuminate\Database\Eloquent\Builder. Did you maybe mean createSelectWithConstraint()?

This check marks calls to methods that do not seem to exist on an object.

This is most likely the result of a method being renamed without all references to it being renamed likewise.

Loading history...
90
            ->select('translation_id')
91
            ->where('translatable_type', '=', get_class($this))
92
            ->orderBy('translation_id', 'desc')
93
            ->first();
94
95
        return ! empty($lastTranslation) ? ($lastTranslation->translation_id + 1) : 1;
96
    }
97
98
    /**
99
     * Scope a query to only retrieve items from given locale.
100
     *
101
     * @param  \Illuminate\Database\Eloquent\Builder  $builder
102
     * @param  string  $iso
103
     * @return \Illuminate\Database\Eloquent\Builder
104
     * @throws \Exception
105
     */
106
    public function scopeLocale(Builder $builder, string $iso = '')
107
    {
108
        $iso = ! empty($iso) ? $iso : app()->getLocale();
109
110
        /** @var \BBSLab\NovaTranslation\Models\Locale $locale */
111
        $locale = Locale::query()->select('id')->where('iso', '=', $iso)->first();
0 ignored issues
show
Bug introduced by
The method select() does not exist on Illuminate\Database\Eloquent\Builder. Did you maybe mean createSelectWithConstraint()?

This check marks calls to methods that do not seem to exist on an object.

This is most likely the result of a method being renamed without all references to it being renamed likewise.

Loading history...
112
        if (empty($locale)) {
113
            throw new Exception('Invalid locale provided in locale() scope "'.$iso.'"');
114
        }
115
116
        return $builder->join('translations', function ($join) use ($locale) {
117
            $model = new static;
118
119
            $join
120
                ->on($model->getTable().'.'.$model->getKeyName(), '=', 'translations.translatable_id')
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?

This check looks for methods that are used by a trait but not required by it.

To illustrate, let’s look at the following code example

trait Idable {
    public function equalIds(Idable $other) {
        return $this->getId() === $other->getId();
    }
}

The trait Idable provides a method equalsId that in turn relies on the method getId(). If this method does not exist on a class mixing in this trait, the method will fail.

Adding the getId() as an abstract method to the trait will make sure it is available.

Loading history...
Bug introduced by
It seems like getKeyName() must be provided by classes using this trait. How about adding it as abstract method to this trait?

This check looks for methods that are used by a trait but not required by it.

To illustrate, let’s look at the following code example

trait Idable {
    public function equalIds(Idable $other) {
        return $this->getId() === $other->getId();
    }
}

The trait Idable provides a method equalsId that in turn relies on the method getId(). If this method does not exist on a class mixing in this trait, the method will fail.

Adding the getId() as an abstract method to the trait will make sure it is available.

Loading history...
121
                ->where('translations.translatable_type', '=', get_class($model))
122
                ->where('translations.locale_id', '=', $locale->id);
123
        });
124
    }
125
}
126