Passed
Push — ft/pagefield ( db2ad6...f2722b )
by Ben
10:27
created

AbstractManager::updateRequest()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 1
CRAP Score 1

Importance

Changes 0
Metric Value
eloc 1
c 0
b 0
f 0
dl 0
loc 3
ccs 1
cts 1
cp 1
rs 10
cc 1
nc 1
nop 1
crap 1
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\Concerns\Translatable\TranslatableCommand;
12
use Thinktomorrow\Chief\Fields\FieldReference;
13
use Thinktomorrow\Chief\Fields\Fields;
14
use Thinktomorrow\Chief\Fields\SavingFields;
15
use Thinktomorrow\Chief\Fields\Types\Field;
16
use Thinktomorrow\Chief\Filters\Filters;
17
use Thinktomorrow\Chief\Fragments\ManagesFragments;
18
use Thinktomorrow\Chief\Management\Assistants\ManagesAssistants;
19
use Thinktomorrow\Chief\Management\Details\HasDetails;
20
use Thinktomorrow\Chief\Management\Details\HasDetailSections;
21
use Thinktomorrow\Chief\Management\Exceptions\NonExistingRecord;
22
use Thinktomorrow\Chief\Management\Exceptions\NotAllowedManagerRoute;
23
use Thinktomorrow\Chief\Relations\ActsAsChild;
24
use Thinktomorrow\Chief\Relations\ActsAsParent;
25
26
abstract class AbstractManager
27
{
28
    use SavingFields;
29
    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...
30
    use HasDetailSections;
31
    use ManagesMedia;
32
    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, $slug, $page_id, $id
Loading history...
33
    use TranslatableCommand;
34
    use ManagesAssistants;
35
    use ManagesFragments;
36
37
    protected $translation_columns = [];
38
39
    protected $model;
40
41
    /** @var Register */
42
    protected $registration;
43
44
    protected $pageCount = 20;
45
    protected $paginated = true;
46
    protected static $bootedTraitMethods = [];
47 209
48
    final public function __construct(Registration $registration)
49 209
    {
50
        $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...
51
52 209
        // Upon instantiation, a general model is set that doesn't point to a persisted record.
53
        $this->manage(app($this->registration->model()));
54
55 209
        // Check if key and model are present since the model should be set by the manager itself
56
        $this->validateConstraints();
57 209
58 209
        static::bootTraitMethods();
59
    }
60 16
61
    public function managerKey(): string
62 16
    {
63
        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

63
        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...
64
    }
65 209
66
    public function manage($model): Manager
67 209
    {
68
        $this->model = $model;
69 209
70
        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...
71
    }
72 136
73
    public function findManaged($id): Manager
74 136
    {
75
        $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

75
        $modelInstance = $this->modelInstance()::/** @scrutinizer ignore-call */ where('id', $id)->withoutGlobalScopes()->first();
Loading history...
76 136
77
        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

77
        return (new static(/** @scrutinizer ignore-type */ $this->registration))->manage($modelInstance);
Loading history...
78
    }
79 6
80
    public function indexCollection()
81 6
    {
82
        $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

82
        $builder = ($this->modelInstance())->/** @scrutinizer ignore-call */ query();
Loading history...
83 6
84
        $this->filters()->apply($builder);
85 6
86
        $builder = $this->indexBuilder($builder);
87 6
88
        $builder = $this->indexSorting($builder);
89 6
90 6
        if ($this->paginated) {
91
            return $this->indexPagination($builder);
92
        }
93
94
        return $builder->get()->map(function ($model) {
95
            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

95
            return (new static(/** @scrutinizer ignore-type */ $this->registration))->manage($model);
Loading history...
96
        });
97
    }
98 6
99
    protected function indexBuilder(Builder $builder): Builder
100 6
    {
101
        return $builder;
102
    }
103 6
104
    protected function indexSorting(Builder $builder): Builder
105 6
    {
106
        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

106
        if ($this->isAssistedBy('publish') && Schema::hasColumn($this->modelInstance()->/** @scrutinizer ignore-call */ getTable(), 'published_at')) {
Loading history...
107
            $builder->orderBy('published_at', 'DESC');
108
        }
109
110 6
        // if model has no timestamps, updated_at doesn't exist
111 6
        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...
112
            $builder->orderBy('updated_at', 'DESC');
113
        }
114 6
115
        return $builder;
116
    }
117 6
118
    protected function indexPagination($builder): Paginator
119 6
    {
120
        $paginator = $builder->paginate($this->pageCount);
121
122 4
        $modifiedCollection = $builder->paginate($this->pageCount)->getCollection()->transform(function ($model) {
123 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

123
            return (new static(/** @scrutinizer ignore-type */ $this->registration))->manage($model);
Loading history...
124
        });
125 6
126
        return $paginator->setCollection($modifiedCollection);
127
    }
128 188
129
    public function modelInstance(): ManagedModel
130 188
    {
131
        $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

131
        /** @scrutinizer ignore-call */ 
132
        $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...
132 188
133
        return new $class();
134
    }
135 167
136
    public function existingModel(): ManagedModel
137 167
    {
138 3
        if (!$this->hasExistingModel()) {
139
            throw new NonExistingRecord('Model does not exist yet but is expected.');
140
        }
141 165
142
        return $this->model;
143
    }
144 189
145
    public function hasExistingModel(): bool
146 189
    {
147
        return ($this->model && $this->model->exists);
148
    }
149
150
    /**
151
     * Determine which actions should be available for this
152
     * manager and their respective routed urls.
153
     *
154
     * @param $verb
155
     * @return null|string
156
     * @throws NonExistingRecord
157 162
     */
