diff --git a/src/Util/Arrays.php b/src/Util/Arrays.php index 1cdf94a..60b8801 100644 --- a/src/Util/Arrays.php +++ b/src/Util/Arrays.php @@ -371,4 +371,40 @@ public static function partition(array $input, $partitionCount, $preserveKeys = return $partitions; } + + /** + * Unsets all elements in the given $array specified by $keys + * + * @param array &$array The array containing the elements to unset. + * @param array $keys Array of keys to unset. + * + * @return void + */ + public static function unsetAll(array &$array, array $keys) + { + foreach ($keys as $key) { + unset($array[$key]); + } + } + + /** + * Convert all empty strings to null in the given array + * + * @param array &$array The array containing empty strings + * + * @return void + */ + public static function nullifyEmptyStrings(array &$array) + { + $arrayCopy = $array; + foreach ($arrayCopy as $key => $value) { + if (!is_string($value)) { + continue; + } + + if (trim($value) === '') { + $array[$key] = null; + } + } + } } diff --git a/tests/Util/ArraysTest.php b/tests/Util/ArraysTest.php index 377100f..914a36d 100644 --- a/tests/Util/ArraysTest.php +++ b/tests/Util/ArraysTest.php @@ -707,4 +707,29 @@ public function partition_nonBoolPreserveKeys() { A::partition(['a', 'b', 'c'], 3, 'not a bool'); } + + /** + * Verify basic behavior of unsetAll(). + * + * @test + * @covers ::unsetAll + */ + public function unsetAll() + { + $array = ['a', 'b', 'c']; + A::unsetAll($array, [0, 2]); + $this->assertSame([1 => 'b'], $array); + } + + /** + * Verify basic behavior of nullifyEmptyStrings(). + * @test + * @covers ::nullifyEmptyStrings + */ + public function nullifyEmptyStrings() + { + $array = ['a' => '', 'b' => true, 'c' => "\n\t", 'd' => "\tstring with whitespace\n"]; + A::nullifyEmptyStrings($array); + $this->assertSame(['a' => null, 'b' => true, 'c' => null, 'd' => "\tstring with whitespace\n"], $array); + } }