Completed
Push — master ( e08fa1...2c7876 )
by
unknown
09:46
created

Translatable::scopeInLocale()   A

Complexity

Conditions 3
Paths 4

Size

Total Lines 17

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 17
rs 9.7
c 0
b 0
f 0
cc 3
nc 4
nop 2
1
<?php
2
3
namespace BBS\Nova\Translation\Models\Traits;
4
5
use Exception;
6
use BBS\Nova\Translation\Models\Locale;
7
use BBS\Nova\Translation\Models\Translation;
8
use Illuminate\Database\Eloquent\Builder;
9
10
/**
11
 * @property array $nonTranslatable
12
 * @property \Illuminate\Database\Eloquent\Collection $translations
13
 * @mixin \Illuminate\Database\Eloquent\Model
14
 */
15
trait Translatable
16
{
17
    /**
18
     * {@inheritdoc}
19
     */
20
    public static function bootTranslatable()
21
    {
22
        static::deleted(function ($model) {
23
            Translation::query()
24
                ->where('translatable_id', '=', $model->getKey())
25
                ->where('translatable_type', '=', get_class($model))
26
                ->delete();
27
        });
28
    }
29
30
    /**
31
     * Initialize a translatable model.
32
     *
33
     * @return void
34
     */
35
    public function initializeTranslatable()
36
    {
37
        $translationIdField = $this->translationIdField();
38
39
        $this->fillable[] = $translationIdField;
0 ignored issues
show
Bug introduced by
The property fillable 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...
40
        $this->nonTranslatable[] = $translationIdField;
41
        $this->casts[$translationIdField] = 'integer';
0 ignored issues
show
Bug introduced by
The property casts 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...
42
    }
43
44
    /**
45
     * Scope a query to only retrieve items from given locale.
46
     *
47
     * @param  \Illuminate\Database\Eloquent\Builder  $builder
48
     * @param  string  $iso
49
     * @return \Illuminate\Database\Eloquent\Builder
50
     * @throws \Exception
51
     */
52
    public function scopeInLocale(Builder $builder, string $iso = '')
53
    {
54
        $iso = ! empty($iso) ? $iso : app()->getLocale();
55
56
        /** @var \BBS\Nova\Translation\Models\Locale $locale */
57
        $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...
58
        if (empty($locale)) {
59
            throw new Exception('Invalid locale provided in inLocale scope "' . $iso . '"');
60
        }
61
62
        return $builder->join('translations', function ($join) use ($model, $locale) {
0 ignored issues
show
Bug introduced by
The variable $model does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
63
            $join
64
                ->on($model->getTable().'.'.$model->getKeyName(), '=', 'translations.translatable_id')
65
                ->where('translations.translatable_type', '=', get_class($model))
66
                ->where('translations.locale_id', '=', $locale->id);
67
        });
68
    }
69
70
    /**
71
     * Return next fresh translation ID.
72
     *
73
     * @return int
74
     */
75
    public static function freshTranslationId()
76
    {
77
        $instance = new static;
78
        $translationIdField = $instance->translationIdField();
79
80
        /** @var \Illuminate\Database\Eloquent\Model $lastTranslation */
81
        $lastTranslation = static::query()
82
            ->select($instance->getTable().'.'.$translationIdField)
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...
83
            ->orderBy($translationIdField, 'desc')
84
            ->first();
85
86
        return ! empty($lastTranslation) ? ($lastTranslation->getAttribute($translationIdField) + 1) : 1;
87
    }
88
89
    /**
90
     * Translations relationship.
91
     *
92
     * @return \Illuminate\Database\Eloquent\Relations\MorphMany
93
     */
94
    public function translations(): MorphMany
95
    {
96
        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...
97
    }
98
99
    /**
100
     * Get the list of non translatable fields.
101
     *
102
     * @return array
103
     */
104
    public function getNonTranslatable()
105
    {
106
        return $this->nonTranslatable;
107
    }
108
109
    /**
110
     * Translation ID accessor.
111
     *
112
     * @return int
113
     */
114
    public function getTranslationIdAttribute()
115
    {
116
        return $this->translationId();
117
    }
118
119
    /**
120
     * Return translation ID value.
121
     *
122
     * @return int
123
     */
124
    public function translationId()
125
    {
126
        return $this->getAttribute($this->translationIdField());
0 ignored issues
show
Bug introduced by
It seems like getAttribute() 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...
127
    }
128
129
    /**
130
     * Define translation ID field name.
131
     *
132
     * @return string
133
     */
134
    public function translationIdField()
135
    {
136
        return 'translation_id';
137
    }
138
139
    /**
140
     * Create and return a translation entry for given locale ID.
141
     *
142
     * @param  int  $localeId
143
     * @return \BBS\Nova\Translation\Models\Translation
144
     */
145
    public function createTranslationEntry(int $localeId)
146
    {
147
        Translation::query()->create([
148
            'locale_id' => $localeId,
149
            'translation_id' => $this->translationId(),
150
            '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...
151
            'translatable_type' => get_class($this),
152
        ]);
153
    }
154
}
155