endtoend-test-psl/tests/Psl/Arr/GroupByTest.php

59 lines
1.7 KiB
PHP
Raw Normal View History

2019-12-24 01:52:07 +01:00
<?php
declare(strict_types=1);
namespace Psl\Tests\Arr;
use PHPUnit\Framework\TestCase;
2019-12-25 00:35:14 +01:00
use Psl\Arr;
use Psl\Collection;
use Psl\Exception;
use Psl\Str;
2019-12-24 01:52:07 +01:00
final class GroupByTest extends TestCase
2019-12-24 01:52:07 +01:00
{
2019-12-25 00:35:14 +01:00
/**
* @dataProvider provideData
*/
2020-08-27 16:14:37 +02:00
public function testGroupBy(array $expected, array $values, callable $callable): void
2019-12-25 00:35:14 +01:00
{
static::assertSame($expected, Arr\group_by($values, $callable));
2019-12-25 00:35:14 +01:00
}
public function provideData(): array
{
return [
[
[7 => [2], 8 => [3], 9 => [4], 10 => [5], 11 => [6], 12 => [7, 8, 9, 10]],
2020-08-27 16:14:37 +02:00
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
static fn ($i) => $i < 2 ? null : (($i >= 7) ? 12 : ($i + 5)),
2019-12-25 00:35:14 +01:00
],
[
[7 => [2], 8 => [3], 9 => [4], 10 => [5], 11 => [6], 12 => [7], 13 => [8], 14 => [9], 15 => [10]],
2020-08-27 16:14:37 +02:00
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
static fn ($i) => $i < 2 ? null : $i + 5,
2019-12-25 00:35:14 +01:00
],
[
['username' => ['@azjezz', '@fabpot', '@blacksun'], 'name' => ['Saif Eddin', 'Fabien', 'Gabrielle']],
2020-08-27 16:14:37 +02:00
['@azjezz', 'Saif Eddin', '@fabpot', 'Fabien', '@blacksun', 'Gabrielle'],
static fn ($name) => Str\starts_with($name, '@') ? 'username' : 'name',
2019-12-25 00:35:14 +01:00
],
];
}
public function testGroupByThrowsWhenKeyFunReturnsNonArrayKey(): void
{
$this->expectException(Exception\InvariantViolationException::class);
$this->expectExceptionMessage(
'Expected $key_func to return a value of type array-key, value of type (object) returned.'
);
2019-12-25 00:35:14 +01:00
Arr\group_by(
2020-08-27 16:14:37 +02:00
[0, 1, 2, 3, 4, 5],
static fn ($x) => new Collection\Vector([$x, $x])
2019-12-25 00:35:14 +01:00
);
}
2019-12-24 01:52:07 +01:00
}