Completed
Pull Request — master (#3)
by Mikaël
09:25
created

Translatable::translate()   A

Complexity

Conditions 1
Paths 1

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 1
nc 1
nop 1
1
<?php
2
3
namespace BBSLab\NovaTranslation\Models\Traits;
4
5
use BBSLab\NovaTranslation\Models\Contracts\IsTranslatable;
6
use BBSLab\NovaTranslation\Models\Locale;
7
use BBSLab\NovaTranslation\Models\Observers\TranslatableObserver;
8
use BBSLab\NovaTranslation\Models\Translation;
9
use Illuminate\Database\Eloquent\Builder as EloquentBuilder;
10
use Illuminate\Database\Eloquent\Collection;
11
use Illuminate\Database\Eloquent\Relations\MorphOne;
12
use Illuminate\Database\Query\Builder as QueryBuilder;
13
use Illuminate\Database\Query\JoinClause;
14
use Illuminate\Support\Facades\DB;
15
16
/**
17
 * @property \BBSLab\NovaTranslation\Models\Translation $translation
18
 * @method static \Illuminate\Database\Eloquent\Builder locale(?string $iso = null)
19
 */
20
trait Translatable
21
{
22
    /**
23
     * {@inheritdoc}
24
     */
25
    public static function bootTranslatable()
26
    {
27
        static::observe(TranslatableObserver::class);
28
    }
29
30
    /**
31
     * Get the list of non translatable fields.
32
     *
33
     * @return array
34
     */
35
    public function getNonTranslatable(): array
36
    {
37
        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...
38
    }
39
40
    /**
41
     * Get the list of fields to duplicate on create.
42
     * (Other fields MUST BE nullable in database).
43
     *
44
     * @return array
45
     */
46
    public function getOnCreateTranslatable(): array
47
    {
48
        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...
49
    }
50
51
    /**
52
     * Translation relationship.
53
     *
54
     * @return \Illuminate\Database\Eloquent\Relations\MorphOne
55
     */
56
    public function translation(): MorphOne
57
    {
58
        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...
59
    }
60
61
    /**
62
     * Return current item translations.
63
     *
64
     * @return \Illuminate\Database\Eloquent\Collection|self[]
65
     */
66
    public function translations(): Collection
67
    {
68
        return static::query()
69
            ->select($this->qualifyColumn('*'), 'translations.locale_id', 'translations.translation_id')
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...
70
            ->with('translation')
71
            ->join('translations', $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...
72
            ->whereExists(function (QueryBuilder $query) {
73
                return $query->select(DB::raw(1))
74
                    ->from('translations as t')
75
                    ->whereRaw('t.translation_id = translations.translation_id')
76
                    ->where('t.translatable_type', '=', static::class)
77
                    ->where('t.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...
78
            })
79
            ->where('translations.translatable_type', '=', static::class)
80
            ->where($this->getQualifiedKeyName(), '<>', $this->getKey())
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...
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...
81
            ->get();
82
    }
83
84
    /**
85
     * Create and return a translation entry for given locale ID.
86
     *
87
     * @param  int  $localeId
88
     * @param  int  $translationId
89
     * @return \BBSLab\NovaTranslation\Models\Translation
90
     */
91
    public function upsertTranslationEntry(int $localeId, int $translationId = 0): Translation
92
    {
93
        /** @var \BBSLab\NovaTranslation\Models\Translation $translation */
94
        $translation = Translation::query()
95
            ->firstOrCreate([
96
                'locale_id' => $localeId,
97
                'translation_id' => ! empty($translationId) ? $translationId : $this->freshTranslationId(),
98
                '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...
99
                'translatable_type' => static::class,
100
            ]);
101
102
        return $translation;
103
    }
104
105
    /**
106
     * Return next fresh translation ID.
107
     *
108
     * @return int
109
     */
110
    public function freshTranslationId(): int
111
    {
112
        $lastTranslation = Translation::query()
113
            ->where('translatable_type', '=', static::class)
114
            ->max('translation_id') ?? 0;
115
116
        return $lastTranslation + 1;
117
    }
118
119
    /**
120
     * Scope a query to only retrieve items from given locale.
121
     *
122
     * @param  \Illuminate\Database\Eloquent\Builder  $builder
123
     * @param  string  $iso
124
     * @return \Illuminate\Database\Eloquent\Builder
125
     */
126
    public function scopeLocale(EloquentBuilder $builder, string $iso = null)
127
    {
128
        return $builder->join('translations', function (JoinClause $join) {
129
            $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...
130
                ->where('translations.translatable_type', '=', static::class);
131
        })
132
            ->join('locales', function (JoinClause $join) use ($iso) {
133
                $join->on('locales.id', '=', 'translations.locale_id')
134
                    ->where('locales.iso', '=', $iso ?? app()->getLocale());
135
            })
136
            ->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...
137
    }
138
139
    /**
140
     * Translate model to given locale and return translated model.
141
     *
142
     * @param  \BBSLab\NovaTranslation\Models\Locale  $locale
143
     * @return \BBSLab\NovaTranslation\Models\Contracts\IsTranslatable
144
     */
145
    public function translate(Locale $locale)
146
    {
147
        /** @var \BBSLab\NovaTranslation\Models\Contracts\IsTranslatable $translated */
148
        $translated = $this->translations()->first(function (IsTranslatable $translatable) use ($locale) {
149
            return $translatable->translation->locale_id === $locale->getKey();
0 ignored issues
show
Bug introduced by
Accessing translation on the interface BBSLab\NovaTranslation\M...ontracts\IsTranslatable suggest that you code against a concrete implementation. How about adding an instanceof check?

If you access a property on an interface, you most likely code against a concrete implementation of the interface.

Available Fixes

  1. Adding an additional type check:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeInterface $object) {
        if ($object instanceof SomeClass) {
            $a = $object->a;
        }
    }
    
  2. Changing the type hint:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeClass $object) {
        $a = $object->a;
    }
    
Loading history...
150
        });
151
152
        return $translated ?? static::withoutEvents(function () use ($locale) {
153
            /** @var self $translated */
154
            $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...
155
                $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...
156
                    $this->getOnCreateTranslatable()
157
                )
158
            );
159
            $translated->upsertTranslationEntry($locale->getKey(), $this->translation->translation_id);
160
161
            return $translated;
162
        });
163
    }
164
}
165