|
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
|
|
|
use Yaro\Jarboe\Table\Fields\AbstractField; |
|
10
|
|
|
|
|
11
|
|
|
trait UpdateHandlerTrait |
|
12
|
|
|
{ |
|
13
|
|
|
/** |
|
14
|
|
|
* Handle update action. |
|
15
|
|
|
* |
|
16
|
|
|
* @param Request $request |
|
17
|
|
|
* @param $id |
|
18
|
|
|
* @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector |
|
19
|
|
|
* @throws PermissionDenied |
|
20
|
|
|
* @throws UnauthorizedException |
|
21
|
|
|
*/ |
|
22
|
4 |
|
public function handleUpdate(Request $request, $id) |
|
23
|
|
|
{ |
|
24
|
4 |
|
$this->init(); |
|
25
|
4 |
|
$this->bound(); |
|
26
|
|
|
|
|
27
|
4 |
|
if (!$this->can('update')) { |
|
28
|
2 |
|
throw UnauthorizedException::forPermissions(['update']); |
|
29
|
|
|
} |
|
30
|
|
|
|
|
31
|
2 |
|
$model = $this->crud()->repo()->find($id); |
|
32
|
2 |
|
if (!$this->crud()->actions()->isAllowed('edit', $model)) { |
|
33
|
1 |
|
throw new PermissionDenied(); |
|
34
|
|
|
} |
|
35
|
|
|
|
|
36
|
1 |
|
$fields = $this->crud()->getFieldsWithoutMarkup(); |
|
37
|
1 |
|
$data = []; |
|
38
|
|
|
/** @var AbstractField $field */ |
|
39
|
1 |
|
foreach ($fields as $field) { |
|
40
|
1 |
|
if ($field->hidden('edit') || $field->isReadonly() || $field->shouldSkip($request)) { |
|
41
|
|
|
continue; |
|
42
|
|
|
} |
|
43
|
1 |
|
$data += [$field->name() => $field->value($request)]; |
|
44
|
|
|
} |
|
45
|
|
|
|
|
46
|
1 |
|
$model = $this->crud()->repo()->update($id, $data); |
|
47
|
|
|
/** @var AbstractField $field */ |
|
48
|
1 |
|
foreach ($fields as $field) { |
|
49
|
1 |
|
$field->afterUpdate($model, $request); |
|
50
|
|
|
} |
|
51
|
1 |
|
$this->idEntity = $model->getKey(); |
|
|
|
|
|
|
52
|
|
|
|
|
53
|
1 |
|
return redirect($this->crud()->listUrl()); |
|
54
|
|
|
} |
|
55
|
|
|
|
|
56
|
|
|
abstract protected function init(); |
|
|
|
|
|
|
57
|
|
|
abstract protected function bound(); |
|
|
|
|
|
|
58
|
|
|
abstract protected function crud(): CRUD; |
|
59
|
|
|
abstract protected function can($action): bool; |
|
60
|
|
|
} |
|
61
|
|
|
|
In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:
Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion: