AbstractTableController::__construct()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 13
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 11
CRAP Score 1

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 10
c 1
b 0
f 0
nc 1
nop 0
dl 0
loc 13
rs 9.9332
ccs 11
cts 11
cp 1
crap 1
1
<?php
2
3
namespace Yaro\Jarboe\Http\Controllers;
4
5
use Illuminate\Foundation\Validation\ValidatesRequests;
6
use Illuminate\Http\RedirectResponse;
7
use Illuminate\Http\Request;
8
use Illuminate\Support\Facades\Request as RequestFacade;
9
use Illuminate\Validation\ValidationException;
10
use Spatie\Permission\Exceptions\UnauthorizedException;
11
use Yaro\Jarboe\Http\Controllers\Traits\AliasesTrait;
12
use Yaro\Jarboe\Http\Controllers\Traits\BreadcrumbsTrait;
13
use Yaro\Jarboe\Http\Controllers\Traits\Handlers\CreateHandlerTrait;
14
use Yaro\Jarboe\Http\Controllers\Traits\Handlers\DeleteHandlerTrait;
15
use Yaro\Jarboe\Http\Controllers\Traits\Handlers\EditHandlerTrait;
16
use Yaro\Jarboe\Http\Controllers\Traits\Handlers\ForceDeleteHandlerTrait;
17
use Yaro\Jarboe\Http\Controllers\Traits\Handlers\HistoryHandlerTrait;
18
use Yaro\Jarboe\Http\Controllers\Traits\Handlers\RevertHandlerTrait;
19
use Yaro\Jarboe\Http\Controllers\Traits\Handlers\InlineHandlerTrait;
20
use Yaro\Jarboe\Http\Controllers\Traits\Handlers\ListHandlerTrait;
21
use Yaro\Jarboe\Http\Controllers\Traits\Handlers\OrderByHandlerTrait;
22
use Yaro\Jarboe\Http\Controllers\Traits\Handlers\PerPageHandlerTrait;
23
use Yaro\Jarboe\Http\Controllers\Traits\Handlers\RenderRepeaterItemHandlerTrait;
24
use Yaro\Jarboe\Http\Controllers\Traits\Handlers\RestoreHandlerTrait;
25
use Yaro\Jarboe\Http\Controllers\Traits\Handlers\SearchHandlerTrait;
26
use Yaro\Jarboe\Http\Controllers\Traits\Handlers\SearchRelationHandlerTrait;
27
use Yaro\Jarboe\Http\Controllers\Traits\Handlers\SortableHandlerTrait;
28
use Yaro\Jarboe\Http\Controllers\Traits\Handlers\StoreHandlerTrait;
29
use Yaro\Jarboe\Http\Controllers\Traits\Handlers\ToolbarHandlerTrait;
30
use Yaro\Jarboe\Http\Controllers\Traits\Handlers\UpdateHandlerTrait;
31
use Yaro\Jarboe\Http\Controllers\Traits\NotifyTrait;
32
use Yaro\Jarboe\Table\Actions\CreateAction;
33
use Yaro\Jarboe\Table\Actions\DeleteAction;
34
use Yaro\Jarboe\Table\Actions\EditAction;
35
use Yaro\Jarboe\Table\Actions\ForceDeleteAction;
36
use Yaro\Jarboe\Table\Actions\RestoreAction;
37
use Yaro\Jarboe\Table\CRUD;
38
use Yaro\Jarboe\Table\Fields\AbstractField;
0 ignored issues
show
Bug introduced by
The type Yaro\Jarboe\Table\Fields\AbstractField was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
39
use Yaro\Jarboe\Table\Toolbar\TranslationLocalesSelectorTool;
40
use Yaro\Jarboe\ViewComponents\Breadcrumbs\BreadcrumbsInterface;
41
42
/**
43
 * @method mixed list(Request $request)
44
 * @method mixed search(Request $request)
45
 * @method mixed create(Request $request)
46
 * @method mixed store(Request $request)
47
 * @method mixed edit(Request $request, $id)
48
 * @method mixed update(Request $request, $id)
49
 * @method mixed delete(Request $request, $id)
50
 * @method mixed restore(Request $request, $id)
51
 * @method mixed forceDelete(Request $request, $id)
52
 * @method mixed inline(Request $request)
53
 * @method mixed history(Request $request, $id)
54
 * @method mixed revert(Request $request, $id)
55
 */
