|
1
|
|
|
<?php |
|
2
|
|
|
declare(strict_types=1); |
|
3
|
|
|
/** |
|
4
|
|
|
* Caridea |
|
5
|
|
|
* |
|
6
|
|
|
* Licensed under the Apache License, Version 2.0 (the "License"); you may not |
|
7
|
|
|
* use this file except in compliance with the License. You may obtain a copy of |
|
8
|
|
|
* the License at |
|
9
|
|
|
* |
|
10
|
|
|
* http://www.apache.org/licenses/LICENSE-2.0 |
|
11
|
|
|
* |
|
12
|
|
|
* Unless required by applicable law or agreed to in writing, software |
|
13
|
|
|
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT |
|
14
|
|
|
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the |
|
15
|
|
|
* License for the specific language governing permissions and limitations under |
|
16
|
|
|
* the License. |
|
17
|
|
|
* |
|
18
|
|
|
* @copyright 2015-2018 LibreWorks contributors |
|
19
|
|
|
* @license Apache-2.0 |
|
20
|
|
|
*/ |
|
21
|
|
|
namespace Caridea\Validate; |
|
22
|
|
|
|
|
23
|
|
|
/** |
|
24
|
|
|
* A validation result. |
|
25
|
|
|
* |
|
26
|
|
|
* @copyright 2015-2018 LibreWorks contributors |
|
27
|
|
|
* @license Apache-2.0 |
|
28
|
|
|
*/ |
|
29
|
|
|
class Result |
|
30
|
|
|
{ |
|
31
|
|
|
/** |
|
32
|
|
|
* @var bool Whether the validation passed |
|
33
|
|
|
*/ |
|
34
|
|
|
private $passed; |
|
35
|
|
|
/** |
|
36
|
|
|
* @var array The result errors |
|
37
|
|
|
*/ |
|
38
|
|
|
private $errors; |
|
39
|
|
|
|
|
40
|
|
|
/** |
|
41
|
|
|
* Creates a new validation result. |
|
42
|
|
|
* |
|
43
|
|
|
* @param array $errors Associative array of field name to error |
|
44
|
|
|
*/ |
|
45
|
1 |
|
public function __construct(array $errors) |
|
46
|
|
|
{ |
|
47
|
1 |
|
$this->passed = empty($errors); |
|
48
|
1 |
|
$this->errors = $errors; |
|
49
|
1 |
|
} |
|
50
|
|
|
|
|
51
|
|
|
/** |
|
52
|
|
|
* Whether the validation passed. |
|
53
|
|
|
* |
|
54
|
|
|
* @return bool |
|
55
|
|
|
*/ |
|
56
|
1 |
|
public function hasErrors(): bool |
|
57
|
|
|
{ |
|
58
|
1 |
|
return !$this->passed; |
|
59
|
|
|
} |
|
60
|
|
|
|
|
61
|
|
|
/** |
|
62
|
|
|
* Gets all errors. |
|
63
|
|
|
* |
|
64
|
|
|
* ``` |
|
65
|
|
|
* [ |
|
66
|
|
|
* 'name' => 'REQUIRED', |
|
67
|
|
|
* 'phone' => 'CANNOT_BE_EMPTY' |
|
68
|
|
|
* ] |
|
69
|
|
|
* ``` |
|
70
|
|
|
* |
|
71
|
|
|
* @return array Associative array of field name to error |
|
72
|
|
|
*/ |
|
73
|
1 |
|
public function getErrors(): array |
|
74
|
|
|
{ |
|
75
|
1 |
|
return $this->errors; |
|
76
|
|
|
} |
|
77
|
|
|
|
|
78
|
|
|
/** |
|
79
|
|
|
* Gets the errors as a JSON string. |
|
80
|
|
|
* |
|
81
|
|
|
* @return string The errors as a JSON string |
|
82
|
|
|
*/ |
|
83
|
1 |
|
public function __toString(): string |
|
84
|
|
|
{ |
|
85
|
1 |
|
return json_encode($this->errors); |
|
86
|
|
|
} |
|
87
|
|
|
} |
|
88
|
|
|
|