|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace Backpack\CRUD\app\Library\Validation\Rules; |
|
4
|
|
|
|
|
5
|
|
|
use Backpack\CRUD\app\Library\CrudPanel\CrudPanelFacade; |
|
6
|
|
|
use Illuminate\Contracts\Validation\Rule; |
|
7
|
|
|
use Illuminate\Contracts\Validation\ValidationRule; |
|
8
|
|
|
use Illuminate\Http\UploadedFile; |
|
9
|
|
|
use Illuminate\Support\Arr; |
|
10
|
|
|
use Illuminate\Support\Str; |
|
11
|
|
|
|
|
12
|
|
|
class ValidUpload extends BackpackCustomRule |
|
13
|
|
|
{ |
|
14
|
|
|
/** |
|
15
|
|
|
* Run the validation rule and return the array of errors. |
|
16
|
|
|
*/ |
|
17
|
|
|
public function validateRules(string $attribute, mixed $value): array |
|
18
|
|
|
{ |
|
19
|
|
|
$entry = CrudPanelFacade::getCurrentEntry(); |
|
|
|
|
|
|
20
|
|
|
|
|
21
|
|
|
// if the attribute is not set in the request, and an entry exists, |
|
22
|
|
|
// we will check if there is a previous value, as this field might not have changed. |
|
23
|
|
|
if (! Arr::has($this->data, $attribute) && $entry) { |
|
24
|
|
|
if (str_contains($attribute, '.') && get_class($entry) === get_class(CrudPanelFacade::getModel())) { |
|
|
|
|
|
|
25
|
|
|
$previousValue = Arr::get($this->data, '_order_'.Str::before($attribute, '.')); |
|
26
|
|
|
$previousValue = Arr::get($previousValue, Str::after($attribute, '.')); |
|
27
|
|
|
} else { |
|
28
|
|
|
$previousValue = Arr::get($entry, $attribute); |
|
29
|
|
|
} |
|
30
|
|
|
|
|
31
|
|
|
if ($previousValue && empty($value)) { |
|
32
|
|
|
return []; |
|
33
|
|
|
} |
|
34
|
|
|
|
|
35
|
|
|
Arr::set($this->data, $attribute, $previousValue ?? $value); |
|
36
|
|
|
} |
|
37
|
|
|
|
|
38
|
|
|
// if the value is an uploaded file, or the attribute is not |
|
39
|
|
|
// set in the request, we force fill the data with the value |
|
40
|
|
|
if ($value instanceof UploadedFile || ! Arr::has($this->data, $attribute)) { |
|
41
|
|
|
Arr::set($this->data, $attribute, $value); |
|
42
|
|
|
} |
|
43
|
|
|
|
|
44
|
|
|
// if there are no entry, and the new value it's not a file ... well we don't want it at all. |
|
45
|
|
|
if (! $entry && ! $value instanceof UploadedFile) { |
|
46
|
|
|
Arr::set($this->data, $attribute, null); |
|
47
|
|
|
} |
|
48
|
|
|
|
|
49
|
|
|
$fieldErrors = $this->validateFieldRules($attribute); |
|
50
|
|
|
|
|
51
|
|
|
if (! empty($value) && ! empty($this->getFileRules())) { |
|
52
|
|
|
$fileErrors = $this->validateFileRules($attribute, $value); |
|
53
|
|
|
} |
|
54
|
|
|
|
|
55
|
|
|
return array_merge($fieldErrors, $fileErrors ?? []); |
|
56
|
|
|
} |
|
57
|
|
|
|
|
58
|
|
|
public static function field(string|array|ValidationRule|Rule $rules = []): self |
|
59
|
|
|
{ |
|
60
|
|
|
return parent::field($rules); |
|
|
|
|
|
|
61
|
|
|
} |
|
62
|
|
|
} |
|
63
|
|
|
|