Completed
Push — master ( ad2c0d...49711d )
by Yaro
10:29
created

AbstractTableController::__call()   C

Complexity

Conditions 15
Paths 86

Size

Total Lines 45

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 25
CRAP Score 18.2046

Importance

Changes 0
Metric Value
dl 0
loc 45
ccs 25
cts 33
cp 0.7576
rs 5.9166
c 0
b 0
f 0
cc 15
nc 86
nop 2
crap 18.2046

How to fix   Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
namespace Yaro\Jarboe\Http\Controllers;
4
5
use Illuminate\Foundation\Validation\ValidatesRequests;
6
use Illuminate\Http\Request;
7
use Illuminate\Support\Facades\Request as RequestFacade;
8
use Illuminate\Validation\ValidationException;
9
use Spatie\Permission\Exceptions\UnauthorizedException;
10
use Yaro\Jarboe\Http\Controllers\Traits\AliasesTrait;
11
use Yaro\Jarboe\Http\Controllers\Traits\Handlers\CreateHandlerTrait;
12
use Yaro\Jarboe\Http\Controllers\Traits\Handlers\DeleteHandlerTrait;
13
use Yaro\Jarboe\Http\Controllers\Traits\Handlers\EditHandlerTrait;
14
use Yaro\Jarboe\Http\Controllers\Traits\Handlers\ForceDeleteHandlerTrait;
15
use Yaro\Jarboe\Http\Controllers\Traits\Handlers\InlineHandlerTrait;
16
use Yaro\Jarboe\Http\Controllers\Traits\Handlers\ListHandlerTrait;
17
use Yaro\Jarboe\Http\Controllers\Traits\Handlers\OrderByHandlerTrait;
18
use Yaro\Jarboe\Http\Controllers\Traits\Handlers\PerPageHandlerTrait;
19
use Yaro\Jarboe\Http\Controllers\Traits\Handlers\RestoreHandlerTrait;
20
use Yaro\Jarboe\Http\Controllers\Traits\Handlers\SearchHandlerTrait;
21
use Yaro\Jarboe\Http\Controllers\Traits\Handlers\SearchRelationHandlerTrait;
22
use Yaro\Jarboe\Http\Controllers\Traits\Handlers\SortableHandlerTrait;
23
use Yaro\Jarboe\Http\Controllers\Traits\Handlers\StoreHandlerTrait;
24
use Yaro\Jarboe\Http\Controllers\Traits\Handlers\ToolbarHandlerTrait;
25
use Yaro\Jarboe\Http\Controllers\Traits\Handlers\UpdateHandlerTrait;
26
use Yaro\Jarboe\Http\Controllers\Traits\NotifyTrait;
27
use Yaro\Jarboe\Table\Actions\CreateAction;
28
use Yaro\Jarboe\Table\Actions\DeleteAction;
29
use Yaro\Jarboe\Table\Actions\EditAction;
30
use Yaro\Jarboe\Table\Actions\ForceDeleteAction;
31
use Yaro\Jarboe\Table\Actions\RestoreAction;
32
use Yaro\Jarboe\Table\CRUD;
33
use Yaro\Jarboe\Table\Fields\AbstractField;
34
use Yaro\Jarboe\Table\Toolbar\TranslationLocalesSelectorTool;
35
36
/**
37
 * @method mixed list(Request $request)
38
 * @method mixed search(Request $request)
39
 * @method mixed create(Request $request)
40
 * @method mixed store(Request $request)
41
 * @method mixed edit(Request $request, $id)
42
 * @method mixed update(Request $request, $id)
43
 * @method mixed delete(Request $request, $id)
44
 * @method mixed restore(Request $request, $id)
45
 * @method mixed forceDelete(Request $request, $id)
46
 * @method mixed inline(Request $request)
47
 */
