Completed
Push — master ( 17739d...6c5d1a )
by Yaro
07:08
created

AbstractTableController::crud()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 4
ccs 2
cts 2
cp 1
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 0
crap 1
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 41
    public function __construct()
101
    {
102 41
        $this->crud = app(CRUD::class);
103 41
        $this->crud()->tableIdentifier(crc32(static::class));
104 41
        $this->crud()->formClass(config('jarboe.crud.form_class'));
105 41
        $this->crud()->actions()->set([
106 41
            CreateAction::make(),
107 41
            EditAction::make(),
108 41
            RestoreAction::make(),
109 41
            DeleteAction::make(),
110 41
            ForceDeleteAction::make(),
111
        ]);
112 41
    }
113
114 41
    protected function crud(): CRUD
115
    {
116 41
        return $this->crud;
117
    }
118
119
    /**
120
     * Check if user has permission for the action.
121
     *
122
     * @param $action
123
     * @return bool
124
     */
125 32
    protected function can($action): bool
126
    {
127 32
        if (!$this->permissions) {
128 12
            return true;
129
        }
130 21
        if (is_array($this->permissions) && !array_key_exists($action, $this->permissions)) {
131 1
            return true;
132
        }
133
134 21
        if (is_array($this->permissions)) {
135 1
            $permission = $this->permissions[$action];
136
        } else {
137 21
            $permission = sprintf('%s:%s', $this->permissions, $action);
138
        }
139
140 21
        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 22
    public function __call($name, $arguments)
144
    {
145
        /** @var Request $request */
146 22
        $request = RequestFacade::instance();
147
148 22
        $id = null;
149 22
        if (isset($arguments[0])) {
150 21
            $id = $arguments[1] ?? $arguments[0];
151
        }
152
153
        try {
154
            switch ($name) {
155 22
                case 'list':
156 3
                    return $this->handleList($request);
157 19
                case 'search':
158 2
                    return $this->handleSearch($request);
159 17
                case 'create':
160 2
                    return $this->handleCreate($request);
161 15
                case 'store':
162 2
                    return $this->handleStore($request);
163 13
                case 'edit':
164 2
                    return $this->handleEdit($request, $id);
165 11
                case 'update':
166 2
                    return $this->handleUpdate($request, $id);
167 9
                case 'delete':
168 2
                    return $this->handleDelete($request, $id);
169 7
                case 'restore':
170 2
                    return $this->handleRestore($request, $id);
171 5
                case 'forceDelete':
172 2
                    return $this->handleForceDelete($request, $id);
173 3
                case 'inline':
174 2
                    return $this->handleInline($request);
175
176
                default:
177 1
                    throw new \RuntimeException('Invalid method ' . $name);
178
            }
179 12
        } catch (ValidationException $e) {
180 1
            throw $e;
181 11
        } catch (UnauthorizedException $e) {
182 10
            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 33
    protected function bound()
193
    {
194
        /** @var AbstractField $field */
195 33
        foreach ($this->crud()->getAllFieldObjects() as $field) {
196 33
            $field->prepare($this->crud);
197
        }
198
199
        /** @var AbstractField $field */
200 33
        foreach ($this->crud()->getFieldsWithoutMarkup() as $field) {
201 33
            if ($field->isTranslatable()) {
202
                $this->addTool(new TranslationLocalesSelectorTool());
203 33
                break;
204
            }
205
        }
206
207 33
        $this->crud()->actions()->setCrud($this->crud());
208 33
    }
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 11
    protected function createUnauthorizedResponse(Request $request, UnauthorizedException $exception)
218
    {
219 11
        if ($request->wantsJson()) {
220 1
            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 1
                'message' => $exception->getMessage()
222 1
            ], 401);
223
        }
224
225 11
        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