Completed
Push — master ( 372073...79accf )
by
unknown
08:59
created

TranslatableResource::availablePanelsForCreate()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 8
rs 10
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 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\Http\Requests\NovaRequest;
18
use Laravel\Nova\Panel;
19
use Laravel\Nova\Resource;
20
use Laravel\Nova\ResourceToolElement;
21
22
abstract class TranslatableResource extends Resource
23
{
24
    use TabsOnEdit;
25
26
    /**
27
     * {@inheritdoc}
28
     */
29
    public function availablePanelsForDetail($request)
30
    {
31
        $panels = parent::availablePanelsForDetail($request);
32
33
        $panels[] = $this->translationsPanel('detail-tabs');
34
35
        return $panels;
36
    }
37
38
    /**
39
     * {@inheritdoc}
40
     */
41
    public function availablePanelsForCreate($request)
42
    {
43
        $panels = parent::availablePanelsForCreate($request);
44
45
        $panels[] = $this->translationsPanel('detail-tabs');
46
47
        return $panels;
48
    }
49
50
    /**
51
     * {@inheritdoc}
52
     */
53
    public function availablePanelsForUpdate($request)
54
    {
55
        $panels = parent::availablePanelsForUpdate($request);
56
57
        $panels[] = $this->translationsPanel('tabs');
58
59
        return $panels;
60
    }
61
62
    /**
63
     * Return configured translations panel.
64
     *
65
     * @param  string  $component
66
     * @return \Laravel\Nova\Panel
67
     */
68
    protected function translationsPanel(string $component = 'detail-tabs')
69
    {
70
        $panelTranslations = new Panel($this->translationsPanelName());
71
72
        $panelTranslations->withToolbar();
73
        $panelTranslations->withMeta([
74
            'component' => $component,
75
            'defaultSearch' => $this->defaultSearch,
76
        ]);
77
78
        return $panelTranslations;
79
    }
80
81
    /**
82
     * Translations panel name.
83
     *
84
     * @return string
85
     */
86
    protected function translationsPanelName()
87
    {
88
        return 'Translations '.Str::lower(static::label());
89
    }
90
91
    // --------------------------------------------------------------------------------
92
    // --------------------------------------------------------------------------------
93
    // --------------------------------------------------------------------------------
94
95
    /**
96
     * {@inheritdoc}
97
     */
98
    public function detailFields(NovaRequest $request)
99
    {
100
        $fields = parent::detailFields($request);
101
102
        $fields = $this->translationsFields($fields);
103
104
        return $fields;
105
    }
106
107
    /**
108
     * {@inheritdoc}
109
     */
110 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...
111
    {
112
        $fields = $this->removeNonCreationFields($request, $this->resolveFields($request));
113
114
        return new FieldCollection([
115
            'Tabs' => [
116
                'panel' => Panel::defaultNameForCreate($request->newResource()),
117
                'fields' => $this->translationsFields($fields),
118
                'component' => 'tabs',
119
            ],
120
        ]);
121
    }
122
123
    /**
124
     * {@inheritdoc}
125
     */
126 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...
127
    {
128
        $fields = $this->removeNonUpdateFields($request, $this->resolveFields($request));
129
130
        return new FieldCollection([
131
            'Tabs' => [
132
                'panel' => Panel::defaultNameForUpdate($request->newResource()),
133
                'fields' => $this->translationsFields($fields, true),
134
                'component' => 'tabs',
135
            ],
136
        ]);
137
    }
138
139
    /**
140
     * {@inheritdoc}
141
     */
142
    protected function removeNonUpdateFields(NovaRequest $request, FieldCollection $fields)
143
    {
144
        // Here we override this to keep ID field
145
        return $fields->reject(function ($field) use ($request) {
146
            return
147
                $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...
148
                $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...
149
                $field->attribute === 'ComputedField' ||
150
                ! $field->isShownOnUpdate($request, $this->resource);
151
        });
152
    }
153
154
    // --------------------------------------------------------------------------------
155
    // --------------------------------------------------------------------------------
156
    // --------------------------------------------------------------------------------
157
158
    /**
159
     * Transform fields to handle translation system.
160
     *
161
     * @param  \Laravel\Nova\Fields\FieldCollection  $fields
162
     * @param  bool  $forceReadonlyIds
163
     * @return \Laravel\Nova\Fields\FieldCollection
164
     * @throws \Exception
165
     */
166
    protected function translationsFields(FieldCollection $fields, $forceReadonlyIds = false)
167
    {
168
        $translationsFields = [];
169
170
        $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...
171
        $translations = $this->getResourceTranslations($locales);
172
173
        foreach ($locales as $locale) {
174
            /** @var \BBSLab\NovaTranslation\Models\Locale $locale */
175
            $localeResource = $translations->where('locale_id', '=', $locale->id)->first();
176
            if (empty($localeResource)) {
177
                throw new Exception('Invalid locale resource for "'.$locale->label.'"');
178
            }
179
180
            foreach ($fields as $field) {
181
                /** @var \Laravel\Nova\Fields\Field $field */
182
                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...
183
                    $field->readonly();
184
                }
185
                $translationsFields[] = $this->translationField($field, $locale, $localeResource);
186
            }
187
        }
188
189
        return new FieldCollection($translationsFields);
190
    }
