Skip to content

Commit

Permalink
fix: improve KeyMatch method to avoid endless loop
Browse files Browse the repository at this point in the history
  • Loading branch information
leeqvip committed May 19, 2020
1 parent 970ba59 commit e2ce186
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 29 deletions.
49 changes: 20 additions & 29 deletions src/Util/BuiltinOperations.php
Expand Up @@ -63,21 +63,17 @@ public static function keyMatch2(string $key1, string $key2): bool
{
$key2 = str_replace(['/*'], ['/.*'], $key2);

$pattern = '/(.*):[^\/]+(.*)/';
for (; ;) {
if (false === strpos($key2, '/:')) {
break;
}
$key2 = preg_replace_callback(
$pattern,
function ($m) {
return $m[1].'[^\/]+'.$m[2];
},
$key2
);
}
$pattern = '/:[^\/]+/';

$key2 = preg_replace_callback(
$pattern,
function ($m) {
return '[^\/]+';
},
$key2
);

return self::regexMatch($key1, '^'.$key2.'$');
return self::regexMatch($key1, '^' . $key2 . '$');
}

/**
Expand Down Expand Up @@ -108,21 +104,16 @@ public static function keyMatch3(string $key1, string $key2): bool
{
$key2 = str_replace(['/*'], ['/.*'], $key2);

$pattern = '/(.*)\{[^\/]+\}(.*)/';
for (; ;) {
if (false === strpos($key2, '/{')) {
break;
}
$key2 = preg_replace_callback(
$pattern,
function ($m) {
return $m[1].'[^\/]+'.$m[2];
},
$key2
);
}
$pattern = '/\{[^\/]+\}/';
$key2 = preg_replace_callback(
$pattern,
function ($m) {
return '[^\/]+';
},
$key2
);

return self::regexMatch($key1, '^'.$key2.'$');
return self::regexMatch($key1, '^' . $key2 . '$');
}

/**
Expand Down Expand Up @@ -150,7 +141,7 @@ public static function keyMatch3Func(...$args): bool
*/
public static function regexMatch(string $key1, string $key2): bool
{
return (bool) preg_match('~'.$key2.'~', $key1);
return (bool) preg_match('~' . $key2 . '~', $key1);
}

/**
Expand Down
4 changes: 4 additions & 0 deletions tests/Unit/Util/BuiltinOperationsTest.php
Expand Up @@ -68,6 +68,8 @@ public function testKeyMatch2Func()
$this->assertTrue($this->keyMatch2Func('/alice/all', '/:id/all'));
$this->assertFalse($this->keyMatch2Func('/alice', '/:id/all'));
$this->assertFalse($this->keyMatch2Func('/alice/all', '/:id'));

$this->assertFalse($this->keyMatch2Func('/alice/all', '/:/all'));
}

public function testKeyMatch3Func()
Expand All @@ -93,5 +95,7 @@ public function testKeyMatch3Func()
$this->assertTrue($this->keyMatch3Func('/proxy/myid/res/res2', '/proxy/{id}/*'));
$this->assertTrue($this->keyMatch3Func('/proxy/myid/res/res2/res3', '/proxy/{id}/*'));
$this->assertFalse($this->keyMatch3Func('/proxy/', '/proxy/{id}/*'));

$this->assertFalse($this->keyMatch3Func('/myid/using/myresid', '/{id/using/{resId}'));
}
}

0 comments on commit e2ce186

Please sign in to comment.