Skip to content

Commit

Permalink
Add FluentMatchPattern.groupByCallback() #35
Browse files Browse the repository at this point in the history
  • Loading branch information
danon committed Nov 4, 2019
1 parent c7c1e4c commit a868811
Show file tree
Hide file tree
Showing 3 changed files with 62 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -25,4 +25,9 @@ public static function forFilter($value): self
{
return new self($value, 'filter', 'bool');
}

public static function forGroupBy($value): self
{
return new self($value, 'groupBy', 'int|string');
}
}
15 changes: 15 additions & 0 deletions src/TRegx/CleanRegex/Match/FluentMatchPattern.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
use Iterator;
use TRegx\CleanRegex\Exception\CleanRegex\FluentMatchPatternException;
use TRegx\CleanRegex\Exception\CleanRegex\IntegerFormatException;
use TRegx\CleanRegex\Exception\CleanRegex\InvalidReturnValueException;
use TRegx\CleanRegex\Exception\CleanRegex\NoFirstElementFluentException;
use TRegx\CleanRegex\Internal\Factory\NotMatchedFluentOptionalWorker;
use TRegx\CleanRegex\Internal\Factory\NotMatchedWorker;
Expand Down Expand Up @@ -131,6 +132,20 @@ public function asInt(): FluentMatchPattern
});
}

public function groupByCallback(callable $groupMapper): FluentMatchPattern
{
$map = [];
foreach ($this->elements as $element) {
$key = $groupMapper($element);
if (\is_int($key) || \is_string($key)) {
$map[$key][] = $element;
} else {
throw InvalidReturnValueException::forGroupBy($key);
}
}
return $this->next($map);
}

private function next(array $elements): FluentMatchPattern
{
return new FluentMatchPattern($elements, $this->worker);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -282,6 +282,48 @@ public function shouldThrowForNonStringAndNonInt()
$pattern->asInt();
}

/**
* @test
*/
public function shouldGroupBy()
{
// given
$pattern = new FluentMatchPattern(['Father', 'Mother', 'Maiden', 'Crone', 'Warrior', 'Smith', 'Stranger'], $this->mock());

// when
$result = $pattern->groupByCallback(function (string $fucker) {
return $fucker[0];
});

// then
$expected = [
'F' => ['Father'],
'M' => ['Mother', 'Maiden'],
'C' => ['Crone'],
'W' => ['Warrior'],
'S' => ['Smith', 'Stranger'],
];
$this->assertSame($expected, $result->all());
}

/**
* @test
*/
public function shouldThrowForInvalidGroupByType()
{
// given
$pattern = new FluentMatchPattern([''], $this->mock());

// then
$this->expectException(InvalidReturnValueException::class);
$this->expectExceptionMessage('Invalid groupBy() callback return type. Expected int|string, but array (0) given');

// when
$pattern->groupByCallback(function () {
return [];
});
}

private function mock(): NotMatchedWorker
{
/** @var NotMatchedWorker $mockObject */
Expand Down

0 comments on commit a868811

Please sign in to comment.