Skip to content

Commit 3497679

Browse files
integerdg
authored andcommitted
Added support for pattern() (#6)
1 parent b314c64 commit 3497679

File tree

3 files changed

+50
-0
lines changed

3 files changed

+50
-0
lines changed

readme.md

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -221,6 +221,16 @@ Ranges of numbers are specified using a combination of `min()` and `max()`:
221221
$schema = Expect::int()->min(10)->max(20);
222222
```
223223

224+
Regular expressions
225+
-------------------
226+
227+
String can be restricted by regular expression using the `pattern()`:
228+
229+
```php
230+
// just 9 numbers
231+
$schema = Expect::string()->pattern('\d{9}');
232+
```
233+
224234
Data mapping to objects
225235
-----------------------
226236

src/Schema/Elements/Type.php

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,9 @@ final class Type implements Schema
3030
/** @var array */
3131
private $range = [null, null];
3232

33+
/** @var string|null */
34+
private $pattern;
35+
3336

3437
public function __construct(string $type)
3538
{
@@ -77,6 +80,13 @@ public function items($type = 'mixed'): self
7780
}
7881

7982

83+
public function pattern(string $pattern): self
84+
{
85+
$this->pattern = $pattern;
86+
return $this;
87+
}
88+
89+
8090
/********************* processing ****************d*g**/
8191

8292

@@ -129,6 +139,10 @@ public function complete($value, Context $context)
129139
if (!$this->doValidate($value, $expected, $context)) {
130140
return;
131141
}
142+
if ($this->pattern !== null && !preg_match("\x01^(?:$this->pattern)$\x01Du", $value)) {
143+
$context->addError("The option %path% expects to match pattern '$this->pattern', '$value' given.");
144+
return;
145+
}
132146

133147
if ($value instanceof DynamicParameter) {
134148
$context->dynamics[] = [$value, str_replace('|' . DynamicParameter::class, '', $expected)];

tests/Schema/Expect.pattern.phpt

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
<?php
2+
3+
declare(strict_types=1);
4+
5+
use Nette\Schema\Expect;
6+
use Nette\Schema\Processor;
7+
use Tester\Assert;
8+
9+
10+
require __DIR__ . '/../bootstrap.php';
11+
12+
13+
test(function () {
14+
$schema = Expect::string()->pattern('\d{9}');
15+
16+
Assert::same('123456789', (new Processor)->process($schema, '123456789'));
17+
});
18+
19+
20+
test(function () {
21+
$schema = Expect::string()->pattern('\d{9}');
22+
23+
checkValidationErrors(function () use ($schema) {
24+
(new Processor)->process($schema, '123');
25+
}, ["The option expects to match pattern '\\d{9}', '123' given."]);
26+
});

0 commit comments

Comments
 (0)