Completed
Push — master ( e6b195...a64aa1 )
by Ondřej
03:03
created

Polygon::getArea()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 12
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 12
rs 9.4285
c 0
b 0
f 0
cc 2
eloc 7
nc 2
nop 0
1
<?php
2
namespace Ivory\Value;
3
4
/**
5
 * Representation of a polygon on a plane.
6
 *
7
 * The objects are immutable.
8
 */
9
class Polygon
0 ignored issues
show
Coding Style introduced by
Since you have declared the constructor as private, maybe you should also declare the class as final.
Loading history...
10
{
11
    /** @var Point[] */
12
    private $points;
13
14
15
    /**
16
     * Creates a new polygon defined by the list of its vertices.
17
     *
18
     * @param Point[]|float[][] $points
19
     * @return Polygon
20
     */
21
    public static function fromPoints($points): Polygon
22
    {
23
        if (count($points) == 0) {
24
            throw new \InvalidArgumentException('points');
25
        }
26
27
        $normalized = [];
28 View Code Duplication
        foreach ($points as $i => $point) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
29
            if ($point instanceof Point) {
30
                $normalized[] = $point;
31
            } elseif (is_array($point)) {
32
                $normalized[] = Point::fromCoords($point[0], $point[1]);
33
            } else {
34
                throw new \InvalidArgumentException("points[$i]");
35
            }
36
        }
37
38
        return new Polygon($normalized);
39
    }
40
41
    private function __construct($points)
42
    {
43
        $this->points = $points;
44
    }
45
46
    /**
47
     * @return Point[] the list of vertices determining this polygon
48
     */
49
    public function getPoints()
50
    {
51
        return $this->points;
52
    }
53
54
    /**
55
     * Computes the area of the polygon.
56
     *
57
     * The algorithm taken from http://alienryderflex.com/polygon_area/
58
     *
59
     * @return float area of the polygon
60
     */
61
    public function getArea(): float
62
    {
63
        $area = 0;
64
65
        $from = $this->points[count($this->points) - 1];
66
        foreach ($this->points as $to) {
67
            $area += ($to->getX() + $from->getX()) * ($to->getY() - $from->getY());
68
            $from = $to;
69
        }
70
71
        return abs($area) / 2;
72
    }
73
74
    public function __toString()
75
    {
76
        return '(' . implode(',', $this->points) . ')';
77
    }
78
}
79