Test Setup Failed
Push — master ( bf4a35...908938 )
by Ben
23:24 queued 15:29
created

AbstractManager::saveCreateFields()   A

Complexity

Conditions 3
Paths 2

Size

Total Lines 7
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 3

Importance

Changes 0
Metric Value
eloc 3
c 0
b 0
f 0
dl 0
loc 7
ccs 4
cts 4
cp 1
rs 10
cc 3
nc 2
nop 1
crap 3
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Thinktomorrow\Chief\Management;
6
7
use Illuminate\Support\Facades\Schema;
8
use Illuminate\Contracts\Pagination\Paginator;
9
use Illuminate\Database\Eloquent\Builder;
10
use Illuminate\Http\Request;
11
use Thinktomorrow\Chief\Fields\Types\NumberField;
12
use Thinktomorrow\Chief\Concerns\Translatable\TranslatableCommand;
13
use Thinktomorrow\Chief\Fields\FieldReference;
14
use Thinktomorrow\Chief\Fields\Fields;
15
use Thinktomorrow\Chief\Fields\SavingFields;
16
use Thinktomorrow\Chief\Fields\Types\Field;
17
use Thinktomorrow\Chief\Filters\Filters;
18
use Thinktomorrow\Chief\Fragments\ManagesFragments;
19
use Thinktomorrow\Chief\Management\Assistants\ManagesAssistants;
20
use Thinktomorrow\Chief\Management\Details\HasDetails;
21
use Thinktomorrow\Chief\Management\Details\HasDetailSections;
22
use Thinktomorrow\Chief\Management\Exceptions\NonExistingRecord;
23
use Thinktomorrow\Chief\Management\Exceptions\NotAllowedManagerRoute;
24
use Thinktomorrow\Chief\Relations\ActsAsChild;
25
use Thinktomorrow\Chief\Relations\ActsAsParent;
26
27
abstract class AbstractManager
28
{
29
    use SavingFields;
30
    use HasDetails;
0 ignored issues
show
introduced by
The trait Thinktomorrow\Chief\Management\Details\HasDetails requires some properties which are not provided by Thinktomorrow\Chief\Management\AbstractManager: $labelPlural, $id, $labelSingular, $title
Loading history...
31
    use HasDetailSections;
32
    use ManagesMedia;
33
    use ManagesPagebuilder;
0 ignored issues
show
introduced by
The trait Thinktomorrow\Chief\Management\ManagesPagebuilder requires some properties which are not provided by Thinktomorrow\Chief\Management\AbstractManager: $trans, $relation, $owner_id, $slug, $id
Loading history...
34
    use TranslatableCommand;
35
    use ManagesAssistants;
36
    use ManagesFragments;
37
38
    protected $translation_columns = [];
39
40
    protected $model;
41
42
    /** @var Register */
43
    protected $registration;
44 169
45
    protected $pageCount = 20;
46 169
    protected $paginated = true;
47
    protected static $bootedTraitMethods = [];
48
49 169
    final public function __construct(Registration $registration)
50
    {
51
        $this->registration = $registration;
0 ignored issues
show
Documentation Bug introduced by
It seems like $registration of type Thinktomorrow\Chief\Management\Registration is incompatible with the declared type Thinktomorrow\Chief\Management\Register of property $registration.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
52 169
53
        // Upon instantiation, a general model is set that doesn't point to a persisted record.
54 169
        $this->manage(app($this->registration->model()));
55 169
56
        // Check if key and model are present since the model should be set by the manager itself
57 169
        $this->validateConstraints();
58
59 169
        static::bootTraitMethods();
60
    }
61 169
62
    public function managerKey(): string
63
    {
64 98
        return $this->registration->key();
0 ignored issues
show
Bug introduced by
The method key() does not exist on Thinktomorrow\Chief\Management\Register. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

64
        return $this->registration->/** @scrutinizer ignore-call */ key();

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
65
    }
66 98
67
    public function manage($model): Manager
68 98
    {
69
        $this->model = $model;
70 98
71
        return $this;
0 ignored issues
show
Bug Best Practice introduced by
The expression return $this returns the type Thinktomorrow\Chief\Management\AbstractManager which is incompatible with the type-hinted return Thinktomorrow\Chief\Management\Manager.
Loading history...
72
    }
73 6
74
    public function isManualSortable(): bool
75 6
    {
76
        return (isset($this->useManualSorting) && $this->useManualSorting && method_exists($this->modelInstance(), 'scopeSortedManually'));
77 6
    }
78
79 6
    public function saveCreateFields(Request $request): void
80
    {
81 6
        if($this->isManualSortable() && !$request->has('order')) {
82
            $this->model->order = $this->modelInstance()::orderBy('order', 'desc')->first()->order + 1;
0 ignored issues
show
Bug introduced by
The method orderBy() does not exist on Thinktomorrow\Chief\Management\ManagedModel. Since it exists in all sub-types, consider adding an abstract or default implementation to Thinktomorrow\Chief\Management\ManagedModel. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

82
            $this->model->order = $this->modelInstance()::/** @scrutinizer ignore-call */ orderBy('order', 'desc')->first()->order + 1;
Loading history...
83 6
        }
84
85 6
        $this->saveFields($request, $this->createFields());
86 6
    }
87
88
    public function findManaged($id): Manager
89
    {
90
        $modelInstance = $this->modelInstance()::where('id', $id)->withoutGlobalScopes()->first();
0 ignored issues
show
Bug introduced by
The method where() does not exist on Thinktomorrow\Chief\Management\ManagedModel. Since it exists in all sub-types, consider adding an abstract or default implementation to Thinktomorrow\Chief\Management\ManagedModel. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

90
        $modelInstance = $this->modelInstance()::/** @scrutinizer ignore-call */ where('id', $id)->withoutGlobalScopes()->first();
Loading history...
91
92
        return (new static($this->registration))->manage($modelInstance);
0 ignored issues
show
Bug introduced by
$this->registration of type Thinktomorrow\Chief\Management\Register is incompatible with the type Thinktomorrow\Chief\Management\Registration expected by parameter $registration of Thinktomorrow\Chief\Mana...tManager::__construct(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

92
        return (new static(/** @scrutinizer ignore-type */ $this->registration))->manage($modelInstance);
Loading history...
93
    }
94 6
95
    public function indexCollection()
96 6
    {
97
        $builder = ($this->modelInstance())->query();
0 ignored issues
show
Bug introduced by
The method query() does not exist on Thinktomorrow\Chief\Management\ManagedModel. Since it exists in all sub-types, consider adding an abstract or default implementation to Thinktomorrow\Chief\Management\ManagedModel. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

97
        $builder = ($this->modelInstance())->/** @scrutinizer ignore-call */ query();
Loading history...
98
99 6
        $this->filters()->apply($builder);
100
101 6
        $builder = $this->indexBuilder($builder);
102 3
103
        $builder = $this->indexSorting($builder);
104
105
        if ($this->paginated) {
106 6
            return $this->indexPagination($builder);
107 6
        }
108
109
        return $builder->get()->map(function ($model) {
110 6
            return (new static($this->registration))->manage($model);
0 ignored issues
show
Bug introduced by
$this->registration of type Thinktomorrow\Chief\Management\Register is incompatible with the type Thinktomorrow\Chief\Management\Registration expected by parameter $registration of Thinktomorrow\Chief\Mana...tManager::__construct(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

110
            return (new static(/** @scrutinizer ignore-type */ $this->registration))->manage($model);
Loading history...
111
        });
112
    }
113 6
114
    protected function indexBuilder(Builder $builder): Builder
115 6
    {
116
        return $builder;
117
    }
118 4
119 6
    protected function indexSorting(Builder $builder): Builder
120
    {
121 6
        if($this->isManualSortable()) {
122
            $builder->sortedManually();
123
        }
124 106
125
        if ($this->isAssistedBy('publish') && Schema::hasColumn($this->modelInstance()->getTable(), 'published_at')) {
0 ignored issues
show
Bug introduced by
The method getTable() does not exist on Thinktomorrow\Chief\Management\ManagedModel. Since it exists in all sub-types, consider adding an abstract or default implementation to Thinktomorrow\Chief\Management\ManagedModel. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

125
        if ($this->isAssistedBy('publish') && Schema::hasColumn($this->modelInstance()->/** @scrutinizer ignore-call */ getTable(), 'published_at')) {
Loading history...
126 106
            $builder->orderBy('published_at', 'DESC');
127
        }
128
129 119
        // if model has no timestamps, updated_at doesn't exist
130
        if ($this->modelInstance()->timestamps) {
0 ignored issues
show
Bug introduced by
Accessing timestamps on the interface Thinktomorrow\Chief\Management\ManagedModel suggest that you code against a concrete implementation. How about adding an instanceof check?
Loading history...
131 119
            $builder->orderBy('updated_at', 'DESC');
132
        }
133
134
        return $builder;
135
    }
136
137
    protected function indexPagination($builder): Paginator
138
    {
139
        $paginator = $builder->paginate($this->pageCount);
140 119
141
        $modifiedCollection = $builder->paginate($this->pageCount)->getCollection()->transform(function ($model) {
142 119
            return (new static($this->registration))->manage($model);
0 ignored issues
show
Bug introduced by
$this->registration of type Thinktomorrow\Chief\Management\Register is incompatible with the type Thinktomorrow\Chief\Management\Registration expected by parameter $registration of Thinktomorrow\Chief\Mana...tManager::__construct(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

142
            return (new static(/** @scrutinizer ignore-type */ $this->registration))->manage($model);
Loading history...
143 1
        });
144
145
        return $paginator->setCollection($modifiedCollection);
146 118
    }
147
148
    public function indexView(): string
149
    {
150
        return 'chief::back.managers._partials._rowitems';
151
    }
152
153
    public function indexViewData(): array
154
    {
155
        return [];
156
    }
157 130
158
    public function modelInstance(): ManagedModel
159
    {
160 130
        $class = $this->registration->model();
0 ignored issues
show
Bug introduced by
The method model() does not exist on Thinktomorrow\Chief\Management\Register. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

160
        /** @scrutinizer ignore-call */ 
161
        $class = $this->registration->model();

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
161 130
162 130
        return new $class();
163
    }
164
165 130
    public function existingModel(): ManagedModel
166 76
    {
167
        if (!$this->hasExistingModel()) {
168
            throw new NonExistingRecord('Model does not exist yet but is expected.');
169
        }
170
171 107
        return $this->model;
0 ignored issues
show
Bug Best Practice introduced by
The expression return $this->model could return the type Illuminate\Contracts\Foundation\Application which is incompatible with the type-hinted return Thinktomorrow\Chief\Management\ManagedModel. Consider adding an additional type-check to rule them out.
Loading history...
172 106
    }
173 106
174 106
    public function hasExistingModel(): bool
175
    {
176
        return ($this->model && $this->model->exists);
177 106
    }
178
179
    /**
180 140
     * Determine which actions should be available for this
181
     * manager and their respective routed urls.
182 140
     *
183 8
     * @param $verb
184
     * @return null|string
185
     * @throws NonExistingRecord
186 8
     */
187
    public function route($verb): ?string
188
    {
189 136
        $routes = [
190
            'index'  => route('chief.back.managers.index', [$this->registration->key()]),
191
            'create' => route('chief.back.managers.create', [$this->registration->key()]),
192 126
            'store'  => route('chief.back.managers.store', [$this->registration->key()]),
193
        ];
194 126
195 5
        if (array_key_exists($verb, $routes)) {
196
            return $routes[$verb] ?? null;
197
        }
198 121
199
        //These routes expect the model to be persisted in the database
200
        $modelRoutes = [
201 87
            'edit'   => route('chief.back.managers.edit', [$this->registration->key(), $this->existingModel()->id]),
0 ignored issues
show
Bug introduced by
Accessing id on the interface Thinktomorrow\Chief\Management\ManagedModel suggest that you code against a concrete implementation. How about adding an instanceof check?
Loading history...
202
            'update' => route('chief.back.managers.update', [$this->registration->key(), $this->existingModel()->id]),
203 87
            'delete' => route('chief.back.managers.delete', [$this->registration->key(), $this->existingModel()->id]),
204
            'upload' => route('chief.back.managers.media.upload', [
205
                $this->registration->key(),
206
                $this->existingModel()->id,
207
            ]),
208
        ];
209
210
        return $modelRoutes[$verb] ?? null;
211
    }
212 111
213
    public function can($verb): bool
214 111
    {
215
        foreach (static::$bootedTraitMethods['can'] as $method) {
216 111
            if (!method_exists($this, $method)) {
217 85
                continue;
218 83
            }
219
            $this->$method($verb);
220
        }
221 85
222
        return !is_null($this->route($verb));
223
    }
224 111
225
    public function guard($verb): Manager
226
    {
227
        if (!$this->can($verb)) {
228
            NotAllowedManagerRoute::notAllowedVerb($verb, $this);
229
        }
230
231
        return $this;
0 ignored issues
show
Bug Best Practice introduced by
The expression return $this returns the type Thinktomorrow\Chief\Management\AbstractManager which is incompatible with the type-hinted return Thinktomorrow\Chief\Management\Manager.
Loading history...
232
    }
233
234
    public function fields(): Fields
235
    {
236 3
        return new Fields();
237
    }
238 3
239
    /**
240
     * Enrich the manager fields with any of the assistant specified fields
241 2
     *
242
     * @return Fields
243 2
     * @throws \Exception
244 2
     */
245
    public function fieldsWithAssistantFields(): Fields
246
    {
247 2
        $fields = $this->fields();
248 2
249
        foreach ($this->assistantsAsClassNames() as $assistantClass) {
250
            if (!method_exists($assistantClass, 'fields')) {
251 2
                continue;
252 2
            }
253
254 3
            $fields = $fields->merge($this->assistant($assistantClass)->fields());
0 ignored issues
show
Bug introduced by
The method fields() does not exist on Thinktomorrow\Chief\Mana...nt\Assistants\Assistant. It seems like you code against a sub-type of Thinktomorrow\Chief\Mana...nt\Assistants\Assistant such as Thinktomorrow\Chief\Mana...Assistants\UrlAssistant or Thinktomorrow\Chief\Test...FakeAssistantWithFields. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

254
            $fields = $fields->merge($this->assistant($assistantClass)->/** @scrutinizer ignore-call */ fields());
Loading history...
Bug introduced by
$assistantClass of type object is incompatible with the type string expected by parameter $assistantKey of Thinktomorrow\Chief\Mana...actManager::assistant(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

254
            $fields = $fields->merge($this->assistant(/** @scrutinizer ignore-type */ $assistantClass)->fields());
Loading history...
255
        }
256 3
257
        return $fields;
258
    }
259
260
    public function createFields(): Fields
261
    {
262
        $fields = $this->fieldsWithAssistantFields();
263
264
        if($this->isManualSortable() && !$fields->offsetExists('order')) {
265
            $fields = $fields->add(NumberField::make('order'));
266 26
        }
267
trap($fields);
268 26
        return $fields;
269
    }
270
271
    public function editFields(): Fields
272
    {
273
        return $this->fieldsWithAssistantFields()->map(function (Field $field) {
274
            return $field->model($this->model);
0 ignored issues
show
Bug introduced by
The method model() does not exist on Thinktomorrow\Chief\Fields\Types\Field. Since it exists in all sub-types, consider adding an abstract or default implementation to Thinktomorrow\Chief\Fields\Types\Field. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

274
            return $field->/** @scrutinizer ignore-call */ model($this->model);
Loading history...
275
        });
276
    }
277
278 24
    public function createView(): string
279
    {
280 24
        return 'chief::back.managers._partials._form';
281
    }
282
283 83
    public function createViewData(): array
284
    {
285 83
        return [];
286
    }
287
288 169
    public function editView(): string
289
    {
290 169
        return 'chief::back.managers._partials._form';
291
    }
292
293 169
    public function editViewData(): array
294
    {
295 169
        return [];
296
    }
297 169
298
    public function delete()
299
    {
300 169
        $this->guard('delete');
301
302
        if ($this->model instanceof ActsAsChild) {
303 169
            $this->model->detachAllParentRelations();
304 169
        }
305
306 169
        if ($this->model instanceof ActsAsParent) {
307 169
            $this->model->detachAllChildRelations();
308
        }
309 169
310 169
        $this->model->delete();
0 ignored issues
show
Bug introduced by
The method delete() does not exist on Illuminate\Contracts\Foundation\Application. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

310
        $this->model->/** @scrutinizer ignore-call */ 
311
                      delete();

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
311
    }
312
313
    public static function filters(): Filters
314 169
    {
315
        return new Filters();
316
    }
317
318
    /**
319
     * This method can be used to manipulate the store request payload
320
     * before being passed to the storing / updating the models.
321
     *
322
     * @param Request $request
323
     * @return Request
324
     */
325
    public function storeRequest(Request $request): Request
326
    {
327
        return $request;
328
    }
329
330
    /**
331
     * This method can be used to manipulate the update request payload
332
     * before being passed to the storing / updating the models.
333
     *
334
     * @param Request $request
335
     * @return Request
336
     */
337
    public function updateRequest(Request $request): Request
338
    {
339
        return $request;
340
    }
341
342
    protected function requestContainsTranslations(Request $request): bool
343
    {
344
        return $request->has('trans');
345
    }
346
347
    protected function validateConstraints()
348
    {
349
        if (!$this->model) {
350
            throw new \DomainException('Model class should be set for this manager. Please set the model property default via the constructor or by extending the setupDefaults method.');
351
        }
352
    }
353
354
    public static function bootTraitMethods()
355
    {
356
        $class = static::class;
357
358
        $methods = [
359
            'can',
360
        ];
361
362
        foreach ($methods as $baseMethod) {
363
            static::$bootedTraitMethods[$baseMethod] = [];
364
365
            foreach (class_uses_recursive($class) as $trait) {
366
                $method = class_basename($trait) . ucfirst($baseMethod);
367
368
                if (method_exists($class, $method) && !in_array($method, static::$bootedTraitMethods[$baseMethod])) {
369
                    static::$bootedTraitMethods[$baseMethod][] = lcfirst($method);
370
                }
371
            }
372
        }
373
    }
374
}
375