Passed
Push — ft/nomadic ( fe3ddc...e98568 )
by Philippe
44:02 queued 36:12
created

AbstractManager::bootTraitMethods()   A

Complexity

Conditions 5
Paths 4

Size

Total Lines 17
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 5

Importance

Changes 0
Metric Value
eloc 9
c 0
b 0
f 0
dl 0
loc 17
ccs 7
cts 7
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 $booted    = [];
41 154
42
    public function __construct(Registration $registration)
43 154
    {
44
        $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 154
        // Upon instantiation, a general model is set that doesn't point to a persisted record.
47
        $this->manage(app($this->registration->model()));
48
49 154
        // Check if key and model are present since the model should be set by the manager itself
50
        $this->validateConstraints();
51 154
52 154
        static::bootTraitMethods();
53
    }
54 154
55
    public function manage($model): Manager
56 154
    {
57
        $this->model = $model;
58 154
59
        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 86
62
    public function findManaged($id): Manager
63 86
    {
64
        $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 86
66
        $modelInstance = $model::where('id', $id)->withoutGlobalScopes()->first();
67 86
68
        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 6
71
    public function indexCollection()
72 6
    {
73
        $model = $this->registration->model();
74 6
75
        $builder = (new $model)->query();
76 6
77
        $this->filters()->apply($builder);
78 6
79
        $builder = $this->indexBuilder($builder);
80 6
81
        $builder = $this->indexSorting($builder);
82 6
        
83 6
        if ($this->paginated) {
84
            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 6
92
    protected function indexBuilder(Builder $builder): Builder
93 6
    {
94
        return $builder;
95
    }
96 6
97
    protected function indexSorting(Builder $builder): Builder
98 6
    {
99 1
        if ($this->isAssistedBy('publish')) {
100
            $builder->orderBy('published', 'DESC');
101
        }
102
103 6
        // if model has no timestamps, updated_at doesn't exist
104 6
        if ($this->model()->timestamps) {
105
            $builder->orderBy('updated_at', 'DESC');
106
        }
107 6
108
        return $builder;
109
    }
110 6
111
    protected function indexPagination($builder): Paginator
112 6
    {
113
        $paginator = $builder->paginate($this->pageCount);
114
115 5
        $modifiedCollection = $builder->paginate($this->pageCount)->getCollection()->transform(function ($model) {
116 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

116
            return (new static(/** @scrutinizer ignore-type */ $this->registration))->manage($model);
Loading history...
117
        });
118 6
119
        return $paginator->setCollection($modifiedCollection);
120
    }
121 95
122
    public function model()
123 95
    {
124
        return $this->model;
125
    }
126 95
127
    public function hasExistingModel(): bool
128 95
    {
129
        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 95
     */
138
    protected function existingModel()
139 95
    {
140 1
        if (!$this->hasExistingModel()) {
141
            throw new NonExistingRecord('Model does not exist yet but is expected.');
142
        }
143 94
144
        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 118
     */
155
    public function route($verb): ?string
156
    {
157 118
        $routes = [
158 118
            '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 118
            'create'  => route('chief.back.managers.create', [$this->registration->key()]),
160
            'store'   => route('chief.back.managers.store', [$this->registration->key()]),
161
        ];
162 118
163 69
        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 95
        $modelRoutes = [
169 94
            'edit'    => route('chief.back.managers.edit', [$this->registration->key(), $this->existingModel()->id]),
170 94
            'update'  => route('chief.back.managers.update', [$this->registration->key(), $this->existingModel()->id]),
171 94
            '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 94
175
        return $modelRoutes[$verb] ?? null;
176
    }
177 126
178
    public function can($verb): bool
179 126
    {
180 4
        foreach (static::$booted['can'] as $method) {
181
            $this->$method($verb);
182
        }
183 124
184
        return !is_null($this->route($verb));
185
    }
186 112
187
    public function guard($verb): Manager
188 112
    {
189 3
        if (! $this->can($verb)) {
190
            NotAllowedManagerRoute::notAllowedVerb($verb, $this);
191
        }
192 109
193
        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 83
196
    public function fields(): Fields
197 83
    {
198
        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 103
     */
207
    public function fieldsWithAssistantFields(): Fields
208 103
    {
209
        $fields = $this->fields();
210 103
211 77
        foreach ($this->assistants() as $assistant) {
212 75
            if (! method_exists($assistant, 'fields')) {
213
                continue;
214
            }
215 77
216
            $fields = $fields->merge($assistant->fields());
217
        }
218 103
219
        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 3
     */
231
    public function fieldArrangement($key = null): FieldArrangement
232 3
    {
233
        return new FieldArrangement($this->fieldsWithAssistantFields());
234
    }
235 1
236
    public function delete()
237 1
    {
238 1
        $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

238
        $this->model->/** @scrutinizer ignore-call */ 
239
                      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...
239
    }
240 5
241
    public static function filters(): Filters
242 5
    {
243
        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 24
     */
253
    public function storeRequest(Request $request): Request
254 24
    {
255
        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 22
     */
265
    public function updateRequest(Request $request): Request
266 22
    {
267
        return $request;
268
    }
269 79
270
    protected function requestContainsTranslations(Request $request): bool
271 79
    {
272
        return $request->has('trans');
273
    }
274 154
275
    protected function validateConstraints()
276 154
    {
277
        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 154
        }
280
    }
281 154
282
    public static function bootTraitMethods()
283 154
    {
284
        $class = static::class;
285 154
286
        $methods = [
287 154
            'can'
288 154
        ];
289
290 154
        foreach($methods as $baseMethod)
291 154
        {
292
            static::$booted[$baseMethod] = [];
293
        
294 154
            foreach (class_uses_recursive($class) as $trait) {
295
                $method = class_basename($trait) . ucfirst($baseMethod);
296
                
297
                if (method_exists($class, $method) && ! in_array($method, static::$booted[$baseMethod])) {
298
                    static::$booted[$baseMethod][] = lcfirst($method);
299
                }
300
            }
301
        }
302
    }
303
}
304