summaryrefslogtreecommitdiffstats
path: root/tests/Inc/ArrayUtilTest.php
diff options
context:
space:
mode:
Diffstat (limited to 'tests/Inc/ArrayUtilTest.php')
-rw-r--r--tests/Inc/ArrayUtilTest.php91
1 files changed, 91 insertions, 0 deletions
diff --git a/tests/Inc/ArrayUtilTest.php b/tests/Inc/ArrayUtilTest.php
new file mode 100644
index 00000000..0423e6da
--- /dev/null
+++ b/tests/Inc/ArrayUtilTest.php
@@ -0,0 +1,91 @@
+<?php
+
+use PHPUnit\Framework\TestCase;
+
+class ArrayUtilTest extends TestCase
+{
+ public function testFlattenByKeyBasicAndMissingKeys(): void
+ {
+ $in = [
+ ['id' => 1, 'name' => 'a'],
+ ['id' => 2, 'name' => 'b', 'x' => 5],
+ ['name' => 'c'], // missing 'id' -> skipped by array_column()
+ ];
+ $this->assertSame([1, 2], ArrayUtil::flattenByKey($in, 'id'));
+ }
+
+ public function testMergeByKeyMergesAcrossSubArrays(): void
+ {
+ $in = [
+ 'a' => ['k1' => 1, 'k2' => 2],
+ 'b' => ['k1' => 3],
+ ];
+ $expected = [
+ 'k1' => ['a' => 1, 'b' => 3],
+ 'k2' => ['a' => 2, 'b' => false],
+ ];
+ $this->assertSame($expected, ArrayUtil::mergeByKey($in));
+ }
+
+ public function testSortByColumnAscendingAndDescending(): void
+ {
+ $rows = [
+ ['n' => 'b', 'v' => 2],
+ ['n' => 'a', 'v' => 3],
+ ['n' => 'c', 'v' => 1],
+ ];
+ $copy = $rows;
+ ArrayUtil::sortByColumn($rows, 'v', SORT_ASC);
+ $this->assertSame([
+ ['n' => 'c', 'v' => 1],
+ ['n' => 'b', 'v' => 2],
+ ['n' => 'a', 'v' => 3],
+ ], $rows);
+
+ ArrayUtil::sortByColumn($copy, 'n', SORT_DESC, SORT_STRING);
+ $this->assertSame([
+ ['n' => 'c', 'v' => 1],
+ ['n' => 'b', 'v' => 2],
+ ['n' => 'a', 'v' => 3],
+ ], $copy);
+ }
+
+ public function testHasAllKeys(): void
+ {
+ $arr = ['a' => 1, 'b' => 2];
+ $this->assertTrue(ArrayUtil::hasAllKeys($arr, ['a', 'b']));
+ $this->assertFalse(ArrayUtil::hasAllKeys($arr, ['a', 'c']));
+ $this->assertTrue(ArrayUtil::hasAllKeys($arr, []));
+ }
+
+ public function testIsOnlyPrimitiveTypes(): void
+ {
+ $this->assertTrue(ArrayUtil::isOnlyPrimitiveTypes([1, 'x', 1.2, null, true, false, 0]));
+ $this->assertFalse(ArrayUtil::isOnlyPrimitiveTypes([[]]));
+ $this->assertFalse(ArrayUtil::isOnlyPrimitiveTypes([new stdClass()]));
+
+ $h = fopen('php://memory', 'r');
+ try {
+ $this->assertFalse(ArrayUtil::isOnlyPrimitiveTypes([$h]));
+ } finally {
+ if (is_resource($h))
+ fclose($h);
+ }
+ }
+
+ public function testForceTypeMutatesArrayInPlace(): void
+ {
+ $arr = ['1', '2', '3'];
+ ArrayUtil::forceType($arr, 'int');
+ $this->assertSame([1, 2, 3], $arr);
+
+ $arr = ['0', '1', '', 'foo'];
+ ArrayUtil::forceType($arr, 'bool');
+ // In PHP, (bool) '0' is false; non-empty strings except '0' are true; empty string is false
+ $this->assertSame([false, true, false, true], $arr);
+
+ $arr = [1, 2, 3];
+ ArrayUtil::forceType($arr, 'string');
+ $this->assertSame(['1', '2', '3'], $arr);
+ }
+}