Page MenuHomeDevCentral

D2955.id7523.diff
No OneTemporary

D2955.id7523.diff

diff --git a/omnitools/src/Collections/HashMap.php b/omnitools/src/Collections/HashMap.php
--- a/omnitools/src/Collections/HashMap.php
+++ b/omnitools/src/Collections/HashMap.php
@@ -39,7 +39,35 @@
}
}
- public static function from (iterable $items) : static {
+ ///
+ /// Convert to HashMap
+ ///
+
+ private static function convertToArray ($data) {
+ if (is_iterable($data) || is_object($data)) {
+ $result = [];
+ foreach ($data as $key => $value) {
+ $result[$key] = self::convertToArray($value);
+ }
+ return $result;
+ }
+
+ return $data;
+ }
+
+ /**
+ * Converts deeply an element to a map.
+ *
+ * If $from is an object or iterable, each element will be:
+ * - converted to an array (deep array) if iterable or object
+ * - kept as is if it's a scalar
+ */
+ public static function from (iterable|object|null $from) : static {
+ if ($from === null) {
+ return new self;
+ }
+
+ $items = self::convertToArray($from);
return new self($items);
}
diff --git a/omnitools/tests/Collections/HashMapTest.php b/omnitools/tests/Collections/HashMapTest.php
--- a/omnitools/tests/Collections/HashMapTest.php
+++ b/omnitools/tests/Collections/HashMapTest.php
@@ -57,9 +57,37 @@
$this->assertSame($expected, $map->toArray());
}
- public function testFrom () {
- $map = HashMap::from(self::MAP_CONTENT);
- $this->assertSame(self::MAP_CONTENT, $map->toArray());
+ private function provideDeepArrays() : iterable {
+ yield [self::MAP_CONTENT, self::MAP_CONTENT];
+
+ yield [[], []];
+ yield [null, []];
+
+ $caps = new \stdClass;
+ $caps->color = "red";
+ $caps->logo = "HCKR";
+ yield [$caps, [
+ "color" => "red",
+ "logo" => "HCKR",
+ ]];
+
+ $sizedCaps = clone $caps;
+ $sizedCaps->size = new \stdClass;
+ $sizedCaps->size->h = 8;
+ $sizedCaps->size->r = 20;
+ yield [$sizedCaps, [
+ "color" => "red",
+ "logo" => "HCKR",
+ "size" => ["h" => 8, "r" => 20],
+ ]];
+ }
+
+ /**
+ * @dataProvider provideDeepArrays
+ */
+ public function testFrom($from, array $expected) : void {
+ $map = HashMap::from($from);
+ $this->assertEquals($expected, $map->toArray());
}
///

File Metadata

Mime Type
text/plain
Expires
Tue, Nov 26, 03:31 (19 h, 40 m)
Storage Engine
blob
Storage Format
Raw Data
Storage Handle
2263740
Default Alt Text
D2955.id7523.diff (2 KB)

Event Timeline