Skip to content

Commit

Permalink
Add anchors to pattern string in all cases
Browse files Browse the repository at this point in the history
canvural authored and scaytrase committed Jun 12, 2020
1 parent ff590d3 commit ac49e52
Showing 3 changed files with 24 additions and 10 deletions.
7 changes: 2 additions & 5 deletions src/Schema/Keywords/Pattern.php
Original file line number Diff line number Diff line change
@@ -10,7 +10,7 @@
use Respect\Validation\Validator;
use function preg_match;
use function sprintf;
use function strlen;
use function str_replace;

class Pattern extends BaseKeyword
{
@@ -36,10 +36,7 @@ public function validate($data, string $pattern) : void
throw InvalidSchema::becauseDefensiveSchemaValidationFailed($e);
}

// add anchors
if ($pattern[0] !== $pattern[strlen($pattern) - 1]) {
$pattern = sprintf('#%s#', $pattern);
}
$pattern = sprintf('#%s#', str_replace('#', '\#', $pattern));

if (! preg_match($pattern, $data)) {
throw KeywordMismatch::fromKeyword('pattern', $data, sprintf('Data does not match pattern \'%s\'', $pattern));
25 changes: 21 additions & 4 deletions tests/Schema/Keywords/PatternTest.php
Original file line number Diff line number Diff line change
@@ -10,16 +10,33 @@

final class PatternTest extends SchemaValidatorTest
{
public function testItValidatesPatternGreen() : void
/**
* @return array<array<string, string>>
*/
public function validDataProvider() : array
{
return [
['^[a|b]+$', 'abba'],
['foo', 'foo'], // Tests adding anchors
['foof', 'foof'], // Tests adding anchors when first and last character is same
['1foo1', '1foo1'], // Tests adding anchors when first and last character is same with numbers
['^#\d+$', '#123'], // Tests adding anchors to string which has #
['^#(\d+)#$', '#123#'], // Tests adding anchors to string which has multiple#
];
}

/**
* @dataProvider validDataProvider
*/
public function testItValidatesPatternGreen(string $pattern, string $data) : void
{
$spec = <<<SPEC
schema:
type: string
pattern: "#^[a|b]+$#"
pattern: $pattern
SPEC;

$schema = $this->loadRawSchema($spec);
$data = 'abba';

(new SchemaValidator())->validate($data, $schema);
$this->addToAssertionCount(1);
@@ -30,7 +47,7 @@ public function testItValidatesPatternRed() : void
$spec = <<<SPEC
schema:
type: string
pattern: "#^[a|b]+$#"
pattern: "^[a|b]+$"
SPEC;

$schema = $this->loadRawSchema($spec);
2 changes: 1 addition & 1 deletion tests/stubs/complete.yaml
Original file line number Diff line number Diff line change
@@ -29,7 +29,7 @@ paths:
required: true
schema:
type: string
pattern: "#^[a-z]{4}$#"
pattern: "^[a-z]{4}$"
- in: cookie
name: session_id
required: true

0 comments on commit ac49e52

Please sign in to comment.