<?php

namespace Linksy\SearchAndReplace\Plugli\Standard\Helpers;

class Arr
{
    public static function some($callback, $array = [])
    {
        foreach ($array as $item) {
            if ($callback($item)) {
                return \true;
            }
        }
        return \false;
    }
    public static function find($callback, $array = [])
    {
        foreach ($array as $k => $v) {
            if ($callback($v, $k)) {
                return $v;
            }
        }
        return null;
    }
    public static function findIndex($callback, $array = [])
    {
        foreach ($array as $k => $v) {
            if ($callback($v, $k)) {
                return $k;
            }
        }
        return -1;
    }
    public static function last($array = [], $callback = null)
    {
        if ($callback) {
            $array = array_filter($array, $callback);
        }
        $last = end($array);
        return $last === \false ? null : $last;
    }
    public static function filter(array $array, callable $callback, $preserve_keys = \false)
    {
        $new_arr = [];
        foreach ($array as $k => $v) {
            if ($callback($v, $k)) {
                if ($preserve_keys) {
                    $new_arr[$k] = $v;
                } else {
                    $new_arr[] = $v;
                }
            }
        }
        return $new_arr;
    }
    public static function groupBy($array = [], $callback = null)
    {
        $new_arr = [];
        foreach ($array as $k => $v) {
            if (is_callable($callback)) {
                $key = $callback($v, $k);
            } else {
                $key = is_object($v) ? $v->{$callback} : $v[$callback];
            }
            if (!isset($new_arr[$key])) {
                $new_arr[$key] = [];
            }
            $new_arr[$key][] = $v;
        }
        return $new_arr;
    }
    public static function isMap($array)
    {
        return count(array_filter(array_keys($array), 'is_string')) > 0;
    }
    public static function get_value($row, $column, $callback = null)
    {
        $value = null;
        if (is_object($row)) {
            if (property_exists($row, $column)) {
                $value = $row->{$column};
            }
        } else if (isset($row[$column])) {
            $value = $row[$column];
        }
        if (is_callable($callback)) {
            return $callback($value);
        }
        return $value;
    }
    public static function split($string, $separator = ',', $default = [], $callback = null)
    {
        $result = self::filter(explode($separator, $string), $callback ? $callback : 'trim');
        return count($result) > 0 ? $result : $default;
    }
}
