bdelespierre /
php-kmeans
| 1 | <?php |
||
| 2 | |||
| 3 | namespace Kmeans\Euclidean; |
||
| 4 | |||
| 5 | use Kmeans\Concerns\HasDataTrait; |
||
| 6 | use Kmeans\Concerns\HasSpaceTrait; |
||
| 7 | use Kmeans\Interfaces\PointInterface; |
||
| 8 | use Kmeans\Interfaces\SpaceInterface; |
||
| 9 | |||
| 10 | class Point implements PointInterface |
||
| 11 | { |
||
| 12 | use HasSpaceTrait; |
||
| 13 | use HasDataTrait; |
||
| 14 | |||
| 15 | /** |
||
| 16 | * @var array<float> |
||
| 17 | */ |
||
| 18 | private array $coordinates; |
||
| 19 | |||
| 20 | /** |
||
| 21 | * @param array<int, float> $coordinates |
||
| 22 | */ |
||
| 23 | public function __construct(SpaceInterface $space, array $coordinates) |
||
| 24 | { |
||
| 25 | if (! $space instanceof Space) { |
||
| 26 | throw new \LogicException( |
||
| 27 | "An euclidean point must belong to an euclidean space" |
||
| 28 | ); |
||
| 29 | } |
||
| 30 | |||
| 31 | $this->setSpace($space); |
||
| 32 | $this->coordinates = $this->sanitizeCoordinates($coordinates); |
||
| 33 | } |
||
| 34 | |||
| 35 | public function getCoordinates(): array |
||
| 36 | { |
||
| 37 | return $this->coordinates; |
||
| 38 | } |
||
| 39 | |||
| 40 | /** |
||
| 41 | * @param array<float> $coordinates |
||
| 42 | * @return array<float> |
||
| 43 | */ |
||
| 44 | private function sanitizeCoordinates(array $coordinates): array |
||
| 45 | { |
||
| 46 | assert($this->space instanceof Space); |
||
| 47 | if (count($coordinates) != $this->space->getDimensions()) { |
||
|
0 ignored issues
–
show
Bug
introduced
by
Loading history...
|
|||
| 48 | throw new \InvalidArgumentException(sprintf( |
||
| 49 | "Invalid set of coordinates: %d coordinates expected, %d given", |
||
| 50 | $this->space->getDimensions(), |
||
| 51 | count($coordinates) |
||
| 52 | )); |
||
| 53 | } |
||
| 54 | |||
| 55 | $coordinates = filter_var_array($coordinates, FILTER_VALIDATE_FLOAT); |
||
| 56 | assert(is_array($coordinates)); |
||
| 57 | $errors = array_keys($coordinates, false, true); |
||
| 58 | |||
| 59 | if ($errors) { |
||
|
0 ignored issues
–
show
The expression
$errors of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.
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 Loading history...
|
|||
| 60 | throw new \InvalidArgumentException(sprintf( |
||
| 61 | "Invalid set of coordinates: values at offsets [%s] could not be converted to numbers", |
||
| 62 | implode(',', $errors) |
||
| 63 | )); |
||
| 64 | } |
||
| 65 | |||
| 66 | return $coordinates; |
||
| 67 | } |
||
| 68 | } |
||
| 69 |