1
|
|
|
<?php |
2
|
|
|
namespace Algorithms\GraphTools; |
3
|
|
|
|
4
|
|
|
class ConnectionsContainer |
5
|
|
|
{ |
6
|
|
|
private $connections = array(); |
7
|
|
|
|
8
|
|
|
public function __construct($connections = null) |
9
|
|
|
{ |
10
|
|
|
if (is_array($connections)) { |
11
|
|
|
foreach ($connections as $connection) { |
12
|
|
|
$this->add($connection); |
13
|
|
|
} |
14
|
|
|
} elseif(!is_null($connections)) { |
15
|
|
|
throw new ConnectionException('ConnectionsContainer contructor only accept connections array'); |
16
|
|
|
} |
17
|
|
|
} |
18
|
|
|
|
19
|
|
|
protected function getLastConnection() |
20
|
|
|
{ |
21
|
|
|
$lastPos = count($this->connections) - 1; |
22
|
|
|
if ($lastPos == -1) { |
23
|
|
|
return null; |
24
|
|
|
} else { |
25
|
|
|
return $this->connections[$lastPos]; |
26
|
|
|
} |
27
|
|
|
} |
28
|
|
|
|
29
|
|
|
protected function addToLastConnection(Point $point, $distance) |
30
|
|
|
{ |
31
|
|
|
$lastConnection = $this->getLastConnection(); |
32
|
|
|
if (is_null($lastConnection)) { |
33
|
|
|
throw new ConnectionException('Can\'t add to last connection because last connection do not exists'); |
34
|
|
|
} |
35
|
|
|
|
36
|
|
|
return $this->add($this->createNewConnection($lastConnection->from, $point, $distance)); |
37
|
|
|
} |
38
|
|
|
|
39
|
|
|
protected function createNewConnection(Point $from, Point $to, $distance) |
40
|
|
|
{ |
41
|
|
|
return new Connection($from, $to, $distance); |
42
|
|
|
} |
43
|
|
|
|
44
|
|
|
public function addConnection(Point $first, $second, $third = null) |
45
|
|
|
{ |
46
|
|
|
if (!Point::check($second) && is_null($third)) { |
47
|
|
|
return $this->addToLastConnection($first, $second); |
48
|
|
|
} else { |
49
|
|
|
return $this->add($this->createNewConnection($first, $second, $third)); |
50
|
|
|
} |
51
|
|
|
} |
52
|
|
|
|
53
|
|
|
public function add(Connection $connection) |
54
|
|
|
{ |
55
|
|
|
$this->connections[] = $connection; |
56
|
|
|
|
57
|
|
|
return $this; |
58
|
|
|
} |
59
|
|
|
|
60
|
|
|
public function each(\Closure $function) |
61
|
|
|
{ |
62
|
|
|
foreach ($this->connections as $connection) { |
63
|
|
|
call_user_func($function, $connection); |
64
|
|
|
} |
65
|
|
|
} |
66
|
|
|
|
67
|
|
|
public function get($from) |
68
|
|
|
{ |
69
|
|
|
$connections = array(); |
70
|
|
|
|
71
|
|
|
$this->each(function ($connection) use (&$connections, $from) { |
72
|
|
|
if ($connection->from |
73
|
|
|
->id == $from) { |
74
|
|
|
$connections[] = $connection; |
75
|
|
|
} |
76
|
|
|
}); |
77
|
|
|
|
78
|
|
|
return $connections; |
79
|
|
|
} |
80
|
|
|
|
81
|
|
|
public function all() |
82
|
|
|
{ |
83
|
|
|
return $this->connections; |
84
|
|
|
} |
85
|
|
|
} |
86
|
|
|
|