1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Logikos\Util\Config\Field\Adapter; |
4
|
|
|
|
5
|
|
|
use Logikos\Util\Config\Field; |
6
|
|
|
use Particle\Validator\ValidationResult; |
7
|
|
|
|
8
|
|
|
|
9
|
|
|
class Particle implements Field { |
10
|
|
|
/** |
11
|
|
|
* @var Particle\Validator |
12
|
|
|
*/ |
13
|
|
|
private $validator; |
14
|
|
|
private $name; |
15
|
|
|
/** |
16
|
|
|
* @var Particle\Chain |
17
|
|
|
*/ |
18
|
|
|
private $chain; |
19
|
|
|
|
20
|
8 |
|
protected function __construct($name, Particle\Validator $validator, Particle\Chain $chain) { |
21
|
8 |
|
$this->validator = $validator; |
22
|
8 |
|
$this->name = $name; |
23
|
8 |
|
$this->chain = $chain; |
24
|
8 |
|
} |
25
|
|
|
|
26
|
7 |
|
public static function required($name) : Particle { |
27
|
7 |
|
$v = new Particle\Validator();; |
28
|
7 |
|
return new self($name, $v, $v->required($name)); |
29
|
|
|
} |
30
|
|
|
|
31
|
1 |
|
public static function optional($name) : Particle { |
32
|
1 |
|
$v = new Particle\Validator();; |
33
|
1 |
|
return new self($name, $v, $v->optional($name)); |
34
|
|
|
} |
35
|
|
|
|
36
|
2 |
|
public function getName() { |
37
|
2 |
|
return $this->name; |
38
|
|
|
} |
39
|
|
|
|
40
|
3 |
|
public function validate($value): Field\Validation\Result { |
41
|
3 |
|
$particleResult = $this->validator->validate([ |
42
|
3 |
|
$this->name => $value |
43
|
|
|
]); |
44
|
3 |
|
if ($particleResult->isValid()) |
45
|
3 |
|
return new Field\Validation\ValidResult(); |
46
|
|
|
|
47
|
2 |
|
return $this->invalidResult($particleResult); |
48
|
|
|
} |
49
|
|
|
|
50
|
2 |
|
private function invalidResult(ValidationResult $particleResult) { |
51
|
2 |
|
$messages = []; |
52
|
2 |
|
foreach ($particleResult->getFailures() as $failure) { |
53
|
2 |
|
array_push($messages, $failure->format()); |
54
|
|
|
} |
55
|
2 |
|
return new Field\Validation\InvalidResult($messages); |
56
|
|
|
} |
57
|
|
|
|
58
|
5 |
|
public function chain() { |
59
|
5 |
|
return $this->chain; |
60
|
|
|
} |
61
|
|
|
} |