1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Kmeans; |
4
|
|
|
|
5
|
|
|
use Kmeans\Concerns\HasSpaceTrait; |
6
|
|
|
use Kmeans\Interfaces\ClusterCollectionInterface; |
7
|
|
|
use Kmeans\Interfaces\ClusterInterface; |
8
|
|
|
use Kmeans\Interfaces\SpaceInterface; |
9
|
|
|
|
10
|
|
|
class ClusterCollection implements ClusterCollectionInterface |
11
|
|
|
{ |
12
|
|
|
use HasSpaceTrait; |
13
|
|
|
|
14
|
|
|
/** |
15
|
|
|
* @var \SplObjectStorage<ClusterInterface, null> |
16
|
|
|
*/ |
17
|
|
|
protected \SplObjectStorage $clusters; |
18
|
|
|
|
19
|
|
|
/** |
20
|
|
|
* @param array<ClusterInterface> $clusters |
21
|
|
|
*/ |
22
|
|
|
public function __construct(SpaceInterface $space, array $clusters = []) |
23
|
|
|
{ |
24
|
|
|
$this->setSpace($space); |
25
|
|
|
$this->clusters = new \SplObjectStorage(); |
26
|
|
|
|
27
|
|
|
foreach ($clusters as $cluster) { |
28
|
|
|
$this->attach($cluster); |
29
|
|
|
} |
30
|
|
|
} |
31
|
|
|
|
32
|
|
|
// ------------------------------------------------------------------------ |
33
|
|
|
// ClusterCollectionInterface |
34
|
|
|
|
35
|
|
|
public function contains(ClusterInterface $cluster): bool |
36
|
|
|
{ |
37
|
|
|
return $this->clusters->contains($cluster); |
38
|
|
|
} |
39
|
|
|
|
40
|
|
|
public function attach(ClusterInterface $cluster): void |
41
|
|
|
{ |
42
|
|
|
if (! $this->getSpace()->isEqualTo($cluster->getSpace())) { |
43
|
|
|
throw new \InvalidArgumentException( |
44
|
|
|
"Cannot add cluster to collection: cluster space is not same as collection space" |
45
|
|
|
); |
46
|
|
|
} |
47
|
|
|
|
48
|
|
|
$this->clusters->attach($cluster); |
49
|
|
|
} |
50
|
|
|
|
51
|
|
|
public function detach(ClusterInterface $cluster): void |
52
|
|
|
{ |
53
|
|
|
$this->clusters->detach($cluster); |
54
|
|
|
} |
55
|
|
|
|
56
|
|
|
// ------------------------------------------------------------------------ |
57
|
|
|
// Iterator |
58
|
|
|
|
59
|
|
|
public function current() |
60
|
|
|
{ |
61
|
|
|
return $this->clusters->current(); |
62
|
|
|
} |
63
|
|
|
|
64
|
|
|
public function key() |
65
|
|
|
{ |
66
|
|
|
return $this->clusters->key(); |
67
|
|
|
} |
68
|
|
|
|
69
|
|
|
public function next(): void |
70
|
|
|
{ |
71
|
|
|
$this->clusters->next(); |
72
|
|
|
} |
73
|
|
|
|
74
|
|
|
public function rewind(): void |
75
|
|
|
{ |
76
|
|
|
$this->clusters->rewind(); |
77
|
|
|
} |
78
|
|
|
|
79
|
|
|
public function valid(): bool |
80
|
|
|
{ |
81
|
|
|
return $this->clusters->valid(); |
82
|
|
|
} |
83
|
|
|
|
84
|
|
|
// ------------------------------------------------------------------------ |
85
|
|
|
// Countable |
86
|
|
|
|
87
|
|
|
public function count(): int |
88
|
|
|
{ |
89
|
|
|
return count($this->clusters); |
90
|
|
|
} |
91
|
|
|
} |
92
|
|
|
|