|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace Yaro\Jarboe\Http\Controllers\Traits\Handlers; |
|
4
|
|
|
|
|
5
|
|
|
use Illuminate\Http\Request; |
|
6
|
|
|
use Spatie\Permission\Exceptions\UnauthorizedException; |
|
7
|
|
|
use Yaro\Jarboe\Exceptions\PermissionDenied; |
|
8
|
|
|
use Yaro\Jarboe\Table\CRUD; |
|
9
|
|
|
|
|
10
|
|
|
trait DeleteHandlerTrait |
|
11
|
|
|
{ |
|
12
|
|
|
/** |
|
13
|
|
|
* Handle delete action. |
|
14
|
|
|
* |
|
15
|
|
|
* @param Request $request |
|
16
|
|
|
* @param $id |
|
17
|
|
|
* @return \Illuminate\Http\JsonResponse |
|
18
|
|
|
* @throws PermissionDenied |
|
19
|
|
|
* @throws UnauthorizedException |
|
20
|
|
|
*/ |
|
21
|
1 |
|
public function handleDelete(Request $request, $id) |
|
22
|
|
|
{ |
|
23
|
1 |
|
$this->init(); |
|
24
|
1 |
|
$this->bound(); |
|
25
|
|
|
|
|
26
|
1 |
|
$model = $this->crud()->repo()->find($id); |
|
27
|
1 |
|
if (!$this->crud()->actions()->isAllowed('delete', $model)) { |
|
28
|
|
|
throw new PermissionDenied(); |
|
29
|
|
|
} |
|
30
|
|
|
|
|
31
|
1 |
|
if (!$this->can('delete')) { |
|
|
|
|
|
|
32
|
|
|
throw UnauthorizedException::forPermissions(['delete']); |
|
33
|
|
|
} |
|
34
|
|
|
|
|
35
|
1 |
|
$this->idEntity = $model->getKey(); |
|
|
|
|
|
|
36
|
|
|
|
|
37
|
1 |
|
if ($this->crud()->repo()->delete($id)) { |
|
38
|
1 |
|
$type = 'hidden'; |
|
39
|
|
|
try { |
|
40
|
1 |
|
$this->crud()->repo()->find($id); |
|
41
|
|
|
} catch (\Exception $e) { |
|
42
|
|
|
$type = 'removed'; |
|
43
|
|
|
} |
|
44
|
|
|
|
|
45
|
1 |
|
return response()->json([ |
|
|
|
|
|
|
46
|
1 |
|
'type' => $type, |
|
47
|
1 |
|
'message' => __('jarboe::common.list.delete_success_message', ['id' => $id]), |
|
48
|
|
|
]); |
|
49
|
|
|
} |
|
50
|
|
|
|
|
51
|
|
|
return response()->json([ |
|
52
|
|
|
'message' => __('jarboe::common.list.delete_failed_message', ['id' => $id]), |
|
53
|
|
|
], 422); |
|
54
|
|
|
} |
|
55
|
|
|
|
|
56
|
|
|
abstract protected function init(); |
|
|
|
|
|
|
57
|
|
|
abstract protected function bound(); |
|
|
|
|
|
|
58
|
|
|
abstract protected function crud(): CRUD; |
|
59
|
|
|
} |
|
60
|
|
|
|
This check looks for methods that are used by a trait but not required by it.
To illustrate, let’s look at the following code example
The trait
Idableprovides a methodequalsIdthat in turn relies on the methodgetId(). If this method does not exist on a class mixing in this trait, the method will fail.Adding the
getId()as an abstract method to the trait will make sure it is available.