Skip to content

Commit

Permalink
Added support for pattern() (nette#6)
Browse files Browse the repository at this point in the history
  • Loading branch information
integer authored and dg committed Jul 9, 2019
1 parent b314c64 commit a307303
Show file tree
Hide file tree
Showing 3 changed files with 50 additions and 0 deletions.
10 changes: 10 additions & 0 deletions readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
-----------------------

Expand Down
14 changes: 14 additions & 0 deletions src/Schema/Elements/Type.php
Original file line number Diff line number Diff line change
Expand Up @@ -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)
{
Expand Down Expand Up @@ -77,6 +80,13 @@ public function items($type = 'mixed'): self
}


public function pattern(string $pattern): self
{
$this->pattern = $pattern;
return $this;
}


/********************* processing ****************d*g**/


Expand Down Expand Up @@ -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)\\z\x01u", $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)];
Expand Down
26 changes: 26 additions & 0 deletions tests/Schema/Expect.pattern.phpt
Original file line number Diff line number Diff line change
@@ -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 a307303

Please sign in to comment.