44
55namespace Yiisoft \Strings ;
66
7+ use Exception ;
8+
9+ use InvalidArgumentException ;
10+
11+ use function count ;
12+
713/**
814 * `CombinedRegexp` optimizes matching of multiple regular expressions.
915 * Read more about the concept in
@@ -28,11 +34,11 @@ public function __construct(
2834 array $ patterns ,
2935 string $ flags = ''
3036 ) {
31- if (count ($ patterns ) === 0 ) {
32- throw new \ InvalidArgumentException ('At least one pattern should be specified. ' );
37+ if (empty ($ patterns )) {
38+ throw new InvalidArgumentException ('At least one pattern should be specified. ' );
3339 }
34- $ this ->patterns = $ patterns ;
35- $ this ->compiledPattern = $ this ->compilePatterns ($ patterns ) . $ flags ;
40+ $ this ->patterns = array_values ( $ patterns) ;
41+ $ this ->compiledPattern = $ this ->compilePatterns ($ this -> patterns ) . $ flags ;
3642 }
3743
3844 /**
@@ -53,7 +59,7 @@ public function matches(string $string): bool
5359
5460 /**
5561 * Returns pattern that matches the given string.
56- * @throws \ Exception if the string does not match any of the patterns.
62+ * @throws Exception if the string does not match any of the patterns.
5763 */
5864 public function getMatchingPattern (string $ string ): string
5965 {
@@ -62,13 +68,13 @@ public function getMatchingPattern(string $string): string
6268
6369 /**
6470 * Returns position of the pattern that matches the given string.
65- * @throws \ Exception if the string does not match any of the patterns.
71+ * @throws Exception if the string does not match any of the patterns.
6672 */
6773 public function getMatchingPatternPosition (string $ string ): int
6874 {
6975 $ match = preg_match ($ this ->compiledPattern , $ string , $ matches );
7076 if ($ match !== 1 ) {
71- throw new \ Exception (
77+ throw new Exception (
7278 sprintf (
7379 'Failed to match pattern "%s" with string "%s". ' ,
7480 $ this ->getCompiledPattern (),
@@ -82,6 +88,8 @@ public function getMatchingPatternPosition(string $string): int
8288
8389 /**
8490 * @param string[] $patterns
91+ *
92+ * @psalm-param list<string> $patterns
8593 */
8694 private function compilePatterns (array $ patterns ): string
8795 {
@@ -92,8 +100,8 @@ private function compilePatterns(array $patterns): string
92100 * It doesn't matter where to place `()` in the pattern:
93101 * https://regex101.com/r/lE1Q1S/1, https://regex101.com/r/rWg7Fj/1
94102 */
95- for ($ i = 0 ; $ i < count ( $ patterns ); $ i ++ ) {
96- $ quotedPatterns [] = $ patterns [ $ i ] . str_repeat ('() ' , $ i );
103+ foreach ($ patterns as $ i => $ pattern ) {
104+ $ quotedPatterns [] = $ pattern . str_repeat ('() ' , $ i );
97105 }
98106 $ combinedRegexps = '(?| ' . strtr (
99107 implode ('| ' , $ quotedPatterns ),
0 commit comments