Passed
Pull Request — master (#34)
by Benjamin
12:13
created

Point::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 2
nc 1
nop 2
dl 0
loc 4
rs 10
c 0
b 0
f 0
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) {
0 ignored issues
show
Bug Best Practice introduced by
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 empty(..) or ! empty(...) instead.

Loading history...
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