Skip to content

Commit

Permalink
Improve regex delimiters, fixes swaggest#71
Browse files Browse the repository at this point in the history
  • Loading branch information
vearutop committed Apr 16, 2019
1 parent d404217 commit a3942df
Show file tree
Hide file tree
Showing 4 changed files with 9 additions and 30 deletions.
10 changes: 1 addition & 9 deletions src/Constraint/Format.php
Original file line number Diff line number Diff line change
Expand Up @@ -108,15 +108,7 @@ public static function regexError($data)
return 'Invalid regex: \A is not supported';
}


$d = null;
foreach (array('/', '_', '~', '#', '!', '%', '`', '=') as $delimiter) {
if (strpos($data, $delimiter) === false) {
$d = $delimiter;
break;
}
}
return @preg_match($d . $data . $d, '') === false ? 'Invalid regex: ' . $data : null;
return @preg_match('{' . $data . '}', '') === false ? 'Invalid regex: ' . $data : null;
}

public static function jsonPointerError($data, $isRelative = false)
Expand Down
19 changes: 2 additions & 17 deletions src/Helper.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,26 +7,11 @@ class Helper
{
/**
* @param string $jsonPattern
* @return bool|string
* @throws InvalidValue
* @return string
*/
public static function toPregPattern($jsonPattern)
{
static $delimiters = array('/', '#', '+', '~', '%');

$pattern = false;
foreach ($delimiters as $delimiter) {
if (strpos($jsonPattern, $delimiter) === false) {
$pattern = $delimiter . $jsonPattern . $delimiter . 'u';
break;
}
}

if (false === $pattern) {
throw new InvalidValue('Failed to prepare preg pattern');
}

return $pattern;
return '{' . $jsonPattern . '}u';
}

/**
Expand Down
2 changes: 2 additions & 0 deletions src/Schema.php
Original file line number Diff line number Diff line change
Expand Up @@ -1310,6 +1310,8 @@ public function makeObjectItem(Context $options = null)
}

/**
* Resolves boolean schema into Schema instance
*
* @param mixed $schema
* @return mixed|Schema
*/
Expand Down
8 changes: 4 additions & 4 deletions tests/src/PHPUnit/Misc/PreparePatternTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,13 @@
namespace Swaggest\JsonSchema\Tests\PHPUnit\Misc;

use Swaggest\JsonSchema\Helper;
use Swaggest\JsonSchema\InvalidValue;

class PreparePatternTest extends \PHPUnit_Framework_TestCase
{
public function testFailedToPreparePattern()
public function testPreparePatternForEmail()
{
$this->setExpectedException(get_class(new InvalidValue()), 'Failed to prepare preg pattern');
Helper::toPregPattern('/#+~%');
$pattern = Helper::toPregPattern('^[a-zA-Z0-9.!#$%&\'*+\/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$');
$this->assertEquals(1, preg_match($pattern, '[email protected]'));
$this->assertEquals(0, preg_match($pattern, "malformed-email"));
}
}

0 comments on commit a3942df

Please sign in to comment.