191
192
    /**
193
     * Override field to handle translation system.
194
     *
195
     * @param  \Laravel\Nova\Fields\Field  $field
196
     * @param  \BBSLab\NovaTranslation\Models\Locale  $locale
197
     * @param  \Illuminate\Database\Eloquent\Model  $localeResource
198
     * @return void
199
     */
200
    protected function translationField(Field $field, Locale $locale, Model $localeResource)
201
    {
202
        $cloneField = clone $field;
203
204
        // @TODO... Debug $field->resolve()
205
        // $value = ($cloneField instanceof Resolvable) ? $cloneField->resolve($localeResource) : $localeResource->{$cloneField->attribute};
206
        $value = $localeResource->{$cloneField->attribute};
207
208
        $cloneField->panel = $this->translationsPanelName();
209
        $cloneField->value = $value;
210
        $cloneField->attribute = $cloneField->attribute.'['.$locale->id.']';
211
        $cloneField->withMeta([
212
            'tab' => $locale->label,
213
            'localeId' => $locale->id,
214
            'localeValue' => $value,
215
        ]);
216
217
        return $cloneField;
218
    }
219
220
    /**
221
     * Return resource translations.
222
     *
223
     * @param  \Illuminate\Database\Eloquent\Collection  $locales
224
     * @return \Illuminate\Database\Eloquent\Collection
225
     */
226
    protected function getResourceTranslations(Collection $locales)
227
    {
228
        $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...
229
            ->select('translation_id')
230
            ->where('translatable_id', '=', $this->resource->getKey())
231
            ->where('translatable_type', '=', get_class($this->resource))
232
            ->first();
233
234
        if (empty($baseTranslation)) {
235
            $translationId = $this->resource->freshTranslationId();
236
            $translations = new Collection();
237
            foreach ($locales as $locale) {
238
                /** @var \BBSLab\NovaTranslation\Models\Locale $locale */
239
                $translation = new $this->resource;
240
                $translation->locale_id = $locale->id;
241
                $translation->translation_id = $translationId;
242
                $translations->push($translation);
243
            }
244
        } else {
245
            $translations = $this->resource->translations();
246
        }
247
248
        return $translations;
249
    }
250
251
    // --------------------------------------------------------------------------------
252
    // --------------------------------------------------------------------------------
253
    // --------------------------------------------------------------------------------
254
255
    /**
256
     * {@inheritdoc}
257
     */
258
    public static function indexQuery(NovaRequest $request, $query)
259
    {
260
        return $query->locale();
261
    }
262
263
    /**
264
     * {@inheritdoc}
265
     */
266
    public static function scoutQuery(NovaRequest $request, $query)
267
    {
268
        return $query;
269
    }
270
271
    /**
272
     * {@inheritdoc}
273
     */
274
    public static function detailQuery(NovaRequest $request, $query)
275
    {
276
        return parent::detailQuery($request, $query);
277
    }
278
279
    /**
280
     * {@inheritdoc}
281
     */
282
    public static function relatableQuery(NovaRequest $request, $query)
283
    {
284
        return parent::relatableQuery($request, $query);
285
    }
286
}
287