Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: Adds groupBy method to Collection for grouping elements by a specified criterion. #13

Merged
merged 1 commit into from
Oct 8, 2024
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
3 changes: 2 additions & 1 deletion .gitattributes
Original file line number Diff line number Diff line change
@@ -1,13 +1,14 @@
/tests export-ignore
/vendor export-ignore

/README.md export-ignore
/LICENSE export-ignore
/Makefile export-ignore
/README.md export-ignore
/phpmd.xml export-ignore
/phpunit.xml export-ignore
/phpstan.neon.dist export-ignore
/infection.json.dist export-ignore

/.github export-ignore
/.gitignore export-ignore
/.gitattributes export-ignore
24 changes: 16 additions & 8 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -259,22 +259,30 @@ combining elements.

These methods allow the Collection's elements to be transformed or converted into different formats.

#### Mapping elements
#### Applying actions without modifying elements

- `map`: Applies transformations to each element in the Collection and returns a new collection with the transformed
elements.
- `each`: Executes actions on each element in the Collection without modification.
The method is helpful for performing side effects, such as logging or adding elements to another collection.

```php
$collection->map(transformations: fn(int $value): int => $value * 2);
$collection->each(actions: fn(Invoice $invoice): void => $collectionB->add(elements: new InvoiceSummary(amount: $invoice->amount, customer: $invoice->customer)));
```

#### Grouping elements

#### Applying actions without modifying elements
- `groupBy`: Groups the elements in the Collection based on the provided grouping criterion.

- `each`: Executes actions on each element in the Collection without modification.
The method is helpful for performing side effects, such as logging or adding elements to another collection.
```php
$collection->groupBy(grouping: fn(Amount $amount): string => $amount->currency->name);
```

#### Mapping elements

- `map`: Applies transformations to each element in the Collection and returns a new collection with the transformed
elements.

```php
$collection->each(actions: fn(Invoice $invoice): void => $collectionB->add(elements: new InvoiceSummary(amount: $invoice->amount, customer: $invoice->customer)));
$collection->map(transformations: fn(int $value): int => $value * 2);
```

#### Convert to array
Expand Down
1 change: 1 addition & 0 deletions composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
"array",
"yield",
"iterator",
"iterators",
"generator",
"collection",
"tiny-blocks"
Expand Down
6 changes: 1 addition & 5 deletions phpstan.neon.dist
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,5 @@ parameters:
ignoreErrors:
- '#Unsafe usage of new static#'
- '#does not specify its types#'
- '#contains incompatible type#'
- '#specified in iterable type iterable#'
- '#is not subtype of native type static#'
- '#PHPDoc tag @extends has invalid value#'
- '#type has no value type specified in iterable type array#'
- '#type specified in iterable type#'
reportUnmatchedIgnoredErrors: false
13 changes: 11 additions & 2 deletions src/Collectible.php
Original file line number Diff line number Diff line change
Expand Up @@ -27,14 +27,14 @@ interface Collectible extends Countable, IteratorAggregate
* @param iterable<Element> $elements The elements to initialize the collection with.
* @return Collectible<Element> A new Collectible instance.
*/
public static function createFrom(iterable $elements): static;
public static function createFrom(iterable $elements): Collectible;

/**
* Creates an empty Collectible instance.
*
* @return Collectible<Element> An empty Collectible instance.
*/
public static function createFromEmpty(): static;
public static function createFromEmpty(): Collectible;

/**
* Adds one or more elements to the collection.
Expand Down Expand Up @@ -116,6 +116,15 @@ public function getBy(int $index, mixed $defaultValueIfNotFound = null): mixed;
*/
public function getIterator(): Traversable;

/**
* Groups the elements in the collection based on the provided criteria.
*
* @param Closure(Element): Key $grouping The function to define the group key for each element.
* @return Collectible<Key, Collectible<Key, Element, Element>, Element> A collection of collections,
* grouped by the key returned by the closure.
*/
public function groupBy(Closure $grouping): Collectible;

/**
* Determines if the collection is empty.
*
Expand Down
9 changes: 6 additions & 3 deletions src/Collection.php
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
use TinyBlocks\Collection\Internal\Operations\Retrieve\Get;
use TinyBlocks\Collection\Internal\Operations\Retrieve\Last;
use TinyBlocks\Collection\Internal\Operations\Transform\Each;
use TinyBlocks\Collection\Internal\Operations\Transform\GroupBy;
use TinyBlocks\Collection\Internal\Operations\Transform\Map;
use TinyBlocks\Collection\Internal\Operations\Transform\MapToArray;
use TinyBlocks\Collection\Internal\Operations\Transform\MapToJson;
Expand All @@ -31,9 +32,6 @@
* Represents a collection that provides a set of utility methods for operations like adding,
* filtering, mapping, and transforming elements. Internally uses iterators to apply operations
* lazily and efficiently.
*
* @template Element of mixed
* @implements Collectible<Element>
*/
class Collection implements Collectible
{
Expand Down Expand Up @@ -108,6 +106,11 @@ public function getIterator(): Traversable
yield from $this->iterator->getIterator();
}

public function groupBy(Closure $grouping): Collectible
{
return new static(iterator: $this->iterator->add(operation: GroupBy::from(grouping: $grouping)));
}

