From a82b9e1052c17e33d2f868223025d0fe155e311b Mon Sep 17 00:00:00 2001 From: Joby Elliott Date: Wed, 12 Jan 2022 18:11:09 -0700 Subject: [PATCH] Update FlatArrayTrait.php Made some speed improvements at the cost of memory and key validation. All defined tests should still work though. --- src/FlatArrayTrait.php | 34 ++++++++++++++++++++++++---------- 1 file changed, 24 insertions(+), 10 deletions(-) diff --git a/src/FlatArrayTrait.php b/src/FlatArrayTrait.php index e985190..3225986 100644 --- a/src/FlatArrayTrait.php +++ b/src/FlatArrayTrait.php @@ -1,10 +1,12 @@ flattenSearch($name); } - function unset(?string $name) { + function unset(?string $name) + { $this->flattenSearch($name, null, true); } @@ -148,7 +151,17 @@ trait FlatArrayTrait */ protected function flattenSearch(?string $name, $value = null, $unset = false) { + if ($value !== null || $unset) { + $this->_flattenCache = array(); + } + if (!isset($this->_flattenCache[$name])) { + $this->_flattenCache[$name] = $this->doFlattenSearch($name, $value, $unset); + } + return $this->_flattenCache[$name]; + } + protected function doFlattenSearch(?string $name, $value = null, $unset = false) + { //check for home strings if ($name == '' || $name === null) { if ($unset) { @@ -158,23 +171,24 @@ trait FlatArrayTrait } return $this->_arrayData; } - //validate - if (substr($name, -1, 1) == '.' || substr($name, 0, 1) == '..' || strpos($name, '..') !== false) { - return null; - } //build a reference to where this name should be $parent = &$this->_arrayData; $name = explode('.', $name); $key = array_pop($name); - foreach ($name as $part) { - if (!isset($parent[$part])) { - if ($value !== null) { + if ($value !== null) { + foreach ($name as $part) { + if (!isset($parent[$part])) { $parent[$part] = array(); - } else { + } + $parent = &$parent[$part]; + } + } else { + foreach ($name as $part) { + if (!isset($parent[$part])) { return null; } + $parent = &$parent[$part]; } - $parent = &$parent[$part]; } //now we have a ref, see if we can unset or set it if ($unset) {