GeoJSON::format()   A
last analyzed

Complexity

Conditions 3
Paths 3

Size

Total Lines 20

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 20
rs 9.6
c 0
b 0
f 0
cc 3
nc 3
nop 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Location\Formatter\Polygon;
6
7
use Location\Coordinate;
8
use Location\Exception\InvalidPolygonException;
9
use Location\Polygon;
10
11
/**
12
 * GeoJSON Polygon Formatter
13
 *
14
 * @author Richard Barnes <[email protected]>
15
 */
16
class GeoJSON implements FormatterInterface
17
{
18
    /**
19
     * @param Polygon $polygon
20
     *
21
     * @return string
22
     *
23
     * @throws InvalidPolygonException
24
     */
25
    public function format(Polygon $polygon): string
26
    {
27
        if ($polygon->getNumberOfPoints() < 3) {
28
            throw new InvalidPolygonException('A polygon must consist of at least three points.');
29
        }
30
31
        $points = [];
32
33
        /** @var Coordinate $point */
34
        foreach ($polygon->getPoints() as $point) {
35
            $points[] = [$point->getLng(), $point->getLat()];
36
        }
37
38
        return json_encode(
39
            [
40
                'type' => 'Polygon',
41
                'coordinates' => [$points],
42
            ]
43
        );
44
    }
45
}
46