|
| 1 | +<?php |
| 2 | + |
| 3 | +declare(strict_types=1); |
| 4 | + |
| 5 | +namespace Yiisoft\Validator\Tests; |
| 6 | + |
| 7 | +use PHPUnit\Framework\TestCase; |
| 8 | +use Yiisoft\Validator\Result; |
| 9 | +use Yiisoft\Validator\ResultSet; |
| 10 | +use Yiisoft\Validator\Rule\Boolean; |
| 11 | +use Yiisoft\Validator\Rule\Number; |
| 12 | + |
| 13 | +abstract class AbstractDataSetTest extends TestCase |
| 14 | +{ |
| 15 | + /** |
| 16 | + * @dataProvider validationCasesDataProvider() |
| 17 | + * |
| 18 | + * @param array $dataSet |
| 19 | + */ |
| 20 | + final public function test(array $dataSet, array $rules): void |
| 21 | + { |
| 22 | + $resultSet = $this->validate($dataSet, $rules); |
| 23 | + |
| 24 | + $this->assertTrue($resultSet->isValid()); |
| 25 | + } |
| 26 | + |
| 27 | + public function validationCasesDataProvider(): array |
| 28 | + { |
| 29 | + return [ |
| 30 | + [ |
| 31 | + [ |
| 32 | + 'bool' => true, |
| 33 | + 'int' => 41, |
| 34 | + ], |
| 35 | + [ |
| 36 | + 'bool' => [new Boolean()], |
| 37 | + 'int' => [new Number()], |
| 38 | + ], |
| 39 | + ], |
| 40 | + ]; |
| 41 | + } |
| 42 | + |
| 43 | + /** |
| 44 | + * @dataProvider resultDataProvider() |
| 45 | + * |
| 46 | + * @param array $dataSet |
| 47 | + */ |
| 48 | + public function testResult(array $dataSet, array $rules): void |
| 49 | + { |
| 50 | + $resultSet = $this->validate($dataSet, $rules); |
| 51 | + |
| 52 | + $this->assertTrue($resultSet->getResult('bool')->isValid()); |
| 53 | + |
| 54 | + $intResult = $resultSet->getResult('int'); |
| 55 | + $this->assertFalse($intResult->isValid()); |
| 56 | + $this->assertCount(1, $intResult->getErrors()); |
| 57 | + } |
| 58 | + |
| 59 | + public function resultDataProvider(): array |
| 60 | + { |
| 61 | + return [ |
| 62 | + [ |
| 63 | + [ |
| 64 | + 'bool' => true, |
| 65 | + 'int' => 41, |
| 66 | + ], |
| 67 | + [ |
| 68 | + 'bool' => [new Boolean()], |
| 69 | + 'int' => [ |
| 70 | + (new Number())->integer(), |
| 71 | + (new Number())->integer()->min(44), |
| 72 | + static function ($value): Result { |
| 73 | + $result = new Result(); |
| 74 | + if ($value !== 42) { |
| 75 | + $result->addError('Value should be 42!'); |
| 76 | + } |
| 77 | + return $result; |
| 78 | + }, |
| 79 | + ], |
| 80 | + ], |
| 81 | + ], |
| 82 | + ]; |
| 83 | + } |
| 84 | + |
| 85 | + abstract protected function validate(array $dataSet, array $rules): ResultSet; |
| 86 | +} |
0 commit comments