From dff9a5eca27d2fb564519cac749671df3ea35787 Mon Sep 17 00:00:00 2001 From: Jakub Onderka Date: Sat, 27 Jan 2024 12:44:14 +0100 Subject: [PATCH] chg: [internal] Faster checking if array is list --- .../Component/RestResponseComponent.php | 2 +- app/Lib/Tools/JsonTool.php | 21 +++++++++++++++++++ app/Model/Warninglist.php | 3 +-- 3 files changed, 23 insertions(+), 3 deletions(-) diff --git a/app/Controller/Component/RestResponseComponent.php b/app/Controller/Component/RestResponseComponent.php index 3ea480278..3f760f056 100644 --- a/app/Controller/Component/RestResponseComponent.php +++ b/app/Controller/Component/RestResponseComponent.php @@ -633,7 +633,7 @@ class RestResponseComponent extends Component } // If response is big array, encode items separately to save memory - if (is_array($response) && count($response) > 10000) { + if (is_array($response) && count($response) > 10000 && JsonTool::arrayIsList($response)) { $output = new TmpFileTool(); $output->write('['); diff --git a/app/Lib/Tools/JsonTool.php b/app/Lib/Tools/JsonTool.php index a3c27727e..c23abc7e7 100644 --- a/app/Lib/Tools/JsonTool.php +++ b/app/Lib/Tools/JsonTool.php @@ -68,6 +68,27 @@ class JsonTool } } + /** + * @see https://www.php.net/manual/en/function.array-is-list.php + * @param array $array + * @return bool + */ + public static function arrayIsList(array $array) + { + if (function_exists('array_is_list')) { + return array_is_list($array); + } + + $i = -1; + foreach ($array as $k => $v) { + ++$i; + if ($k !== $i) { + return false; + } + } + return true; + } + /** * JSON supports just unicode strings. This helper method converts non unicode chars to Unicode Replacement Character U+FFFD (UTF-8) * @param string $string diff --git a/app/Model/Warninglist.php b/app/Model/Warninglist.php index b4313ddc2..bc3e649d4 100644 --- a/app/Model/Warninglist.php +++ b/app/Model/Warninglist.php @@ -390,8 +390,7 @@ class Warninglist extends AppModel $warninglistId = (int)$this->id; $result = true; - $keys = array_keys($list['list']); - if ($keys === array_keys($keys)) { + if (JsonTool::arrayIsList($list['list'])) { foreach (array_chunk($list['list'], 1000) as $chunk) { $valuesToInsert = []; foreach ($chunk as $value) {