Completed
Push — master ( b0ce29...cf5725 )
by Yaro
05:59
created

AbstractTableController   A

Complexity

Total Complexity 30

Size/Duplication

Total Lines 200
Duplicated Lines 0 %

Coupling/Cohesion

Components 2
Dependencies 33

Test Coverage

Coverage 82.43%

Importance

Changes 0
Metric Value
wmc 30
lcom 2
cbo 33
dl 0
loc 200
ccs 61
cts 74
cp 0.8243
rs 10
c 0
b 0
f 0

7 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 13 1
A createUnauthorizedResponse() 0 10 2
A model() 0 8 2
A bound() 0 17 4
A crud() 0 4 1
A can() 0 17 5
C __call() 0 45 15
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 19
    public function __construct()
101
    {
102 19
        $this->crud = app(CRUD::class);
103 19
        $this->crud()->tableIdentifier(crc32(static::class));
104 19
        $this->crud()->formClass(config('jarboe.crud.form_class'));
105 19
        $this->crud()->actions()->set([
106 19
            CreateAction::make(),
107 19
            EditAction::make(),
108 19
            RestoreAction::make(),
109 19
            DeleteAction::make(),
110 19
            ForceDeleteAction::make(),
111
        ]);
112 19
    }
113
114 19
    protected function crud(): CRUD
115
    {
116 19
        return $this->crud;
117
    }
118
119
    /**
120
     * Check if user has permission for the action.
121
     *
122
     * @param $action
123
     * @return bool
124
     */
125 12
    protected function can($action): bool
126
    {
127 12
        if (!$this->permissions) {
128 12
            return true;
129
        }
130 1
        if (is_array($this->permissions) && !array_key_exists($action, $this->permissions)) {
131 1
            return true;
132
        }
133
134 1
        if (is_array($this->permissions)) {
135 1
            $permission = $this->permissions[$action];
136
        } else {
137 1
            $permission = sprintf('%s:%s', $this->permissions, $action);
138
        }
139
140 1
        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 11
    public function __call($name, $arguments)
144
    {
145
        /** @var Request $request */
146 11
        $request = RequestFacade::instance();
147
148 11
        $id = null;
149 11
        if (isset($arguments[0])) {
150 10
            $id = $arguments[1] ?? $arguments[0];
151
        }
152
153
        try {
154
            switch ($name) {
155 11
                case 'list':
156 1
                    return $this->handleList($request);
157 10
                case 'search':
158 1
                    return $this->handleSearch($request);
159 9
                case 'create':
160 1
                    return $this->handleCreate($request);
161 8
                case 'store':
162 1
                    return $this->handleStore($request);
163 7
                case 'edit':
164 1
                    return $this->handleEdit($request, $id);
165 6
                case 'update':
166 1
                    return $this->handleUpdate($request, $id);
167 5
                case 'delete':
168 1
                    return $this->handleDelete($request, $id);
169 4
                case 'restore':
170 1
                    return $this->handleRestore($request, $id);
171 3
                case 'forceDelete':
172 1
                    return $this->handleForceDelete($request, $id);
173 2
                case 'inline':
174 1
                    return $this->handleInline($request);
175
176
                default:
177 1
                    throw new \RuntimeException('Invalid method ' . $name);
178
            }
179 1
        } catch (ValidationException $e) {
180
            throw $e;
181 1
        } catch (UnauthorizedException $e) {
182
            return $this->createUnauthorizedResponse($request, $e);
183 1
        } catch (\Exception $e) {
184 1
            $this->notifyBigDanger(get_class($e), $e->getMessage(), 0);
185 1
            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