1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Backpack\CRUD\app\Library\Validation\Rules; |
4
|
|
|
|
5
|
|
|
use Backpack\CRUD\app\Library\CrudPanel\CrudPanelFacade; |
6
|
|
|
use Backpack\CRUD\app\Library\Validation\Rules\Support\ValidateArrayContract; |
7
|
|
|
use Illuminate\Support\Arr; |
8
|
|
|
use Illuminate\Support\Str; |
9
|
|
|
|
10
|
|
|
class ValidUploadMultiple extends BackpackCustomRule implements ValidateArrayContract |
11
|
|
|
{ |
12
|
|
|
public function validateRules(string $attribute, mixed $value): array |
13
|
|
|
{ |
14
|
|
|
$entry = CrudPanelFacade::getCurrentEntry() !== false ? CrudPanelFacade::getCurrentEntry() : null; |
|
|
|
|
15
|
|
|
$data = $this->data; |
16
|
|
|
// `upload_multiple` sends [[0 => null]] when user doesn't upload anything |
17
|
|
|
// assume that nothing changed on field so nothing is sent on the request. |
18
|
|
|
if (count($value) === 1 && empty($value[0])) { |
19
|
|
|
Arr::set($data, $attribute, []); |
20
|
|
|
$value = []; |
21
|
|
|
} |
22
|
|
|
|
23
|
|
|
$previousValues = str_contains($attribute, '.') ? |
24
|
|
|
(Arr::get($entry?->{Str::before($attribute, '.')} ?? [], Str::after($attribute, '.')) ?? []) : |
25
|
|
|
($entry?->{$attribute} ?? []); |
26
|
|
|
|
27
|
|
|
if (is_string($previousValues)) { |
28
|
|
|
$previousValues = json_decode($previousValues, true) ?? []; |
29
|
|
|
} |
30
|
|
|
|
31
|
|
|
Arr::set($data, $attribute, array_merge($previousValues, $value)); |
32
|
|
|
|
33
|
|
|
if ($entry) { |
34
|
|
|
$filesDeleted = CrudPanelFacade::getRequest()->input('clear_'.$attribute) ?? []; |
|
|
|
|
35
|
|
|
Arr::set($data, $attribute, array_diff(Arr::get($data, $attribute), $filesDeleted)); |
|
|
|
|
36
|
|
|
|
37
|
|
|
return $this->validateFieldAndFile($attribute, $data); |
38
|
|
|
} |
39
|
|
|
|
40
|
|
|
// if there is no entry, the values we are going to validate need to be files |
41
|
|
|
// the request was tampered so we will set the attribute to null |
42
|
|
|
if (! $entry && ! empty(Arr::get($data, $attribute)) && ! $this->allFiles(Arr::get($data, $attribute))) { |
|
|
|
|
43
|
|
|
Arr::set($data, $attribute, null); |
44
|
|
|
} |
45
|
|
|
|
46
|
|
|
return $this->validateFieldAndFile($attribute, $data); |
47
|
|
|
} |
48
|
|
|
|
49
|
|
|
private function allFiles(array $values): bool |
50
|
|
|
{ |
51
|
|
|
foreach ($values as $value) { |
52
|
|
|
if (! $value instanceof \Illuminate\Http\UploadedFile) { |
53
|
|
|
return false; |
54
|
|
|
} |
55
|
|
|
} |
56
|
|
|
|
57
|
|
|
return true; |
58
|
|
|
} |
59
|
|
|
} |
60
|
|
|
|