Passed
Push — master ( 72cb54...ce8977 )
by Philippe
02:38 queued 14s
created

AbstractManager::bootTraitMethods()   A

Complexity

Conditions 5
Paths 4

Size

Total Lines 16
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 9
CRAP Score 5

Importance

Changes 2
Bugs 1 Features 0
Metric Value
eloc 9
c 2
b 1
f 0
dl 0
loc 16
ccs 9
cts 9
cp 1
rs 9.6111
cc 5
nc 4
nop 0
crap 5
1
<?php
2
3
namespace Thinktomorrow\Chief\Management;
4
5
use Illuminate\Contracts\Pagination\Paginator;
6
use Illuminate\Database\Eloquent\Builder;
7
use Illuminate\Http\Request;
8
use Thinktomorrow\Chief\Concerns\Translatable\TranslatableCommand;
9
use Thinktomorrow\Chief\Fields\FieldArrangement;
10
use Thinktomorrow\Chief\Fields\Fields;
11
use Thinktomorrow\Chief\Fields\RenderingFields;
12
use Thinktomorrow\Chief\Fields\SavingFields;
13
use Thinktomorrow\Chief\Filters\Filters;
14
use Thinktomorrow\Chief\Management\Assistants\AssistedManager;
15
use Thinktomorrow\Chief\Management\Details\HasDetails;
16
use Thinktomorrow\Chief\Management\Details\HasSections;
17
use Thinktomorrow\Chief\Management\Exceptions\NonExistingRecord;
18
use Thinktomorrow\Chief\Management\Exceptions\NotAllowedManagerRoute;
19
20
abstract class AbstractManager
21
{
22
    use RenderingFields,
0 ignored issues
show
Bug introduced by
The trait Thinktomorrow\Chief\Fields\SavingFields requires the property $key which is not provided by Thinktomorrow\Chief\Management\AbstractManager.
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...
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...
23
        SavingFields,
24
        HasDetails,
25
        HasSections,
26
        ManagesMedia,
27
        ManagesPagebuilder,
28
        TranslatableCommand,
29
        AssistedManager;
30
31
    protected $translation_columns = [];
32
33
    protected $model;
34
35
    /** @var Register */
36
    protected $registration;
37
38
    protected $pageCount                 = 20;
39
    protected $paginated                 = true;
40
    protected static $bootedTraitMethods = [];
41
42 162
    public function __construct(Registration $registration)
43
    {
44 162
        $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...
45
46
        // Upon instantiation, a general model is set that doesn't point to a persisted record.
47 162
        $this->manage(app($this->registration->model()));
48
49
        // Check if key and model are present since the model should be set by the manager itself
50 162
        $this->validateConstraints();
51
52 162
        static::bootTraitMethods();
53 162
    }
54
55 162
    public function manage($model): Manager
56
    {
57 162
        $this->model = $model;
58
59 162
        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...
60
    }
61
62 91
    public function findManaged($id): Manager
63
    {
64 91
        $model = $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

64
        /** @scrutinizer ignore-call */ 
65
        $model = $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...
65
66 91
        $modelInstance = $model::where('id', $id)->withoutGlobalScopes()->first();
67
68 91
        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

68
        return (new static(/** @scrutinizer ignore-type */ $this->registration))->manage($modelInstance);
Loading history...
69
    }
70
71 6
    public function indexCollection()
72
    {
73 6
        $model = $this->registration->model();
74
75 6
        $builder = (new $model)->query();
76
77 6
        $this->filters()->apply($builder);
78
79 6
        $builder = $this->indexBuilder($builder);
80
81 6
        $builder = $this->indexSorting($builder);
82
        
83 6
        if ($this->paginated) {
84 6
            return $this->indexPagination($builder);
85
        }
86
        
87
        return $builder->get()->map(function ($model) {
88
            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

88
            return (new static(/** @scrutinizer ignore-type */ $this->registration))->manage($model);
Loading history...
89
        });
90
    }
91
92 6
    protected function indexBuilder(Builder $builder): Builder
93
    {
94 6
        return $builder;
95
    }
96
97 6
    protected function indexSorting(Builder $builder): Builder
98
    {
99 6
        if ($this->isAssistedBy('publish')) {
100 3
            $builder->orderBy('published', 'DESC');
101
        }
102
103
        // if model has no timestamps, updated_at doesn't exist
104 6
        if ($this->model()->timestamps) {
105 6
            $builder->orderBy('updated_at', 'DESC');
106
        }
107
108 6
        return $builder;
109
    }
110
111 6
    protected function indexPagination($builder): Paginator
112
    {
113 6
        $paginator = $builder->paginate($this->pageCount);
114
115
        $modifiedCollection = $builder->paginate($this->pageCount)->getCollection()->transform(function ($model) {
116 4
            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

116
            return (new static(/** @scrutinizer ignore-type */ $this->registration))->manage($model);
Loading history...
117 6
        });
118
119 6
        return $paginator->setCollection($modifiedCollection);
120
    }
121
122 100
    public function model()
123
    {
124 100
        return $this->model;
125
    }
126
127 101
    public function hasExistingModel(): bool
128
    {
129 101
        return ($this->model && $this->model->exists);
130
    }
131
132
    /**
133
     * If the model exists return it otherwise
134
     * throws a nonExistingRecord exception;
135
     *
136
     * @throws NonExistingRecord
137
     */
138 101
    protected function existingModel()
139
    {
140 101
        if (!$this->hasExistingModel()) {
141 1
            throw new NonExistingRecord('Model does not exist yet but is expected.');
142
        }
143
144 100
        return $this->model;
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 124
    public function route($verb): ?string
156
    {
157
        $routes = [
158 124
            'index'   => route('chief.back.managers.index', [$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

158
            'index'   => route('chief.back.managers.index', [$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...
159 124
            'create'  => route('chief.back.managers.create', [$this->registration->key()]),
160 124
            'store'   => route('chief.back.managers.store', [$this->registration->key()]),
161
        ];
162
163 124
        if (array_key_exists($verb, $routes)) {
164 74
            return $routes[$verb] ?? null;
165
        }
166
167
        //These routes expect the model to be persisted in the database
168
        $modelRoutes = [
169 101
            'edit'    => route('chief.back.managers.edit', [$this->registration->key(), $this->existingModel()->id]),
170 100
            'update'  => route('chief.back.managers.update', [$this->registration->key(), $this->existingModel()->id]),
171 100
            'delete'  => route('chief.back.managers.delete', [$this->registration->key(), $this->existingModel()->id]),
172 100
            'upload'  => route('chief.back.managers.media.upload', [$this->registration->key(), $this->existingModel()->id]),
173
        ];
174
175 100
        return $modelRoutes[$verb] ?? null;
176
    }
177
178 134
    public function can($verb): bool
179
    {
180 134
        foreach (static::$bootedTraitMethods['can'] as $method) {
181 8
            $this->$method($verb);
182
        }
183
184 130
        return !is_null($this->route($verb));
185
    }
186
187 120
    public function guard($verb): Manager
188
    {
189 120
        if (! $this->can($verb)) {
190 5
            NotAllowedManagerRoute::notAllowedVerb($verb, $this);
191
        }
192
193 115
        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...
194
    }
195
196 87
    public function fields(): Fields
197
    {
198 87
        return new Fields();
199
    }
200
201
    /**
202
     * Enrich the manager fields with any of the assistant specified fields
203
     *
204
     * @return Fields
205
     * @throws \Exception
206
     */
207 107
    public function fieldsWithAssistantFields(): Fields
208
    {
209 107
        $fields = $this->fields();
210
211 107
        foreach ($this->assistants() as $assistant) {
212 81
            if (! method_exists($assistant, 'fields')) {
213 79
                continue;
214
            }
215
216 81
            $fields = $fields->merge($assistant->fields());
217
        }
218
219 107
        return $fields;
220
    }
221
222
    /**
223
     * This determines the arrangement of the manageable fields
224
     * on the create and edit forms. By default, all fields
225
     * are presented in their order of appearance
226
     *
227
     * @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...
228
     * @return FieldArrangement
229
     * @throws \Exception
230
     */
231 3
    public function fieldArrangement($key = null): FieldArrangement
232
    {
233 3
        return new FieldArrangement($this->fieldsWithAssistantFields());
234
    }
235
236 1
    public function delete()
237
    {
238 1
        $this->model->delete();
239 1
    }
240
241 3
    public static function filters(): Filters
242
    {
243 3
        return new Filters();
244
    }
245
246
    /**
247
     * This method can be used to manipulate the store request payload
248
     * before being passed to the storing / updating the models.
249
     *
250
     * @param Request $request
251
     * @return Request
252
     */
253 26
    public function storeRequest(Request $request): Request
254
    {
255 26
        return $request;
256
    }
257
258
    /**
259
     * This method can be used to manipulate the update request payload
260
     * before being passed to the storing / updating the models.
261
     *
262
     * @param Request $request
263
     * @return Request
264
     */
265 24
    public function updateRequest(Request $request): Request
266
    {
267 24
        return $request;
268
    }
269
270 83
    protected function requestContainsTranslations(Request $request): bool
271
    {
272 83
        return $request->has('trans');
273
    }
274
275 162
    protected function validateConstraints()
276
    {
277 162
        if (!$this->model) {
278
            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.');
279
        }
280 162
    }
281
282 162
    public static function bootTraitMethods()
283
    {
284 162
        $class = static::class;
285
286
        $methods = [
287 162
            'can'
288
        ];
289
290 162
        foreach ($methods as $baseMethod) {
291 162
            static::$bootedTraitMethods[$baseMethod] = [];
292
        
293 162
            foreach (class_uses_recursive($class) as $trait) {
294 162
                $method = class_basename($trait) . ucfirst($baseMethod);
295
                
296 162
                if (method_exists($class, $method) && ! in_array($method, static::$bootedTraitMethods[$baseMethod])) {
297 162
                    static::$bootedTraitMethods[$baseMethod][] = lcfirst($method);
298
                }
299
            }
300
        }
301 162
    }
302
}
303