Passed
Push — master ( 0f8e83...edb234 )
by Philippe
02:11 queued 12s
created

AbstractManager::manage()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 2
nc 1
nop 1
dl 0
loc 5
ccs 3
cts 3
cp 1
crap 1
rs 10
c 0
b 0
f 0
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 Illuminate\Support\Collection;
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\AssistedManager;
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
21
abstract class AbstractManager
22
{
23
    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...
24
        SavingFields,
25
        HasDetails,
26
        HasSections,
27
        ManagesMedia,
28
        ManagesPagebuilder,
29
        TranslatableCommand,
30
        AssistedManager;
31
32
    protected $translation_columns = [];
33
34
    protected $model;
35
36
    /** @var Register */
37
    protected $registration;
38
39
    protected $pageCount = 20;
40
    protected $paginated = true;
41
42 150
    public function __construct(Registration $registration)
43
    {
44 150
        $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 150
        $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 150
        $this->validateConstraints();
51 150
    }
52
53 150
    public function manage($model): Manager
54
    {
55 150
        $this->model = $model;
56
57 150
        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...
58
    }
59
60 85
    public function findManaged($id): Manager
61
    {
62 85
        $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

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

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

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

114
            return (new static(/** @scrutinizer ignore-type */ $this->registration))->manage($model);
Loading history...
115 2
        });
116
117 2
        return $paginator->setCollection($modifiedCollection);
118
    }
119
120 91
    public function model()
121
    {
122 91
        return $this->model;
123
    }
124
125 95
    public function hasExistingModel(): bool
126
    {
127 95
        return ($this->model && $this->model->exists);
128
    }
129
130
    /**
131
     * If the model exists return it otherwise
132
     * throws a nonExistingRecord exception;
133
     *
134
     * @throws NonExistingRecord
135
     */
136 95
    protected function existingModel()
137
    {
138 95
        if (!$this->hasExistingModel()) {
139 1
            throw new NonExistingRecord('Model does not exist yet but is expected.');
140
        }
141
142 94
        return $this->model;
143
    }
144
145
    /**
146
     * Determine which actions should be available for this
147
     * manager and their respective routed urls.
148
     *
149
     * @param $verb
150
     * @return null|string
151
     * @throws NonExistingRecord
152
     */
153 118
    public function route($verb): ?string
154
    {
155
        $routes = [
156 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

156
            '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...
157 118
            'create'  => route('chief.back.managers.create', [$this->registration->key()]),
158 118
            'store'   => route('chief.back.managers.store', [$this->registration->key()]),
159
        ];
160
161 118
        if (array_key_exists($verb, $routes)) {
162 69
            return $routes[$verb] ?? null;
163
        }
164
165
        //These routes expect the model to be persisted in the database
166
        $modelRoutes = [
167 95
            'edit'    => route('chief.back.managers.edit', [$this->registration->key(), $this->existingModel()->id]),
168 94
            'update'  => route('chief.back.managers.update', [$this->registration->key(), $this->existingModel()->id]),
169 94
            'delete'  => route('chief.back.managers.delete', [$this->registration->key(), $this->existingModel()->id]),
170 94
            'upload'  => route('chief.back.managers.media.upload', [$this->registration->key(), $this->existingModel()->id]),
171
        ];
172
173 94
        return $modelRoutes[$verb] ?? null;
174
    }
175
176 122
    public function can($verb): bool
177
    {
178 122
        return !is_null($this->route($verb));
179
    }
180
181 108
    public function guard($verb): Manager
182
    {
183 108
        if (! $this->can($verb)) {
184 1
            NotAllowedManagerRoute::notAllowedVerb($verb, $this);
185
        }
186
187 107
        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...
188
    }
189
190 83
    public function fields(): Fields
191
    {
192 83
        return new Fields();
193
    }
194
195
    /**
196
     * Enrich the manager fields with any of the assistant specified fields
197
     *
198
     * @return Fields
199
     * @throws \Exception
200
     */
201 101
    public function fieldsWithAssistantFields(): Fields
202
    {
203 101
        $fields = $this->fields();
204
205 101
        foreach ($this->assistants() as $assistant) {
206 77
            if (! method_exists($assistant, 'fields')) {
207 75
                continue;
208
            }
209
210 77
            $fields = $fields->merge($assistant->fields());
211
        }
212
213 101
        return $fields;
214
    }
215
216
    /**
217
     * This determines the arrangement of the manageable fields
218
     * on the create and edit forms. By default, all fields
219
     * are presented in their order of appearance
220
     *
221
     * @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...
222
     * @return FieldArrangement
223
     * @throws \Exception
224
     */
225 3
    public function fieldArrangement($key = null): FieldArrangement
226
    {
227 3
        return new FieldArrangement($this->fieldsWithAssistantFields());
228
    }
229
230 1
    public function delete()
231
    {
232 1
        $this->model->delete();
233 1
    }
234
235 1
    public static function filters(): Filters
236
    {
237 1
        return new Filters();
238
    }
239
240
    /**
241
     * This method can be used to manipulate the store request payload
242
     * before being passed to the storing / updating the models.
243
     *
244
     * @param Request $request
245
     * @return Request
246
     */
247 24
    public function storeRequest(Request $request): Request
248
    {
249 24
        return $request;
250
    }
251
252
    /**
253
     * This method can be used to manipulate the update request payload
254
     * before being passed to the storing / updating the models.
255
     *
256
     * @param Request $request
257
     * @return Request
258
     */
259 22
    public function updateRequest(Request $request): Request
260
    {
261 22
        return $request;
262
    }
263
264 77
    protected function requestContainsTranslations(Request $request): bool
265
    {
266 77
        return $request->has('trans');
267
    }
268
269 150
    protected function validateConstraints()
270
    {
271 150
        if (!$this->model) {
272
            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.');
273
        }
274 150
    }
275
}
276