56
abstract class AbstractTableController
57
{
58
    use ValidatesRequests;
59
    use NotifyTrait;
60
    use AliasesTrait;
61
    use DeleteHandlerTrait;
62
    use ToolbarHandlerTrait;
63
    use InlineHandlerTrait;
64
    use ForceDeleteHandlerTrait;
65
    use RestoreHandlerTrait;
66
    use UpdateHandlerTrait;
67
    use StoreHandlerTrait;
68
    use ListHandlerTrait;
69
    use EditHandlerTrait;
70
    use CreateHandlerTrait;
71
    use OrderByHandlerTrait;
72
    use PerPageHandlerTrait;
73
    use SortableHandlerTrait;
74
    use SearchRelationHandlerTrait;
75
    use SearchHandlerTrait;
76
    use BreadcrumbsTrait;
77
    use RenderRepeaterItemHandlerTrait;
78
    use HistoryHandlerTrait;
79
    use RevertHandlerTrait;
80
81
    /**
82
     * Permission group name.
83
     *
84
     * @var string|array
85
     * array(
86
     *     'list'        => 'permission:list',
87
     *     'search'      => 'permission:search',
88
     *     'create'      => 'permission:create',
89
     *     'store'       => 'permission:store',
90
     *     'edit'        => 'permission:edit',
91
     *     'update'      => 'permission:update',
92
     *     'inline'      => 'permission:inline',
93
     *     'delete'      => 'permission:delete',
94
     *     'restore'     => 'permission:restore',
95
     *     'forceDelete' => 'permission:force-delete',
96
     *     'history'     => 'permission:history',
97
     *     'revert'      => 'permission:revert',
98
     * )
99
     */
100
    protected $permissions = '';
101
102
    /**
103
     * @var CRUD
104
     */
105
    protected $crud;
106
107
    /**
108
     * ID of manipulated model.
109
     *
110
     * @var mixed
111
     */
112
    protected $idEntity;
113
114 79
    public function __construct()
115
    {
116 79
        $this->crud = app(CRUD::class);
117 79
        $this->crud()->tableIdentifier(crc32(static::class));
118 79
        $this->crud()->formClass(config('jarboe.crud.form_class'));
119 79
        $this->crud()->actions()->set([
120 79
            CreateAction::make(),
121 79
            EditAction::make(),
122 79
            RestoreAction::make(),
123 79
            DeleteAction::make(),
124 79
            ForceDeleteAction::make(),
125
        ]);
126 79
        $this->breadcrumbs = app(BreadcrumbsInterface::class);
127 79
    }
128
129 79
    protected function crud(): CRUD
130
    {
131 79
        return $this->crud;
132
    }
133
134
    /**
135
     * Check if user has permission for the action.
136
     *
137
     * @param $action
138
     * @return bool
139
     */
140 44
    protected function can($action): bool
141
    {
142 44
        if (!$this->permissions) {
143 21
            return true;
144
        }
145 24
        if (is_array($this->permissions) && !array_key_exists($action, $this->permissions)) {
146 1
            return true;
147
        }
148
149 24
        if (is_array($this->permissions)) {
150 1
            $permission = $this->permissions[$action];
151
        } else {
152 24
            $permission = sprintf('%s:%s', $this->permissions, $action);
153
        }
154
155 24
        return $this->admin()->can($permission);
156
    }
157
158 27
    public function __call($name, $arguments)
159
    {
160
        /** @var Request $request */
161 27
        $request = RequestFacade::instance();
162
163 27
        $id = null;
164 27
        if (isset($arguments[0])) {
165 26
            $id = $arguments[1] ?? $arguments[0];
166
        }
167
168
        try {
169 27
            switch ($name) {
170 27
                case 'list':
171 4
                    return $this->handleList($request);
172 23
                case 'search':
173 2
                    return $this->handleSearch($request);
174 21
                case 'create':
175 2
                    return $this->handleCreate($request);
176 19
                case 'store':
177 2
                    return $this->handleStore($request);
178 17
                case 'edit':
179 2
                    return $this->handleEdit($request, $id);
180 15
                case 'update':
181 2
                    return $this->handleUpdate($request, $id);
182 13
                case 'delete':
183 2
                    return $this->handleDelete($request, $id);
184 11
                case 'restore':
185 3
                    return $this->handleRestore($request, $id);
186 8
                case 'forceDelete':
187 2
                    return $this->handleForceDelete($request, $id);
188 6
                case 'inline':
189 2
                    return $this->handleInline($request);
190 4
                case 'renderRepeaterItem':
191
                    $fieldName = $id;
192
                    return $this->handleRenderRepeaterItem($request, $fieldName);
193 4
                case 'history':
194 2
                    return $this->handleHistory($request, $id);
195 2
                case 'revert':
196 1
                    return $this->handleRevert($request, $id);
197
198
                default:
199 1
                    throw new \RuntimeException('Invalid method ' . $name);
200
            }
201 13
        } catch (ValidationException $e) {
202 1
            throw $e;
203 12
        } catch (UnauthorizedException $e) {
204 11
            return $this->createUnauthorizedResponse($request, $e);
205 1
        } catch (\Throwable $e) {
206 1
            $response = $this->onException($e);
0 ignored issues
show
Bug introduced by
Are you sure the assignment to $response is correct as $this->onException($e) targeting Yaro\Jarboe\Http\Control...ntroller::onException() seems to always return null.

This check looks for function or method calls that always return null and whose return value is assigned to a variable.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
$object = $a->getObject();

The method getObject() can return nothing but null, so it makes no sense to assign that value to a variable.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
207 1
            if (!is_null($response)) {
0 ignored issues
show
introduced by
The condition is_null($response) is always true.
Loading history...
208
                return $response;
209
            }
210
211
            // TODO: response objects
212 1
            if ($request->isXmlHttpRequest() || $request->wantsJson()) {
213
                return response()->json([
214
                    'title' => get_class($e),
215
                    'description' => $e->getMessage(),
216
                ], 406);
217
            }
218
219 1
            $this->notifyBigDanger(get_class($e), $e->getMessage(), 0);
220
221
            /** @var RedirectResponse $redirect */
222 1
            $redirect = redirect()->back();
223 1
            if ($redirect->getTargetUrl() == $request->url()) {
224 1
                $redirect->setTargetUrl(admin_url());
225
            }
226
227 1
            return $redirect->withInput($request->input());
228
        }
229
    }
230
231
    /**
232
     * Event for processing exceptions before forming error response.
233
     * Non-null return value will be processed as response.
234
     *
235
     * @param \Throwable $exception
236
     *
237
     * @return mixed|void
238
     */
239 1
    protected function onException(\Throwable $exception)
0 ignored issues
show
Unused Code introduced by
The parameter $exception is not used and could be removed. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-unused  annotation

239
    protected function onException(/** @scrutinizer ignore-unused */ \Throwable $exception)

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
240
    {
241
        // dummy
242 1
    }
243
244
    /**
245
     * Method for overriding to define basic/common init() settings.
246
     *
247
     * @return void
248
     */
249 51
    protected function beforeInit()
250
    {
251
        // dummy
252 51
    }
253
254
    /**
255
     * Bound fields/tools/etc with global data.
256
     */
257 59
    protected function bound()
258
    {
259
        /** @var AbstractField $field */
260 59
        foreach ($this->crud()->getAllFieldObjects() as $field) {
261 58
            $field->prepare($this->crud);
262
        }
263
264
        /** @var AbstractField $field */
265 59
        foreach ($this->crud()->getFieldsWithoutMarkup() as $field) {
266 58
            if ($field->isTranslatable()) {
267
                $this->addTool(new TranslationLocalesSelectorTool());
268
                break;
269
            }
270
        }
271
272 59
        $this->crud()->actions()->setCrud($this->crud());
273 59
        $this->initBreadcrumbs();
274 59
    }
275
276
    /**
277
     * Create response for unauthorized request.
278
     *
279
     * @param Request $request
280
     * @param UnauthorizedException $exception
281
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\Http\JsonResponse|\Illuminate\View\View
282
     */
283 12
    protected function createUnauthorizedResponse(Request $request, UnauthorizedException $exception)
284
    {
285 12
        if ($request->wantsJson()) {
286 1
            return response()->json([
287 1
                'message' => $exception->getMessage()
288 1
            ], 401);
289
        }
290
291 12
        return view('jarboe::errors.401');
292
    }
293
294
    /**
295
     * Get model for current request.
296
     *
297
     * @return string
298
     * @throws \RuntimeException
299
     */
300
    protected function model()
301
    {
302
        if (!$this->idEntity) {
303
            throw new \RuntimeException('Trying to access to non-existed entity');
304
        }
305
306
        return $this->crud()->repo()->find($this->idEntity);
307
    }
308
309
    /**
310
     * @return void
311
     */
312
    abstract protected function init();
313
}
314