Skip to content

Commit da3a0d9

Browse files
committed
fix: allow array_group_by to group object rows
1 parent 6478758 commit da3a0d9

3 files changed

Lines changed: 153 additions & 13 deletions

File tree

‎system/Helpers/Array/ArrayHelper.php‎

Lines changed: 90 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -202,13 +202,16 @@ public static function groupBy(array $array, array $indexes, bool $includeEmpty
202202

203203
/**
204204
* Recursively attach $row to the $indexes path of values found by
205-
* `dot_array_search()`.
205+
* dot syntax.
206206
*
207207
* @used-by groupBy()
208+
*
209+
* @param array<array-key, mixed>|object $row
210+
* @param list<string> $indexes
208211
*/
209212
private static function arrayAttachIndexedValue(
210213
array $result,
211-
array $row,
214+
array|object $row,
212215
array $indexes,
213216
bool $includeEmpty,
214217
): array {
@@ -218,7 +221,7 @@ private static function arrayAttachIndexedValue(
218221
return $result;
219222
}
220223

221-
$value = dot_array_search($index, $row);
224+
$value = self::arrayObjectSearchDot(self::convertToArray($index), $row);
222225

223226
if (! is_scalar($value)) {
224227
$value = '';
@@ -241,6 +244,90 @@ private static function arrayAttachIndexedValue(
241244
return $result;
242245
}
243246

247+
/**
248+
* Recursively search an array or object with wildcards.
249+
*
250+
* @param list<string> $indexes
251+
* @param array<array-key, mixed>|object $data
252+
*
253+
* @return array<array-key, mixed>|bool|float|int|object|string|null
254+
*/
255+
private static function arrayObjectSearchDot(array $indexes, array|object $data)
256+
{
257+
// If index is empty, returns null.
258+
if ($indexes === []) {
259+
return null;
260+
}
261+
262+
// Grab the current index
263+
$currentIndex = array_shift($indexes);
264+
265+
if ($currentIndex === '*') {
266+
$answer = [];
267+
268+
foreach ($data as $value) {
269+
if (! is_array($value) && ! is_object($value)) {
270+
return null;
271+
}
272+
273+
$answer[] = self::arrayObjectSearchDot($indexes, $value);
274+
}
275+
276+
$answer = array_filter($answer, static fn ($value): bool => $value !== null);
277+
278+
if ($answer !== []) {
279+
// If array only has one element, we return that element for BC.
280+
return count($answer) === 1 ? current($answer) : $answer;
281+
}
282+
283+
return null;
284+
}
285+
286+
if (! self::arrayObjectKeyExists($currentIndex, $data)) {
287+
return null;
288+
}
289+
290+
$value = self::arrayObjectValue($currentIndex, $data);
291+
292+
// If this is the last index, make sure to return it now,
293+
// and not try to recurse through things.
294+
if ($indexes === []) {
295+
return $value;
296+
}
297+
298+
// Do we need to recursively search this value?
299+
if ((is_array($value) && $value !== []) || is_object($value)) {
300+
return self::arrayObjectSearchDot($indexes, $value);
301+
}
302+
303+
// Otherwise, not found.
304+
return null;
305+
}
306+
307+
/**
308+
* @param array<array-key, mixed>|object $data
309+
*/
310+
private static function arrayObjectKeyExists(string $key, array|object $data): bool
311+
{
312+
if (is_array($data)) {
313+
return isset($data[$key]);
314+
}
315+
316+
return array_key_exists($key, get_object_vars($data));
317+
}
318+
319+
/**
320+
* @param array<array-key, mixed>|object $data
321+
*/
322+
private static function arrayObjectValue(string $key, array|object $data): mixed
323+
{
324+
if (is_array($data)) {
325+
return $data[$key];
326+
}
327+
328+
return get_object_vars($data)[$key];
329+
}
330+
244331
/**
245332
* Compare recursively two associative arrays and return difference as new array.
246333
* Returns keys that exist in `$original` but not in `$compareWith`.

‎tests/system/Helpers/ArrayHelperTest.php‎

Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@
1616
use CodeIgniter\Test\CIUnitTestCase;
1717
use PHPUnit\Framework\Attributes\DataProvider;
1818
use PHPUnit\Framework\Attributes\Group;
19+
use stdClass;
1920
use ValueError;
2021

2122
/**
@@ -1274,4 +1275,66 @@ public static function provideArrayGroupByExcludeEmpty(): iterable
12741275
],
12751276
];
12761277
}
1278+
1279+
/**
1280+
* @see https://github.com/codeigniter4/CodeIgniter4/issues/10225
1281+
*/
1282+
public function testArrayGroupByWithObjectRows(): void
1283+
{
1284+
$json = <<<'JSON'
1285+
[
1286+
{ "id": 1, "name": "Giraffe", "group": "Mammals" },
1287+
{ "id": 2, "name": "Zebra", "group": "Mammals" },
1288+
{ "id": 3, "name": "Crow", "group": "Birds" }
1289+
]
1290+
JSON;
1291+
$data = json_decode($json);
1292+
1293+
$this->assertIsArray($data);
1294+
1295+
$actual = array_group_by($data, ['group']);
1296+
1297+
$this->assertSame(
1298+
[
1299+
'Mammals' => [$data[0], $data[1]],
1300+
'Birds' => [$data[2]],
1301+
],
1302+
$actual,
1303+
);
1304+
$this->assertInstanceOf(stdClass::class, $actual['Mammals'][0]);
1305+
}
1306+
1307+
public function testArrayGroupByWithNestedObjectRows(): void
1308+
{
1309+
$data = [
1310+
(object) [
1311+
'id' => 1,
1312+
'hr' => (object) [
1313+
'department' => 'Engineering',
1314+
],
1315+
],
1316+
(object) [
1317+
'id' => 2,
1318+
'hr' => (object) [
1319+
'department' => 'Marketing',
1320+
],
1321+
],
1322+
(object) [
1323+
'id' => 3,
1324+
'hr' => (object) [
1325+
'department' => 'Engineering',
1326+
],
1327+
],
1328+
];
1329+
1330+
$actual = array_group_by($data, ['hr.department']);
1331+
1332+
$this->assertSame(
1333+
[
1334+
'Engineering' => [$data[0], $data[2]],
1335+
'Marketing' => [$data[1]],
1336+
],
1337+
$actual,
1338+
);
1339+
}
12771340
}

‎utils/phpstan-baseline/missingType.iterableValue.neon‎

Lines changed: 0 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -3082,21 +3082,11 @@ parameters:
30823082
count: 1
30833083
path: ../../system/HTTP/URI.php
30843084

3085-
-
3086-
message: '#^Method CodeIgniter\\Helpers\\Array\\ArrayHelper\:\:arrayAttachIndexedValue\(\) has parameter \$indexes with no value type specified in iterable type array\.$#'
3087-
count: 1
3088-
path: ../../system/Helpers/Array/ArrayHelper.php
3089-
30903085
-
30913086
message: '#^Method CodeIgniter\\Helpers\\Array\\ArrayHelper\:\:arrayAttachIndexedValue\(\) has parameter \$result with no value type specified in iterable type array\.$#'
30923087
count: 1
30933088
path: ../../system/Helpers/Array/ArrayHelper.php
30943089

3095-
-
3096-
message: '#^Method CodeIgniter\\Helpers\\Array\\ArrayHelper\:\:arrayAttachIndexedValue\(\) has parameter \$row with no value type specified in iterable type array\.$#'
3097-
count: 1
3098-
path: ../../system/Helpers/Array/ArrayHelper.php
3099-
31003090
-
31013091
message: '#^Method CodeIgniter\\Helpers\\Array\\ArrayHelper\:\:arrayAttachIndexedValue\(\) return type has no value type specified in iterable type array\.$#'
31023092
count: 1

0 commit comments

Comments
 (0)