Skip to content

Commit

Permalink
Support # comments in regex with x modifier
Browse files Browse the repository at this point in the history
  • Loading branch information
staabm authored Dec 17, 2024
1 parent 73d0f13 commit c053dbc
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 7 deletions.
20 changes: 13 additions & 7 deletions src/Type/Regex/RegexGroupParser.php
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@
use function count;
use function in_array;
use function is_int;
use function preg_replace;
use function rtrim;
use function sscanf;
use function str_contains;
Expand Down Expand Up @@ -64,20 +65,25 @@ public function parseGroups(string $regex): ?array
return null;
}

$rawRegex = $this->regexExpressionHelper->removeDelimitersAndModifiers($regex);
try {
$ast = self::$parser->parse($rawRegex);
} catch (Exception) {
return null;
}

$modifiers = $this->regexExpressionHelper->getPatternModifiers($regex) ?? '';
foreach (self::NOT_SUPPORTED_MODIFIERS as $notSupportedModifier) {
if (str_contains($modifiers, $notSupportedModifier)) {
return null;
}
}

if (str_contains($modifiers, 'x')) {
// in freespacing mode the # character starts a comment and runs until the end of the line
$regex = preg_replace('/[^?]#.*/', '', $regex) ?? '';
}

$rawRegex = $this->regexExpressionHelper->removeDelimitersAndModifiers($regex);
try {
$ast = self::$parser->parse($rawRegex);
} catch (Exception) {
return null;
}

$captureOnlyNamed = false;
if ($this->phpVersion->supportsPregCaptureOnlyNamedGroups()) {
$captureOnlyNamed = str_contains($modifiers, 'n');
Expand Down
32 changes: 32 additions & 0 deletions tests/PHPStan/Analyser/nsrt/bug-12242.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
<?php // lint >= 7.4

namespace Bug12242;

use function PHPStan\Testing\assertType;

function foo(string $str): void
{
$regexp = '/
# (
([\d,]*)
# )
/x';
if (preg_match($regexp, $str, $match)) {
assertType('array{string, string}', $match);
}
}

function bar(string $str): void
{
$regexp = '/^
(\w+) # column type [1]
[\(] # (
?([\d,]*) # size or size, precision [2]
[\)] # )
?\s* # whitespace
(\w*) # extra description (UNSIGNED, CHARACTER SET, ...) [3]
$/x';
if (preg_match($regexp, $str, $matches)) {
assertType('array{string, non-empty-string, string, string}', $matches);
}
}

0 comments on commit c053dbc

Please sign in to comment.