Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 26 additions & 0 deletions src/Phaseolies/Database/Entity/Builder.php
Original file line number Diff line number Diff line change
Expand Up @@ -3008,6 +3008,32 @@ public function groupByCallback(callable $callback): array
return $grouped;
}

/**
* Partition results into two groups based on a callback
*
* @param callable $callback
* @return array [matched, unmatched]
*/
public function partition(callable $callback): array
{
$results = $this->get();
$matched = [];
$unmatched = [];

foreach ($results as $item) {
if ($callback($item)) {
$matched[] = $item;
} else {
$unmatched[] = $item;
}
}

return [
new Collection($this->modelClass, $matched),
new Collection($this->modelClass, $unmatched)
];
}

/**
* Convert camelCase to snake_case for column names
*
Expand Down
15 changes: 13 additions & 2 deletions src/Phaseolies/Support/Collection.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,9 @@
use IteratorAggregate;
use ArrayIterator;
use ArrayAccess;
use JsonSerializable;

class Collection extends RamseyCollection implements IteratorAggregate, ArrayAccess
class Collection extends RamseyCollection implements IteratorAggregate, ArrayAccess, JsonSerializable
{
/**
* @var array
Expand Down Expand Up @@ -148,14 +149,24 @@ public function offsetUnset($offset): void

/**
* Required for looping data
*
*
* @return Traversable
*/
public function getIterator(): Traversable
{
return new ArrayIterator($this->data);
}

/**
* Specify data which should be serialized to JSON
*
* @return array
*/
public function jsonSerialize(): array
{
return $this->toArray();
}

/**
* Count the number of data in the collection.
*
Expand Down
20 changes: 20 additions & 0 deletions tests/Model/Query/EntityModelQueryTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -2691,4 +2691,24 @@ public function testGroupByCallback()
);
}
}

public function testPartition()
{
[$higher, $lower] = MockProduct::query()
->partition(fn($product) => $product->price > 500);

// We have 2 products greater than 500
$this->assertCount(2, $higher);

// We have 1 products lower than 500
$this->assertCount(1, $lower);

foreach ($higher as $product) {
$this->assertGreaterThan(
500,
$product->price,
"Expected product ID {$product->id} to have price > 500"
);
}
}
}
Loading