Completed
Push — master ( ae45f7...196539 )
by
unknown
09:38
created

TranslatableResource   A

Complexity

Total Complexity 28

Size/Duplication

Total Lines 292
Duplicated Lines 8.22 %

Coupling/Cohesion

Components 1
Dependencies 4

Importance

Changes 0
Metric Value
wmc 28
lcom 1
cbo 4
dl 24
loc 292
rs 10
c 0
b 0
f 0

17 Methods

Rating   Name   Duplication   Size   Complexity  
A availablePanelsForDetail() 0 8 1
A availablePanelsForCreate() 0 8 1
A availablePanelsForUpdate() 0 8 1
A translationsPanel() 0 12 1
A translationsPanelName() 0 4 1
A detailFields() 0 8 1
A creationFields() 12 12 1
A updateFields() 12 12 1
A removeNonUpdateFields() 0 11 4
B translationsFields() 0 27 7
A translationField() 0 19 1
A translationIdField() 0 17 1
A getResourceTranslations() 0 24 3
A indexQuery() 0 4 1
A scoutQuery() 0 4 1
A detailQuery() 0 4 1
A relatableQuery() 0 4 1

How to fix   Duplicated Code   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

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 Illuminate\Support\Str;
12
use Laravel\Nova\Contracts\ListableField;
13
use Laravel\Nova\Contracts\Resolvable;
14
use Laravel\Nova\Fields\Field;
15
use Laravel\Nova\Fields\FieldCollection;
16
use Laravel\Nova\Fields\ID;
17
use Laravel\Nova\Fields\Text;
18
use Laravel\Nova\Http\Requests\NovaRequest;
19
use Laravel\Nova\Panel;
20
use Laravel\Nova\Resource;
21
use Laravel\Nova\ResourceToolElement;
22
23
abstract class TranslatableResource extends Resource
24
{
25
    use TabsOnEdit;
26
27
    /**
28
     * {@inheritdoc}
29
     */
30
    public function availablePanelsForDetail($request)
31
    {
32
        $panels = parent::availablePanelsForDetail($request);
33
34
        $panels[] = $this->translationsPanel('detail-tabs');
35
36
        return $panels;
37
    }
38
39
    /**
40
     * {@inheritdoc}
41
     */
42
    public function availablePanelsForCreate($request)
43
    {
44
        $panels = parent::availablePanelsForCreate($request);
45
46
        $panels[] = $this->translationsPanel('detail-tabs');
47
48
        return $panels;
49
    }
50
51
    /**
52
     * {@inheritdoc}
53
     */
54
    public function availablePanelsForUpdate($request)
55
    {
56
        $panels = parent::availablePanelsForUpdate($request);
57
58
        $panels[] = $this->translationsPanel('tabs');
59
60
        return $panels;
61
    }
62
63
    /**
64
     * Return configured translations panel.
65
     *
66
     * @param  string  $component
67
     * @return \Laravel\Nova\Panel
68
     */
69
    protected function translationsPanel(string $component = 'detail-tabs')
70
    {
71
        $panelTranslations = new Panel($this->translationsPanelName());
72
73
        $panelTranslations->withToolbar();
74
        $panelTranslations->withMeta([
75
            'component' => $component,
76
            'defaultSearch' => $this->defaultSearch,
77
        ]);
78
79
        return $panelTranslations;
80
    }
81
82
    /**
83
     * Translations panel name.
84
     *
85
     * @return string
86
     */
87
    protected function translationsPanelName()
88
    {
89
        return 'Translations '.Str::lower(static::label());
90
    }
91
92
    // --------------------------------------------------------------------------------
93
    // --------------------------------------------------------------------------------
94
    // --------------------------------------------------------------------------------
95
96
    /**
97
     * {@inheritdoc}
98
     */
99
    public function detailFields(NovaRequest $request)
100
    {
101
        $fields = parent::detailFields($request);
102
103
        $fields = $this->translationsFields($fields);
104
105
        return $fields;
106
    }
107
108
    /**
109
     * {@inheritdoc}
110
     */
111 View Code Duplication
    public function creationFields(NovaRequest $request)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
112
    {
113
        $fields = $this->removeNonCreationFields($request, $this->resolveFields($request));
114
115
        return new FieldCollection([
116
            'Tabs' => [
117
                'panel' => Panel::defaultNameForCreate($request->newResource()),
118
                'fields' => $this->translationsFields($fields),
119
                'component' => 'tabs',
120
            ],
121
        ]);
122
    }
123
124
    /**
125
     * {@inheritdoc}
126
     */
127 View Code Duplication
    public function updateFields(NovaRequest $request)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
128
    {
129
        $fields = $this->removeNonUpdateFields($request, $this->resolveFields($request));
130
131
        return new FieldCollection([
132
            'Tabs' => [
133
                'panel' => Panel::defaultNameForUpdate($request->newResource()),
134
                'fields' => $this->translationsFields($fields, true),
135
                'component' => 'tabs',
136
            ],
137
        ]);
138
    }
139
140
    /**
141
     * {@inheritdoc}
142
     */
143
    protected function removeNonUpdateFields(NovaRequest $request, FieldCollection $fields)
144
    {
145
        // Here we override this to keep ID field
146
        return $fields->reject(function ($field) use ($request) {
147
            return
148
                $field instanceof ListableField ||
0 ignored issues
show
Bug introduced by
The class Laravel\Nova\Contracts\ListableField does not exist. Did you forget a USE statement, or did you not list all dependencies?

This error could be the result of:

1. Missing dependencies

PHP Analyzer uses your composer.json file (if available) to determine the dependencies of your project and to determine all the available classes and functions. It expects the composer.json to be in the root folder of your repository.

Are you sure this class is defined by one of your dependencies, or did you maybe not list a dependency in either the require or require-dev section?

2. Missing use statement

PHP does not complain about undefined classes in ìnstanceof checks. For example, the following PHP code will work perfectly fine:

if ($x instanceof DoesNotExist) {
    // Do something.
}

If you have not tested against this specific condition, such errors might go unnoticed.

Loading history...
149
                $field instanceof ResourceToolElement ||
0 ignored issues
show
Bug introduced by
The class Laravel\Nova\ResourceToolElement does not exist. Did you forget a USE statement, or did you not list all dependencies?

This error could be the result of:

1. Missing dependencies

PHP Analyzer uses your composer.json file (if available) to determine the dependencies of your project and to determine all the available classes and functions. It expects the composer.json to be in the root folder of your repository.

Are you sure this class is defined by one of your dependencies, or did you maybe not list a dependency in either the require or require-dev section?

2. Missing use statement

PHP does not complain about undefined classes in ìnstanceof checks. For example, the following PHP code will work perfectly fine:

if ($x instanceof DoesNotExist) {
    // Do something.
}

If you have not tested against this specific condition, such errors might go unnoticed.

Loading history...
150
                $field->attribute === 'ComputedField' ||
151
                ! $field->isShownOnUpdate($request, $this->resource);
152
        });
153
    }
154
155
    // --------------------------------------------------------------------------------
156
    // --------------------------------------------------------------------------------
157
    // --------------------------------------------------------------------------------
158
159
    /**
160
     * Transform fields to handle translation system.
161
     *
162
     * @param  \Laravel\Nova\Fields\FieldCollection  $fields
163
     * @param  bool  $forceReadonlyIds
164
     * @return \Laravel\Nova\Fields\FieldCollection
165
     * @throws \Exception
166
     */
167
    protected function translationsFields(FieldCollection $fields, $forceReadonlyIds = false)
168
    {
169
        $translationsFields = [];
170
171
        $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...
172
        $translations = $this->getResourceTranslations($locales);
173
174
        foreach ($locales as $locale) {
175
            /** @var \BBSLab\NovaTranslation\Models\Locale $locale */
176
            $localeResource = $translations->where('locale_id', '=', $locale->id)->first();
177
            if (empty($localeResource)) {
178
                throw new Exception('Invalid locale resource for "'.$locale->label.'"');
179
            }
180
181
            $translationsFields[] = $this->translationIdField($locale, $localeResource);
182
183
            foreach ($fields as $field) {
184
                /** @var \Laravel\Nova\Fields\Field $field */
185
                if ($forceReadonlyIds && $field instanceof ID && ($field->attribute === $this->resource->getKeyName())) {
0 ignored issues
show
Bug introduced by
The class Laravel\Nova\Fields\ID does not exist. Did you forget a USE statement, or did you not list all dependencies?

This error could be the result of:

1. Missing dependencies

PHP Analyzer uses your composer.json file (if available) to determine the dependencies of your project and to determine all the available classes and functions. It expects the composer.json to be in the root folder of your repository.

Are you sure this class is defined by one of your dependencies, or did you maybe not list a dependency in either the require or require-dev section?

2. Missing use statement

PHP does not complain about undefined classes in ìnstanceof checks. For example, the following PHP code will work perfectly fine:

if ($x instanceof DoesNotExist) {
    // Do something.
}

If you have not tested against this specific condition, such errors might go unnoticed.

Loading history...
186
                    $field->readonly();
187
                }
188
                $translationsFields[] = $this->translationField($field, $locale, $localeResource);
189
            }
190
        }
191
192
        return new FieldCollection($translationsFields);
193
    }
194
195
    /**
196
     * Override field to handle translation system.
197
     *
198
     * @param  \Laravel\Nova\Fields\Field  $field
199
     * @param  \BBSLab\NovaTranslation\Models\Locale  $locale
200
     * @param  \Illuminate\Database\Eloquent\Model  $localeResource
201
     * @return void
202
     */
203
    protected function translationField(Field $field, Locale $locale, Model $localeResource)
204
    {
205
        $cloneField = clone $field;
206
207
        // @TODO... Debug $field->resolve()
208
        // $value = ($cloneField instanceof Resolvable) ? $cloneField->resolve($localeResource) : $localeResource->{$cloneField->attribute};
209
        $value = $localeResource->{$cloneField->attribute};
210
211
        $cloneField->panel = $this->translationsPanelName();
212
        $cloneField->value = $value;
213
        $cloneField->attribute = $cloneField->attribute.'['.$locale->id.']';
214
        $cloneField->withMeta([
215
            'tab' => $locale->label,
216
            'localeId' => $locale->id,
217
            'localeValue' => $value,
218
        ]);
219
220
        return $cloneField;
221
    }
222
223
    /**
224
     * Return hidden translation ID field.
225
     *
226
     * @param  \BBSLab\NovaTranslation\Models\Locale  $locale
227
     * @param  \Illuminate\Database\Eloquent\Model  $localeResource
228
     * @return \Laravel\Nova\Fields\Text
229
     */
230
    protected function translationIdField(Locale $locale, Model $localeResource)
231
    {
232
        $field = new Text('Translation ID');
233
234
        $field->panel = $this->translationsPanelName();
235
        $field->value = $localeResource->translation_id;
236
        $field->attribute = 'translation_id['.$locale->id.']';
237
238
        $field->readonly();
239
        $field->withMeta([
240
            'tab' => $locale->label,
241
            'localeId' => $locale->id,
242
            'localeValue' => $localeResource->translation_id,
243
        ]);
244
245
        return $field;
246
    }
247
248
    /**
249
     * Return resource translations.
250
     *
251
     * @param  \Illuminate\Database\Eloquent\Collection  $locales
252
     * @return \Illuminate\Database\Eloquent\Collection
253
     */
254
    protected function getResourceTranslations(Collection $locales)
255
    {
256
        $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...
257
            ->select('translation_id')
258
            ->where('translatable_id', '=', $this->resource->getKey())
259
            ->where('translatable_type', '=', get_class($this->resource))
260
            ->first();
261
262
        if (empty($baseTranslation)) {
263
            $translationId = $this->resource->freshTranslationId();
264
            $translations = new Collection();
265
            foreach ($locales as $locale) {
266
                /** @var \BBSLab\NovaTranslation\Models\Locale $locale */
267
                $translation = new $this->resource;
268
                $translation->locale_id = $locale->id;
269
                $translation->translation_id = $translationId;
270
                $translations->push($translation);
271
            }
272
        } else {
273
            $translations = $this->resource->translations();
274
        }
275
276
        return $translations;
277
    }
278
279
    // --------------------------------------------------------------------------------
280
    // --------------------------------------------------------------------------------
281
    // --------------------------------------------------------------------------------
282
283
    /**
284
     * {@inheritdoc}
285
     */
286
    public static function indexQuery(NovaRequest $request, $query)
287
    {
288
        return $query->locale();
289
    }
290
291
    /**
292
     * {@inheritdoc}
293
     */
294
    public static function scoutQuery(NovaRequest $request, $query)
295
    {
296
        return $query;
297
    }
298
299
    /**
300
     * {@inheritdoc}
301
     */
302
    public static function detailQuery(NovaRequest $request, $query)
303
    {
304
        return parent::detailQuery($request, $query);
305
    }
306
307
    /**
308
     * {@inheritdoc}
309
     */
310
    public static function relatableQuery(NovaRequest $request, $query)
311
    {
312
        return parent::relatableQuery($request, $query);
313
    }
314
}
315