Skip to content
Permalink
Browse files

Added support for pattern() (#6)

  • Loading branch information...
integer authored and dg committed Jul 9, 2019
1 parent b314c64 commit 34976792c24f1af184cd840f5f38533fdef0ca09
Showing with 50 additions and 0 deletions.
  1. +10 −0 readme.md
  2. +14 −0 src/Schema/Elements/Type.php
  3. +26 −0 tests/Schema/Expect.pattern.phpt
@@ -221,6 +221,16 @@ Ranges of numbers are specified using a combination of `min()` and `max()`:
$schema = Expect::int()->min(10)->max(20);
```

Regular expressions
-------------------

String can be restricted by regular expression using the `pattern()`:

```php
// just 9 numbers
$schema = Expect::string()->pattern('\d{9}');
```

Data mapping to objects
-----------------------

@@ -30,6 +30,9 @@ final class Type implements Schema
/** @var array */
private $range = [null, null];
/** @var string|null */
private $pattern;
public function __construct(string $type)
{
@@ -77,6 +80,13 @@ public function items($type = 'mixed'): self
}
public function pattern(string $pattern): self
{
$this->pattern = $pattern;
return $this;
}
/********************* processing ****************d*g**/
@@ -129,6 +139,10 @@ public function complete($value, Context $context)
if (!$this->doValidate($value, $expected, $context)) {
return;
}
if ($this->pattern !== null && !preg_match("\x01^(?:$this->pattern)$\x01Du", $value)) {
$context->addError("The option %path% expects to match pattern '$this->pattern', '$value' given.");
return;
}
if ($value instanceof DynamicParameter) {
$context->dynamics[] = [$value, str_replace('|' . DynamicParameter::class, '', $expected)];
@@ -0,0 +1,26 @@
<?php
declare(strict_types=1);
use Nette\Schema\Expect;
use Nette\Schema\Processor;
use Tester\Assert;
require __DIR__ . '/../bootstrap.php';
test(function () {
$schema = Expect::string()->pattern('\d{9}');
Assert::same('123456789', (new Processor)->process($schema, '123456789'));
});
test(function () {
$schema = Expect::string()->pattern('\d{9}');
checkValidationErrors(function () use ($schema) {
(new Processor)->process($schema, '123');
}, ["The option expects to match pattern '\\d{9}', '123' given."]);
});

0 comments on commit 3497679

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