Passed
Pull Request — 2.x (#729)
by Antonio Carlos
06:06
created

HasTranslation::scopeOrderByTranslation()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 18
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 2
eloc 14
c 1
b 0
f 0
nc 2
nop 4
dl 0
loc 18
ccs 0
cts 14
cp 0
crap 6
rs 9.7998
1
<?php
2
3
namespace A17\Twill\Models\Behaviors;
4
5
use Astrotomic\Translatable\Translatable;
6
use Illuminate\Database\Query\JoinClause;
7
use A17\Twill\Services\Capsules\HasCapsules;
8
9
trait HasTranslation
10
{
11
    use Translatable, HasCapsules;
12
13 36
    public function getTranslationModelNameDefault()
14
    {
15 36
        $repository = config('twill.namespace') . "\Models\Translations\\" . class_basename($this) . 'Translation';
16
17 36
        if (@class_exists($repository)) {
18 32
            return $repository;
19
        }
20
21 4
        return $this->getCapsuleTranslationClass(class_basename($this));
22
    }
23
24
    public function scopeWithActiveTranslations($query, $locale = null)
25
    {
26
        if (method_exists($query->getModel(), 'translations')) {
27
            $locale = $locale == null ? app()->getLocale() : $locale;
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

27
            $locale = $locale == null ? app()->/** @scrutinizer ignore-call */ getLocale() : $locale;
Loading history...
28
29
            $query->whereHas('translations', function ($query) use ($locale) {
30
                $query->whereActive(true);
31
                $query->whereLocale($locale);
32
33
                if (config('translatable.use_property_fallback', false)) {
34
                    $query->orWhere('locale', config('translatable.fallback_locale'));
35
                }
36
            });
37
38
            return $query->with(['translations' => function ($query) use ($locale) {
39
                $query->whereActive(true);
40
                $query->whereLocale($locale);
41
42
                if (config('translatable.use_property_fallback', false)) {
43
                    $query->orWhere('locale', config('translatable.fallback_locale'));
44
                }
45
            }]);
46
        }
47
    }
48
49
    public function scopeOrderByTranslation($query, $orderField, $orderType = 'ASC', $locale = null)
50
    {
51
        $translationTable = $this->getTranslationsTable();
52
        $localeKey = $this->getLocaleKey();
53
        $table = $this->getTable();
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

53
        /** @scrutinizer ignore-call */ 
54
        $table = $this->getTable();
Loading history...
54
        $keyName = $this->getKeyName();
0 ignored issues
show
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? ( Ignorable by Annotation )

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

54
        /** @scrutinizer ignore-call */ 
55
        $keyName = $this->getKeyName();
Loading history...
55
        $locale = $locale == null ? app()->getLocale() : $locale;
56
57
        return $query
58
            ->join($translationTable, function (JoinClause $join) use ($translationTable, $localeKey, $table, $keyName) {
59
                $join
60
                    ->on($translationTable.'.'.$this->getRelationKey(), '=', $table.'.'.$keyName)
0 ignored issues
show
Deprecated Code introduced by
The function A17\Twill\Models\Behavio...ation::getRelationKey() has been deprecated. ( Ignorable by Annotation )

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

60
                    ->on($translationTable.'.'./** @scrutinizer ignore-deprecated */ $this->getRelationKey(), '=', $table.'.'.$keyName)
Loading history...
61
                    ->where($translationTable.'.'.$localeKey, $this->locale());
62
            })
63
            ->where($translationTable.'.'.$this->getLocaleKey(), $locale)
64
            ->orderBy($translationTable.'.'.$orderField, $orderType)
65
            ->select($table.'.*')
66
            ->with('translations');
67
    }
68
69
    public function scopeOrderByRawByTranslation($query, $orderRawString, $groupByField, $locale = null)
70
    {
71
        $translationTable = $this->getTranslationsTable();
72
        $table = $this->getTable();
73
        $locale = $locale == null ? app()->getLocale() : $locale;
74
75
        return $query->join("{$translationTable} as t", "t.{$this->getRelationKey()}", "=", "{$table}.id")
0 ignored issues
show
Deprecated Code introduced by
The function A17\Twill\Models\Behavio...ation::getRelationKey() has been deprecated. ( Ignorable by Annotation )

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

75
        return $query->join("{$translationTable} as t", "t.{/** @scrutinizer ignore-deprecated */ $this->getRelationKey()}", "=", "{$table}.id")
Loading history...
76
            ->where($this->getLocaleKey(), $locale)
77
            ->groupBy("{$table}.id")
78
            ->groupBy("t.{$groupByField}")
79
            ->select("{$table}.*")
80
            ->orderByRaw($orderRawString)
81
            ->with('translations');
82
    }
83
84
    public function hasActiveTranslation($locale = null)
85
    {
86
        $locale = $locale ?: $this->locale();
87
88
        $translations = $this->memoizedTranslations ?? ($this->memoizedTranslations = $this->translations()->get());
0 ignored issues
show
Bug Best Practice introduced by
The property memoizedTranslations does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
89
90
        foreach ($translations as $translation) {
91
            if ($translation->getAttribute($this->getLocaleKey()) == $locale && $translation->getAttribute('active')) {
92
                return true;
93
            }
94
        }
95
96
        return false;
97
    }
98
99 5
    public function getActiveLanguages()
100
    {
101 5
        return $this->translations->map(function ($translation) {
102
            return [
103 5
                'shortlabel' => strtoupper($translation->locale),
104 5
                'label' => getLanguageLabelFromLocaleCode($translation->locale),
105 5
                'value' => $translation->locale,
106 5
                'published' => $translation->active ?? false,
107
            ];
108 5
        })->sortBy(function ($translation) {
109 5
            $localesOrdered = config('translatable.locales');
110 5
            return array_search($translation['value'], $localesOrdered);
111 5
        })->values();
112
    }
113
114
    public function translatedAttribute($key)
115
    {
116
        return $this->translations->mapWithKeys(function ($translation) use ($key) {
117
            return [$translation->locale => $this->translate($translation->locale)->$key];
118
        });
119
    }
120
121
}
122