forked from DataValues/Interfaces
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathResult.php
More file actions
86 lines (73 loc) · 1.76 KB
/
Result.php
File metadata and controls
86 lines (73 loc) · 1.76 KB
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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
<?php
declare( strict_types = 1 );
namespace ValueValidators;
/**
* @license GPL-2.0-or-later
* @author Jeroen De Dauw < jeroendedauw@gmail.com >
*/
final class Result {
private bool $isValid;
private array $errors;
/**
* @return self
*/
public static function newSuccess(): self {
return new static( true );
}
/**
* @param Error[] $errors
*
* @return self
*/
public static function newError( array $errors ): self {
return new static( false, $errors );
}
/**
* Returns a result that represents the combination of the two given results.
* In particular, this means:
*
* If $a->getErrors() is empty and $a->isValid() is true, $b is returned.
* If $b->getErrors() is empty and $b->isValid() is true, $a is returned.
*
* Otherwise, a new Result is constructed that contains
* all errors from $a and $b, and is considered valid
* if both $a and $b were valid.
*
* @param self $a
* @param self $b
*
* @return self
*/
public static function merge( self $a, self $b ): self {
$aErrors = $a->getErrors();
$bErrors = $b->getErrors();
if ( $a->isValid() && empty( $aErrors ) ) {
return $b;
} elseif ( $b->isValid() && empty( $bErrors ) ) {
return $a;
} else {
$errors = array_merge( $aErrors, $bErrors );
$valid = ( $a->isValid() && $b->isValid() );
return new self( $valid, $errors );
}
}
/**
* @param bool $isValid
* @param Error[] $errors
*/
protected function __construct( bool $isValid, array $errors = [] ) {
$this->isValid = $isValid;
$this->errors = $errors;
}
public function isValid(): bool {
return $this->isValid;
}
/**
* Returns an array with the errors that occurred during validation.
*
* @return Error[]
*/
public function getErrors(): array {
return $this->errors;
}
}