From 54383e5d8a9690914fdbac9a4429d5c75c066986 Mon Sep 17 00:00:00 2001 From: webeweb Date: Tue, 20 Mar 2018 10:32:36 +0100 Subject: [PATCH] Add set() method into ArrayUtility --- Tests/Utility/ArrayUtilityTest.php | 53 ++++++++++++++++++++++++++++++ Utility/ArrayUtility.php | 18 ++++++++++ 2 files changed, 71 insertions(+) diff --git a/Tests/Utility/ArrayUtilityTest.php b/Tests/Utility/ArrayUtilityTest.php index 23b85107b..170cac13c 100644 --- a/Tests/Utility/ArrayUtilityTest.php +++ b/Tests/Utility/ArrayUtilityTest.php @@ -54,4 +54,57 @@ public function testGet() { $this->assertEquals("exception", ArrayUtility::get($arg, "inexistant_string", "exception")); } + /** + * Tests the set() method. + * + * @return void + */ + public function testSet() { + + $objN = []; + + ArrayUtility::set($objN, "key", null, [null]); + $this->assertEquals([], $objN); + + $objB1 = []; + + ArrayUtility::set($objB1, "key", true, [null, false]); + $this->assertEquals(["key" => true], $objB1); + + $objB2 = []; + + ArrayUtility::set($objB2, "key", false, [null, false]); + $this->assertEquals([], $objB2); + + $objF1 = []; + + ArrayUtility::set($objF1, "key", 1.0, [null, 0.0]); + $this->assertEquals(["key" => 1.0], $objF1); + + $objF2 = []; + + ArrayUtility::set($objF2, "key", 0.0, [null, 0.0]); + $this->assertEquals([], $objF2); + + $objI1 = []; + + ArrayUtility::set($objI1, "key", 1, [null, 0]); + $this->assertEquals(["key" => 1], $objI1); + + $objI2 = []; + + ArrayUtility::set($objI2, "key", 0, [null, 0]); + $this->assertEquals([], $objI2); + + $objS1 = []; + + ArrayUtility::set($objS1, "key", "true", [null, "false"]); + $this->assertEquals(["key" => "true"], $objS1); + + $objS2 = []; + + ArrayUtility::set($objS2, "key", "false", [null, "false"]); + $this->assertEquals([], $objS2); + } + } diff --git a/Utility/ArrayUtility.php b/Utility/ArrayUtility.php index bf4291f48..320dcea9c 100644 --- a/Utility/ArrayUtility.php +++ b/Utility/ArrayUtility.php @@ -32,4 +32,22 @@ public static function get(array $array, $key, $default = null) { return true === array_key_exists($key, $array) ? $array[$key] : $default; } + /** + * Set a value. + * + * @param array $array The array. + * @param string $key The key. + * @param mixed $value The value. + * @param array $tests The tests. + */ + public static function set(array &$array, $key, $value, array $tests = []) { + foreach ($tests as $current) { + if ($current !== $value) { + continue; + } + return; + } + $array[$key] = $value; + } + }