Completed
Push — master ( 79186c...935f65 )
by Yaro
04:21
created

AbstractTableController::beforeInit()   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\BreadcrumbsTrait;
12
use Yaro\Jarboe\Http\Controllers\Traits\Handlers\CreateHandlerTrait;
13
use Yaro\Jarboe\Http\Controllers\Traits\Handlers\DeleteHandlerTrait;
14
use Yaro\Jarboe\Http\Controllers\Traits\Handlers\EditHandlerTrait;
15
use Yaro\Jarboe\Http\Controllers\Traits\Handlers\ForceDeleteHandlerTrait;
16
use Yaro\Jarboe\Http\Controllers\Traits\Handlers\InlineHandlerTrait;
17
use Yaro\Jarboe\Http\Controllers\Traits\Handlers\ListHandlerTrait;
18
use Yaro\Jarboe\Http\Controllers\Traits\Handlers\OrderByHandlerTrait;
19
use Yaro\Jarboe\Http\Controllers\Traits\Handlers\PerPageHandlerTrait;
20
use Yaro\Jarboe\Http\Controllers\Traits\Handlers\RenderRepeaterItemHandlerTrait;
21
use Yaro\Jarboe\Http\Controllers\Traits\Handlers\RestoreHandlerTrait;
22
use Yaro\Jarboe\Http\Controllers\Traits\Handlers\SearchHandlerTrait;
23
use Yaro\Jarboe\Http\Controllers\Traits\Handlers\SearchRelationHandlerTrait;
24
use Yaro\Jarboe\Http\Controllers\Traits\Handlers\SortableHandlerTrait;
25
use Yaro\Jarboe\Http\Controllers\Traits\Handlers\StoreHandlerTrait;
26
use Yaro\Jarboe\Http\Controllers\Traits\Handlers\ToolbarHandlerTrait;
27
use Yaro\Jarboe\Http\Controllers\Traits\Handlers\UpdateHandlerTrait;
28
use Yaro\Jarboe\Http\Controllers\Traits\NotifyTrait;
29
use Yaro\Jarboe\Table\Actions\CreateAction;
30
use Yaro\Jarboe\Table\Actions\DeleteAction;
31
use Yaro\Jarboe\Table\Actions\EditAction;
32
use Yaro\Jarboe\Table\Actions\ForceDeleteAction;
33
use Yaro\Jarboe\Table\Actions\RestoreAction;
34
use Yaro\Jarboe\Table\CRUD;
35
use Yaro\Jarboe\Table\Fields\AbstractField;
36
use Yaro\Jarboe\Table\Toolbar\TranslationLocalesSelectorTool;
37
use Yaro\Jarboe\ViewComponents\Breadcrumbs\BreadcrumbsInterface;
38
39
/**
40
 * @method mixed list(Request $request)
41
 * @method mixed search(Request $request)
42
 * @method mixed create(Request $request)
43
 * @method mixed store(Request $request)
44
 * @method mixed edit(Request $request, $id)
45
 * @method mixed update(Request $request, $id)
46
 * @method mixed delete(Request $request, $id)
47
 * @method mixed restore(Request $request, $id)
48
 * @method mixed forceDelete(Request $request, $id)
49
 * @method mixed inline(Request $request)
50
 */
