1
|
|
|
<?php declare(strict_types=1); |
2
|
|
|
|
3
|
|
|
namespace Thinktomorrow\Chief\Fields\Validation; |
4
|
|
|
|
5
|
|
|
use Thinktomorrow\Chief\Fields\Fields; |
6
|
|
|
use Thinktomorrow\Chief\Fields\Types\Field; |
7
|
|
|
use Illuminate\Contracts\Validation\Factory; |
8
|
|
|
use Illuminate\Contracts\Validation\Validator; |
9
|
|
|
|
10
|
|
|
class FieldValidator |
11
|
|
|
{ |
12
|
|
|
/** @var Factory */ |
13
|
|
|
private $validatorFactory; |
14
|
|
|
|
15
|
|
|
public function __construct(Factory $validatorFactory) |
16
|
|
|
{ |
17
|
|
|
$this->validatorFactory = $validatorFactory; |
18
|
|
|
} |
19
|
|
|
|
20
|
|
|
public function handle(Fields $fields, array $payload) |
21
|
|
|
{ |
22
|
|
|
foreach($fields as $field) { |
23
|
|
|
if ($field->hasValidation()) { |
24
|
|
|
$this->createValidator($field, $payload)->validate(); |
25
|
|
|
} |
26
|
|
|
} |
27
|
|
|
} |
28
|
|
|
|
29
|
|
|
private function createValidator(Field $field, array $payload): Validator |
30
|
|
|
{ |
31
|
|
|
return $this->validatorFactory->make($payload, |
32
|
|
|
$this->ruleMatrix($field->getValidationNames($payload), $field->getValidationParameters()->getRules()), // rules |
|
|
|
|
33
|
|
|
$this->matrix($field->getValidationNames($payload), $field->getValidationParameters()->getMessages()), // messages |
34
|
|
|
$this->matrix($field->getValidationNames($payload), $field->getValidationParameters()->getAttributes()) // attributes |
35
|
|
|
); |
36
|
|
|
} |
37
|
|
|
|
38
|
|
|
/* |
39
|
|
|
* Complete rule definitions - in the format of [attribute => rules] - will be left as is and are not being manipulated e.g. ['foobar' => 'required'] |
40
|
|
|
* Otherwise if the rules are being passed as an array, they will be normalized to a string. |
41
|
|
|
*/ |
42
|
|
|
private function ruleMatrix(array $keys, array $values): array |
43
|
|
|
{ |
44
|
|
|
if(is_string(key($values))) { |
45
|
|
|
return $values; |
46
|
|
|
} |
47
|
|
|
|
48
|
|
|
return array_fill_keys($keys , $values); |
49
|
|
|
} |
50
|
|
|
|
51
|
|
|
private function matrix(array $keys, array $values): array |
52
|
|
|
{ |
53
|
|
|
if(empty($values)) return []; |
54
|
|
|
|
55
|
|
|
return array_fill_keys($keys, reset($values)); |
56
|
|
|
} |
57
|
|
|
} |
58
|
|
|
|
This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.
If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress. Please note the @ignore annotation hint above.