Completed
Push — master ( 723848...f6a9f3 )
by Yaro
05:45
created

AbstractTableController::model()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

Changes 0
Metric Value
dl 0
loc 8
rs 10
c 0
b 0
f 0
ccs 0
cts 4
cp 0
cc 2
nc 2
nop 0
crap 6
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\RestoreHandlerTrait;
21
use Yaro\Jarboe\Http\Controllers\Traits\Handlers\SearchHandlerTrait;
22
use Yaro\Jarboe\Http\Controllers\Traits\Handlers\SearchRelationHandlerTrait;
23
use Yaro\Jarboe\Http\Controllers\Traits\Handlers\SortableHandlerTrait;
24
use Yaro\Jarboe\Http\Controllers\Traits\Handlers\StoreHandlerTrait;
25
use Yaro\Jarboe\Http\Controllers\Traits\Handlers\ToolbarHandlerTrait;
26
use Yaro\Jarboe\Http\Controllers\Traits\Handlers\UpdateHandlerTrait;
27
use Yaro\Jarboe\Http\Controllers\Traits\NotifyTrait;
28
use Yaro\Jarboe\Table\Actions\CreateAction;
29
use Yaro\Jarboe\Table\Actions\DeleteAction;
30
use Yaro\Jarboe\Table\Actions\EditAction;
31
use Yaro\Jarboe\Table\Actions\ForceDeleteAction;
32
use Yaro\Jarboe\Table\Actions\RestoreAction;
33
use Yaro\Jarboe\Table\CRUD;
34
use Yaro\Jarboe\Table\Fields\AbstractField;
35
use Yaro\Jarboe\Table\Toolbar\TranslationLocalesSelectorTool;
36
use Yaro\Jarboe\ViewComponents\Breadcrumbs\BreadcrumbsInterface;
37
38
/**
39
 * @method mixed list(Request $request)
40
 * @method mixed search(Request $request)
41
 * @method mixed create(Request $request)
42
 * @method mixed store(Request $request)
43
 * @method mixed edit(Request $request, $id)
44
 * @method mixed update(Request $request, $id)
45
 * @method mixed delete(Request $request, $id)
46
 * @method mixed restore(Request $request, $id)
47
 * @method mixed forceDelete(Request $request, $id)
48
 * @method mixed inline(Request $request)
49
 */