48
abstract class AbstractTableController
49
{
50
    use ValidatesRequests;
51
    use NotifyTrait;
52
    use AliasesTrait;
53
    use DeleteHandlerTrait;
54
    use ToolbarHandlerTrait;
55
    use InlineHandlerTrait;
56
    use ForceDeleteHandlerTrait;
57
    use RestoreHandlerTrait;
58
    use UpdateHandlerTrait;
59
    use StoreHandlerTrait;
60
    use ListHandlerTrait;
61
    use EditHandlerTrait;
62
    use CreateHandlerTrait;
63
    use OrderByHandlerTrait;
64
    use PerPageHandlerTrait;
65
    use SortableHandlerTrait;
66
    use SearchRelationHandlerTrait;
67
    use SearchHandlerTrait;
68
69
    /**
70
     * Permission group name.
71
     *
72
     * @var string|array
73
     * array(
74
     *     'list'        => 'permission:list',
75
     *     'search'      => 'permission:search',
76
     *     'create'      => 'permission:create',
77
     *     'store'       => 'permission:store',
78
     *     'edit'        => 'permission:edit',
79
     *     'update'      => 'permission:update',
80
     *     'inline'      => 'permission:inline',
81
     *     'delete'      => 'permission:delete',
82
     *     'restore'     => 'permission:restore',
83
     *     'forceDelete' => 'permission:force-delete',
84
     * )
85
     */
86
    protected $permissions = '';
87
88
    /**
89
     * @var CRUD
90
     */
91
    protected $crud;
92
93
    /**
94
     * ID of manipulated model.
95
     *
96
     * @var mixed
97
     */
98
    protected $idEntity;
99
100 17
    public function __construct()
101
    {
102 17
        $this->crud = app(CRUD::class);
103 17
        $this->crud()->tableIdentifier(crc32(static::class));
104 17
        $this->crud()->formClass(config('jarboe.crud.form_class'));
105 17
        $this->crud()->actions()->set([
106 17
            CreateAction::make(),
107 17
            EditAction::make(),
108 17
            RestoreAction::make(),
109 17
            DeleteAction::make(),
110 17
            ForceDeleteAction::make(),
111
        ]);
112 17
    }
113
114
    protected function crud(): CRUD
115
    {
116
        return $this->crud;
117
    }
118
119
    /**
120
     * Check if user has permission for the action.
121
     *
122
     * @param $action
123
     * @return bool
124
     */
125 11
    protected function can($action): bool
126
    {
127 11
        if (!$this->permissions) {
128 11
            return true;
129
        }
130
        if (is_array($this->permissions) && !array_key_exists($action, $this->permissions)) {
131
            return true;
132
        }
133
134
        if (is_array($this->permissions)) {
135
            $permission = $this->permissions[$action];
136
        } else {
137
            $permission = sprintf('%s:%s', $this->permissions, $action);
138
        }
139
140
        return $this->admin()->can($permission);
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface Illuminate\Contracts\Auth\Authenticatable as the method can() does only exist in the following implementations of said interface: Illuminate\Foundation\Auth\User, Yaro\Jarboe\Models\Admin.

Let’s take a look at an example:

interface User
{
    /** @return string */
    public function getPassword();
}

class MyUser implements User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different implementation of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the interface:

    interface User
    {
        /** @return string */
        public function getPassword();
    
        /** @return string */
        public function getDisplayName();
    }
    
Loading history...
141
    }
142
143 10
    public function __call($name, $arguments)
144
    {
145
        /** @var Request $request */
146 10
        $request = RequestFacade::instance();
147
148 10
        $id = null;
149 10
        if (isset($arguments[0])) {
150 9
            $id = $arguments[1] ?? $arguments[0];
151
        }
152
153
        try {
154
            switch ($name) {
155 10
                case 'list':
156 1
                    return $this->handleList($request);
157 9
                case 'search':
158 1
                    return $this->handleSearch($request);
159 8
                case 'create':
160 1
                    return $this->handleCreate($request);
161 7
                case 'store':
162 1
                    return $this->handleStore($request);
163 6
                case 'edit':
164 1
                    return $this->handleEdit($request, $id);
165 5
                case 'update':
166 1
                    return $this->handleUpdate($request, $id);
167 4
                case 'delete':
168 1
                    return $this->handleDelete($request, $id);
169 3
                case 'restore':
170 1
                    return $this->handleRestore($request, $id);
171 2
                case 'forceDelete':
172 1
                    return $this->handleForceDelete($request, $id);
173 1
                case 'inline':
174 1
                    return $this->handleInline($request);
175
176
                default:
177
                    throw new \RuntimeException('Invalid method ' . $name);
178
            }
179
        } catch (ValidationException $e) {
180
            throw $e;
181
        } catch (UnauthorizedException $e) {
182
            return $this->createUnauthorizedResponse($request, $e);
183
        } catch (\Exception $e) {
184
            $this->notifyBigDanger(get_class($e), $e->getMessage(), 0);
185
            return redirect()->back()->withInput($request->input());
186
        }
187
    }
188
189
    /**
190
     * Bound fields/tools/etc with global data.
191
     */
192 13
    protected function bound()
193
    {
194
        /** @var AbstractField $field */
195 13
        foreach ($this->crud()->getAllFieldObjects() as $field) {
196 13
            $field->prepare($this->crud);
197
        }
198
199
        /** @var AbstractField $field */
200 13
        foreach ($this->crud()->getFieldsWithoutMarkup() as $field) {
201 13
            if ($field->isTranslatable()) {
202
                $this->addTool(new TranslationLocalesSelectorTool());
203 13
                break;
204
            }
205
        }
206
207 13
        $this->crud()->actions()->setCrud($this->crud());
208 13
    }
209
210
    /**
211
     * Create response for unauthorized request.
212
     *
213
     * @param Request $request
214
     * @param UnauthorizedException $exception
215
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\Http\JsonResponse|\Illuminate\View\View
216
     */
217
    protected function createUnauthorizedResponse(Request $request, UnauthorizedException $exception)
218
    {
219
        if ($request->wantsJson()) {
220
            return response()->json([
0 ignored issues
show
Bug introduced by
The method json does only exist in Illuminate\Contracts\Routing\ResponseFactory, but not in Illuminate\Http\Response.

It seems like the method you are trying to call exists only in some of the possible types.

Let’s take a look at an example:

class A
{
    public function foo() { }
}

class B extends A
{
    public function bar() { }
}

/**
 * @param A|B $x
 */
function someFunction($x)
{
    $x->foo(); // This call is fine as the method exists in A and B.
    $x->bar(); // This method only exists in B and might cause an error.
}

Available Fixes

  1. Add an additional type-check:

    /**
     * @param A|B $x
     */
    function someFunction($x)
    {
        $x->foo();
    
        if ($x instanceof B) {
            $x->bar();
        }
    }
    
  2. Only allow a single type to be passed if the variable comes from a parameter:

    function someFunction(B $x) { /** ... */ }
    
Loading history...
221
                'message' => $exception->getMessage()
222
            ], 401);
223
        }
224
225
        return view('jarboe::errors.401');
226
    }
227
228
    /**
229
     * Get model for current request.
230
     *
231
     * @return string
232
     * @throws \RuntimeException
233
     */
234
    protected function model()
235
    {
236
        if (!$this->idEntity) {
237
            throw new \RuntimeException('Trying to access to non-existed entity');
238
        }
239
240
        return $this->crud()->repo()->find($this->idEntity);
241
    }
242
243
    /**
244
     * @return void
245
     */
246
    abstract protected function init();
247
}
248