Passed
Push — ft/field-contract ( 898325 )
by Ben
10:44
created

AbstractManager   B

Complexity

Total Complexity 43

Size/Duplication

Total Lines 288
Duplicated Lines 0 %

Importance

Changes 7
Bugs 3 Features 0
Metric Value
wmc 43
eloc 97
c 7
b 3
f 0
dl 0
loc 288
rs 8.96

24 Methods

Rating   Name   Duplication   Size   Complexity  
A route() 0 21 2
A guard() 0 7 2
A fieldsWithAssistantFields() 0 13 3
A can() 0 10 3
A fieldArrangement() 0 3 1
A fields() 0 3 1
A __construct() 0 11 1
A storeRequest() 0 3 1
A validateConstraints() 0 4 2
A updateRequest() 0 3 1
A filters() 0 3 1
A bootTraitMethods() 0 16 5
A requestContainsTranslations() 0 3 1
A managerKey() 0 3 1
A hasExistingModel() 0 3 2
A indexSorting() 0 12 4
A delete() 0 13 3
A indexPagination() 0 9 1
A findManaged() 0 5 1
A manage() 0 5 1
A indexCollection() 0 16 2
A existingModel() 0 7 2
A modelInstance() 0 5 1
A indexBuilder() 0 3 1

How to fix   Complexity   

Complex Class

Complex classes like AbstractManager often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use AbstractManager, and based on these observations, apply Extract Interface, too.

1
<?php declare(strict_types=1);
2
3
namespace Thinktomorrow\Chief\Management;
4
5
use Illuminate\Support\Facades\Schema;
6
use Illuminate\Contracts\Pagination\Paginator;
7
use Illuminate\Database\Eloquent\Builder;
8
use Illuminate\Http\Request;
9
use Thinktomorrow\Chief\Concerns\Translatable\TranslatableCommand;
10
use Thinktomorrow\Chief\Fields\FieldArrangement;
11
use Thinktomorrow\Chief\Fields\Fields;
12
use Thinktomorrow\Chief\Fields\RenderingFields;
13
use Thinktomorrow\Chief\Fields\SavingFields;
14
use Thinktomorrow\Chief\Filters\Filters;
15
use Thinktomorrow\Chief\Management\Assistants\ManagesAssistants;
16
use Thinktomorrow\Chief\Management\Details\HasDetails;
17
use Thinktomorrow\Chief\Management\Details\HasSections;
18
use Thinktomorrow\Chief\Management\Exceptions\NonExistingRecord;
19
use Thinktomorrow\Chief\Management\Exceptions\NotAllowedManagerRoute;
20
use Thinktomorrow\Chief\Relations\ActsAsChild;
21
use Thinktomorrow\Chief\Relations\ActsAsParent;
22
23
abstract class AbstractManager
24
{
25
    use RenderingFields,
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...
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...
26
        SavingFields,
27
        HasDetails,
28
        HasSections,
29
        ManagesMedia,
30
        ManagesPagebuilder,
31
        TranslatableCommand,
32
        ManagesAssistants;
33
34
    protected $translation_columns = [];
35
36
    protected $model;
37
38
    /** @var Register */
39
    protected $registration;
40
41
    protected $pageCount = 20;
42
    protected $paginated = true;
43
    protected static $bootedTraitMethods = [];
44
45
    final public function __construct(Registration $registration)
46
    {
47
        $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...
48
49
        // Upon instantiation, a general model is set that doesn't point to a persisted record.
50
        $this->manage(app($this->registration->model()));
51
52
        // Check if key and model are present since the model should be set by the manager itself
53
        $this->validateConstraints();
54
55
        static::bootTraitMethods();
56
    }
57
58
    public function managerKey(): string
59
    {
60
        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

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

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

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

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

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

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

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

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

219
            $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

219
            $fields = $fields->merge($this->assistant(/** @scrutinizer ignore-type */ $assistantClass)->fields());
Loading history...
220
        }
221
222
        return $fields;
223
    }
224
225
    /**
226
     * This determines the arrangement of the manageable fields
227
     * on the create and edit forms. By default, all fields
228
     * are presented in their order of appearance
229
     *
230
     * @param null $key pinpoint to a specific field arrangement e.g. for create page.
0 ignored issues
show
Documentation Bug introduced by
Are you sure the doc-type for parameter $key is correct as it would always require null to be passed?
Loading history...
231
     * @return FieldArrangement
232
     * @throws \Exception
233
     */
234
    public function fieldArrangement($key = null): FieldArrangement
235
    {
236
        return new FieldArrangement($this->fieldsWithAssistantFields());
237
    }
238
239
    public function delete()
240
    {
241
        $this->guard('delete');
242
243
        if ($this->model instanceof ActsAsChild) {
244
            $this->model->detachAllParentRelations();
245
        }
246
247
        if ($this->model instanceof ActsAsParent) {
248
            $this->model->detachAllChildRelations();
249
        }
250
251
        $this->model->delete();
252
    }
253
254
    public static function filters(): Filters
255
    {
256
        return new Filters();
257
    }
258
259
    /**
260
     * This method can be used to manipulate the store request payload
261
     * before being passed to the storing / updating the models.
262
     *
263
     * @param Request $request
264
     * @return Request
265
     */
266
    public function storeRequest(Request $request): Request
267
    {
268
        return $request;
269
    }
270
271
    /**
272
     * This method can be used to manipulate the update request payload
273
     * before being passed to the storing / updating the models.
274
     *
275
     * @param Request $request
276
     * @return Request
277
     */
278
    public function updateRequest(Request $request): Request
279
    {
280
        return $request;
281
    }
282
283
    protected function requestContainsTranslations(Request $request): bool
284
    {
285
        return $request->has('trans');
286
    }
287
288
    protected function validateConstraints()
289
    {
290
        if (!$this->model) {
291
            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.');
292
        }
293
    }
294
295
    public static function bootTraitMethods()
296
    {
297
        $class = static::class;
298
299
        $methods = [
300
            'can'
301
        ];
302
303
        foreach ($methods as $baseMethod) {
304
            static::$bootedTraitMethods[$baseMethod] = [];
305
306
            foreach (class_uses_recursive($class) as $trait) {
307
                $method = class_basename($trait) . ucfirst($baseMethod);
308
309
                if (method_exists($class, $method) && ! in_array($method, static::$bootedTraitMethods[$baseMethod])) {
310
                    static::$bootedTraitMethods[$baseMethod][] = lcfirst($method);
311
                }
312
            }
313
        }
314
    }
315
}
316