From 98a0e074840f710f0c357b17b89d257c0d059952 Mon Sep 17 00:00:00 2001 From: Alex Tselegidis Date: Sun, 16 Oct 2022 18:03:55 +0300 Subject: [PATCH] Add and autoload the array helper --- application/config/autoload.php | 1 + application/helpers/array_helper.php | 78 ++++++++++++++++++++++++++++ 2 files changed, 79 insertions(+) create mode 100644 application/helpers/array_helper.php diff --git a/application/config/autoload.php b/application/config/autoload.php index 088477d5..4f4042bc 100644 --- a/application/config/autoload.php +++ b/application/config/autoload.php @@ -66,6 +66,7 @@ $autoload['libraries'] = ['database', 'session']; */ $autoload['helper'] = [ + 'array', 'asset', 'config', 'debug', diff --git a/application/helpers/array_helper.php b/application/helpers/array_helper.php new file mode 100644 index 00000000..f14f2233 --- /dev/null +++ b/application/helpers/array_helper.php @@ -0,0 +1,78 @@ + + * @copyright Copyright (c) 2013 - 2020, Alex Tselegidis + * @license http://opensource.org/licenses/GPL-3.0 - GPLv3 + * @link http://easyappointments.org + * @since v1.4.0 + * ---------------------------------------------------------------------------- */ + +if ( ! function_exists('is_assoc')) +{ + /** + * Check if an array is an associative array. + * + * @param array $array + * + * @return bool + */ + function is_assoc(array $array): bool + { + if (empty($array)) + { + return FALSE; + } + + return array_keys($array) !== range(0, count($array) - 1); + } +} + +if ( ! function_exists('array_find')) +{ + /** + * Find the first array element based on the provided function. + * + * @param array $array + * @param callable $callback + * + * @return mixed + */ + function array_find(array $array, callable $callback): mixed + { + if (empty($array)) + { + return NULL; + } + + if ( ! is_callable($callback)) + { + throw new InvalidArgumentException('No filter function provided.'); + } + + return array_filter($array, $callback)[0] ?? NULL; + + } +} + +if ( ! function_exists('array_fields')) +{ + /** + * Keep only the provided fields of an array. + * + * @param array $array + * @param array $fields + * + * @return array + */ + function array_fields(array $array, array $fields): array + { + return array_filter($array, function ($field) use ($fields) { + return in_array($field, $fields); + }, ARRAY_FILTER_USE_KEY); + } +} +