Skip to content

Commit

Permalink
add array pack
Browse files Browse the repository at this point in the history
  • Loading branch information
rodber committed Dec 20, 2023
1 parent d91563b commit c1528e2
Show file tree
Hide file tree
Showing 2 changed files with 83 additions and 0 deletions.
30 changes: 30 additions & 0 deletions src/functions.php
Original file line number Diff line number Diff line change
Expand Up @@ -118,6 +118,36 @@ function arrayFromKey(array $array, string|int ...$key): array
return (new ArrayStandard($array))->fromKey(...$key);
}

/**
* Takes packing instruction and generates sub-arrays with matched keys.
* @param string ...$packing Named packing as `startNeedle: 'grouping',`
* @phpstan-ignore-next-line
*/
function arrayPack(array $array, string ...$packing): array
{
$return = $array;
$trash = [];
$keys = array_keys($array);
foreach ($packing as $split => $group) {
$split = (string) $split;
$find = array_filter($keys, function ($key) use ($split) {
return strpos($key, $split) === 0;
});
if ($find === []) {
continue;
}
$return[$group] = [];
foreach ($find as $key) {
$key = (string) $key;
$trash[] = $key;
$groupedKey = (string) str_replace($split, '', $key);
$return[$group][$groupedKey] = $array[$key];
}
}

return arrayUnsetKey($return, ...$trash);
}

function randomString(int $length): string
{
// @phpstan-ignore-next-line
Expand Down
53 changes: 53 additions & 0 deletions tests/ArrayPackTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
<?php

/*
* This file is part of Chevere.
*
* (c) Rodolfo Berrios <rodolfo@chevere.org>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

declare(strict_types=1);

namespace Chevere\Tests;

use PHPUnit\Framework\TestCase;
use function Chevere\Standard\arrayPack;

final class ArrayPackTest extends TestCase
{
public function testNoPacking(): void
{
$array = [
'a_id' => 1,
'b_num' => 2,
'c_val' => 3,
];
$packed = arrayPack($array);
$this->assertSame($array, $packed);
}

public function testPacking(): void
{
$array = [
'a_id' => null,
'b_num' => 2,
'c_val' => 3,
];
$expected = [
'a' => [
'id' => null,
],
'b' => [
'num' => 2,
],
'c' => [
'val' => 3,
],
];
$packed = arrayPack($array, a_: 'a', b_: 'b', c_: 'c');
$this->assertSame($expected, $packed);
}
}

0 comments on commit c1528e2

Please sign in to comment.