Skip to content

Commit 2284d42

Browse files
committed
refactor: scope object support to dot_array_search and array_group_by
Per review feedback on #10226 from @michalsn: - Revert object support added to `dot_array_has()` and `dot_array_only()` so the scope matches the original issue (#10225). They can be proposed in follow-up PRs. - Add `toIterable()` helper and use it before the wildcard `foreach` in `arraySearchDot()` so iterating an Entity does not expose internals like `$_options` / `$_cast`. - Simplify `objectToArray()` to short-circuit on `Entity` via `toArray()` and drop the per-property `ReflectionMethod` lookups. Non-Entity objects keep working through the existing point accessors (ArrayAccess, public props, magic `__get`). - Narrow user guide and v4.8.0 changelog entries accordingly; trim the out-of-scope object tests and add explicit Entity coverage for `dot_array_search()` and `array_group_by()`.
1 parent d038e12 commit 2284d42

4 files changed

Lines changed: 77 additions & 140 deletions

File tree

‎system/Helpers/Array/ArrayHelper.php‎

Lines changed: 40 additions & 62 deletions
Original file line numberDiff line numberDiff line change
@@ -14,8 +14,9 @@
1414
namespace CodeIgniter\Helpers\Array;
1515

1616
use ArrayAccess;
17+
use CodeIgniter\Entity\Entity;
1718
use CodeIgniter\Exceptions\InvalidArgumentException;
18-
use ReflectionMethod;
19+
use Traversable;
1920