public function isEmpty(): bool
{
return !$this->iterator->getIterator()->valid();
Expand Down
3 changes: 3 additions & 0 deletions src/Internal/Iterators/InternalIterator.php
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,9 @@
*/
final class InternalIterator implements IteratorAggregate
{
/**
* @var LazyOperation[]
*/
private array $operations;

/**
Expand Down
2 changes: 1 addition & 1 deletion src/Internal/Operations/Filter/Filter.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
use Generator;
use TinyBlocks\Collection\Internal\Operations\LazyOperation;

final class Filter implements LazyOperation
final readonly class Filter implements LazyOperation
{
private array $predicates;

Expand Down
2 changes: 0 additions & 2 deletions src/Internal/Operations/ImmediateOperation.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,6 @@

/**
* Interface for operations that are applied immediately and not lazily.
*
* @extends Operation
*/
interface ImmediateOperation extends Operation
{
Expand Down
1 change: 0 additions & 1 deletion src/Internal/Operations/LazyOperation.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,6 @@
*
* @template Key of array-key
* @template Value
* @extends Operation
*/
interface LazyOperation extends Operation
{
Expand Down
2 changes: 1 addition & 1 deletion src/Internal/Operations/Transform/Each.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
use Closure;
use TinyBlocks\Collection\Internal\Operations\ImmediateOperation;

final class Each implements ImmediateOperation
final readonly class Each implements ImmediateOperation
{
private array $actions;

Expand Down
35 changes: 35 additions & 0 deletions src/Internal/Operations/Transform/GroupBy.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
<?php

declare(strict_types=1);

namespace TinyBlocks\Collection\Internal\Operations\Transform;

use Closure;
use Generator;
use TinyBlocks\Collection\Internal\Operations\LazyOperation;

final readonly class GroupBy implements LazyOperation
{
private function __construct(private Closure $grouping)
{
}

public static function from(Closure $grouping): GroupBy
{
return new GroupBy(grouping: $grouping);
}

public function apply(iterable $elements): Generator
{
$groupedElements = [];

foreach ($elements as $element) {
$key = ($this->grouping)($element);
$groupedElements[$key][] = $element;
}

foreach ($groupedElements as $key => $group) {
yield $key => $group;
}
}
}
2 changes: 1 addition & 1 deletion src/Internal/Operations/Transform/Map.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
use Generator;
use TinyBlocks\Collection\Internal\Operations\LazyOperation;

final class Map implements LazyOperation
final readonly class Map implements LazyOperation
{
private array $transformations;

Expand Down
2 changes: 1 addition & 1 deletion src/Internal/Operations/Write/Create.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
use Generator;
use TinyBlocks\Collection\Internal\Operations\LazyOperation;

final class Create implements LazyOperation
final readonly class Create implements LazyOperation
{
public static function fromEmpty(): Create
{
Expand Down
98 changes: 98 additions & 0 deletions tests/Operations/Transform/CollectionGroupByOperationTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@
<?php

declare(strict_types=1);

namespace TinyBlocks\Collection\Operations\Transform;

use PHPUnit\Framework\TestCase;
use TinyBlocks\Collection\Collection;
use TinyBlocks\Collection\Models\Amount;
use TinyBlocks\Collection\Models\Currency;

final class CollectionGroupByOperationTest extends TestCase
{
public function testGroupByObjects(): void
{
/** @Given a collection of Amount objects with different currencies */
$collection = Collection::createFrom(elements: [
new Amount(value: 55.1, currency: Currency::BRL),
new Amount(value: 100.5, currency: Currency::USD),
new Amount(value: 23.3, currency: Currency::BRL),
new Amount(value: 200.0, currency: Currency::USD)
]);

/** @When grouping by the currency property */
$actual = $collection->groupBy(grouping: static fn(Amount $amount): string => $amount->currency->name);

/** @Then the collection should be grouped by the currency */
$expected = Collection::createFrom(elements: [
'BRL' => [
new Amount(value: 55.1, currency: Currency::BRL),
new Amount(value: 23.3, currency: Currency::BRL)
],
'USD' => [
new Amount(value: 100.5, currency: Currency::USD),
new Amount(value: 200.0, currency: Currency::USD)
]
]);

self::assertEquals($expected->toArray(), $actual->toArray());
}

public function testGroupBySimpleKey(): void
{
/** @Given a collection of elements with a type property */
$collection = Collection::createFrom(elements: [
['type' => 'fruit', 'name' => 'apple'],
['type' => 'fruit', 'name' => 'banana'],
['type' => 'vegetable', 'name' => 'carrot'],
['type' => 'vegetable', 'name' => 'broccoli']
]);

/** @When grouping by the 'type' key */
$actual = $collection->groupBy(grouping: static fn(array $item): string => $item['type']);

/** @Then the collection should be grouped by the type property */
$expected = Collection::createFrom(elements: [
'fruit' => Collection::createFrom(elements: [
['type' => 'fruit', 'name' => 'apple'],
['type' => 'fruit', 'name' => 'banana']
]),
'vegetable' => Collection::createFrom(elements: [
['type' => 'vegetable', 'name' => 'carrot'],
['type' => 'vegetable', 'name' => 'broccoli']
])
]);

self::assertSame($expected->toArray(), $actual->toArray());
}

public function testGroupByNumericKey(): void
{
/** @Given a collection of numbers */
$collection = Collection::createFrom(elements: [1, 2, 3, 4, 5, 6]);

/** @When grouping by even and odd numbers */
$actual = $collection->groupBy(grouping: static fn(int $item): string => $item % 2 === 0 ? 'even' : 'odd');

/** @Then the collection should be grouped into even and odd */
$expected = Collection::createFrom(elements: [
'odd' => Collection::createFrom(elements: [1, 3, 5]),
'even' => Collection::createFrom(elements: [2, 4, 6])
]);

self::assertSame($expected->toArray(), $actual->toArray());
}

public function testGroupByEmptyCollection(): void
{
/** @Given an empty collection */
$collection = Collection::createFromEmpty();

/** @When applying groupBy on the empty collection */
$actual = $collection->groupBy(grouping: static fn(array $item): array => $item);

/** @Then the collection should remain empty */
self::assertEmpty($actual->toArray());
}
}
Loading