Skip to content

Commit

Permalink
Add set() method into ArrayUtility
Browse files Browse the repository at this point in the history
  • Loading branch information
webeweb committed Mar 20, 2018
1 parent 9ed60c3 commit 54383e5
Show file tree
Hide file tree
Showing 2 changed files with 71 additions and 0 deletions.
53 changes: 53 additions & 0 deletions Tests/Utility/ArrayUtilityTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}

}
18 changes: 18 additions & 0 deletions Utility/ArrayUtility.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}

}

0 comments on commit 54383e5

Please sign in to comment.