|
1
|
|
|
<?php declare(strict_types=1); |
|
2
|
|
|
|
|
3
|
|
|
namespace Thinktomorrow\Chief\Fields\Validation; |
|
4
|
|
|
|
|
5
|
|
|
use Thinktomorrow\Chief\Fields\Types\Field; |
|
6
|
|
|
use Illuminate\Contracts\Validation\Validator; |
|
7
|
|
|
use Illuminate\Contracts\Validation\Factory; |
|
8
|
|
|
|
|
9
|
|
|
class FieldValidatorFactory |
|
10
|
|
|
{ |
|
11
|
|
|
/** @var Factory */ |
|
12
|
|
|
private $validatorFactory; |
|
13
|
|
|
|
|
14
|
|
|
public function __construct(Factory $validatorFactory) |
|
15
|
|
|
{ |
|
16
|
|
|
$this->validatorFactory = $validatorFactory; |
|
17
|
|
|
} |
|
18
|
|
|
|
|
19
|
|
|
public function create(Field $field, array $data): Validator |
|
20
|
|
|
{ |
|
21
|
|
|
if (!$field->hasValidation()) { |
|
22
|
|
|
return new NullValidator(); |
|
23
|
|
|
} |
|
24
|
|
|
|
|
25
|
|
|
if ($field->getValidation() instanceof Validator) { |
|
26
|
|
|
return $field->getValidation(); |
|
27
|
|
|
} |
|
28
|
|
|
|
|
29
|
|
|
if ($field->getValidation() instanceof \Closure) { |
|
30
|
|
|
$closure = $field->getValidation(); |
|
31
|
|
|
return $closure($this->validatorFactory, $data); |
|
32
|
|
|
} |
|
33
|
|
|
|
|
34
|
|
|
return $this->composeValidatorFromRules($field, $data); |
|
35
|
|
|
} |
|
36
|
|
|
|
|
37
|
|
|
private function composeValidatorFromRules(Field $field, array $data): Validator |
|
38
|
|
|
{ |
|
39
|
|
|
$validation = $field->getValidation(); |
|
40
|
|
|
|
|
41
|
|
|
return $this->validatorFactory->make($data, |
|
42
|
|
|
$this->sanitizeValidationValues($field, $validation[0] ?? [], $data), // rules |
|
43
|
|
|
$this->sanitizeValidationValues($field, $validation[1] ?? [], $data), // messages |
|
44
|
|
|
$this->sanitizeValidationValues($field, $validation[2] ?? [], $data) // attributes |
|
45
|
|
|
); |
|
46
|
|
|
} |
|
47
|
|
|
|
|
48
|
|
|
/** |
|
49
|
|
|
* @param Field $field |
|
50
|
|
|
* @param string|array $values |
|
51
|
|
|
* @param array $payload |
|
52
|
|
|
* @return array|null |
|
53
|
|
|
*/ |
|
54
|
|
|
private function sanitizeValidationValues(Field $field, $values, array $payload): array |
|
55
|
|
|
{ |
|
56
|
|
|
// Complete rule definitions - in the format of [attribute => rules] - will be left as is and are not being manipulated e.g. ['foobar' => 'required'] |
|
57
|
|
|
// Otherwise if the rules are being passed as an array, they will be normalized to a string. |
|
58
|
|
|
if(is_array($values)){ |
|
59
|
|
|
if(is_string(key($values))) { |
|
60
|
|
|
return $values; |
|
61
|
|
|
} |
|
62
|
|
|
|
|
63
|
|
|
$values = reset($values); |
|
64
|
|
|
} |
|
65
|
|
|
|
|
66
|
|
|
return array_fill_keys( $field->getValidationNames($payload) , $values); |
|
|
|
|
|
|
67
|
|
|
} |
|
68
|
|
|
} |
|
69
|
|
|
|
This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.
This is most likely a typographical error or the method has been renamed.