prepareFieldsBeforeSaveHandleTranslations()   B
last analyzed

Complexity

Conditions 7
Paths 2

Size

Total Lines 43
Code Lines 23

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 24
CRAP Score 7

Importance

Changes 0
Metric Value
cc 7
eloc 23
nc 2
nop 2
dl 0
loc 43
ccs 24
cts 24
cp 1
crap 7
rs 8.6186
c 0
b 0
f 0
1
<?php
2
3
namespace A17\Twill\Repositories\Behaviors;
4
5
use Illuminate\Support\Arr;
6
use Illuminate\Support\Collection;
7
8
trait HandleTranslations
9
{
10
    protected $nullableFields = [];
11
12 21
    /**
13
     * @param array $fields
14 21
     * @return array
15
     */
16
    public function prepareFieldsBeforeCreateHandleTranslations($fields)
17 21
    {
18
        return $this->prepareFieldsBeforeSaveHandleTranslations(null, $fields);
19 21
    }
20 21
21 21
    /**
22 21
     * @param \A17\Twill\Models\Model|null $object
23
     * @param array $fields
24 21
     * @return array
25
     */
26 21
    public function prepareFieldsBeforeSaveHandleTranslations($object, $fields)
27 21
    {
28 21
        if ($this->model->isTranslatable()) {
29
            $locales = getLocales();
30 21
            $localesCount = count($locales);
31 21
            $attributes = Collection::make($this->model->translatedAttributes);
32 21
33 21
            $submittedLanguages = Collection::make($fields['languages'] ?? []);
34
35 21
            $atLeastOneLanguageIsPublished = $submittedLanguages->contains(function ($language) {
36
                return $language['published'];
37 21
            });
38
39 21
            foreach ($locales as $index => $locale) {
40 21
                $submittedLanguage = Arr::first($submittedLanguages->filter(function ($lang) use ($locale) {
41 21
                    return $lang['value'] == $locale;
42 21
                }));
43
44
                $shouldPublishFirstLanguage = ($index === 0 && !$atLeastOneLanguageIsPublished);
45
46 21
                $activeField = $shouldPublishFirstLanguage || (isset($submittedLanguage) ? $submittedLanguage['published'] : false);
47 21
48
                $fields[$locale] = [
49
                    'active' => $activeField,
50
                ] + $attributes->mapWithKeys(function ($attribute) use (&$fields, $locale, $localesCount, $index) {
51 21
                    $attributeValue = $fields[$attribute] ?? null;
52
53 21
                    // if we are at the last locale,
54
                    // let's unset this field as it is now managed by this trait
55
                    if ($index + 1 === $localesCount) {
56 21
                        unset($fields[$attribute]);
57
                    }
58
59 21
                    return [
60
                        $attribute => ($attributeValue[$locale] ?? null),
61
                    ];
62 5
                })->toArray();
63
            }
64 5
65
            unset($fields['languages']);
66 5
        }
67 5
68 5
        return $fields;
69 5
    }
70 5
71
    /**
72
     * @param \A17\Twill\Models\Model $object
73
     * @param array $fields
74
     * @return array
75 5
     */
76
    public function getFormFieldsHandleTranslations($object, $fields)
77
    {
78 32
        unset($fields['translations']);
79
80 32
        if ($object->translations != null && $object->translatedAttributes != null) {
0 ignored issues
show
Bug introduced by
The property translations does not seem to exist on A17\Twill\Models\Model. Are you sure there is no database migration missing?

Checks if undeclared accessed properties appear in database migrations and if the creating migration is correct.

Loading history...
Bug introduced by
The property translatedAttributes does not seem to exist on A17\Twill\Models\Model. Are you sure there is no database migration missing?

Checks if undeclared accessed properties appear in database migrations and if the creating migration is correct.

Loading history...
81 32
            foreach ($object->translations as $translation) {
82 32
                foreach ($object->translatedAttributes as $attribute) {
83 32
                    unset($fields[$attribute]);
84 32
                    if (array_key_exists($attribute, $this->fieldsGroups) && is_array($translation->{$attribute})) {
85
                        foreach ($this->fieldsGroups[$attribute] as $field_name) {
86
                            if (isset($translation->{$attribute}[$field_name])) {
87
                                if ($this->fieldsGroupsFormFieldNamesAutoPrefix) {
88 32
                                    $fields['translations'][$attribute . $this->fieldsGroupsFormFieldNameSeparator . $field_name][$translation->locale] = $translation->{$attribute}[$field_name];
89
                                } else {
90 32
                                    $fields['translations'][$field_name][$translation->locale] = $translation->{$attribute}[$field_name];
91 32
                                }
92
                            }
93
                        }
94
                        unset($fields['translations'][$attribute]);
95
                    } else {
96 32
                        $fields['translations'][$attribute][$translation->locale] = $translation->{$attribute};
97
                    }
98 7
                }
99
            }
100 7
        }
101 7
102 7
        return $fields;
103 7
    }
104 7
105 7
    protected function filterHandleTranslations($query, &$scopes)
106
    {
107 7
        if ($this->model->isTranslatable()) {
108 7
            $attributes = $this->model->translatedAttributes;
109 7
            $query->whereHas('translations', function ($q) use ($scopes, $attributes) {
110
                foreach ($attributes as $attribute) {
111
                    if (isset($scopes[$attribute]) && is_string($scopes[$attribute])) {
112
                        $q->where($attribute, $this->getLikeOperator(), '%' . $scopes[$attribute] . '%');
0 ignored issues
show
Bug introduced by
It seems like getLikeOperator() 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

112
                        $q->where($attribute, $this->/** @scrutinizer ignore-call */ getLikeOperator(), '%' . $scopes[$attribute] . '%');
Loading history...
113
                    }
114
                }
115
            });
116 7
117
            foreach ($attributes as $attribute) {
118
                if (isset($scopes[$attribute])) {
119
                    unset($scopes[$attribute]);
120
                }
121
            }
122
        }
123
    }
124 7
125
    /**
126
     * @param \Illuminate\Database\Eloquent\Builder $query
127
     * @param array $orders
128
     * @return void
129
     */
130
    public function orderHandleTranslations($query, &$orders)
131
    {
132
        if ($this->model->isTranslatable()) {
133
            $attributes = $this->model->translatedAttributes;
134
            $table = $this->model->getTable();
135
            $tableTranslation = $this->model->translations()->getRelated()->getTable();
136
            $foreignKeyMethod = method_exists($this->model->translations(), 'getQualifiedForeignKeyName') ? 'getQualifiedForeignKeyName' : 'getForeignKey';
137
            $foreignKey = $this->model->translations()->$foreignKeyMethod();
138
139
            $isOrdered = false;
140
            foreach ($attributes as $attribute) {
141
                if (isset($orders[$attribute])) {
142
                    $query->orderBy($tableTranslation . '.' . $attribute, $orders[$attribute]);
143
                    $isOrdered = true;
144
                    unset($orders[$attribute]);
145
                }
146
            }
147
148
            if ($isOrdered) {
149
                $query
150
                    ->join($tableTranslation, $foreignKey, '=', $table . '.id')
151
                    ->where($tableTranslation . '.locale', '=', $orders['locale'] ?? app()->getLocale())
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

151
                    ->where($tableTranslation . '.locale', '=', $orders['locale'] ?? app()->/** @scrutinizer ignore-call */ getLocale())
Loading history...
152
                    ->select($table . '.*')
153
                ;
154
            }
155
        }
156
    }
157
158
    /**
159
     * @return array
160
     */
161
    public function getPublishedScopesHandleTranslations()
162
    {
163
        return ['withActiveTranslations'];
164
    }
165
}
166