1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Selective\Validation\Converter; |
4
|
|
|
|
5
|
|
|
use Selective\Validation\ValidationResult; |
6
|
|
|
|
7
|
|
|
/** |
8
|
|
|
* CakePHP validation error convert. |
9
|
|
|
*/ |
10
|
|
|
final class CakeValidationConverter implements ValidationConverterInterface |
11
|
|
|
{ |
12
|
|
|
/** |
13
|
|
|
* Create validation result from array with errors. |
14
|
|
|
* |
15
|
|
|
* @param array $errors The validation errors |
16
|
|
|
* |
17
|
|
|
* @return ValidationResult The result |
18
|
|
|
*/ |
19
|
4 |
|
public function createValidationResult($errors): ValidationResult |
20
|
|
|
{ |
21
|
4 |
|
$result = new ValidationResult(); |
22
|
|
|
|
23
|
4 |
|
$this->addErrors($result, (array)$errors); |
24
|
|
|
|
25
|
4 |
|
return $result; |
26
|
|
|
} |
27
|
|
|
|
28
|
|
|
/** |
29
|
|
|
* Add errors. |
30
|
|
|
* |
31
|
|
|
* @param ValidationResult $result The result |
32
|
|
|
* @param array $errors The errors |
33
|
|
|
* @param string $path The path |
34
|
|
|
* |
35
|
|
|
* @return void |
36
|
|
|
*/ |
37
|
4 |
|
private function addErrors(ValidationResult $result, array $errors, string $path = ''): void |
38
|
|
|
{ |
39
|
4 |
|
foreach ($errors as $field => $error) { |
40
|
4 |
|
$oldPath = $path; |
41
|
4 |
|
$path .= ($path === '' ? '' : '.') . $field; |
42
|
4 |
|
$this->addSubErrors($result, $error, $path); |
43
|
4 |
|
$path = $oldPath; |
44
|
|
|
} |
45
|
4 |
|
} |
46
|
|
|
|
47
|
|
|
/** |
48
|
|
|
* Add sub errors. |
49
|
|
|
* |
50
|
|
|
* @param ValidationResult $result The result |
51
|
|
|
* @param array $error The error |
52
|
|
|
* @param string $path The path |
53
|
|
|
* |
54
|
|
|
* @return void |
55
|
|
|
*/ |
56
|
4 |
|
private function addSubErrors(ValidationResult $result, array $error, string $path = ''): void |
57
|
|
|
{ |
58
|
4 |
|
foreach ($error as $field2 => $errorMessage) { |
59
|
4 |
|
if (is_array($errorMessage)) { |
60
|
2 |
|
$this->addErrors($result, [$field2 => $errorMessage], $path); |
61
|
|
|
} else { |
62
|
4 |
|
$result->addError($path, $errorMessage); |
63
|
|
|
} |
64
|
|
|
} |
65
|
4 |
|
} |
66
|
|
|
} |
67
|
|
|
|