Completed
Push — master ( ae5cd7...ef0263 )
by
unknown
07:39
created

TranslatableResource::updateFieldsWithinPanels()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 12

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 12
rs 9.8666
c 0
b 0
f 0
cc 1
nc 1
nop 1
1
<?php
2
3
namespace BBSLab\NovaTranslation\Resources;
4
5
use BBSLab\NovaTranslation\Models\Locale;
0 ignored issues
show
Bug introduced by
This use statement conflicts with another class in this namespace, BBSLab\NovaTranslation\Resources\Locale.

Let’s assume that you have a directory layout like this:

.
|-- OtherDir
|   |-- Bar.php
|   `-- Foo.php
`-- SomeDir
    `-- Foo.php

and let’s assume the following content of Bar.php:

// Bar.php
namespace OtherDir;

use SomeDir\Foo; // This now conflicts the class OtherDir\Foo

If both files OtherDir/Foo.php and SomeDir/Foo.php are loaded in the same runtime, you will see a PHP error such as the following:

PHP Fatal error:  Cannot use SomeDir\Foo as Foo because the name is already in use in OtherDir/Foo.php

However, as OtherDir/Foo.php does not necessarily have to be loaded and the error is only triggered if it is loaded before OtherDir/Bar.php, this problem might go unnoticed for a while. In order to prevent this error from surfacing, you must import the namespace with a different alias:

// Bar.php
namespace OtherDir;

use SomeDir\Foo as SomeDirFoo; // There is no conflict anymore.
Loading history...
6
use BBSLab\NovaTranslation\Models\Translation;
7
use Eminiarts\Tabs\TabsOnEdit;
8
use Exception;
9
use Illuminate\Database\Eloquent\Collection;
10
use Illuminate\Database\Eloquent\Model;
11
use Laravel\Nova\Fields\Field;
12
use Laravel\Nova\Fields\FieldCollection;
13
use Laravel\Nova\Http\Requests\NovaRequest;
14
use Laravel\Nova\Panel;
15
use Laravel\Nova\Resource;
16
17
abstract class TranslatableResource extends Resource
18
{
19
    use TabsOnEdit;
20
21
    const PANEL_TRANSLATIONS = 'Translations';
22
23
    /**
24
     * Return resource translations.
25
     *
26
     * @return \Illuminate\Database\Eloquent\Collection
27
     */
28
    protected function getResourceTranslations()
29
    {
30
        $baseTranslation = Translation::query()
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...
31
            ->select('translation_id')
32
            ->where('translatable_id', '=', $this->resource->getKey())
33
            ->where('translatable_type', '=', get_class($this->resource))
34
            ->first();
35
36
        if (empty($baseTranslation)) {
37
            $translationId = $this->resource->freshTranslationId();
0 ignored issues
show
Unused Code introduced by
$translationId is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
38
            $translations = new Collection();
39
            foreach ($this->indexedLocales as $localeId => $locale) {
40
                // @TODO... Instantiate new model (maybe with nonTranslatable() already filled in + "locale_id" and "translation_id")
41
            }
42
        } else {
43
            $translations = $this->resource->translations();
44
        }
45
46
        return $translations;
47
    }
48
49
    // --------------------------------------------------------------------------------
50
    // --------------------------------------------------------------------------------
51
    // --------------------------------------------------------------------------------
52
53
    /**
54
     * {@inheritdoc}
55
     */
56
    public function availablePanelsForDetail($request)
57
    {
58
        $panels = parent::availablePanelsForDetail($request);
59
60
        $panels[] = $this->translationsPanel('detail-tabs');
61
62
        return $panels;
63
    }
64
65
    /**
66
     * {@inheritdoc}
67
     */
68
    public function availablePanelsForUpdate($request)
69
    {
70
        $panels = parent::availablePanelsForUpdate($request);
71
72
        $panels[] = $this->translationsPanel('tabs');
73
74
        return $panels;
75
    }
76
77
    /**
78
     * Return configured translations panel.
79
     *
80
     * @param  string  $component
81
     * @return \Laravel\Nova\Panel
82
     */
83
    protected function translationsPanel(string $component = 'detail-tabs')
84
    {
85
        $panelTranslations = new Panel(static::PANEL_TRANSLATIONS);
86
87
        $panelTranslations->withToolbar();
88
        $panelTranslations->withMeta([
89
            'component' => $component,
90
            'defaultSearch' => $this->defaultSearch,
91
        ]);
92
93
        return $panelTranslations;
94
    }
95
96
    // --------------------------------------------------------------------------------
97
    // --------------------------------------------------------------------------------
98
    // --------------------------------------------------------------------------------
99
100
    /**
101
     * {@inheritdoc}
102
     */
103
    public function serializeForDetail(NovaRequest $request)
104
    {
105
        $serialized = parent::serializeForDetail($request);
106
        if (! empty($serialized['id'])) {
107
            unset($serialized['id']);
108
        }
109
110
        $serialized['fields'] = $this->translationsFields($request, $serialized['fields']);
111
112
        return $serialized;
113
    }
114
115
    /**
116
     * {@inheritdoc}
117
     */
118
    public function updateFieldsWithinPanels($request)
119
    {
120
        $panels = parent::updateFieldsWithinPanels($request);
121
122
        /*
123
        foreach ($panels as $panel) {
124
            $panels['fields'] = new FieldCollection($this->translationsFields($request, $panel['fields']->all()));
125
        }
126
        */
127
128
        return $panels;
129
    }
130
131
    /**
132
     * Transform fields to handle translation system.
133
     *
134
     * @param  \Laravel\Nova\Http\Requests\NovaRequest  $request
135
     * @param  array  $fields
136
     * @return array
137
     * @throws \Exception
138
     */
139
    protected function translationsFields(NovaRequest $request, array $fields)
140
    {
141
        $translationsFields = [];
142
143
        $locales = Locale::query()->select('id', 'iso', 'label')->get();
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...
144
        $translations = $this->getResourceTranslations();
145
146
        foreach ($locales as $locale) {
147
            /** @var \BBSLab\NovaTranslation\Models\Locale $locale */
148
            $localeResource = $translations->where('locale_id', '=', $locale->id)->first();
149
            if (empty($localeResource)) {
150
                throw new Exception('Invalid locale resource for "'.$locale->label.'"');
151
            }
152
153
            foreach ($fields as $field) {
154
                $translationsFields[] = $this->translationField($field, $locale, $localeResource);
155
            }
156
        }
157
158
        return $translationsFields;
159
    }
160
161
    /**
162
     * Override field to handle translation system.
163
     *
164
     * @param  \Laravel\Nova\Fields\Field  $field
165
     * @param  \BBSLab\NovaTranslation\Models\Locale  $locale
166
     * @param  \Illuminate\Database\Eloquent\Model  $localeResource
167
     * @return void
168
     */
169
    protected function translationField(Field $field, Locale $locale, Model $localeResource)
170
    {
171
        $cloneField = clone $field;
172
173
        // @TODO... Use Field resolve()??
174
        // Compute value (resolve() on detail AND direct attribute on update)
175
        $value = $localeResource->{$field->attribute};
176
177
        $cloneField->panel = static::PANEL_TRANSLATIONS;
178
        $cloneField->value = $value;
179
        $cloneField->attribute = $cloneField->attribute.'['.$locale->id.']';
180
        $cloneField->withMeta([
181
            'tab' => $locale->label,
182
            'locale' => $locale->id,
183
        ]);
184
185
        return $cloneField;
186
    }
187
188
    // --------------------------------------------------------------------------------
189
    // --------------------------------------------------------------------------------
190
    // --------------------------------------------------------------------------------
191
192
    /**
193
     * {@inheritdoc}
194
     */
195
    public static function indexQuery(NovaRequest $request, $query)
196
    {
197
        return $query->locale();
198
    }
199
200
    /**
201
     * {@inheritdoc}
202
     */
203
    public static function scoutQuery(NovaRequest $request, $query)
204
    {
205
        return $query;
206
    }
207
208
    /**
209
     * {@inheritdoc}
210
     */
211
    public static function detailQuery(NovaRequest $request, $query)
212
    {
213
        return parent::detailQuery($request, $query);
214
    }
215
216
    /**
217
     * {@inheritdoc}
218
     */
219
    public static function relatableQuery(NovaRequest $request, $query)
220
    {
221
        return parent::relatableQuery($request, $query);
222
    }
223
}
224