This repository has been archived by the owner on Mar 28, 2022. It is now read-only.
/
MappingTrait.php
65 lines (54 loc) · 2 KB
/
MappingTrait.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
<?php
declare(strict_types = 1);
namespace DASPRiD\Formidable\Mapping;
use DASPRiD\Formidable\FormError\FormError;
use DASPRiD\Formidable\Mapping\Constraint\ConstraintInterface;
use DASPRiD\Formidable\Mapping\Constraint\ValidationError;
use DASPRiD\Formidable\Mapping\Constraint\ValidationResult;
trait MappingTrait
{
/**
* @var ConstraintInterface[]
*/
private $constraints = [];
public function verifying(ConstraintInterface ...$constraints) : MappingInterface
{
$mapping = clone $this;
$mapping->constraints = array_merge($this->constraints, $constraints);
return $mapping;
}
protected function applyConstraints($value, string $key) : BindResult
{
$validationResult = new ValidationResult();
foreach ($this->constraints as $constraint) {
$validationResult = $validationResult->merge($constraint($value));
}
if ($validationResult->isSuccess()) {
return BindResult::fromValue($value);
}
return BindResult::fromFormErrors(...array_map(
function (ValidationError $validationError) use ($key) {
if ('' === $key) {
$finalKey = $validationError->getKeySuffix();
} elseif ('' === $validationError->getKeySuffix()) {
$finalKey = $key;
} else {
$finalKey = $key . preg_replace('(^[^\[]+)', '[\0]', $validationError->getKeySuffix());
}
return new FormError(
$finalKey,
$validationError->getMessage(),
$validationError->getArguments()
);
},
iterator_to_array($validationResult->getValidationErrors())
));
}
protected function createKeyFromPrefixAndRelativeKey(string $prefix, string $relativeKey) : string
{
if ('' === $prefix) {
return $relativeKey;
}
return $prefix . '[' . $relativeKey . ']';
}
}