Skip to content

Commit 3812cf8

Browse files
committed
Added support for multiple capturing groups to Regex strategy.
1 parent 7292fdb commit 3812cf8

File tree

2 files changed

+16
-2
lines changed

2 files changed

+16
-2
lines changed

src/Strategy/Regex.php

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -8,14 +8,21 @@
88
*/
99
final class Regex extends Delegate
1010
{
11-
public function __construct($expression, private readonly string $regex, private readonly int $capturingGroup = 0)
12-
{
11+
public function __construct(
12+
$expression,
13+
private readonly string $regex,
14+
private readonly int|array $capturingGroup = 0,
15+
) {
1316
parent::__construct($expression);
1417
}
1518

1619
public function __invoke($data, $context = null)
1720
{
1821
if (preg_match($this->regex, parent::__invoke($data, $context), $matches)) {
22+
if (is_array($this->capturingGroup)) {
23+
return array_values(array_intersect_key($matches, array_flip($this->capturingGroup)));
24+
}
25+
1926
return $matches[$this->capturingGroup];
2027
}
2128
}

test/Unit/Mapper/Strategy/RegexTest.php

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,4 +22,11 @@ public function testRegexNonMatch(): void
2222

2323
self::assertNull($regex([]));
2424
}
25+
26+
public function testRegexMatchArray(): void
27+
{
28+
$regex = (new Regex('Alfa Beta Charlie', '[(A\w+).+?(C\w+)]', [1, 2]))->setMapper(MockFactory::mockMapperEcho());
29+
30+
self::assertSame(['Alfa', 'Charlie'], $regex([]));
31+
}
2532
}

0 commit comments

Comments
 (0)