Completed
Push — master ( ef0263...372073 )
by
unknown
10:11
created

TranslatableResource::translationsFields()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 21

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 21
rs 9.584
c 0
b 0
f 0
cc 4
nc 4
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 Closure;
8
use Eminiarts\Tabs\TabsOnEdit;
9
use Exception;
10
use Illuminate\Database\Eloquent\Collection;
11
use Illuminate\Database\Eloquent\Model;
12
use Laravel\Nova\Contracts\Resolvable;
13
use Laravel\Nova\Fields\Field;
14
use Laravel\Nova\Fields\FieldCollection;
15
use Laravel\Nova\Http\Requests\NovaRequest;
16
use Laravel\Nova\Panel;
17
use Laravel\Nova\Resource;
18
19
abstract class TranslatableResource extends Resource
20
{
21
    use TabsOnEdit;
22
23
    const PANEL_TRANSLATIONS = 'Translations';
24
25
    /**
26
     * Return resource translations.
27
     *
28
     * @return \Illuminate\Database\Eloquent\Collection
29
     */
30
    protected function getResourceTranslations()
31
    {
32
        $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...
33
            ->select('translation_id')
34
            ->where('translatable_id', '=', $this->resource->getKey())
35
            ->where('translatable_type', '=', get_class($this->resource))
36
            ->first();
37
38
        if (empty($baseTranslation)) {
39
            $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...
40
            $translations = new Collection();
41
            foreach ($this->indexedLocales as $localeId => $locale) {
42
                // @TODO... Instantiate new model (maybe with nonTranslatable() already filled in + "locale_id" and "translation_id")
43
            }
44
        } else {
45
            $translations = $this->resource->translations();
46
        }
47
48
        return $translations;
49
    }
50
51
    // --------------------------------------------------------------------------------
52
    // --------------------------------------------------------------------------------
53
    // --------------------------------------------------------------------------------
54
55
    /**
56
     * {@inheritdoc}
57
     */
58
    public function availablePanelsForDetail($request)
59
    {
60
        $panels = parent::availablePanelsForDetail($request);
61
62
        $panels[] = $this->translationsPanel('detail-tabs');
63
64
        return $panels;
65
    }
66
67
    /**
68
     * {@inheritdoc}
69
     */
70
    public function availablePanelsForUpdate($request)
71
    {
72
        $panels = parent::availablePanelsForUpdate($request);
73
74
        $panels[] = $this->translationsPanel('tabs');
75
76
        return $panels;
77
    }
78
79
    /**
80
     * Return configured translations panel.
81
     *
82
     * @param  string  $component
83
     * @return \Laravel\Nova\Panel
84
     */
85
    protected function translationsPanel(string $component = 'detail-tabs')
86
    {
87
        $panelTranslations = new Panel(static::PANEL_TRANSLATIONS);
88
89
        $panelTranslations->withToolbar();
90
        $panelTranslations->withMeta([
91
            'component' => $component,
92
            'defaultSearch' => $this->defaultSearch,
93
        ]);
94
95
        return $panelTranslations;
96
    }
97
98
    // --------------------------------------------------------------------------------
99
    // --------------------------------------------------------------------------------
100
    // --------------------------------------------------------------------------------
101
102
    /**
103
     * {@inheritdoc}
104
     */
105
    protected function resolveFields(NovaRequest $request, Closure $filter = null)
106
    {
107
        $fields = parent::resolveFields($request, $filter);
108
109
        $fields = $this->translationsFields($fields);
110
111
        return $fields;
112
    }
113
114
    /**
115
     * Transform fields to handle translation system.
116
     *
117
     * @param  \Laravel\Nova\Fields\FieldCollection  $fields
118
     * @return \Laravel\Nova\Fields\FieldCollection
119
     * @throws \Exception
120
     */
121
    protected function translationsFields(FieldCollection $fields)
122
    {
123
        $translationsFields = [];
124
125
        $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...
126
        $translations = $this->getResourceTranslations();
127
128
        foreach ($locales as $locale) {
129
            /** @var \BBSLab\NovaTranslation\Models\Locale $locale */
130
            $localeResource = $translations->where('locale_id', '=', $locale->id)->first();
131
            if (empty($localeResource)) {
132
                throw new Exception('Invalid locale resource for "'.$locale->label.'"');
133
            }
134
135
            foreach ($fields as $field) {
136
                $translationsFields[] = $this->translationField($field, $locale, $localeResource);
137
            }
138
        }
139
140
        return new FieldCollection($translationsFields);
141
    }
142
143
    /**
144
     * Override field to handle translation system.
145
     *
146
     * @param  \Laravel\Nova\Fields\Field  $field
147
     * @param  \BBSLab\NovaTranslation\Models\Locale  $locale
148
     * @param  \Illuminate\Database\Eloquent\Model  $localeResource
149
     * @return void
150
     */
151
    protected function translationField(Field $field, Locale $locale, Model $localeResource)
152
    {
153
        $cloneField = clone $field;
154
155
        // @TODO... Use Field resolve()??
156
        // Compute value (resolve() on detail AND direct attribute on update)
157
        // $value = ($field instanceof Resolvable) ? $field->resolve($localeResource) : $localeResource->{$field->attribute};
158
        dump($field->attribute);
159
        dump($localeResource->toArray());
160
        $value = $localeResource->{$field->attribute};
161
        dump($value);
162
163
        $cloneField->panel = static::PANEL_TRANSLATIONS;
164
        $cloneField->value = $value;
165
        $cloneField->attribute = $cloneField->attribute.'['.$locale->id.']';
166
        $cloneField->withMeta([
167
            'tab' => $locale->label,
168
            'locale' => $locale->id,
169
        ]);
170
171
        return $cloneField;
172
    }
173
174
    // --------------------------------------------------------------------------------
175
    // --------------------------------------------------------------------------------
176
    // --------------------------------------------------------------------------------
177
178
    /**
179
     * {@inheritdoc}
180
     */
181
    public static function indexQuery(NovaRequest $request, $query)
182
    {
183
        return $query->locale();
184
    }
185
186
    /**
187
     * {@inheritdoc}
188
     */
189
    public static function scoutQuery(NovaRequest $request, $query)
190
    {
191
        return $query;
192
    }
193
194
    /**
195
     * {@inheritdoc}
196
     */
197
    public static function detailQuery(NovaRequest $request, $query)
198
    {
199
        return parent::detailQuery($request, $query);
200
    }
201
202
    /**
203
     * {@inheritdoc}
204
     */
205
    public static function relatableQuery(NovaRequest $request, $query)
206
    {
207
        return parent::relatableQuery($request, $query);
208
    }
209
}
210