Skip to content

Commit ea00721

Browse files
committed
Map factory common methods created
1 parent 9e5d316 commit ea00721

File tree

2 files changed

+98
-0
lines changed

2 files changed

+98
-0
lines changed
Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
<?php
2+
/**
3+
* @author Maxim Sokolovsky
4+
*/
5+
6+
namespace WS\Utils\Collections;
7+
8+
/**
9+
* Class MapFactory
10+
* @package WS\Utils\Collections
11+
*/
12+
class MapFactory
13+
{
14+
/**
15+
* Creates Map from assoc array
16+
* @param array $assocArray
17+
* @return Map
18+
*/
19+
public static function assoc(array $assocArray): Map
20+
{
21+
return self::fromIterable($assocArray);
22+
}
23+
24+
public static function fromIterable(iterable $iterable): Map
25+
{
26+
$map = self::newObject();
27+
foreach ($iterable as $key => $value) {
28+
$map->put($key, $value);
29+
}
30+
31+
return $map;
32+
}
33+
34+
/**
35+
* Creates empty map object
36+
* @return Map
37+
*/
38+
public static function emptyObject(): Map
39+
{
40+
return self::newObject();
41+
}
42+
43+
/**
44+
* Creates empty Map object
45+
* @return Map
46+
*/
47+
private static function newObject(): Map
48+
{
49+
return new HashMap();
50+
}
51+
}
Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
<?php
2+
/**
3+
* @author Maxim Sokolovsky
4+
*/
5+
6+
namespace WS\Utils\Collections;
7+
8+
use ArrayIterator;
9+
use PHPUnit\Framework\TestCase;
10+
11+
class MapFactoryTest extends TestCase
12+
{
13+
14+
/**
15+
* @test
16+
*/
17+
public function emptyMapIsCreated(): void
18+
{
19+
$map = MapFactory::emptyObject();
20+
self::assertInstanceOf(Map::class, $map);
21+
self::assertEquals(0, $map->size());
22+
}
23+
24+
/**
25+
* @test
26+
*/
27+
public function mapFromIterableIsCreated(): void
28+
{
29+
$arrayIterator = new ArrayIterator(['a' => 'A', 'b' => 'B']);
30+
$map = MapFactory::fromIterable($arrayIterator);
31+
self::assertEquals(2, $map->size());
32+
self::assertEquals(['a', 'b'], $map->keys()->toArray());
33+
self::assertEquals(['A', 'B'], $map->values()->toArray());
34+
}
35+
36+
/**
37+
* @test
38+
*/
39+
public function mapFromAssocArrayCreated(): void
40+
{
41+
$assoc = ['a' => 'A', 'b' => 'B'];
42+
$map = MapFactory::assoc($assoc);
43+
self::assertEquals(2, $map->size());
44+
self::assertEquals(['a', 'b'], $map->keys()->toArray());
45+
self::assertEquals(['A', 'B'], $map->values()->toArray());
46+
}
47+
}

0 commit comments

Comments
 (0)