50
abstract class AbstractTableController
51
{
52
    use ValidatesRequests;
53
    use NotifyTrait;
54
    use AliasesTrait;
55
    use DeleteHandlerTrait;
56
    use ToolbarHandlerTrait;
57
    use InlineHandlerTrait;
58
    use ForceDeleteHandlerTrait;
59
    use RestoreHandlerTrait;
60
    use UpdateHandlerTrait;
61
    use StoreHandlerTrait;
62
    use ListHandlerTrait;
63
    use EditHandlerTrait;
64
    use CreateHandlerTrait;
65
    use OrderByHandlerTrait;
66
    use PerPageHandlerTrait;
67
    use SortableHandlerTrait;
68
    use SearchRelationHandlerTrait;
69
    use SearchHandlerTrait;
70
    use BreadcrumbsTrait;
71
72
    /**
73
     * Permission group name.
74
     *
75
     * @var string|array
76
     * array(
77
     *     'list'        => 'permission:list',
78
     *     'search'      => 'permission:search',
79
     *     'create'      => 'permission:create',
80
     *     'store'       => 'permission:store',
81
     *     'edit'        => 'permission:edit',
82
     *     'update'      => 'permission:update',
83
     *     'inline'      => 'permission:inline',
84
     *     'delete'      => 'permission:delete',
85
     *     'restore'     => 'permission:restore',
86
     *     'forceDelete' => 'permission:force-delete',
87
     * )
88
     */
89
    protected $permissions = '';
90
91
    /**
92
     * @var CRUD
93
     */
94
    protected $crud;
95
96
    /**
97
     * ID of manipulated model.
98
     *
99
     * @var mixed
100
     */
101
    protected $idEntity;
102
103 41
    public function __construct()
104
    {
105 41
        $this->crud = app(CRUD::class);
106 41
        $this->crud()->tableIdentifier(crc32(static::class));
107 41
        $this->crud()->formClass(config('jarboe.crud.form_class'));
108 41
        $this->crud()->actions()->set([
109 41
            CreateAction::make(),
110 41
            EditAction::make(),
111 41
            RestoreAction::make(),
112 41
            DeleteAction::make(),
113 41
            ForceDeleteAction::make(),
114
        ]);
115 41
        $this->breadcrumbs = app(BreadcrumbsInterface::class);
116 41
    }
117
118 41
    protected function crud(): CRUD
119
    {
120 41
        return $this->crud;
121
    }
122
123
    /**
124
     * Check if user has permission for the action.
125
     *
126
     * @param $action
127
     * @return bool
128
     */
129 32
    protected function can($action): bool
130
    {
131 32
        if (!$this->permissions) {
132 12
            return true;
133
        }
134 21
        if (is_array($this->permissions) && !array_key_exists($action, $this->permissions)) {
135 1
            return true;
136
        }
137
138 21
        if (is_array($this->permissions)) {
139 1
            $permission = $this->permissions[$action];
140
        } else {
141 21
            $permission = sprintf('%s:%s', $this->permissions, $action);
142
        }
143
144 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...
145
    }
146
147 22
    public function __call($name, $arguments)
148
    {
149
        /** @var Request $request */
150 22
        $request = RequestFacade::instance();
151
152 22
        $id = null;
153 22
        if (isset($arguments[0])) {
154 21
            $id = $arguments[1] ?? $arguments[0];
155
        }
156
157
        try {
158
            switch ($name) {
159 22
                case 'list':
160 3
                    return $this->handleList($request);
161 19
                case 'search':
162 2
                    return $this->handleSearch($request);
163 17
                case 'create':
164 2
                    return $this->handleCreate($request);
165 15
                case 'store':
166 2
                    return $this->handleStore($request);
167 13
                case 'edit':
168 2
                    return $this->handleEdit($request, $id);
169 11
                case 'update':
170 2
                    return $this->handleUpdate($request, $id);
171 9
                case 'delete':
172 2
                    return $this->handleDelete($request, $id);
173 7
                case 'restore':
174 2
                    return $this->handleRestore($request, $id);
175 5
                case 'forceDelete':
176 2
                    return $this->handleForceDelete($request, $id);
177 3
                case 'inline':
178 2
                    return $this->handleInline($request);
179
180
                default:
181 1
                    throw new \RuntimeException('Invalid method ' . $name);
182
            }
183 12
        } catch (ValidationException $e) {
184 1
            throw $e;
185 11
        } catch (UnauthorizedException $e) {
186 10
            return $this->createUnauthorizedResponse($request, $e);
187 1
        } catch (\Exception $e) {
188 1
            $this->notifyBigDanger(get_class($e), $e->getMessage(), 0);
189 1
            return redirect()->back()->withInput($request->input());
190
        }
191
    }
192
193
    /**
194
     * Bound fields/tools/etc with global data.
195
     */
196 33
    protected function bound()
197
    {
198
        /** @var AbstractField $field */
199 33
        foreach ($this->crud()->getAllFieldObjects() as $field) {
200 33
            $field->prepare($this->crud);
201
        }
202
203
        /** @var AbstractField $field */
204 33
        foreach ($this->crud()->getFieldsWithoutMarkup() as $field) {
205 33
            if ($field->isTranslatable()) {
206
                $this->addTool(new TranslationLocalesSelectorTool());
207 33
                break;
208
            }
209
        }
210
211 33
        $this->crud()->actions()->setCrud($this->crud());
212 33
        $this->initBreadcrumbs();
213 33
    }
214
215
    /**
216
     * Create response for unauthorized request.
217
     *
218
     * @param Request $request
219
     * @param UnauthorizedException $exception
220
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\Http\JsonResponse|\Illuminate\View\View
221
     */
222 11
    protected function createUnauthorizedResponse(Request $request, UnauthorizedException $exception)
223
    {
224 11
        if ($request->wantsJson()) {
225 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...
226 1
                'message' => $exception->getMessage()
227 1
            ], 401);
228
        }
229
230 11
        return view('jarboe::errors.401');
231
    }
232
233
    /**
234
     * Get model for current request.
235
     *
236
     * @return string
237
     * @throws \RuntimeException
238
     */
239
    protected function model()
240
    {
241
        if (!$this->idEntity) {
242
            throw new \RuntimeException('Trying to access to non-existed entity');
243
        }
244
245
        return $this->crud()->repo()->find($this->idEntity);
246
    }
247
248
    /**
249
     * @return void
250
     */
251
    abstract protected function init();
252
}
253