1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Kmeans; |
4
|
|
|
|
5
|
|
|
use Kmeans\Concerns\HasSpaceTrait; |
6
|
|
|
use Kmeans\Interfaces\PointInterface; |
7
|
|
|
use Kmeans\Interfaces\SpaceInterface; |
8
|
|
|
|
9
|
|
|
class Point implements PointInterface |
10
|
|
|
{ |
11
|
|
|
use HasSpaceTrait; |
12
|
|
|
|
13
|
|
|
/** |
14
|
|
|
* @var array<float> |
15
|
|
|
*/ |
16
|
|
|
private array $coordinates; |
17
|
|
|
|
18
|
|
|
/** |
19
|
|
|
* @var mixed |
20
|
|
|
*/ |
21
|
|
|
private $data; |
22
|
|
|
|
23
|
|
|
/** |
24
|
|
|
* @param array<int, float> $coordinates |
25
|
|
|
*/ |
26
|
|
|
public function __construct(SpaceInterface $space, array $coordinates) |
27
|
|
|
{ |
28
|
|
|
$this->setSpace($space); |
29
|
|
|
$this->coordinates = $this->sanitizeCoordinates($coordinates); |
30
|
|
|
} |
31
|
|
|
|
32
|
|
|
public function getCoordinates(): array |
33
|
|
|
{ |
34
|
|
|
return $this->coordinates; |
35
|
|
|
} |
36
|
|
|
|
37
|
|
|
public function getData() |
38
|
|
|
{ |
39
|
|
|
return $this->data; |
40
|
|
|
} |
41
|
|
|
|
42
|
|
|
public function setData($data): void |
43
|
|
|
{ |
44
|
|
|
$this->data = $data; |
45
|
|
|
} |
46
|
|
|
|
47
|
|
|
/** |
48
|
|
|
* @param array<float> $coordinates |
49
|
|
|
* @return array<float> |
50
|
|
|
*/ |
51
|
|
|
private function sanitizeCoordinates(array $coordinates): array |
52
|
|
|
{ |
53
|
|
|
if (count($coordinates) != $this->space->getDimensions()) { |
54
|
|
|
throw new \InvalidArgumentException(sprintf( |
55
|
|
|
"Invalid set of coordinates: %d coordinates expected, %d given", |
56
|
|
|
$this->space->getDimensions(), |
57
|
|
|
count($coordinates) |
58
|
|
|
)); |
59
|
|
|
} |
60
|
|
|
|
61
|
|
|
$coordinates = filter_var_array($coordinates, FILTER_VALIDATE_FLOAT); |
62
|
|
|
assert(is_array($coordinates)); |
63
|
|
|
$errors = array_keys($coordinates, false, true); |
64
|
|
|
|
65
|
|
|
if ($errors) { |
|
|
|
|
66
|
|
|
throw new \InvalidArgumentException(sprintf( |
67
|
|
|
"Invalid set of coordinates: values at offsets [%s] could not be converted to numbers", |
68
|
|
|
implode(',', $errors) |
69
|
|
|
)); |
70
|
|
|
} |
71
|
|
|
|
72
|
|
|
return $coordinates; |
73
|
|
|
} |
74
|
|
|
} |
75
|
|
|
|
This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.
Consider making the comparison explicit by using
empty(..)
or! empty(...)
instead.