Skip to content

[9.x] Support iterables objects on data_get nested arrays #37453

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

Merged
merged 1 commit into from
May 24, 2021
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
2 changes: 1 addition & 1 deletion src/Illuminate/Collections/helpers.php
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ function data_get($target, $key, $default = null)
if ($segment === '*') {
if ($target instanceof Collection) {
$target = $target->all();
} elseif (! is_array($target)) {
} elseif (! is_iterable($target)) {
return value($default);
}

Expand Down
25 changes: 25 additions & 0 deletions tests/Support/SupportHelpersTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,11 @@
namespace Illuminate\Tests\Support;

use ArrayAccess;
use ArrayIterator;
use Illuminate\Contracts\Support\Htmlable;
use Illuminate\Support\Env;
use Illuminate\Support\Optional;
use IteratorAggregate;
use LogicException;
use Mockery as m;
use PHPUnit\Framework\TestCase;
Expand Down Expand Up @@ -87,10 +89,18 @@ public function testDataGetWithNestedArrays()
['name' => 'abigail'],
['name' => 'dayle'],
];
$arrayIterable = new SupportTestArrayIterable([
['name' => 'taylor', 'email' => 'taylorotwell@gmail.com'],
['name' => 'abigail'],
['name' => 'dayle'],
]);

$this->assertEquals(['taylor', 'abigail', 'dayle'], data_get($array, '*.name'));
$this->assertEquals(['taylorotwell@gmail.com', null, null], data_get($array, '*.email', 'irrelevant'));

$this->assertEquals(['taylor', 'abigail', 'dayle'], data_get($arrayIterable, '*.name'));
$this->assertEquals(['taylorotwell@gmail.com', null, null], data_get($arrayIterable, '*.email', 'irrelevant'));

$array = [
'users' => [
['first' => 'taylor', 'last' => 'otwell', 'email' => 'taylorotwell@gmail.com'],
Expand Down Expand Up @@ -792,3 +802,18 @@ public function offsetUnset($offset)
unset($this->attributes[$offset]);
}
}

class SupportTestArrayIterable implements IteratorAggregate
{
protected $items = [];

public function __construct($items = [])
{
$this->items = $items;
}

public function getIterator()
{
return new ArrayIterator($this->items);
}
}