benanamen /
perfect-validation
| 1 | <?php declare(strict_types=1); |
||
| 2 | |||
| 3 | namespace PerfectApp\Validation; |
||
| 4 | |||
| 5 | |||
| 6 | class Validator |
||
| 7 | { |
||
| 8 | /** |
||
| 9 | * @var ValidationStrategy |
||
| 10 | */ |
||
| 11 | private ValidationStrategy $strategy; |
||
| 12 | |||
| 13 | /** |
||
| 14 | * @param ValidationStrategy $strategy |
||
| 15 | */ |
||
| 16 | 5 | public function __construct(ValidationStrategy $strategy) |
|
| 17 | { |
||
| 18 | 5 | $this->strategy = $strategy; |
|
| 19 | } |
||
| 20 | |||
| 21 | /** |
||
| 22 | * @param ValidationStrategy $strategy |
||
| 23 | * @return void |
||
| 24 | */ |
||
| 25 | 1 | public function setValidationStrategy(ValidationStrategy $strategy): void |
|
| 26 | { |
||
| 27 | 1 | $this->strategy = $strategy; |
|
| 28 | } |
||
| 29 | |||
| 30 | /** |
||
| 31 | * @param $data |
||
| 32 | * @return mixed |
||
| 33 | */ |
||
| 34 | 1 | public function validateData($data): mixed |
|
| 35 | { |
||
| 36 | 1 | return $this->strategy->validate($data); |
|
| 37 | } |
||
| 38 | |||
| 39 | 3 | public function validateDataWithErrors($data): array |
|
| 40 | { |
||
| 41 | 3 | $isValid = $this->strategy->validate($data); |
|
| 42 | 3 | if ($isValid) { |
|
| 43 | 1 | return ['isValid' => true]; |
|
| 44 | } |
||
| 45 | |||
| 46 | 2 | if (method_exists($this->strategy, 'getErrors')) { |
|
| 47 | 1 | return [ |
|
| 48 | 1 | 'isValid' => false, |
|
| 49 | 1 | 'errors' => $this->strategy->getErrors() |
|
|
0 ignored issues
–
show
Bug
introduced
by
Loading history...
|
|||
| 50 | 1 | ]; |
|
| 51 | } |
||
| 52 | |||
| 53 | 1 | return ['isValid' => false]; |
|
| 54 | } |
||
| 55 | } |
||
| 56 |