Skip to content

Commit

Permalink
allow cast map to native array
Browse files Browse the repository at this point in the history
  • Loading branch information
akondas committed May 30, 2024
1 parent 886c7f1 commit cab559e
Show file tree
Hide file tree
Showing 3 changed files with 50 additions and 1 deletion.
31 changes: 31 additions & 0 deletions src/Collection/Map.php
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,22 @@ public static function empty(): self
return new self();
}

/**
* @template U
* @template T
*
* @param array<Tuple2<U, T>> $map
*
* @return self<U, T>
*/
public static function from(array $map): self
{
$newMap = new self();
$newMap->map = $map;

return $newMap;
}

/**
* Creates Map from given array, all keys will be cast to string.
*
Expand Down Expand Up @@ -429,6 +445,21 @@ public function offsetUnset(mixed $offset): void
throw new UnsupportedOperationException();
}

/**
* Will try to cast all keys to string, may result in data loss if the keys cannot be converted to a unique string.
*
* @return array<string, V>
*/
public function toNativeArray(): array
{
$map = [];
foreach ($this->map as $tuple) {
$map[(string) $tuple[0]] = $tuple[1];
}

return $map;
}

/**
* @param K $key
*/
Expand Down
13 changes: 13 additions & 0 deletions tests/Collection/MapTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -350,4 +350,17 @@ public function testMapWithObjects(): void
self::assertTrue(Set::of($event1)->equals($map->keys()));
self::assertTrue(Stream::of('magic')->equals($map->values()));
}

public function testMapToNativeArray(): void
{
self::assertSame(['a' => 'b', 'c' => 'd'], Map::fromArray(['a' => 'b', 'c' => 'd'])->toNativeArray());

$map = Map::from([Tuple::of(new Event('a', 'same'), 'one'), Tuple::of(new Event('b', 'same'), 'two')]);

self::assertSame(['a' => 'one', 'b' => 'two'], $map->toNativeArray());

$map = Map::from([Tuple::of(new Event('a', 'same'), 'one'), Tuple::of(new Event('a', 'same'), 'two')]);

self::assertSame(['a' => 'two'], $map->toNativeArray());
}
}
7 changes: 6 additions & 1 deletion tests/Stub/Event.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@

use Munus\Value\Comparable;

final class Event implements Comparable
final class Event implements Comparable, \Stringable
{
public function __construct(public string $id, public string $name)
{
Expand All @@ -16,4 +16,9 @@ public function equals(mixed $other): bool
{
return self::class === $other::class && $this->name === $other->name;
}

public function __toString(): string
{
return $this->id;
}
}

0 comments on commit cab559e

Please sign in to comment.