From cd92e4fcd86309c9ed3dec41cec5f3a88a4f69e2 Mon Sep 17 00:00:00 2001 From: Yuri Kuznetsov Date: Tue, 27 Sep 2022 09:49:14 +0300 Subject: [PATCH] fix util array to object to preserve lists --- application/Espo/Core/Utils/Util.php | 13 +++++++-- tests/unit/Espo/Core/Utils/UtilTest.php | 38 +++++++++++++++---------- 2 files changed, 34 insertions(+), 17 deletions(-) diff --git a/application/Espo/Core/Utils/Util.php b/application/Espo/Core/Utils/Util.php index f04c7f327f..a221c75337 100644 --- a/application/Espo/Core/Utils/Util.php +++ b/application/Espo/Core/Utils/Util.php @@ -305,8 +305,17 @@ class Util */ private static function arrayToObjectInternal($value) { - if (is_array($value)) { - return (object) array_map(fn($v) => self::arrayToObjectInternal($v), $value); + if (!is_array($value)) { + return $value; + } + + // @todo Change to `array_is_list` when PHP 8.1 is the min supported. + $isList = $value === array_values($value); + + $value = array_map(fn($v) => self::arrayToObjectInternal($v), $value); + + if (!$isList) { + $value = (object) $value; } return $value; diff --git a/tests/unit/Espo/Core/Utils/UtilTest.php b/tests/unit/Espo/Core/Utils/UtilTest.php index 61b9f161a1..a1e3682876 100644 --- a/tests/unit/Espo/Core/Utils/UtilTest.php +++ b/tests/unit/Espo/Core/Utils/UtilTest.php @@ -1072,27 +1072,35 @@ class UtilTest extends \PHPUnit\Framework\TestCase $this->assertEquals($result, Util::concatPath($input)); } - public function testArrayToObject() + public function testArrayToObject(): void { - $testArr= array( + $testArr= [ 'useCache' => true, - 'sub' => array ( + 'sub' => [ 'subV' => '125', - 'subO' => array( + 'subO' => [ 'subOV' => '125', - ), - ), - ); + ], + 'subList' => [ + '0', + '1' + ], + ], + ]; - $testResult= (object) array( + $testResult= (object) [ 'useCache' => true, - ); - $testResult->sub = (object) array ( - 'subV' => '125', - ); - $testResult->sub->subO = (object) array ( - 'subOV' => '125', - ); + ]; + + $testResult->sub = (object) [ + 'subV' => '125', + ]; + + $testResult->sub->subO = (object) [ + 'subOV' => '125', + ]; + + $testResult->sub->subList = ['0', '1']; $this->assertEquals($testResult, Util::arrayToObject($testArr)); }