Skip to content

Commit

Permalink
Merge pull request #25 from samsonasik/samsonasik-patch-1
Browse files Browse the repository at this point in the history
Allow optional when on Collector class
  • Loading branch information
samsonasik authored Sep 7, 2024
2 parents d3c90d4 + f423102 commit 1f4027d
Show file tree
Hide file tree
Showing 3 changed files with 36 additions and 13 deletions.
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -396,7 +396,7 @@ $limit = 2;
$transform = fn ($datum): string => trim($datum);

$newArray = Collector::setUp($data)
->when($when)
->when($when) // optional, can just transform without filtering
->withLimit(2) // optional to only collect some data provided by limit config
->withTransform($transform)
->getResults();
Expand Down
32 changes: 20 additions & 12 deletions src/Collector.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,15 +7,17 @@
use Traversable;
use Webmozart\Assert\Assert;

use function is_callable;

final class Collector
{
/** @var array<int|string, mixed>|Traversable<int|string, mixed> */
private iterable $data = [];

/** @var callable(mixed $datum, int|string|null $key=): bool|null */
/** @var null|callable(mixed $datum, int|string|null $key=): bool */
private $when;

/** @var callable(mixed $datum, int|string|null $key=): mixed */
/** @var null|callable(mixed $datum, int|string|null $key=): mixed */
private $transform;

private ?int $limit = null;
Expand Down Expand Up @@ -62,20 +64,26 @@ public function withTransform(callable $transform): self
*/
public function getResults(): array
{
// ensure when property is set early via ->when() and ->withTransform() method
Assert::isCallable($this->when);
// ensure transform property is set early ->withTransform() method
Assert::isCallable($this->transform);

$count = 0;
$collectedData = [];
$count = 0;
$collectedData = [];
$isCallableWhen = is_callable($this->when);

foreach ($this->data as $key => $datum) {
$isFound = ($this->when)($datum, $key);

Assert::boolean($isFound);

if (! $isFound) {
continue;
if ($isCallableWhen) {
/**
* @var callable(mixed $datum, int|string|null $key=): bool $when
*/
$when = $this->when;
$isFound = ($when)($datum, $key);

Assert::boolean($isFound);

if (! $isFound) {
continue;
}
}

$collectedData[] = ($this->transform)($datum, $key);
Expand Down
15 changes: 15 additions & 0 deletions tests/CollectorTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,21 @@

final class CollectorTest extends TestCase
{
public function testWithoutWhen(): void
{
$data = [
' a ',
' b ',
' c ',
];

$results = Collector::setUp($data)
->withTransform(fn (string $datum): string => trim($datum))
->getResults();

$this->assertSame(['a', 'b', 'c'], $results);
}

public function testWithoutLimit(): void
{
$data = [
Expand Down

0 comments on commit 1f4027d

Please sign in to comment.