Completed
Push — master ( 17909b...b957b5 )
by Mikaël
18:52 queued 08:52
created

Translatable::translatingRelation()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 4
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 0
1
<?php
2
3
namespace BBSLab\NovaTranslation\Models\Traits;
4
5
use BBSLab\NovaTranslation\Models\Locale;
6
use BBSLab\NovaTranslation\Models\Observers\TranslatableObserver;
7
use BBSLab\NovaTranslation\Models\Translation;
8
use BBSLab\NovaTranslation\Models\TranslationRelation;
9
use Illuminate\Database\Eloquent\Builder as EloquentBuilder;
10
use Illuminate\Database\Eloquent\Relations\MorphOne;
11
use Illuminate\Database\Query\JoinClause;
12
13
/**
14
 * @property \BBSLab\NovaTranslation\Models\Translation $translation
15
 * @property \Illuminate\Database\Eloquent\Collection|\BBSLab\NovaTranslation\Models\Translation[] $translations
16
 * @method static \Illuminate\Database\Eloquent\Builder locale(?string $iso = null)
17
 */
18
trait Translatable
19
{
20
    protected $_deleting_translation = false;
21
    protected $_translating_relation = false;
22
23
    /**
24
     * {@inheritdoc}
25
     */
26
    public static function bootTranslatable()
27
    {
28
        static::observe(TranslatableObserver::class);
29
    }
30
31
    /**
32
     * Get the list of non translatable fields.
33
     *
34
     * @return array
35
     */
36
    public function getNonTranslatable(): array
37
    {
38
        return isset($this->nonTranslatable) ? $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...
39
    }
40
41
    /**
42
     * Get the list of fields to duplicate on create.
43
     * (Other fields MUST BE nullable in database).
44
     *
45
     * @return array
46
     */
47
    public function getOnCreateTranslatable(): array
48
    {
49
        return isset($this->onCreateTranslatable) ? $this->onCreateTranslatable : $this->getNonTranslatable();
0 ignored issues
show
Bug introduced by
The property onCreateTranslatable 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...
50
    }
51
52
    /**
53
     * Translation relationship.
54
     *
55
     * @return \Illuminate\Database\Eloquent\Relations\MorphOne
56
     */
57
    public function translation(): MorphOne
58
    {
59
        return $this->morphOne(Translation::class, 'translatable');
0 ignored issues
show
Bug introduced by
It seems like morphOne() 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...
60
    }
61
62
    /**
63
     * Return current item translations.
64
     *
65
     * @return \BBSLab\NovaTranslation\Models\TranslationRelation
66
     */
67
    public function translations(): TranslationRelation
68
    {
69
        return new TranslationRelation($this);
70
    }
71
72
    /**
73
     * Create and return a translation entry for given locale ID.
74
     *
75
     * @param  int  $localeId
76
     * @param  int  $sourceId
77
     * @param  int  $translationId
78
     * @return \BBSLab\NovaTranslation\Models\Translation
79
     */
80
    public function upsertTranslationEntry(int $localeId, int $sourceId, int $translationId = 0): Translation
81
    {
82
        /** @var \BBSLab\NovaTranslation\Models\Translation $translation */
83
        $translation = Translation::query()
84
            ->firstOrCreate([
85
                'locale_id' => $localeId,
86
                'translation_id' => ! empty($translationId) ? $translationId : $this->freshTranslationId(),
87
                '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...
88
                'translatable_type' => static::class,
89
                'translatable_source' => $sourceId,
90
            ]);
91
92
        return $translation;
93
    }
94
95
    /**
96
     * Return next fresh translation ID.
97
     *
98
     * @return int
99
     */
100
    public function freshTranslationId(): int
101
    {
102
        $lastTranslation = Translation::query()
103
            ->where('translatable_type', '=', static::class)
104
            ->max('translation_id') ?? 0;
105
106
        return $lastTranslation + 1;
107
    }
108
109
    /**
110
     * Scope a query to only retrieve items from given locale.
111
     *
112
     * @param  \Illuminate\Database\Eloquent\Builder  $builder
113
     * @param  string  $iso
114
     * @return \Illuminate\Database\Eloquent\Builder
115
     */
116
    public function scopeLocale(EloquentBuilder $builder, string $iso = null)
117
    {
118
        return $builder->join('translations', function (JoinClause $join) {
119
            $join->on($this->getQualifiedKeyName(), '=', 'translations.translatable_id')
0 ignored issues
show
Bug introduced by
It seems like getQualifiedKeyName() 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...
120
                ->where('translations.translatable_type', '=', static::class);
121
        })
122
            ->join('locales', function (JoinClause $join) use ($iso) {
123
                $join->on('locales.id', '=', 'translations.locale_id')
124
                    ->where('locales.iso', '=', $iso ?? app()->getLocale());
125
            })
126
            ->select($this->qualifyColumn('*'));
0 ignored issues
show
Bug introduced by
It seems like qualifyColumn() 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
     * Translate model to given locale and return translated model.
131
     *
132
     * @param  \BBSLab\NovaTranslation\Models\Locale  $locale
133
     * @return \BBSLab\NovaTranslation\Models\Contracts\IsTranslatable
134
     */
135
    public function translate(Locale $locale)
136
    {
137
        /** @var \BBSLab\NovaTranslation\Models\Contracts\IsTranslatable $translated */
138
        $translated = optional(
139
            $this->translations()
0 ignored issues
show
Documentation Bug introduced by
The method where does not exist on object<BBSLab\NovaTransl...ls\TranslationRelation>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
140
                ->where('locale_id', '=', $locale->getKey())
141
                ->with('translatable')
142
                ->first()
143
        )->translatable;
144
145
        return $translated ?? static::withoutEvents(function () use ($locale) {
146
            /** @var self $translated */
147
            $translated = $this->newQuery()->create(
0 ignored issues
show
Bug introduced by
It seems like newQuery() 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...
148
                $this->only(
0 ignored issues
show
Bug introduced by
It seems like only() 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...
149
                    $this->getOnCreateTranslatable()
150
                )
151
            );
152
153
            $translated->upsertTranslationEntry(
154
                $locale->getKey(), $this->getKey(), $this->translation->translation_id
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...
155
            );
156
157
            return $translated;
158
        });
159
    }
160
161
    /**
162
     * Set deleting translation state.
163
     *
164
     * @return void
165
     */
166
    public function deletingTranslation(): void
167
    {
168
        $this->_deleting_translation = true;
169
    }
170
171
    /**
172
     * Determine is the model currently in a delete translation process.
173
     *
174
     * @return bool
175
     */
176
    public function isDeletingTranslation(): bool
177
    {
178
        return $this->_deleting_translation;
179
    }
180
181
    /**
182
     * Set translating relation state.
183
     *
184
     * @return void
185
     */
186
    public function translatingRelation(): void
187
    {
188
        $this->_translating_relation = true;
189
    }
190
191
    /**
192
     * Determine is the model currently translating a relation.
193
     *
194
     * @return bool
195
     */
196
    public function isTranslatingRelation(): bool
197
    {
198
        return $this->_translating_relation;
199
    }
200
}
201