158
    public function route($verb): ?string
159
    {
160 162
        $routes = [
161 162
            'index'  => route('chief.back.managers.index', [$this->registration->key()]),
162 162
            'create' => route('chief.back.managers.create', [$this->registration->key()]),
163
            'store'  => route('chief.back.managers.store', [$this->registration->key()]),
164
        ];
165 162
166 80
        if (array_key_exists($verb, $routes)) {
167
            return $routes[$verb] ?? null;
168
        }
169
170
        //These routes expect the model to be persisted in the database
171 138
        $modelRoutes = [
172 137
            '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...
173 137
            'update' => route('chief.back.managers.update', [$this->registration->key(), $this->existingModel()->id]),
174 137
            'delete' => route('chief.back.managers.delete', [$this->registration->key(), $this->existingModel()->id]),
175 137
            'upload' => route('chief.back.managers.media.upload', [
176 137
                $this->registration->key(),
177
                $this->existingModel()->id,
178
            ]),
179
        ];
180 137
181
        return $modelRoutes[$verb] ?? null;
182
    }
183 172
184
    public function can($verb): bool
185 172
    {
186 8
        foreach (static::$bootedTraitMethods['can'] as $method) {
187
            if (!method_exists($this, $method)) {
188
                continue;
189 8
            }
190
            $this->$method($verb);
191
        }
192 168
193
        return !is_null($this->route($verb));
194
    }
195 158
196
    public function guard($verb): Manager
197 158
    {
198 5
        if (!$this->can($verb)) {
199
            NotAllowedManagerRoute::notAllowedVerb($verb, $this);
200
        }
201 153
202
        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...
203
    }
204 87
205
    public function fields(): Fields
206 87
    {
207
        return new Fields();
208
    }
209
210
    /**
211
     * Enrich the manager fields with any of the assistant specified fields
212
     *
213
     * @return Fields
214
     * @throws \Exception
215 141
     */
216
    public function fieldsWithAssistantFields(): Fields
217 141
    {
218
        $fields = $this->fields();
219 141
220 114
        foreach ($this->assistantsAsClassNames() as $assistantClass) {
221 112
            if (!method_exists($assistantClass, 'fields')) {
222
                continue;
223
            }
224 114
225
            $fields = $fields->merge($this->assistant($assistantClass)->fields());
0 ignored issues
show
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

225
            $fields = $fields->merge($this->assistant(/** @scrutinizer ignore-type */ $assistantClass)->fields());
Loading history...
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

225
            $fields = $fields->merge($this->assistant($assistantClass)->/** @scrutinizer ignore-call */ fields());
Loading history...
226
        }
227 141
228
        return $fields;
229
    }
230
231
    public function createFields(): Fields
232
    {
233
        return $this->fieldsWithAssistantFields();
234
    }
235
236
    public function editFields(): Fields
237
    {
238
        return $this->fieldsWithAssistantFields()->map(function (Field $field) {
239 4
            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

239
            return $field->/** @scrutinizer ignore-call */ model($this->model);
Loading history...
240
        });
241 4
    }
242
243
    public function createView(): string
244 4
    {
245
        return 'chief::back.managers._partials._form';
246 4
    }
247
248 3
    public function createViewData(): array
249 3
    {
250
        return [];
251
    }
252 3
253 3
    public function editView(): string
254
    {
255
        return 'chief::back.managers._partials._form';
256 3
    }
257 3
258
    public function editViewData(): array
259 3
    {
260
        return [];
261 3
    }
262
263
    public function delete()
264
    {
265
        $this->guard('delete');
266
267
        if ($this->model instanceof ActsAsChild) {
268
            $this->model->detachAllParentRelations();
269
        }
270
271 26
        if ($this->model instanceof ActsAsParent) {
272
            $this->model->detachAllChildRelations();
273 26
        }
274
275
        $this->model->delete();
276
    }
277
278
    public static function filters(): Filters
279
    {
280
        return new Filters();
281
    }
282
283 24
    /**
284
     * This method can be used to manipulate the store request payload
285 24
     * before being passed to the storing / updating the models.
286
     *
287
     * @param Request $request
288 81
     * @return Request
289
     */
290 81
    public function storeRequest(Request $request): Request
291
    {
292
        return $request;
293 209
    }
294
295 209
    /**
296
     * This method can be used to manipulate the update request payload
297
     * before being passed to the storing / updating the models.
298 209
     *
299
     * @param Request $request
300 209
     * @return Request
301
     */
302 209
    public function updateRequest(Request $request): Request
303
    {
304
        return $request;
305 209
    }
306
307
    protected function requestContainsTranslations(Request $request): bool
308 209
    {
309 209
        return $request->has('trans');
310
    }
311 209
312 209
    protected function validateConstraints()
313
    {
314 209
        if (!$this->model) {
315 209
            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.');
316
        }
317
    }
318
319 209
    public static function bootTraitMethods()
320
    {
321
        $class = static::class;
322
323
        $methods = [
324
            'can',
325
        ];
326
327
        foreach ($methods as $baseMethod) {
328
            static::$bootedTraitMethods[$baseMethod] = [];
329
330
            foreach (class_uses_recursive($class) as $trait) {
331
                $method = class_basename($trait) . ucfirst($baseMethod);
332
333
                if (method_exists($class, $method) && !in_array($method, static::$bootedTraitMethods[$baseMethod])) {
334
                    static::$bootedTraitMethods[$baseMethod][] = lcfirst($method);
335
                }
336
            }
337
        }
338
    }
339
}
340