<?php
namespace Yurun\Util\YurunHttp\Handler\Swoole;
use Yurun\Util\YurunHttp\Handler\Contract\IConnectionManager;
abstract class BaseConnectionManager implements IConnectionManager
{
private $connections = [];
private $sslConnections = [];
public function getConnection($host, $port, $ssl)
{
$key = $this->getKey($host, $port);
if($ssl)
{
if(!isset($this->sslConnections[$key]))
{
$this->sslConnections[$key] = $this->createConnection($host, $port, $ssl);
}
return $this->sslConnections[$key];
}
else
{
if(!isset($this->connections[$key]))
{
$this->connections[$key] = $this->createConnection($host, $port, $ssl);
}
return $this->connections[$key];
}
}
public function removeConnection($host, $port, $ssl)
{
$key = $this->getKey($host, $port);
if($ssl)
{
if(isset($this->sslConnections[$key]))
{
$connection = $this->sslConnections[$key];
unset($this->sslConnections[$key]);
return $connection;
}
else
{
return false;
}
}
else if(isset($this->connections[$key]))
{
$connection = $this->connections[$key];
unset($this->connections[$key]);
return $connection;
}
else
{
return false;
}
}
private function getKey($host, $port)
{
return $host . ':' . $port;
}
public function closeConnection($host, $port, $ssl)
{
$key = $this->getKey($host, $port);
if($ssl)
{
if(isset($this->sslConnections[$key]))
{
$this->sslConnections[$key]->close();
unset($this->sslConnections[$key]);
return true;
}
else
{
return false;
}
}
else if(isset($this->connections[$key]))
{
$this->connections[$key]->close();
unset($this->connections[$key]);
return true;
}
else
{
return false;
}
}
public function close()
{
foreach($this->connections as $client)
{
$client->close();
}
foreach($this->sslConnections as $client)
{
$client->close();
}
}
}