Skip to content

Commit 68100c7

Browse files
committed
GeometryCollection implements JsonSerializable interface
1 parent a7a7b8a commit 68100c7

File tree

2 files changed

+53
-11
lines changed

2 files changed

+53
-11
lines changed

src/Geometries/GeometryCollection.php

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
<?php namespace Phaza\LaravelPostgis\Geometries;
22

33
use Countable;
4+
use GeoJson\GeoJson;
45
use InvalidArgumentException;
56

67
class GeometryCollection extends Geometry implements Countable
@@ -71,4 +72,19 @@ public function count()
7172
{
7273
return count($this->geometries);
7374
}
75+
76+
/**
77+
* Convert to GeoJson GeometryCollection that is jsonable to GeoJSON
78+
*
79+
* @return \GeoJson\Geometry\GeometryCollection
80+
*/
81+
public function jsonSerialize()
82+
{
83+
$geometries = [];
84+
foreach ($this->geometries as $geometry) {
85+
$geometries[] = $geometry->jsonSerialize();
86+
}
87+
88+
return new \GeoJson\Geometry\GeometryCollection($geometries);
89+
}
7490
}

tests/Geometries/GeometryCollectionTest.php

Lines changed: 37 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,29 @@
66

77
class GeometryCollectionTest extends BaseTestCase
88
{
9+
/**
10+
* @var GeometryCollection
11+
*/
12+
private $collection;
13+
14+
protected function setUp()
15+
{
16+
$collection = new LineString(
17+
[
18+
new Point(0, 0),
19+
new Point(0, 1),
20+
new Point(1, 1),
21+
new Point(1, 0),
22+
new Point(0, 0)
23+
]
24+
);
25+
26+
$point = new Point(100, 200);
27+
28+
$this->collection = new GeometryCollection([$collection, $point]);
29+
}
30+
31+
932
public function testFromWKT()
1033
{
1134
/**
@@ -21,20 +44,23 @@ public function testFromWKT()
2144

2245
public function testToWKT()
2346
{
24-
$collection = new LineString(
25-
[
26-
new Point(0, 0),
27-
new Point(0, 1),
28-
new Point(1, 1),
29-
new Point(1, 0),
30-
new Point(0, 0)
31-
]
47+
$this->assertEquals(
48+
'GEOMETRYCOLLECTION(LINESTRING(0 0,1 0,1 1,0 1,0 0),POINT(200 100))',
49+
$this->collection->toWKT()
3250
);
51+
}
3352

34-
$point = new Point(100, 200);
53+
public function testJsonSerialize()
54+
{
55+
$this->assertInstanceOf(
56+
\GeoJson\Geometry\GeometryCollection::class,
57+
$this->collection->jsonSerialize()
58+
);
3559

36-
$polygon = new GeometryCollection([$collection, $point]);
60+
$this->assertSame(
61+
'{"type":"GeometryCollection","geometries":[{"type":"LineString","coordinates":[[0,0],[0,1],[1,1],[1,0],[0,0]]},{"type":"Point","coordinates":[100,200]}]}',
62+
json_encode($this->collection->jsonSerialize())
63+
);
3764

38-
$this->assertEquals('GEOMETRYCOLLECTION(LINESTRING(0 0,1 0,1 1,0 1,0 0),POINT(200 100))', $polygon->toWKT());
3965
}
4066
}

0 commit comments

Comments
 (0)