Skip to content
Permalink
Browse files

Assert with optinal description #7 (#8)

  • Loading branch information...
integer authored and dg committed Sep 15, 2019
1 parent 1e6c878 commit 2aa0542d992f4e97ef541d5226d43a0e519f6267
Showing with 38 additions and 6 deletions.
  1. +15 −0 readme.md
  2. +6 −6 src/Schema/Elements/Base.php
  3. +17 −0 tests/Schema/Expect.assert.phpt
@@ -314,3 +314,18 @@ $schema = Expect::arrayOf('string')
$processor->process($schema, ['a', 'b']); // it passes, 2 is even number
$processor->process($schema, ['a', 'b', 'c']); // error, 3 is not even number
```

Or

```php
$schema = Expect::string()->assert('is_file'); // file must exist
```

You can add custom description for every assert. This description will be part of error message.

```php
$schema = Expect::arrayOf('string')
->assert(function ($v) { return count($v) % 2 === 0; }, 'Even items in array');
$processor->process($schema, ['a', 'b', 'c']); // Failed assertion "Even items in array" for option with value array.
```
@@ -27,7 +27,7 @@ trait Base
/** @var callable|null */
private $before;
/** @var callable[] */
/** @var array[] */
private $asserts = [];
/** @var string|null */
@@ -62,9 +62,9 @@ public function castTo(string $type): self
}
public function assert(callable $handler): self
public function assert(callable $handler, string $description = null): self
{
$this->asserts[] = $handler;
$this->asserts[] = [$handler, $description];
return $this;
}
@@ -110,9 +110,9 @@ private function doFinalize($value, Context $context)
}
}
foreach ($this->asserts as $i => $assert) {
if (!$assert($value)) {
$expected = is_string($assert) ? "$assert()" : "#$i";
foreach ($this->asserts as $i => [$handler, $description]) {
if (!$handler($value)) {
$expected = $description ? ('"' . $description . '"') : (is_string($handler) ? "$handler()" : "#$i");
$context->addError("Failed assertion $expected for option %path% with value " . static::formatValue($value) . '.');
return;
}
@@ -34,3 +34,20 @@ test(function () { // multiple assertions
Assert::same('123', (new Processor)->process($schema, '123'));
});
test(function () { // multiple assertions with custom descriptions
$schema = Expect::string()
->assert('ctype_digit', 'Is number')
->assert(function ($s) { return strlen($s) >= 3; }, 'Minimal lenght');
checkValidationErrors(function () use ($schema) {
(new Processor)->process($schema, '');
}, ["Failed assertion \"Is number\" for option with value ''."]);
checkValidationErrors(function () use ($schema) {
(new Processor)->process($schema, '1');
}, ["Failed assertion \"Minimal lenght\" for option with value '1'."]);
Assert::same('123', (new Processor)->process($schema, '123'));
});

0 comments on commit 2aa0542

Please sign in to comment.
You can’t perform that action at this time.