Hoa central
Group.php
Go to the documentation of this file.
1 <?php
2 
37 namespace Hoa\Socket\Connection;
38 
39 use Hoa\Socket;
40 
50 class Group implements \ArrayAccess, \IteratorAggregate, \Countable
51 {
57  protected $_connections = [];
58 
59 
60 
67  public function offsetExists($offset)
68  {
69  return true === array_key_exists($offset, $this->_connections);
70  }
71 
78  public function offsetGet($offset)
79  {
80  if (false === $this->offsetExists($offset)) {
81  return null;
82  }
83 
84  return $this->_connections[$offset];
85  }
86 
96  public function offsetSet($offset, $connection)
97  {
98  if (!($connection instanceof Handler)) {
99  throw new Socket\Exception(
100  '%s only accepts %s\Handler objects.',
101  0,
102  [__CLASS__, __NAMESPACE__]
103  );
104  }
105 
106  if (null === $offset) {
107  $this->_connections[] = $connection;
108  } else {
109  $this->_connections[$offset] = $connection;
110  }
111 
112  if (1 < count($this)) {
113  $this->getFirstConnection()->merge($connection);
114  }
115 
116  return;
117  }
118 
125  public function offsetUnset($offset)
126  {
127  throw new Socket\Exception(
128  'This operation is not allowed: you cannot unset a connection ' .
129  'from a group.',
130  1
131  );
132 
133  return;
134  }
135 
141  public function getIterator()
142  {
143  return new \ArrayIterator($this->_connections);
144  }
145 
151  public function count()
152  {
153  return count($this->_connections);
154  }
155 
163  public function merge(Handler $connection)
164  {
165  $this[] = $connection;
166 
167  return $this;
168  }
169 
176  public function run()
177  {
178  if (0 === count($this)) {
179  throw new Socket\Exception(
180  'Nothing to run. You should merge a connection.',
181  2
182  );
183  }
184 
185  return $this->getFirstConnection()->run();
186  }
187 
194  public function getFirstConnection()
195  {
196  return $this[key($this->_connections)];
197  }
198 }
merge(Handler $connection)
Definition: Group.php:163
offsetSet($offset, $connection)
Definition: Group.php:96