1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Selective\Validation\Transformer; |
4
|
|
|
|
5
|
|
|
use Selective\Validation\ValidationError; |
6
|
|
|
use Selective\Validation\ValidationResult; |
7
|
|
|
|
8
|
|
|
/** |
9
|
|
|
* Transform validation result to array with error details. |
10
|
|
|
*/ |
11
|
|
|
final class ErrorDetailsTransformer implements TransformerInterface |
12
|
|
|
{ |
13
|
|
|
/** |
14
|
|
|
* @var string |
15
|
|
|
*/ |
16
|
|
|
private $detailsName; |
17
|
|
|
|
18
|
|
|
/** |
19
|
|
|
* The constructor. |
20
|
|
|
* |
21
|
|
|
* @param string $detailsName The name of the details index. |
22
|
|
|
*/ |
23
|
3 |
|
public function __construct(string $detailsName = 'details') |
24
|
|
|
{ |
25
|
3 |
|
$this->detailsName = $detailsName; |
26
|
3 |
|
} |
27
|
|
|
|
28
|
|
|
/** |
29
|
|
|
* Transform the given ValidationResult into an array. |
30
|
|
|
* |
31
|
|
|
* @param ValidationResult $validationResult The validation result |
32
|
|
|
* |
33
|
|
|
* @return array<mixed> The transformed result |
34
|
|
|
*/ |
35
|
2 |
|
public function transform(ValidationResult $validationResult): array |
36
|
|
|
{ |
37
|
2 |
|
$error = []; |
38
|
|
|
|
39
|
2 |
|
$code = $validationResult->getCode(); |
40
|
2 |
|
if ($code !== null) { |
41
|
|
|
$error['code'] = $code; |
42
|
|
|
} |
43
|
|
|
|
44
|
2 |
|
$message = $validationResult->getMessage(); |
45
|
2 |
|
if ($message !== null) { |
46
|
1 |
|
$error['message'] = $message; |
47
|
|
|
} |
48
|
|
|
|
49
|
2 |
|
$errors = $validationResult->getErrors(); |
50
|
2 |
|
if ($errors) { |
|
|
|
|
51
|
2 |
|
$error[$this->detailsName] = $this->getErrorDetails($errors); |
52
|
|
|
} |
53
|
|
|
|
54
|
2 |
|
return ['error' => $error]; |
55
|
|
|
} |
56
|
|
|
|
57
|
|
|
/** |
58
|
|
|
* Get error details. |
59
|
|
|
* |
60
|
|
|
* @param ValidationError[] $errors The errors |
61
|
|
|
* |
62
|
|
|
* @return array<mixed> The details as array |
63
|
|
|
*/ |
64
|
2 |
|
private function getErrorDetails(array $errors): array |
65
|
|
|
{ |
66
|
2 |
|
$details = []; |
67
|
|
|
|
68
|
2 |
|
foreach ($errors as $error) { |
69
|
|
|
$item = [ |
70
|
2 |
|
'message' => $error->getMessage(), |
71
|
|
|
]; |
72
|
|
|
|
73
|
2 |
|
$fieldName = $error->getField(); |
74
|
2 |
|
if ($fieldName !== null) { |
75
|
2 |
|
$item['field'] = $fieldName; |
76
|
|
|
} |
77
|
|
|
|
78
|
2 |
|
$errorCode = $error->getCode(); |
79
|
2 |
|
if ($errorCode !== null) { |
80
|
1 |
|
$item['code'] = $errorCode; |
81
|
|
|
} |
82
|
|
|
|
83
|
2 |
|
$details[] = $item; |
84
|
|
|
} |
85
|
|
|
|
86
|
2 |
|
return $details; |
87
|
|
|
} |
88
|
|
|
} |
89
|
|
|
|
This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.
Consider making the comparison explicit by using
empty(..)
or! empty(...)
instead.