|
1
|
|
|
<?php |
|
2
|
|
|
declare(strict_types=1); |
|
3
|
|
|
namespace Ivory\Value; |
|
4
|
|
|
|
|
5
|
|
|
use Ivory\Utils\IEqualable; |
|
6
|
|
|
|
|
7
|
|
|
/** |
|
8
|
|
|
* Representation of a point on a plane. |
|
9
|
|
|
* |
|
10
|
|
|
* The objects are immutable. |
|
11
|
|
|
*/ |
|
12
|
|
|
class Point implements IEqualable |
|
|
|
|
|
|
13
|
|
|
{ |
|
14
|
|
|
private $x; |
|
15
|
|
|
private $y; |
|
16
|
|
|
|
|
17
|
|
|
|
|
18
|
|
|
/** |
|
19
|
|
|
* Creates a new point from its X- and Y-coordinates, either specified as two arguments or as a two-item array. |
|
20
|
|
|
* |
|
21
|
|
|
* @param float|float[] $x |
|
22
|
|
|
* @param float|null $y |
|
23
|
|
|
* @return Point |
|
24
|
|
|
*/ |
|
25
|
|
|
public static function fromCoords($x, $y = null): Point |
|
26
|
|
|
{ |
|
27
|
|
|
if ($y === null && is_array($x) && count($x) == 2) { |
|
28
|
|
|
$y = $x[1]; |
|
29
|
|
|
$x = $x[0]; |
|
30
|
|
|
} |
|
31
|
|
|
|
|
32
|
|
|
if (!is_numeric($x)) { |
|
33
|
|
|
throw new \InvalidArgumentException('x'); |
|
34
|
|
|
} |
|
35
|
|
|
if (!is_numeric($y)) { |
|
36
|
|
|
throw new \InvalidArgumentException('y'); |
|
37
|
|
|
} |
|
38
|
|
|
|
|
39
|
|
|
return new Point((float)$x, (float)$y); |
|
40
|
|
|
} |
|
41
|
|
|
|
|
42
|
|
|
|
|
43
|
|
|
private function __construct(float $x, float $y) |
|
44
|
|
|
{ |
|
45
|
|
|
$this->x = $x; |
|
46
|
|
|
$this->y = $y; |
|
47
|
|
|
} |
|
48
|
|
|
|
|
49
|
|
|
/** |
|
50
|
|
|
* @return float the X-coordinate of the point |
|
51
|
|
|
*/ |
|
52
|
|
|
public function getX(): float |
|
53
|
|
|
{ |
|
54
|
|
|
return $this->x; |
|
55
|
|
|
} |
|
56
|
|
|
|
|
57
|
|
|
/** |
|
58
|
|
|
* @return float the Y-coordinate of the point |
|
59
|
|
|
*/ |
|
60
|
|
|
public function getY(): float |
|
61
|
|
|
{ |
|
62
|
|
|
return $this->y; |
|
63
|
|
|
} |
|
64
|
|
|
|
|
65
|
|
|
/** |
|
66
|
|
|
* @return float[] pair of the X- and Y-coordinate of the point |
|
67
|
|
|
*/ |
|
68
|
|
|
public function toCoords(): array |
|
69
|
|
|
{ |
|
70
|
|
|
return [$this->x, $this->y]; |
|
71
|
|
|
} |
|
72
|
|
|
|
|
73
|
|
|
public function __toString() |
|
74
|
|
|
{ |
|
75
|
|
|
return "({$this->x},{$this->y})"; |
|
76
|
|
|
} |
|
77
|
|
|
|
|
78
|
|
|
/** |
|
79
|
|
|
* @param object $object |
|
80
|
|
|
* @return bool|null <tt>true</tt> if <tt>$this</tt> and the other <tt>$object</tt> are equal to each other, |
|
81
|
|
|
* <tt>false</tt> if they are not equal, |
|
82
|
|
|
* <tt>null</tt> iff <tt>$object</tt> is <tt>null</tt> |
|
83
|
|
|
*/ |
|
84
|
|
|
public function equals($object): ?bool |
|
85
|
|
|
{ |
|
86
|
|
|
if ($object === null) { |
|
87
|
|
|
return null; |
|
88
|
|
|
} |
|
89
|
|
|
if (!$object instanceof Point) { |
|
90
|
|
|
return false; |
|
91
|
|
|
} |
|
92
|
|
|
return ( |
|
93
|
|
|
$this->getX() == $object->getX() |
|
94
|
|
|
&& |
|
95
|
|
|
$this->getY() == $object->getY() |
|
96
|
|
|
); |
|
97
|
|
|
} |
|
98
|
|
|
} |
|
99
|
|
|
|