carno-php /
log
| 1 | <?php |
||
| 2 | /** |
||
| 3 | * Log connections manager |
||
| 4 | * User: moyo |
||
| 5 | * Date: 22/11/2017 |
||
| 6 | * Time: 10:38 AM |
||
| 7 | */ |
||
| 8 | |||
| 9 | namespace Carno\Log; |
||
| 10 | |||
| 11 | use Carno\Log\Contracts\Closeable; |
||
| 12 | use Carno\Log\Contracts\Outputter; |
||
| 13 | use Carno\Net\Address; |
||
| 14 | use Carno\Promise\Promise; |
||
| 15 | use Carno\Promise\Promised; |
||
| 16 | use Closure; |
||
| 17 | |||
| 18 | class Connections |
||
| 19 | { |
||
| 20 | /** |
||
| 21 | * @var Closeable[] |
||
| 22 | */ |
||
| 23 | private $connected = []; |
||
| 24 | |||
| 25 | /** |
||
| 26 | * @param Address $address |
||
| 27 | * @param Closure $connector |
||
| 28 | * @return Outputter |
||
| 29 | */ |
||
| 30 | public function hosting(Address $address, Closure $connector) : Outputter |
||
| 31 | { |
||
| 32 | return |
||
|
0 ignored issues
–
show
Bug
Best Practice
introduced
by
Loading history...
|
|||
| 33 | $this->connected[$cid = (string)$address] ?? |
||
| 34 | $this->connected[$cid] = $this->watch($cid, $connector($address)) |
||
| 35 | ; |
||
| 36 | } |
||
| 37 | |||
| 38 | /** |
||
| 39 | * @param string $cid |
||
| 40 | * @param Closeable $conn |
||
| 41 | * @return Closeable|Outputter |
||
| 42 | */ |
||
| 43 | private function watch(string $cid, Closeable $conn) : Closeable |
||
| 44 | { |
||
| 45 | $conn->closed()->then(function () use ($cid) { |
||
| 46 | unset($this->connected[$cid]); |
||
| 47 | }); |
||
| 48 | |||
| 49 | return $conn; |
||
| 50 | } |
||
| 51 | |||
| 52 | /** |
||
| 53 | * @param Address $address |
||
| 54 | * @return Promised |
||
| 55 | */ |
||
| 56 | public function close(Address $address) : Promised |
||
| 57 | { |
||
| 58 | return ($c = $this->connected[(string)$address] ?? null) ? $c->close() : Promise::resolved(); |
||
| 59 | } |
||
| 60 | |||
| 61 | /** |
||
| 62 | * @return Promised |
||
| 63 | */ |
||
| 64 | public function release() : Promised |
||
| 65 | { |
||
| 66 | $pending = []; |
||
| 67 | |||
| 68 | foreach ($this->connected as $closeable) { |
||
| 69 | $pending[] = $closeable->close(); |
||
| 70 | } |
||
| 71 | |||
| 72 | return Promise::all(...$pending); |
||
| 73 | } |
||
| 74 | } |
||
| 75 |