1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Yaro\Jarboe\Http\Controllers\Traits\Handlers; |
4
|
|
|
|
5
|
|
|
use Illuminate\Http\JsonResponse; |
6
|
|
|
use Illuminate\Http\Request; |
7
|
|
|
use Illuminate\Support\MessageBag; |
8
|
|
|
use Illuminate\Support\ViewErrorBag; |
9
|
|
|
use Throwable; |
10
|
|
|
use Yaro\Jarboe\Table\CRUD; |
11
|
|
|
use Yaro\Jarboe\Table\Fields\Repeater; |
12
|
|
|
|
13
|
|
|
trait RenderRepeaterItemHandlerTrait |
14
|
|
|
{ |
15
|
|
|
/** |
16
|
|
|
* Handle system render repeater's item action. |
17
|
|
|
* |
18
|
|
|
* @param Request $request |
19
|
|
|
* @return JsonResponse |
20
|
|
|
* @throws Throwable |
21
|
|
|
*/ |
22
|
|
|
public function handleRenderRepeaterItem($request, $fieldName) |
23
|
|
|
{ |
24
|
|
|
$this->beforeInit(); |
25
|
|
|
$this->init(); |
26
|
|
|
$this->bound(); |
27
|
|
|
|
28
|
|
|
$messageBag = new MessageBag( |
29
|
|
|
$this->flatten($request->get('errors', [])) |
30
|
|
|
); |
31
|
|
|
$viewErrorBag = new ViewErrorBag(); |
32
|
|
|
$viewErrorBag->put('default', $messageBag); |
33
|
|
|
|
34
|
|
|
view()->share('errors', $viewErrorBag); |
35
|
|
|
|
36
|
|
|
/** @var Repeater $repeater */ |
37
|
|
|
$repeater = $this->crud()->getFieldByName($fieldName); |
38
|
|
|
|
39
|
|
|
return response()->json([ |
40
|
|
|
'view' => $repeater->getRepeaterItemFormView( |
41
|
|
|
$request->get('data') |
|
|
|
|
42
|
|
|
)->render(), |
43
|
|
|
]); |
44
|
|
|
} |
45
|
|
|
|
46
|
|
|
/** |
47
|
|
|
* Flatten a multi-dimensional associative array with dots, without index part at the end. |
48
|
|
|
* |
49
|
|
|
* @return array |
50
|
|
|
*/ |
51
|
|
|
private function flatten($array, $prepend = '', bool $force = false): array |
52
|
|
|
{ |
53
|
|
|
$results = []; |
54
|
|
|
|
55
|
|
|
if ($force) { |
56
|
|
|
$results[$prepend] = $array; |
57
|
|
|
return $results; |
58
|
|
|
} |
59
|
|
|
|
60
|
|
|
foreach ($array as $key => $value) { |
61
|
|
|
if (is_array($value) && !empty($value)) { |
62
|
|
|
$isLastArray = false; |
63
|
|
|
foreach ($value as $innerValue) { |
64
|
|
|
if (is_array($innerValue)) { |
65
|
|
|
$isLastArray = false; |
66
|
|
|
break; |
67
|
|
|
} |
68
|
|
|
|
69
|
|
|
$isLastArray = true; |
70
|
|
|
} |
71
|
|
|
|
72
|
|
|
if ($isLastArray) { |
73
|
|
|
$results = array_merge($results, $this->flatten($value, $prepend . $key, true)); |
74
|
|
|
} else { |
75
|
|
|
$results = array_merge($results, $this->flatten($value, $prepend . $key . '.')); |
76
|
|
|
} |
77
|
|
|
} else { |
78
|
|
|
$results[$prepend . $key] = $value; |
79
|
|
|
} |
80
|
|
|
} |
81
|
|
|
|
82
|
|
|
return $results; |
83
|
|
|
} |
84
|
|
|
|
85
|
|
|
abstract protected function beforeInit(); |
86
|
|
|
abstract protected function init(); |
87
|
|
|
abstract protected function bound(); |
88
|
|
|
abstract protected function crud(): CRUD; |
89
|
|
|
} |
90
|
|
|
|