Completed
Push — master ( ee59e4...f15ae2 )
by Yaro
14:58 queued 13:07
created

createUnauthorizedResponse()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 10

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 10
ccs 6
cts 6
cp 1
rs 9.9332
c 0
b 0
f 0
cc 2
nc 2
nop 2
crap 2
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 70
    public function __construct()
104
    {
105 70
        $this->crud = app(CRUD::class);
106 70
        $this->crud()->tableIdentifier(crc32(static::class));
107 70
        $this->crud()->formClass(config('jarboe.crud.form_class'));
108 70
        $this->crud()->actions()->set([
109 70
            CreateAction::make(),
110 70
            EditAction::make(),
111 70
            RestoreAction::make(),
112 70
            DeleteAction::make(),
113 70
            ForceDeleteAction::make(),
114
        ]);
115 70
        $this->breadcrumbs = app(BreadcrumbsInterface::class);
116 70
    }
117
118 70
    protected function crud(): CRUD
119
    {
120 70
        return $this->crud;
121
    }
122
123
    /**
124
     * Check if user has permission for the action.
125
     *
126
     * @param $action
127
     * @return bool
128
     */
129 35
    protected function can($action): bool
130
    {
131 35
        if (!$this->permissions) {
132 15
            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 23
    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...
148
    {
149
        /** @var Request $request */
150 23
        $request = RequestFacade::instance();
151
152 23
        $id = null;
153 23
        if (isset($arguments[0])) {
154 22
            $id = $arguments[1] ?? $arguments[0];
155
        }
156
157
        try {
158
            switch ($name) {
159 23
                case 'list':
160 3
                    return $this->handleList($request);
161 20
                case 'search':
162 2
                    return $this->handleSearch($request);
163 18
                case 'create':
164 2
                    return $this->handleCreate($request);
165 16
                case 'store':
166 2
                    return $this->handleStore($request);
167 14
                case 'edit':
168 2
                    return $this->handleEdit($request, $id);
169 12
                case 'update':
170 2
                    return $this->handleUpdate($request, $id);
171 10
                case 'delete':
172 2
                    return $this->handleDelete($request, $id);
173 8
                case 'restore':
174 3
                    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
            // TODO: response objects
189 1
            if ($request->isXmlHttpRequest() || $request->wantsJson()) {
190
                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...
191
                    'title' => get_class($e),
192
                    'description' => $e->getMessage(),
193
                ], 406);
194
            }
195
196 1
            $this->notifyBigDanger(get_class($e), $e->getMessage(), 0);
197 1
            return redirect()->back()->withInput($request->input());
198
        }
199
    }
200
201
    /**
202
     * Bound fields/tools/etc with global data.
203
     */
204 50
    protected function bound()
205
    {
206
        /** @var AbstractField $field */
207 50
        foreach ($this->crud()->getAllFieldObjects() as $field) {
208 49
            $field->prepare($this->crud);
209
        }
210
211
        /** @var AbstractField $field */
212 50
        foreach ($this->crud()->getFieldsWithoutMarkup() as $field) {
213 49
            if ($field->isTranslatable()) {
214
                $this->addTool(new TranslationLocalesSelectorTool());
215 49
                break;
216
            }
217
        }
218
219 50
        $this->crud()->actions()->setCrud($this->crud());
220 50
        $this->initBreadcrumbs();
221 50
    }
222
223
    /**
224
     * Create response for unauthorized request.
225
     *
226
     * @param Request $request
227
     * @param UnauthorizedException $exception
228
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\Http\JsonResponse|\Illuminate\View\View
229
     */
230 11
    protected function createUnauthorizedResponse(Request $request, UnauthorizedException $exception)
231
    {
232 11
        if ($request->wantsJson()) {
233 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...
234 1
                'message' => $exception->getMessage()
235 1
            ], 401);
236
        }
237
238 11
        return view('jarboe::errors.401');
239
    }
240
241
    /**
242
     * Get model for current request.
243
     *
244
     * @return string
245
     * @throws \RuntimeException
246
     */
247
    protected function model()
248
    {
249
        if (!$this->idEntity) {
250
            throw new \RuntimeException('Trying to access to non-existed entity');
251
        }
252
253
        return $this->crud()->repo()->find($this->idEntity);
254
    }
255
256
    /**
257
     * @return void
258
     */
259
    abstract protected function init();
260
}
261