Page Menu
Home
DevCentral
Search
Configure Global Search
Log In
Files
F3778021
D2955.id7524.diff
No One
Temporary
Actions
View File
Edit File
Delete File
View Transforms
Subscribe
Mute Notifications
Award Token
Flag For Later
Size
2 KB
Referenced Files
None
Subscribers
None
D2955.id7524.diff
View Options
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
Details
Attached
Mime Type
text/plain
Expires
Tue, Nov 26, 03:35 (20 h, 7 m)
Storage Engine
blob
Storage Format
Raw Data
Storage Handle
2263740
Default Alt Text
D2955.id7524.diff (2 KB)
Attached To
Mode
D2955: Convert object to array
Attached
Detach File
Event Timeline
Log In to Comment