|
1
|
|
|
<?php declare(strict_types=1); |
|
2
|
|
|
|
|
3
|
|
|
namespace Thinktomorrow\Chief\Fields\ValidationRules; |
|
4
|
|
|
|
|
5
|
|
|
use Symfony\Component\HttpFoundation\File\File; |
|
6
|
|
|
use Illuminate\Validation\Concerns\ValidatesAttributes; |
|
7
|
|
|
use Thinktomorrow\Chief\Media\Application\MediaRequest; |
|
8
|
|
|
|
|
9
|
|
|
abstract class AbstractMediaFieldRule |
|
10
|
|
|
{ |
|
11
|
|
|
use ValidatesAttributes; |
|
|
|
|
|
|
12
|
|
|
use ValidatesExistingAssetAttributes; |
|
|
|
|
|
|
13
|
|
|
|
|
14
|
|
|
protected function normalizePayloadIncludingExistingMedia($value): array |
|
15
|
|
|
{ |
|
16
|
|
|
return $this->normalizePayload($value, false); |
|
17
|
|
|
} |
|
18
|
|
|
|
|
19
|
|
|
protected function normalizePayload($value, $excludeExistingMedia = true): array |
|
20
|
|
|
{ |
|
21
|
|
|
$payload = $this->emptyPayload(); |
|
22
|
|
|
|
|
23
|
|
|
if(!$value || !is_array($value)) return $payload; |
|
24
|
|
|
|
|
25
|
|
|
foreach([MediaRequest::NEW, MediaRequest::REPLACE, MediaRequest::DETACH] as $action) { |
|
26
|
|
|
if(isset($value[$action])){ |
|
27
|
|
|
|
|
28
|
|
|
// Front sometimes gives us a 0 => null array when an image is added and detached at the same time. |
|
29
|
|
|
// Here we check for these fake entries and exclude them. |
|
30
|
|
|
if(!is_array($value[$action]) || (count($value[$action]) === 1 && key($value[$action]) === 0 && is_null(reset($value[$action])))) { |
|
31
|
|
|
continue; |
|
32
|
|
|
} |
|
33
|
|
|
|
|
34
|
|
|
$payload[$action] = $value[$action]; |
|
35
|
|
|
|
|
36
|
|
|
// A replace NULL value passed from frontend is expected as a default so w'll need to remove it here to avoid unwanted validation. |
|
37
|
|
|
if($excludeExistingMedia && $action == MediaRequest::REPLACE && is_array($payload[$action])) { |
|
38
|
|
|
foreach($payload[$action] as $k => $v) { |
|
39
|
|
|
if(is_null($v)) unset($payload[$action][$k]); |
|
40
|
|
|
} |
|
41
|
|
|
} |
|
42
|
|
|
} |
|
43
|
|
|
} |
|
44
|
|
|
|
|
45
|
|
|
return $payload; |
|
46
|
|
|
} |
|
47
|
|
|
|
|
48
|
|
|
private function emptyPayload(): array |
|
49
|
|
|
{ |
|
50
|
|
|
return [ |
|
51
|
|
|
MediaRequest::NEW => [], |
|
52
|
|
|
MediaRequest::REPLACE => [], |
|
53
|
|
|
MediaRequest::DETACH => [], |
|
54
|
|
|
]; |
|
55
|
|
|
} |
|
56
|
|
|
|
|
57
|
|
|
/** |
|
58
|
|
|
* Default getSize method |
|
59
|
|
|
* |
|
60
|
|
|
* Override the default getSize from ValidatesAttributes to avoid calls to a hasRule method |
|
61
|
|
|
* For media fields this is not needed anyways. |
|
62
|
|
|
* |
|
63
|
|
|
* @param $attribute |
|
64
|
|
|
* @param $value |
|
65
|
|
|
* @return bool|false|float|int |
|
66
|
|
|
*/ |
|
67
|
|
|
protected function getSize($attribute, $value) |
|
|
|
|
|
|
68
|
|
|
{ |
|
69
|
|
|
if ($value instanceof File) { |
|
70
|
|
|
return $value->getSize() / 1024; |
|
71
|
|
|
} |
|
72
|
|
|
|
|
73
|
|
|
return mb_strlen($value); |
|
74
|
|
|
} |
|
75
|
|
|
} |
|
76
|
|
|
|