Skip to content

Commit

Permalink
Improve
Browse files Browse the repository at this point in the history
  • Loading branch information
Tigrov committed May 21, 2024
1 parent d7353fc commit 2624980
Showing 1 changed file with 11 additions and 12 deletions.
23 changes: 11 additions & 12 deletions src/ArArrayHelper.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,9 @@

use Closure;

use function array_combine;
use function array_key_exists;
use function array_map;
use function get_object_vars;
use function property_exists;
use function strrpos;
Expand All @@ -16,7 +18,7 @@
* Array manipulation methods for ActiveRecord.
*
* @psalm-type Row = ActiveRecordInterface|array
* @psalm-type PathKey = string|Closure(Row, mixed):mixed
* @psalm-type PathKey = string|Closure(Row, mixed=):mixed
*/
final class ArArrayHelper
{
Expand Down Expand Up @@ -46,9 +48,7 @@ final class ArArrayHelper
public static function getColumn(array $array, string $name): array
{
return array_map(
static function (ActiveRecordInterface|array $element) use ($name): mixed {
return self::getValueByPath($element, $name);
},
static fn (ActiveRecordInterface|array $element): mixed => self::getValueByPath($element, $name),
$array
);
}
Expand Down Expand Up @@ -84,21 +84,16 @@ static function (ActiveRecordInterface|array $element) use ($name): mixed {
* ```
*
* @param ActiveRecordInterface|array $array Array or an {@see ActiveRecordInterface} instance to extract value from.
* @param Closure|string $key Key name of the array element or a property or relation name
* of the {@see ActiveRecordInterface} instance, or an anonymous function returning the value.
* @param string $key Key name of the array element or a property or relation name
* of the {@see ActiveRecordInterface} instance.
* @param mixed|null $default The default value to be returned if the specified `$key` doesn't exist.
*
* @psalm-param Row $array
* @psalm-param PathKey $key
*
* @return mixed The value of the element if found, default value otherwise
*/
public static function getValueByPath(ActiveRecordInterface|array $array, Closure|string $key, mixed $default = null): mixed
public static function getValueByPath(ActiveRecordInterface|array $array, string $key, mixed $default = null): mixed
{
if ($key instanceof Closure) {
return $key($array, $default);
}

if ($array instanceof ActiveRecordInterface) {
if ($array->hasAttribute($key)) {
return $array->getAttribute($key);
Expand Down Expand Up @@ -145,6 +140,10 @@ public static function populate(array $rows, Closure|string|null $indexBy = null
return $rows;
}

if ($indexBy instanceof Closure) {
return array_combine(array_map($indexBy, $rows), $rows);
}

$result = [];

foreach ($rows as $row) {
Expand Down

0 comments on commit 2624980

Please sign in to comment.