Completed
Push — milestone/4.0 ( 4a7219...1803cd )
by Marcus
01:48
created

GeoJSON   A

Complexity

Total Complexity 3

Size/Duplication

Total Lines 31
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 3

Importance

Changes 0
Metric Value
wmc 3
lcom 0
cbo 3
dl 0
loc 31
rs 10
c 0
b 0
f 0

1 Method

Rating   Name   Duplication   Size   Complexity  
A format() 0 21 3
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Phpgeo\Formatter\Polygon;
6
7
use Phpgeo\Point;
8
use Phpgeo\Exception\InvalidPolygonException;
9
use Phpgeo\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 Point $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
            JSON_THROW_ON_ERROR
44
        );
45
    }
46
}
47