2021
/**
2122
* @internal This is internal implementation for the framework.
@@ -102,9 +103,10 @@ private static function arraySearchDot(array $indexes, array|object $array)
102103

103104
// Handle Wildcard (*)
104105
if ($currentIndex === '*') {
105-
$answer = [];
106+
$answer = [];
107+
$iterable = is_object($array) ? self::toIterable($array) : $array;
106108

107-
foreach ($array as $value) {
109+
foreach ($iterable as $value) {
108110
if (! is_array($value) && ! is_object($value)) {
109111
return null;
110112
}
@@ -144,9 +146,9 @@ private static function arraySearchDot(array $indexes, array|object $array)
144146
*
145147
* If wildcard `*` is used, all items for the key after it must have the key.
146148
*
147-
* @param array<array-key, mixed>|object $array
149+
* @param array<array-key, mixed> $array
148150
*/
149-
public static function dotHas(string $index, array|object $array): bool
151+
public static function dotHas(string $index, array $array): bool
150152
{
151153
self::ensureValidWildcardPattern($index);
152154

@@ -162,10 +164,10 @@ public static function dotHas(string $index, array|object $array): bool
162164
/**
163165
* Recursively check key existence by dot path, including wildcard support.
164166
*
165-
* @param array<array-key, mixed>|object $array
166-
* @param list<string> $indexes
167+
* @param array<array-key, mixed> $array
168+
* @param list<string> $indexes
167169
*/
168-
private static function hasByDotPath(array|object $array, array $indexes): bool
170+
private static function hasByDotPath(array $array, array $indexes): bool
169171
{
170172
if ($indexes === []) {
171173
return true;
@@ -175,29 +177,27 @@ private static function hasByDotPath(array|object $array, array $indexes): bool
175177

176178
if ($currentIndex === '*') {
177179
foreach ($array as $item) {
178-
if ((! is_array($item) && ! is_object($item)) || ! self::hasByDotPath($item, $indexes)) {
180+
if (! is_array($item) || ! self::hasByDotPath($item, $indexes)) {
179181
return false;
180182
}
181183
}
182184

183185
return true;
184186
}
185187

186-
if (! self::keyExists($array, $currentIndex)) {
188+
if (! array_key_exists($currentIndex, $array)) {
187189
return false;
188190
}
189191

190192
if ($indexes === []) {
191193
return true;
192194
}
193195

194-
$value = self::value($array, $currentIndex);
195-
196-
if (! is_array($value) && ! is_object($value)) {
196+
if (! is_array($array[$currentIndex])) {
197197
return false;
198198
}
199199

200-
return self::hasByDotPath($value, $indexes);
200+
return self::hasByDotPath($array[$currentIndex], $indexes);
201201
}
202202

203203
/**
@@ -460,32 +460,6 @@ public static function sortValuesByNatural(array &$array, $sortByIndex = null):
460460
});
461461
}
462462

463-
/**
464-
* @param array<array-key, mixed>|object $data
465-
*/
466-
private static function keyExists(array|object $data, string $key): bool
467-
{
468-
if (is_array($data)) {
469-
return array_key_exists($key, $data);
470-
}
471-
472-
$array = self::objectToArray($data);
473-
474-
if ($array !== null) {
475-
return array_key_exists($key, $array);
476-
}
477-
478-
if ($data instanceof ArrayAccess && $data->offsetExists($key)) {
479-
return true;
480-
}
481-
482-
if (array_key_exists($key, get_object_vars($data))) {
483-
return true;
484-
}
485-
486-
return isset($data->{$key});
487-
}
488-
489463
/**
490464
* @param array<array-key, mixed>|object $data
491465
*/
@@ -545,31 +519,35 @@ private static function value(array|object $data, string $key): mixed
545519
*/
546520
private static function objectToArray(object $data): ?array
547521
{
548-
if (method_exists($data, 'toRawArray')) {
549-
$method = new ReflectionMethod($data, 'toRawArray');
550-
551-
if ($method->isPublic() && $method->getNumberOfRequiredParameters() === 0) {
552-
$array = $data->toRawArray();
553-
554-
if (is_array($array)) {
555-
return $array;
556-
}
557-
}
522+
if ($data instanceof Entity) {
523+
return $data->toArray();
558524
}
559525

560-
if (method_exists($data, 'toArray')) {
561-
$method = new ReflectionMethod($data, 'toArray');
526+
return null;
527+
}
562528

563-
if ($method->isPublic() && $method->getNumberOfRequiredParameters() === 0) {
564-
$array = $data->toArray();
529+
/**
530+
* Normalize an object to an array safe to iterate with foreach.
531+
*
532+
* Entities are converted via toArray() so internal properties like
533+
* `_options` or `_cast` are not exposed. Other Traversable objects are
534+
* materialized; plain objects fall back to their public properties.
535+
*
536+
* @return array<array-key, mixed>
537+
*/
538+
private static function toIterable(object $data): array
539+
{
540+
$array = self::objectToArray($data);
565541

566-
if (is_array($array)) {
567-
return $array;
568-
}
569-
}
542+
if ($array !== null) {
543+
return $array;
570544
}
571545

572-
return null;
546+
if ($data instanceof Traversable) {
547+
return iterator_to_array($data);
548+
}
549+
550+
return get_object_vars($data);
573551
}
574552

575553
/**
@@ -731,7 +709,7 @@ private static function projectByDotPath(
731709
$currentIndex = array_shift($indexes);
732710

733711
if ($currentIndex === '*') {
734-
if (! is_array($source) && ! is_object($source)) {
712+
if (! is_array($source)) {
735713
return;
736714
}
737715

@@ -742,10 +720,10 @@ private static function projectByDotPath(
742720
return;
743721
}
744722

745-
if ((! is_array($source) && ! is_object($source)) || ! self::keyExists($source, $currentIndex)) {
723+
if (! is_array($source) || ! array_key_exists($currentIndex, $source)) {
746724
return;
747725
}
748726

749-
self::projectByDotPath(self::value($source, $currentIndex), $indexes, $result, [...$prefix, $currentIndex]);
727+
self::projectByDotPath($source[$currentIndex], $indexes, $result, [...$prefix, $currentIndex]);
750728
}
751729
}

‎tests/system/Helpers/ArrayHelperTest.php‎

Lines changed: 31 additions & 71 deletions
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@
1919
use PHPUnit\Framework\Attributes\DataProvider;
2020
use PHPUnit\Framework\Attributes\Group;
2121
use stdClass;
22-
use Tests\Support\Entity\ArrayObjectWithToArray;
22+
use Tests\Support\SomeEntity;
2323
use ValueError;
2424

2525
/**
@@ -395,8 +395,6 @@ public function testArrayDotWithObjectValues(): void
395395
];
396396

397397
$this->assertSame('Jane', dot_array_search('user.profile.name', $data));
398-
$this->assertTrue(dot_array_has('user.profile.name', $data));
399-
$this->assertFalse(dot_array_has('user.profile.email', $data));
400398
}
401399

402400
public function testArrayDotWithMagicObjectValues(): void
@@ -425,7 +423,6 @@ public function __get(string $key): mixed
425423
];
426424

427425
$this->assertSame('Jane', dot_array_search('user.profile.name', $data));
428-
$this->assertTrue(dot_array_has('user.profile.name', $data));
429426
}
430427

431428
public function testArrayDotWithArrayAccessValues(): void
@@ -439,51 +436,14 @@ public function testArrayDotWithArrayAccessValues(): void
439436
];
440437

441438
$this->assertSame('Jane', dot_array_search('user.profile.name', $data));
442-
$this->assertTrue(dot_array_has('user.profile.name', $data));
443439
}
444440

445-
public function testArrayDotWithObjectToRawArrayValues(): void
441+
public function testArrayDotWithEntityValues(): void
446442
{
447-
$data = [
448-
'user' => new class () {
449-
/**
450-
* @return array<string, array<string, string>>
451-
*/
452-
public function toRawArray(): array
453-
{
454-
return [
455-
'profile' => [
456-
'name' => 'Raw',
457-
],
458-
];
459-
}
460-
461-
/**
462-
* @return array<string, array<string, string>>
463-
*/
464-
public function toArray(): array
465-
{
466-
return [
467-
'profile' => [
468-
'name' => 'Array',
469-
],
470-
];
471-
}
472-
},
473-
];
474-
475-
$this->assertSame('Raw', dot_array_search('user.profile.name', $data));
476-
$this->assertTrue(dot_array_has('user.profile.name', $data));
477-
}
478-
479-
public function testArrayDotWithObjectToArrayValues(): void
480-
{
481-
$data = [
482-
'user' => new ArrayObjectWithToArray(),
483-
];
443+
$entity = new SomeEntity();
444+
$entity->foo = 'value';
484445

485-
$this->assertSame('same', dot_array_search('user.array', $data));
486-
$this->assertTrue(dot_array_has('user.array', $data));
446+
$this->assertSame('value', dot_array_search('user.foo', ['user' => $entity]));
487447
}
488448

489449
public function testArrayDotWildcardWithObjectValues(): void
@@ -496,32 +456,6 @@ public function testArrayDotWildcardWithObjectValues(): void
496456
];
497457

498458
$this->assertSame(['John', 'Maria'], dot_array_search('users.*.name', $data));
499-
$this->assertTrue(dot_array_has('users.*.name', $data));
500-
}
501-
502-
public function testArrayDotOnlyWithObjectValues(): void
503-
{
504-
$data = [
505-
'users' => [
506-
(object) [
507-
'id' => 1,
508-
'name' => 'John',
509-
],
510-
(object) [
511-
'id' => 2,
512-
'name' => 'Maria',
513-
],
514-
],
515-
];
516-
517-
$expected = [
518-
'users' => [
519-
['id' => 1],
520-
['id' => 2],
521-
],
522-
];
523-
524-
$this->assertSame($expected, dot_array_only($data, 'users.*.id'));
525459
}
526460

527461
/**
@@ -1706,4 +1640,30 @@ public function testArrayGroupByWithNestedObjectRows(): void
17061640
$actual,
17071641
);
17081642
}
1643+
1644+
public function testArrayGroupByWithEntityRows(): void
1645+
{
1646+
$a = new SomeEntity();
1647+
$a->foo = 'A';
1648+
$a->bar = 'x';
1649+
1650+
$b = new SomeEntity();
1651+
$b->foo = 'B';
1652+
$b->bar = 'y';
1653+
1654+
$c = new SomeEntity();
1655+
$c->foo = 'A';
1656+
$c->bar = 'z';
1657+
1658+
$actual = array_group_by([$a, $b, $c], ['foo']);
1659+
1660+
$this->assertSame(
1661+
[
1662+
'A' => [$a, $c],
1663+
'B' => [$b],
1664+
],
1665+
$actual,
1666+
);
1667+
$this->assertSame($a, $actual['A'][0]);
1668+
}
17091669
}

‎user_guide_src/source/changelogs/v4.8.0.rst‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -264,9 +264,9 @@ Helpers and Functions
264264
- :doc:`Array Helper </helpers/array_helper>` gained five new dot-path functions:
265265
:php:func:`dot_array_has()`, :php:func:`dot_array_set()`, :php:func:`dot_array_unset()`,
266266
:php:func:`dot_array_only()`, and :php:func:`dot_array_except()`.
267-
- :doc:`Array Helper </helpers/array_helper>` dot-path read operations now support object properties
268-
in :php:func:`dot_array_search()`, :php:func:`dot_array_has()`, :php:func:`dot_array_only()`,
269-
and :php:func:`array_group_by()`.
267+
- :doc:`Array Helper </helpers/array_helper>` dot-path read operations now support
268+
object rows (including ``Entity``) in :php:func:`dot_array_search()` and
269+
:php:func:`array_group_by()`.
270270

271271
HTTP
272272
====

‎user_guide_src/source/helpers/array_helper.rst‎

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -58,16 +58,16 @@ The following functions are available:
5858

5959
.. note:: Prior to v4.8.0, only arrays were supported. Support for objects was added in v4.8.0.
6060

61-
.. php:function:: dot_array_has(string $search, array|object $values): bool
61+
.. php:function:: dot_array_has(string $search, array $values): bool
6262
6363
:param string $search: The dot-notation string describing how to search the array
64-
:param array|object $values: The array or object to check
64+
:param array $values: The array to check
6565
:returns: ``true`` if the key exists, otherwise ``false``
6666
:rtype: bool
6767

6868
.. versionadded:: 4.8.0
6969

70-
Checks if an array key or object property exists using dot syntax.
70+
Checks if an array key exists using dot syntax.
7171
This method supports wildcard ``*`` in the same way as ``dot_array_search()``.
7272

7373
.. literalinclude:: array_helper/015.php
@@ -115,7 +115,6 @@ The following functions are available:
115115
.. versionadded:: 4.8.0
116116

117117
Gets only the specified keys using dot syntax while preserving nested structure.
118-
Nested object properties can be selected in the same way as array keys.
119118

120119
Wildcard ``*`` is supported. Unlike ``dot_array_set()`` and ``dot_array_unset()``,
121120
this method also allows wildcard at the end (for example ``user.*``).

0 commit comments

Comments
 (0)