Skip to content
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

prevent throw array access error when orderByChild('nested/key') #135

Closed
wants to merge 2 commits into from
Closed
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
41 changes: 37 additions & 4 deletions src/Firebase/Database/Query/Sorter/OrderByChild.php
Original file line number Diff line number Diff line change
Expand Up @@ -27,13 +27,46 @@ public function modifyValue($value)
if (!is_array($value)) {
return $value;
}

$childKey = $this->childKey;

uasort($value, function ($a, $b) use ($childKey) {
return ($a[$childKey] ?? null) <=> $b[$childKey] ?? null;
return ($this->accessToArrayPath($a, $childKey) ?? null) <=> $this->accessToArrayPath($b, $childKey) ?? null;
});

return $value;
}

/**
* Function taken from Mohamed Meabed repo:
* https://github.com/tajawal/lodash-php/blob/master/src/collections/get.php
*
* Get item of an array by index , aceepting nested index
*
** __::get(['foo' => ['bar' => 'ter']], 'foo/bar');
** // → 'ter'
*
* @param array $collection array of values
* @param string $key key or index
* @param null $default default value to return if index not exist
*
* @return array|mixed|null
*
*/
function accessToArrayPath($collection = [], $key = '', $default = null)
{
if (is_null($key)) {
return $collection;
}

foreach (explode('/', $key) as $segment) {
if (!isset($collection[$segment])) {
return $default instanceof \Closure ? $default() : $default;
}

$collection = $collection[$segment];
}

return $collection;
}
}