This commit is contained in:
as2252258@163.com
2021-03-23 02:38:20 +08:00
parent b9e2704313
commit e8b0f8da81
3 changed files with 838 additions and 814 deletions
+492 -471
View File
@@ -18,6 +18,8 @@ use HttpServer\Service\Packet;
use HttpServer\Service\Websocket; use HttpServer\Service\Websocket;
use Exception; use Exception;
use ReflectionException; use ReflectionException;
use Rpc\Producer;
use Rpc\Service;
use Snowflake\Abstracts\Config; use Snowflake\Abstracts\Config;
use Snowflake\Core\Json; use Snowflake\Core\Json;
use Snowflake\Error\LoggerProcess; use Snowflake\Error\LoggerProcess;
@@ -49,477 +51,496 @@ defined('PID_PATH') or define('PID_PATH', APP_PATH . 'storage/server.pid');
*/ */
class Server extends HttpService class Server extends HttpService
{ {
use Action; use Action;
const HTTP = 'HTTP'; const HTTP = 'HTTP';
const TCP = 'TCP'; const TCP = 'TCP';
const PACKAGE = 'PACKAGE'; const PACKAGE = 'PACKAGE';
const WEBSOCKET = 'WEBSOCKET'; const WEBSOCKET = 'WEBSOCKET';
private array $listening = []; private array $listening = [];
private array $server = [ private array $server = [
'HTTP' => [SWOOLE_TCP, Http::class], 'HTTP' => [SWOOLE_TCP, Http::class],
'TCP' => [SWOOLE_TCP, Receive::class], 'TCP' => [SWOOLE_TCP, Receive::class],
'PACKAGE' => [SWOOLE_UDP, Packet::class], 'PACKAGE' => [SWOOLE_UDP, Packet::class],
'WEBSOCKET' => [SWOOLE_SOCK_TCP, Websocket::class], 'WEBSOCKET' => [SWOOLE_SOCK_TCP, Websocket::class],
]; ];
private Packet|Websocket|Receive|null|Http $baseServer = null; private Packet|Websocket|Receive|null|Http $baseServer = null;
public int $daemon = 0; public int $daemon = 0;
private array $listenTypes = []; private array $listenTypes = [];
private array $process = [ private array $process = [
'biomonitoring' => Biomonitoring::class, 'biomonitoring' => Biomonitoring::class,
'logger_process' => LoggerProcess::class 'logger_process' => LoggerProcess::class
]; ];
private array $params = []; private array $params = [];
/** /**
* @param $name * @param $name
* @param $process * @param $process
* @param array $params * @param array $params
*/ */
public function addProcess($name, $process, $params = []) public function addProcess($name, $process, $params = [])
{ {
$this->process[$name] = $process; $this->process[$name] = $process;
$this->params[$name] = $params; $this->params[$name] = $params;
} }
/** /**
* @return array * @return array
*/ */
public function getProcesses(): array public function getProcesses(): array
{ {
return $this->process ?? []; return $this->process ?? [];
} }
/** /**
* @param array $configs * @param array $configs
* @return Packet|Websocket|Receive|Http|null * @return Packet|Websocket|Receive|Http|null
* @throws Exception * @throws Exception
*/ */
public function initCore(array $configs): Packet|Websocket|Receive|Http|null public function initCore(array $configs): Packet|Websocket|Receive|Http|null
{ {
$this->orders($configs); $this->orders($configs);
return $this->getServer(); return $this->getServer();
} }
/** /**
* @param $configs * @param $configs
* @return Packet|Websocket|Receive|Http|null * @return Packet|Websocket|Receive|Http|null
* @throws Exception * @throws Exception
*/ */
private function orders($configs): Packet|Websocket|Receive|Http|null private function orders($configs): Packet|Websocket|Receive|Http|null
{ {
$servers = $this->sortServers($configs); $servers = $this->sortServers($configs);
foreach ($servers as $server) { foreach ($servers as $server) {
$this->create($server); $this->create($server);
if (!$this->baseServer) { if (!$this->baseServer) {
return null; return null;
} }
} }
return $this->baseServer; return $this->baseServer;
} }
/** /**
* @return string start server * @return string start server
* *
* start server * start server
* @throws ConfigException * @throws ConfigException
* @throws Exception * @throws Exception
*/ */
public function start(): string public function start(): string
{ {
$configs = Config::get('servers', true); $configs = Config::get('servers', true);
$baseServer = $this->initCore($configs); $baseServer = $this->initCore($configs);
if (!$baseServer) { if (!$baseServer) {
return 'ok'; return 'ok';
} }
Runtime::enableCoroutine(true, SWOOLE_HOOK_ALL ^ SWOOLE_HOOK_BLOCKING_FUNCTION); Runtime::enableCoroutine(true, SWOOLE_HOOK_ALL ^ SWOOLE_HOOK_BLOCKING_FUNCTION);
Coroutine::set(['enable_deadlock_check' => false]); Coroutine::set(['enable_deadlock_check' => false]);
return $baseServer->start(); return $baseServer->start();
} }
/** /**
* @param $host * @param $host
* @param $Port * @param $Port
* @return Packet|Websocket|Receive|Http|null * @return Packet|Websocket|Receive|Http|null
* @throws Exception * @throws Exception
*/ */
public function error_stop($host, $Port): Packet|Websocket|Receive|Http|null public function error_stop($host, $Port): Packet|Websocket|Receive|Http|null
{ {
$this->error(sprintf('Port %s::%d is already.', $host, $Port)); $this->error(sprintf('Port %s::%d is already.', $host, $Port));
if ($this->baseServer) { if ($this->baseServer) {
$this->baseServer->shutdown(); $this->baseServer->shutdown();
} else { } else {
$this->shutdown(); $this->shutdown();
} }
return $this->baseServer; return $this->baseServer;
} }
/** /**
* @return bool * @return bool
* @throws ConfigException * @throws ConfigException
* @throws Exception * @throws Exception
*/ */
public function isRunner(): bool public function isRunner(): bool
{ {
$port = $this->sortServers(Config::get('servers')); $port = $this->sortServers(Config::get('servers'));
if (empty($port)) { if (empty($port)) {
return false; return false;
} }
foreach ($port as $value) { foreach ($port as $value) {
if (Snowflake::getPlatform()->isLinux()) { if (Snowflake::getPlatform()->isLinux()) {
exec('netstat -tunlp | grep ' . $value['port'], $output); exec('netstat -tunlp | grep ' . $value['port'], $output);
} else { } else {
exec('lsof -i :' . $value['port'] . ' | grep -i "LISTEN"', $output); exec('lsof -i :' . $value['port'] . ' | grep -i "LISTEN"', $output);
} }
if (!empty($output)) { if (!empty($output)) {
unset($output); unset($output);
return true; return true;
} }
} }
return false; return false;
} }
/** /**
* @return void * @return void
* *
* start server * start server
* @throws Exception * @throws Exception
*/ */
public function shutdown() public function shutdown()
{ {
$this->stop($this); $this->stop($this);
} }
/** /**
* @throws ConfigException * @throws ConfigException
* @throws Exception * @throws Exception
*/ */
public function onProcessListener(): void public function onProcessListener(): void
{ {
if (!($this->baseServer instanceof \Swoole\Server)) { if (!($this->baseServer instanceof \Swoole\Server)) {
return; return;
} }
$processes = Config::get('processes'); $processes = Config::get('processes');
if (!empty($processes) && is_array($processes)) { if (!empty($processes) && is_array($processes)) {
$this->deliveryProcess(merge($processes, $this->process)); $this->deliveryProcess(merge($processes, $this->process));
} else { } else {
$this->deliveryProcess($this->process); $this->deliveryProcess($this->process);
} }
} }
/** /**
* @param $processes * @param $processes
* @throws Exception * @throws Exception
*/ */
private function deliveryProcess($processes) private function deliveryProcess($processes)
{ {
$application = Snowflake::app(); $application = Snowflake::app();
if (empty($processes) || !is_array($processes)) { if (empty($processes) || !is_array($processes)) {
return; return;
} }
foreach ($processes as $name => $process) { foreach ($processes as $name => $process) {
$this->debug(sprintf('Process %s', $process)); $this->debug(sprintf('Process %s', $process));
if (!is_string($process)) { if (!is_string($process)) {
continue; continue;
} }
$system = new $process(Snowflake::app(), $name, true); $system = new $process(Snowflake::app(), $name, true);
if (isset($this->params[$name])) { if (isset($this->params[$name])) {
$system->write(Json::encode($this->params[$name])); $system->write(Json::encode($this->params[$name]));
} }
$this->baseServer->addProcess($system); $this->baseServer->addProcess($system);
$application->set($process, $system); $application->set($process, $system);
} }
} }
/** /**
* @param $daemon * @param $daemon
* @return Server * @return Server
*/ */
public function setDaemon($daemon): static public function setDaemon($daemon): static
{ {
if (!in_array($daemon, [0, 1])) { if (!in_array($daemon, [0, 1])) {
return $this; return $this;
} }
$this->daemon = $daemon; $this->daemon = $daemon;
return $this; return $this;
} }
/** /**
* @return Packet|Websocket|Receive|Http|null * @return Packet|Websocket|Receive|Http|null
*/ */
public function getServer(): Packet|Websocket|Receive|Http|null public function getServer(): Packet|Websocket|Receive|Http|null
{ {
return $this->baseServer; return $this->baseServer;
} }
/** /**
* @param $config * @param $config
* @return mixed * @return mixed
* @throws Exception * @throws Exception
*/ */
private function create($config): mixed private function create($config): mixed
{ {
$settings = Config::get('settings', false, []); $settings = Config::get('settings', false, []);
if (!isset($this->server[$config['type']])) { if (!isset($this->server[$config['type']])) {
throw new Exception('Unknown server type(' . $config['type'] . ').'); throw new Exception('Unknown server type(' . $config['type'] . ').');
} }
$server = $this->dispatchCreate($config, $settings); $server = $this->dispatchCreate($config, $settings);
if (isset($config['events'])) { if (isset($config['events'])) {
$this->createEventListen($config); $this->createEventListen($config);
} }
return $server; return $server;
} }
/** /**
* @param $config * @param $config
* @throws Exception * @throws Exception
*/ */
protected function createEventListen($config) protected function createEventListen($config)
{ {
if (!is_array($config['events'])) { if (!is_array($config['events'])) {
return; return;
} }
$event = Snowflake::app()->getEvent(); $event = Snowflake::app()->getEvent();
foreach ($config['events'] as $name => $_event) { foreach ($config['events'] as $name => $_event) {
$event->on('listen ' . $config['port'] . ' ' . $name, $_event); $event->on('listen ' . $config['port'] . ' ' . $name, $_event);
} }
} }
/** /**
* @param $config * @param $config
* @param $settings * @param $settings
* @return \Swoole\Server|Packet|Receive|Http|Websocket|null * @return \Swoole\Server|Packet|Receive|Http|Websocket|null
* @throws NotFindClassException * @throws NotFindClassException
* @throws ReflectionException * @throws ReflectionException
* @throws Exception * @throws Exception
*/ */
private function dispatchCreate($config, $settings): \Swoole\Server|Packet|Receive|Http|Websocket|null private function dispatchCreate($config, $settings): \Swoole\Server|Packet|Receive|Http|Websocket|null
{ {
if ($this->isUse($config['port'])) { if ($this->isUse($config['port'])) {
return $this->error_stop($config['host'], $config['port']); return $this->error_stop($config['host'], $config['port']);
} }
if (!($this->baseServer instanceof \Swoole\Server)) { if (!($this->baseServer instanceof \Swoole\Server)) {
return $this->parseServer($config, $settings); return $this->parseServer($config, $settings);
} }
return $this->addListener($config); return $this->addListener($config);
} }
/** /**
* @param $config * @param $config
* @return Http|Packet|Receive|Websocket|null * @return Http|Packet|Receive|Websocket|null
* @throws NotFindClassException * @throws NotFindClassException
* @throws ReflectionException * @throws ReflectionException
* @throws Exception * @throws Exception
*/ */
private function addListener($config): Packet|Websocket|Receive|Http|null private function addListener($config): Packet|Websocket|Receive|Http|null
{ {
$newListener = $this->baseServer->addlistener($config['host'], $config['port'], $config['mode']); $newListener = $this->baseServer->addlistener($config['host'], $config['port'], $config['mode']);
if (!$newListener) { if (!$newListener) {
exit($this->addError(sprintf('Listen %s::%d fail.', $config['host'], $config['port']))); exit($this->addError(sprintf('Listen %s::%d fail.', $config['host'], $config['port'])));
} }
if (isset($config['settings']) && is_array($config['settings'])) { if (isset($config['settings']) && is_array($config['settings'])) {
$newListener->set($config['settings']); $newListener->set($config['settings']);
} }
$this->onListenerBind($config, $this->baseServer); $this->onListenerBind($config, $this->baseServer);
return $this->baseServer; return $this->startRpcService();
} }
/** /**
* @param $config * @return Http|Packet|Receive|Websocket|null
* @param $settings * @throws ComponentException
* @return Packet|Websocket|Receive|Http|null * @throws ConfigException
* @throws Exception * @throws NotFindClassException
*/ * @throws ReflectionException
private function parseServer($config, $settings): Packet|Websocket|Receive|Http|null */
{ private function startRpcService()
$class = $this->dispatch($config['type']); {
if (isset($config['settings']) && !empty($config['settings'])) { $rpcService = Config::get('rpc.service', false, []);
$settings = array_merge($settings, $config['settings']); if (is_array($rpcService) && !empty($rpcService)) {
} /** @var Service $service */
$this->baseServer = new $class($config['host'], $config['port'], SWOOLE_PROCESS, $config['mode']); $service = Snowflake::app()->get('rpc-service');
$settings['daemonize'] = $this->daemon; $service->instance($this->baseServer);
if (!isset($settings['pid_file'])) { }
$settings['pid_file'] = PID_PATH; return $this->baseServer;
} }
$this->debug(sprintf('Check listen %s::%d -> ok', $config['host'], $config['port']));
$this->onLoadWebsocketHandler(); /**
if ($this->baseServer instanceof Http) { * @param $config
$this->onLoadHttpHandler(); * @param $settings
} * @return Packet|Websocket|Receive|Http|null
* @throws Exception
$this->baseServer->set($settings); */
private function parseServer($config, $settings): Packet|Websocket|Receive|Http|null
$this->onProcessListener(); {
$class = $this->dispatch($config['type']);
return $this->baseServer; if (isset($config['settings']) && !empty($config['settings'])) {
} $settings = array_merge($settings, $config['settings']);
}
$this->baseServer = new $class($config['host'], $config['port'], SWOOLE_PROCESS, $config['mode']);
/** $settings['daemonize'] = $this->daemon;
* @param $config if (!isset($settings['pid_file'])) {
* @param $newListener $settings['pid_file'] = PID_PATH;
* @return Packet|Websocket|Receive|Http|null }
* @throws NotFindClassException $this->debug(sprintf('Check listen %s::%d -> ok', $config['host'], $config['port']));
* @throws ReflectionException
* @throws ComponentException $this->onLoadWebsocketHandler();
* @throws Exception if ($this->baseServer instanceof Http) {
*/ $this->onLoadHttpHandler();
private function onListenerBind($config, $newListener): Packet|Websocket|Receive|Http|null }
{
if (!in_array($config['type'], [self::HTTP, self::TCP, self::PACKAGE])) { $this->baseServer->set($settings);
throw new Exception('Unknown server type(' . $config['type'] . ').');
} $this->onProcessListener();
if (in_array($config['type'], $this->listenTypes)) {
return $this->baseServer; return $this->baseServer;
} }
if ($config['type'] == self::HTTP) {
$this->onBind($newListener, 'request', [Snowflake::createObject(OnRequest::class), 'onHandler']);
} else { /**
$this->noHttp($newListener, $config); * @param $config
} * @param $newListener
$this->debug(sprintf('Check listen %s::%d -> ok', $config['host'], $config['port'])); * @return Packet|Websocket|Receive|Http|null
$this->listenTypes[] = $config['type']; * @throws NotFindClassException
return $this->baseServer; * @throws ReflectionException
} * @throws ComponentException
* @throws Exception
*/
/** private function onListenerBind($config, $newListener): Packet|Websocket|Receive|Http|null
* @param $newListener {
* @param $config if (!in_array($config['type'], [self::HTTP, self::TCP, self::PACKAGE])) {
* @throws NotFindClassException throw new Exception('Unknown server type(' . $config['type'] . ').');
* @throws ReflectionException }
* @throws Exception if (in_array($config['type'], $this->listenTypes)) {
*/ return $this->baseServer;
private function noHttp($newListener, $config) }
{ if ($config['type'] == self::HTTP) {
$this->onBind($newListener, 'connect', [Snowflake::createObject(OnConnect::class), 'onHandler']); $this->onBind($newListener, 'request', [Snowflake::createObject(OnRequest::class), 'onHandler']);
$this->onBind($newListener, 'close', [Snowflake::createObject(OnClose::class), 'onHandler']); } else {
if ($config['type'] == self::TCP) { $this->noHttp($newListener, $config);
$this->onBind($newListener, 'receive', [$class = new OnReceive(), 'onHandler']); }
} else { $this->debug(sprintf('Check listen %s::%d -> ok', $config['host'], $config['port']));
$this->onBind($newListener, 'packet', [$class = new OnPacket(), 'onHandler']); $this->listenTypes[] = $config['type'];
} return $this->baseServer;
$class->host = $config['host']; }
$class->port = $config['port'];
}
/**
* @param $newListener
/** * @param $config
* @param $server * @throws NotFindClassException
* @param $name * @throws ReflectionException
* @param $callback * @throws Exception
* @throws Exception */
*/ private function noHttp($newListener, $config)
private function onBind($server, $name, $callback) {
{ $this->onBind($newListener, 'connect', [Snowflake::createObject(OnConnect::class), 'onHandler']);
if (in_array($name, $this->listening)) { $this->onBind($newListener, 'close', [Snowflake::createObject(OnClose::class), 'onHandler']);
return; if ($config['type'] == self::TCP) {
} $this->onBind($newListener, 'receive', [$class = new OnReceive(), 'onHandler']);
array_push($this->listening, $name); } else {
if ($name === 'request') { $this->onBind($newListener, 'packet', [$class = new OnPacket(), 'onHandler']);
$this->onLoadHttpHandler(); }
} $class->host = $config['host'];
$server->on($name, $callback); $class->port = $config['port'];
} }
/** /**
* Load router handler * @param $server
* @throws Exception * @param $name
*/ * @param $callback
public function onLoadHttpHandler() * @throws Exception
{ */
$event = Snowflake::app()->getEvent(); private function onBind($server, $name, $callback)
$event->on(Event::SERVER_WORKER_START, function () { {
router()->loadRouterSetting(); if (in_array($name, $this->listening)) {
return;
$annotation = Snowflake::app()->getAttributes(); }
$annotation->instanceDirectoryFiles(CONTROLLER_PATH); array_push($this->listening, $name);
}); if ($name === 'request') {
} $this->onLoadHttpHandler();
}
$server->on($name, $callback);
/** }
* @throws Exception
*/
public function onLoadWebsocketHandler() /**
{ * Load router handler
$event = Snowflake::app()->getEvent(); * @throws Exception
$event->on(Event::SERVER_WORKER_START, function () { */
$annotation = Snowflake::app()->getAttributes(); public function onLoadHttpHandler()
$annotation->instanceDirectoryFiles(SOCKET_PATH); {
}); $event = Snowflake::app()->getEvent();
} $event->on(Event::SERVER_WORKER_START, function () {
router()->loadRouterSetting();
/** $annotation = Snowflake::app()->getAttributes();
* @param $type $annotation->instanceDirectoryFiles(CONTROLLER_PATH);
* @return string });
*/ }
private function dispatch($type): string
{
return match ($type) { /**
self::HTTP => Http::class, * @throws Exception
self::WEBSOCKET => Websocket::class, */
self::PACKAGE => Packet::class, public function onLoadWebsocketHandler()
default => Receive::class {
}; $event = Snowflake::app()->getEvent();
} $event->on(Event::SERVER_WORKER_START, function () {
$annotation = Snowflake::app()->getAttributes();
/** $annotation->instanceDirectoryFiles(SOCKET_PATH);
* @param $servers });
* @return array }
*/
private function sortServers($servers): array
{ /**
$array = []; * @param $type
foreach ($servers as $server) { * @return string
switch ($server['type']) { */
case self::WEBSOCKET: private function dispatch($type): string
array_unshift($array, $server); {
break; return match ($type) {
case self::HTTP: self::HTTP => Http::class,
case self::PACKAGE | self::TCP: self::WEBSOCKET => Websocket::class,
$array[] = $server; self::PACKAGE => Packet::class,
break; default => Receive::class
default: };
$array[] = $server; }
}
} /**
return $array; * @param $servers
} * @return array
*/
private function sortServers($servers): array
{
$array = [];
foreach ($servers as $server) {
switch ($server['type']) {
case self::WEBSOCKET:
array_unshift($array, $server);
break;
case self::HTTP:
case self::PACKAGE | self::TCP:
$array[] = $server;
break;
default:
$array[] = $server;
}
}
return $array;
}
} }
+5 -4
View File
@@ -3,9 +3,12 @@
namespace Rpc; namespace Rpc;
use HttpServer\Service\Http;
use HttpServer\Service\Packet;
use HttpServer\Service\Receive;
use HttpServer\Service\Websocket;
use Snowflake\Abstracts\Component; use Snowflake\Abstracts\Component;
use Snowflake\Abstracts\Config; use Snowflake\Abstracts\Config;
use Snowflake\Snowflake;
/** /**
@@ -19,14 +22,12 @@ class Service extends Component
/** /**
* @throws \Snowflake\Exception\ConfigException * @throws \Snowflake\Exception\ConfigException
*/ */
public function instance(): void public function instance(Packet|Websocket|Receive|null|Http $server): void
{ {
$services = Config::get('rpc.service', false, []); $services = Config::get('rpc.service', false, []);
if (empty($services)) { if (empty($services)) {
return; return;
} }
$server = Snowflake::app()->getSwoole();
foreach ($services as $service) { foreach ($services as $service) {
$mode = $service['mode'] ?? SWOOLE_SOCK_TCP6; $mode = $service['mode'] ?? SWOOLE_SOCK_TCP6;
$rpcServer = $server->addlistener($service['host'], $service['port'], $mode); $rpcServer = $server->addlistener($service['host'], $service['port'], $mode);
+341 -339
View File
@@ -50,404 +50,406 @@ use Swoole\Table;
abstract class BaseApplication extends Service abstract class BaseApplication extends Service
{ {
use TraitApplication; use TraitApplication;
/** /**
* @var string * @var string
*/ */
public string $storage = APP_PATH . '/storage'; public string $storage = APP_PATH . '/storage';
public string $envPath = APP_PATH . '/.env'; public string $envPath = APP_PATH . '/.env';
/** /**
* Init constructor. * Init constructor.
* *
* @param array $config * @param array $config
* *
* @throws * @throws
*/ */
public function __construct(array $config = []) public function __construct(array $config = [])
{ {
Snowflake::init($this); Snowflake::init($this);
$this->moreComponents(); $this->moreComponents();
$this->parseInt($config); $this->parseInt($config);
$this->parseEvents($config); $this->parseEvents($config);
$this->initErrorHandler(); $this->initErrorHandler();
$this->enableEnvConfig(); $this->enableEnvConfig();
parent::__construct($config); parent::__construct($config);
} }
/** /**
* @return array * @return array
*/ */
public function enableEnvConfig(): array public function enableEnvConfig(): array
{ {
if (!file_exists($this->envPath)) { if (!file_exists($this->envPath)) {
return []; return [];
} }
$lines = $this->readLinesFromFile($this->envPath); $lines = $this->readLinesFromFile($this->envPath);
foreach ($lines as $line) { foreach ($lines as $line) {
if (!$this->isComment($line) && $this->looksLikeSetter($line)) { if (!$this->isComment($line) && $this->looksLikeSetter($line)) {
[$key, $value] = explode('=', $line); [$key, $value] = explode('=', $line);
putenv(trim($key) . '=' . trim($value)); putenv(trim($key) . '=' . trim($value));
} }
} }
return $lines; return $lines;
} }
/** /**
* Read lines from the file, auto detecting line endings. * Read lines from the file, auto detecting line endings.
* *
* @param string $filePath * @param string $filePath
* *
* @return array * @return array
*/ */
protected function readLinesFromFile(string $filePath): array protected function readLinesFromFile(string $filePath): array
{ {
// Read file into an array of lines with auto-detected line endings // Read file into an array of lines with auto-detected line endings
$autodetect = ini_get('auto_detect_line_endings'); $autodetect = ini_get('auto_detect_line_endings');
ini_set('auto_detect_line_endings', '1'); ini_set('auto_detect_line_endings', '1');
$lines = file($filePath, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES); $lines = file($filePath, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
ini_set('auto_detect_line_endings', $autodetect); ini_set('auto_detect_line_endings', $autodetect);
return $lines; return $lines;
} }
/** /**
* Determine if the line in the file is a comment, e.g. begins with a #. * Determine if the line in the file is a comment, e.g. begins with a #.
* *
* @param string $line * @param string $line
* *
* @return bool * @return bool
*/ */
protected function isComment(string $line): bool protected function isComment(string $line): bool
{ {
$line = ltrim($line); $line = ltrim($line);
return isset($line[0]) && $line[0] === '#'; return isset($line[0]) && $line[0] === '#';
} }
/** /**
* Determine if the given line looks like it's setting a variable. * Determine if the given line looks like it's setting a variable.
* *
* @param string $line * @param string $line
* *
* @return bool * @return bool
*/ */
#[Pure] protected function looksLikeSetter(string $line): bool #[Pure] protected function looksLikeSetter(string $line): bool
{ {
return str_contains($line, '='); return str_contains($line, '=');
} }
/** /**
* @param $config * @param $config
* *
* @throws * @throws
*/ */
public function parseInt($config) public function parseInt($config)
{ {
foreach ($config as $key => $value) { foreach ($config as $key => $value) {
Config::set($key, $value); Config::set($key, $value);
} }
if ($storage = Config::get('storage', false, 'storage')) { if ($storage = Config::get('storage', false, 'storage')) {
if (!str_contains($storage, APP_PATH)) { if (!str_contains($storage, APP_PATH)) {
$storage = APP_PATH . $storage . '/'; $storage = APP_PATH . $storage . '/';
} }
if (!is_dir($storage)) { if (!is_dir($storage)) {
mkdir($storage); mkdir($storage);
} }
if (!is_dir($storage) || !is_writeable($storage)) { if (!is_dir($storage) || !is_writeable($storage)) {
throw new InitException("Directory {$storage} does not have write permission"); throw new InitException("Directory {$storage} does not have write permission");
} }
} }
} }
/** /**
* @param $config * @param $config
* *
* @throws * @throws
*/ */
public function parseEvents($config) public function parseEvents($config)
{ {
if (!isset($config['events']) || !is_array($config['events'])) { if (!isset($config['events']) || !is_array($config['events'])) {
return; return;
} }
$event = Snowflake::app()->getEvent(); $event = Snowflake::app()->getEvent();
foreach ($config['events'] as $key => $value) { foreach ($config['events'] as $key => $value) {
if (is_string($value)) { if (is_string($value)) {
if (!class_exists($value)) { if (!class_exists($value)) {
throw new InitException("Class {$value} does not exists."); throw new InitException("Class {$value} does not exists.");
} }
$value = Snowflake::createObject($value); $value = Snowflake::createObject($value);
} else if (is_array($value) && !is_callable($value, true)) { } else if (is_array($value) && !is_callable($value, true)) {
throw new InitException("Class does not hav callback."); throw new InitException("Class does not hav callback.");
} }
$event->on($key, $value); $event->on($key, $value);
} }
} }
/** /**
* @param $name * @param $name
* @return mixed * @return mixed
* @throws Exception * @throws Exception
*/ */
public function clone($name): mixed public function clone($name): mixed
{ {
return clone $this->get($name); return clone $this->get($name);
} }
/** /**
* *
* @throws Exception * @throws Exception
*/ */
public function initErrorHandler() public function initErrorHandler()
{ {
$this->get('error')->register(); $this->get('error')->register();
} }
/** /**
* @return mixed * @return mixed
*/ */
public function getLocalIps(): mixed public function getLocalIps(): mixed
{ {
return swoole_get_local_ip(); return swoole_get_local_ip();
} }
/** /**
* @return mixed * @return mixed
*/ */
public function getFirstLocal(): mixed public function getFirstLocal(): mixed
{ {
return current($this->getLocalIps()); return current($this->getLocalIps());
} }
/** /**
* @return Logger * @return Logger
* @throws Exception * @throws Exception
*/ */
public function getLogger(): Logger public function getLogger(): Logger
{ {
return $this->get('logger'); return $this->get('logger');
} }
/** /**
* @return Producer * @return Producer
* @throws Exception * @throws Exception
*/ */
public function getKafka(): Producer public function getKafka(): Producer
{ {
return $this->get('kafka'); return $this->get('kafka');
} }
/** /**
* @return \Redis|Redis * @return \Redis|Redis
* @throws Exception * @throws Exception
*/ */
public function getRedis(): Redis|\Redis public function getRedis(): Redis|\Redis
{ {
return $this->get('redis'); return $this->get('redis');
} }
/** /**
* @param $ip * @param $ip
* @return bool * @return bool
*/ */
public function isLocal($ip): bool public function isLocal($ip): bool
{ {
return $this->getFirstLocal() == $ip; return $this->getFirstLocal() == $ip;
} }
/** /**
* @return ErrorHandler * @return ErrorHandler
* @throws Exception * @throws Exception
*/ */
public function getError(): ErrorHandler public function getError(): ErrorHandler
{ {
return $this->get('error'); return $this->get('error');
} }
/** /**
* @return Connection * @return Connection
* @throws ComponentException * @throws ComponentException
* @throws NotFindClassException * @throws NotFindClassException
* @throws ReflectionException * @throws ReflectionException
*/ */
public function getMysqlFromPool(): Connection public function getMysqlFromPool(): Connection
{ {
return $this->get('pool')->getDb(); return $this->get('pool')->getDb();
} }
/** /**
* @return SRedis * @return SRedis
* @throws NotFindClassException * @throws NotFindClassException
* @throws ReflectionException * @throws ReflectionException
* @throws ComponentException * @throws ComponentException
*/ */
public function getRedisFromPool(): SRedis public function getRedisFromPool(): SRedis
{ {
return $this->get('pool')->getRedis(); return $this->get('pool')->getRedis();
} }
/** /**
* @return Response * @return Response
* @throws Exception * @throws Exception
*/ */
public function getResponse(): Response public function getResponse(): Response
{ {
return $this->get('response'); return $this->get('response');
} }
/** /**
* @return Request * @return Request
* @throws Exception * @throws Exception
*/ */
public function getRequest(): Request public function getRequest(): Request
{ {
return $this->get('request'); return $this->get('request');
} }
/** /**
* @param $name * @param $name
* @return Table * @return Table
* @throws Exception * @throws Exception
*/ */
public function getTable($name): Table public function getTable($name): Table
{ {
return $this->get($name); return $this->get($name);
} }
/** /**
* @return Config * @return Config
* @throws Exception * @throws Exception
*/ */
public function getConfig(): Config public function getConfig(): Config
{ {
return $this->get('config'); return $this->get('config');
} }
/** /**
* @return Router * @return Router
* @throws Exception * @throws Exception
*/ */
public function getRouter(): Router public function getRouter(): Router
{ {
return $this->get('router'); return $this->get('router');
} }
/** /**
* @return Event * @return Event
* @throws Exception * @throws Exception
*/ */
public function getEvent(): Event public function getEvent(): Event
{ {
return $this->get('event'); return $this->get('event');
} }
/** /**
* @return Jwt * @return Jwt
* @throws Exception * @throws Exception
*/ */
public function getJwt(): Jwt public function getJwt(): Jwt
{ {
return $this->get('jwt'); return $this->get('jwt');
} }
/** /**
* @return Server * @return Server
* @throws Exception * @throws Exception
*/ */
public function getServer(): Server public function getServer(): Server
{ {
return $this->get('server'); return $this->get('server');
} }
/** /**
* @return Http|Packet|Receive|Websocket|null * @return Http|Packet|Receive|Websocket|null
* @throws Exception * @throws Exception
*/ */
public function getSwoole(): Packet|Websocket|Receive|Http|null public function getSwoole(): Packet|Websocket|Receive|Http|null
{ {
return $this->getServer()->getServer(); return $this->getServer()->getServer();
} }
/** /**
* @return SAnnotation * @return SAnnotation
* @throws Exception * @throws Exception
*/ */
public function getAttributes(): SAnnotation public function getAttributes(): SAnnotation
{ {
return $this->get('attributes'); return $this->get('attributes');
} }
/** /**
* @return Async * @return Async
* @throws Exception * @throws Exception
*/ */
public function getAsync(): Async public function getAsync(): Async
{ {
return $this->get('async'); return $this->get('async');
} }
/** /**
* @return ObjectPool * @return ObjectPool
* @throws Exception * @throws Exception
*/ */
public function getObject(): ObjectPool public function getObject(): ObjectPool
{ {
return $this->get('object'); return $this->get('object');
} }
/** /**
* @throws Exception * @throws Exception
*/ */
protected function moreComponents(): void protected function moreComponents(): void
{ {
$this->setComponents([ $this->setComponents([
'error' => ['class' => ErrorHandler::class], 'error' => ['class' => ErrorHandler::class],
'event' => ['class' => Event::class], 'event' => ['class' => Event::class],
'connections' => ['class' => Connection::class], 'connections' => ['class' => Connection::class],
'redis_connections' => ['class' => SRedis::class], 'redis_connections' => ['class' => SRedis::class],
'pool' => ['class' => SPool::class], 'pool' => ['class' => SPool::class],
'response' => ['class' => Response::class], 'response' => ['class' => Response::class],
'request' => ['class' => Request::class], 'request' => ['class' => Request::class],
'config' => ['class' => Config::class], 'config' => ['class' => Config::class],
'logger' => ['class' => Logger::class], 'logger' => ['class' => Logger::class],
'attributes' => ['class' => SAnnotation::class], 'attributes' => ['class' => SAnnotation::class],
'router' => ['class' => Router::class], 'router' => ['class' => Router::class],
'redis' => ['class' => Redis::class], 'redis' => ['class' => Redis::class],
'jwt' => ['class' => Jwt::class], 'jwt' => ['class' => Jwt::class],
'async' => ['class' => Async::class], 'async' => ['class' => Async::class],
'filter' => ['class' => HttpFilter::class], 'filter' => ['class' => HttpFilter::class],
'crontab' => ['class' => Crontab::class], 'crontab' => ['class' => Crontab::class],
'object' => ['class' => ObjectPool::class], 'object' => ['class' => ObjectPool::class],
'goto' => ['class' => BaseGoto::class], 'goto' => ['class' => BaseGoto::class],
'http2' => ['class' => Http2::class], 'rpc' => ['class' => \Rpc\Producer::class],
]); 'rpc-service' => ['class' => \Rpc\Service::class],
} 'http2' => ['class' => Http2::class],
]);
}
} }