51
abstract class AbstractTableController
52
{
53
    use ValidatesRequests;
54
    use NotifyTrait;
55
    use AliasesTrait;
56
    use DeleteHandlerTrait;
57
    use ToolbarHandlerTrait;
58
    use InlineHandlerTrait;
59
    use ForceDeleteHandlerTrait;
60
    use RestoreHandlerTrait;
61
    use UpdateHandlerTrait;
62
    use StoreHandlerTrait;
63
    use ListHandlerTrait;
64
    use EditHandlerTrait;
65
    use CreateHandlerTrait;
66
    use OrderByHandlerTrait;
67
    use PerPageHandlerTrait;
68
    use SortableHandlerTrait;
69
    use SearchRelationHandlerTrait;
70
    use SearchHandlerTrait;
71
    use BreadcrumbsTrait;
72
    use RenderRepeaterItemHandlerTrait;
73
74
    /**
75
     * Permission group name.
76
     *
77
     * @var string|array
78
     * array(
79
     *     'list'        => 'permission:list',
80
     *     'search'      => 'permission:search',
81
     *     'create'      => 'permission:create',
82
     *     'store'       => 'permission:store',
83
     *     'edit'        => 'permission:edit',
84
     *     'update'      => 'permission:update',
85
     *     'inline'      => 'permission:inline',
86
     *     'delete'      => 'permission:delete',
87
     *     'restore'     => 'permission:restore',
88
     *     'forceDelete' => 'permission:force-delete',
89
     * )
90
     */
91
    protected $permissions = '';
92
93
    /**
94
     * @var CRUD
95
     */
96
    protected $crud;
97
98
    /**
99
     * ID of manipulated model.
100
     *
101
     * @var mixed
102
     */
103
    protected $idEntity;
104
105 71
    public function __construct()
106
    {
107 71
        $this->crud = app(CRUD::class);
108 71
        $this->crud()->tableIdentifier(crc32(static::class));
109 71
        $this->crud()->formClass(config('jarboe.crud.form_class'));
110 71
        $this->crud()->actions()->set([
111 71
            CreateAction::make(),
112 71
            EditAction::make(),
113 71
            RestoreAction::make(),
114 71
            DeleteAction::make(),
115 71
            ForceDeleteAction::make(),
116
        ]);
117 71
        $this->breadcrumbs = app(BreadcrumbsInterface::class);
118 71
    }
119
120 71
    protected function crud(): CRUD
121
    {
122 71
        return $this->crud;
123
    }
124
125
    /**
126
     * Check if user has permission for the action.
127
     *
128
     * @param $action
129
     * @return bool
130
     */
131 36
    protected function can($action): bool
132
    {
133 36
        if (!$this->permissions) {
134 16
            return true;
135
        }
136 21
        if (is_array($this->permissions) && !array_key_exists($action, $this->permissions)) {
137 1
            return true;
138
        }
139
140 21
        if (is_array($this->permissions)) {
141 1
            $permission = $this->permissions[$action];
142
        } else {
143 21
            $permission = sprintf('%s:%s', $this->permissions, $action);
144
        }
145
146 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...
147
    }
148
149 24
    public function __call($name, $arguments)
0 ignored issues
show
Documentation introduced by
The return type could not be reliably inferred; please add a @return annotation.

Our type inference engine in quite powerful, but sometimes the code does not provide enough clues to go by. In these cases we request you to add a @return annotation as described here.

Loading history...
150
    {
151
        /** @var Request $request */
152 24
        $request = RequestFacade::instance();
153
154 24
        $id = null;
155 24
        if (isset($arguments[0])) {
156 23
            $id = $arguments[1] ?? $arguments[0];
157
        }
158
159
        try {
160 24
            switch ($name) {
161 24
                case 'list':
162 4
                    return $this->handleList($request);
163 20
                case 'search':
164 2
                    return $this->handleSearch($request);
165 18
                case 'create':
166 2
                    return $this->handleCreate($request);
167 16
                case 'store':
168 2
                    return $this->handleStore($request);
169 14
                case 'edit':
170 2
                    return $this->handleEdit($request, $id);
171 12
                case 'update':
172 2
                    return $this->handleUpdate($request, $id);
173 10
                case 'delete':
174 2
                    return $this->handleDelete($request, $id);
175 8
                case 'restore':
176 3
                    return $this->handleRestore($request, $id);
177 5
                case 'forceDelete':
178 2
                    return $this->handleForceDelete($request, $id);
179 3
                case 'inline':
180 2
                    return $this->handleInline($request);
181 1
                case 'renderRepeaterItem':
182
                    $fieldName = $id;
183
                    return $this->handleRenderRepeaterItem($request, $fieldName);
184
185
                default:
186 1
                    throw new \RuntimeException('Invalid method ' . $name);
187
            }
188 12
        } catch (ValidationException $e) {
189 1
            throw $e;
190 11
        } catch (UnauthorizedException $e) {
191 10
            return $this->createUnauthorizedResponse($request, $e);
192 1
        } catch (\Throwable $e) {
193 1
            $response = $this->onException($e);
194 1
            if (!is_null($response)) {
195
                return $response;
196
            }
197
198
            // TODO: response objects
199 1
            if ($request->isXmlHttpRequest() || $request->wantsJson()) {
200
                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...
201
                    'title' => get_class($e),
202
                    'description' => $e->getMessage(),
203
                ], 406);
204
            }
205
206 1
            $this->notifyBigDanger(get_class($e), $e->getMessage(), 0);
207 1
            return redirect()->back()->withInput($request->input());
208
        }
209
    }
210
211
    /**
212
     * Event for processing exceptions before forming error response.
213
     * Non-null return value will be processed as response.
214
     *
215
     * @param \Throwable $exception
216
     *
217
     * @return mixed|void
218
     */
219 1
    protected function onException(\Throwable $exception)
220
    {
221
        // dummy
222 1
    }
223
224
    /**
225
     * Method for overriding to define basic/common init() settings.
226
     *
227
     * @return void
228
     */
229 43
    protected function beforeInit()
230
    {
231
        // dummy
232 43
    }
233
234
    /**
235
     * Bound fields/tools/etc with global data.
236
     */
237 51
    protected function bound()
238
    {
239
        /** @var AbstractField $field */
240 51
        foreach ($this->crud()->getAllFieldObjects() as $field) {
241 50
            $field->prepare($this->crud);
242
        }
243
244
        /** @var AbstractField $field */
245 51
        foreach ($this->crud()->getFieldsWithoutMarkup() as $field) {
246 50
            if ($field->isTranslatable()) {
247
                $this->addTool(new TranslationLocalesSelectorTool());
248
                break;
249
            }
250
        }
251
252 51
        $this->crud()->actions()->setCrud($this->crud());
253 51
        $this->initBreadcrumbs();
254 51
    }
255
256
    /**
257
     * Create response for unauthorized request.
258
     *
259
     * @param Request $request
260
     * @param UnauthorizedException $exception
261
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\Http\JsonResponse|\Illuminate\View\View
262
     */
263 11
    protected function createUnauthorizedResponse(Request $request, UnauthorizedException $exception)
264
    {
265 11
        if ($request->wantsJson()) {
266 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...
267 1
                'message' => $exception->getMessage()
268 1
            ], 401);
269
        }
270
271 11
        return view('jarboe::errors.401');
272
    }
273
274
    /**
275
     * Get model for current request.
276
     *
277
     * @return string
278
     * @throws \RuntimeException
279
     */
280
    protected function model()
281
    {
282
        if (!$this->idEntity) {
283
            throw new \RuntimeException('Trying to access to non-existed entity');
284
        }
285
286
        return $this->crud()->repo()->find($this->idEntity);
287
    }
288
289
    /**
290
     * @return void
291
     */
292
    abstract protected function init();
293
}
294