This commit is contained in:
as2252258@163.com
2021-03-28 16:09:18 +08:00
parent 7ea7b1e36e
commit 86e8ad68e9
11 changed files with 1341 additions and 1145 deletions
+435 -433
View File
@@ -22,6 +22,7 @@ use HttpServer\Service\Http;
use HttpServer\Service\Packet;
use HttpServer\Service\Receive;
use HttpServer\Service\Websocket;
use HttpServer\Shutdown;
use JetBrains\PhpStorm\Pure;
use Kafka\Producer;
use Annotation\Annotation as SAnnotation;
@@ -51,437 +52,438 @@ use Swoole\Table;
abstract class BaseApplication extends Service
{
use TraitApplication;
/**
* @var string
*/
public string $storage = APP_PATH . 'storage';
public string $envPath = APP_PATH . '.env';
/**
* Init constructor.
*
* @param array $config
*
* @throws
*/
public function __construct(array $config = [])
{
Snowflake::init($this);
$this->moreComponents();
$this->parseInt($config);
$this->parseEvents($config);
$this->initErrorHandler();
$this->enableEnvConfig();
parent::__construct($config);
}
/**
* @return array
*/
public function enableEnvConfig(): array
{
if (!file_exists($this->envPath)) {
return [];
}
$lines = $this->readLinesFromFile($this->envPath);
foreach ($lines as $line) {
if (!$this->isComment($line) && $this->looksLikeSetter($line)) {
[$key, $value] = explode('=', $line);
putenv(trim($key) . '=' . trim($value));
}
}
return $lines;
}
/**
* Read lines from the file, auto detecting line endings.
*
* @param string $filePath
*
* @return array
*/
protected function readLinesFromFile(string $filePath): array
{
// Read file into an array of lines with auto-detected line endings
$autodetect = ini_get('auto_detect_line_endings');
ini_set('auto_detect_line_endings', '1');
$lines = file($filePath, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
ini_set('auto_detect_line_endings', $autodetect);
return $lines;
}
/**
* Determine if the line in the file is a comment, e.g. begins with a #.
*
* @param string $line
*
* @return bool
*/
protected function isComment(string $line): bool
{
$line = ltrim($line);
return isset($line[0]) && $line[0] === '#';
}
/**
* Determine if the given line looks like it's setting a variable.
*
* @param string $line
*
* @return bool
*/
#[Pure] protected function looksLikeSetter(string $line): bool
{
return str_contains($line, '=');
}
/**
* @param $config
*
* @throws
*/
public function parseInt($config)
{
foreach ($config as $key => $value) {
Config::set($key, $value);
}
if ($storage = Config::get('storage', false, 'storage')) {
if (!str_contains($storage, APP_PATH)) {
$storage = APP_PATH . $storage . '/';
}
if (!is_dir($storage)) {
mkdir($storage);
}
if (!is_dir($storage) || !is_writeable($storage)) {
throw new InitException("Directory {$storage} does not have write permission");
}
}
}
/**
* @param $config
*
* @throws
*/
public function parseEvents($config)
{
if (!isset($config['events']) || !is_array($config['events'])) {
return;
}
$event = Snowflake::app()->getEvent();
foreach ($config['events'] as $key => $value) {
if (is_string($value)) {
$value = Snowflake::createObject($value);
}
if (is_array($value) && isset($value[0]) && !($value[0] instanceof \Closure)) {
if (!is_callable($value, true)) {
throw new InitException("Class does not hav callback.");
}
$event->on($key, $value);
} else {
foreach ($value as $item) {
if (!is_callable($item, true)) {
throw new InitException("Class does not hav callback.");
}
$event->on($key, $item);
}
}
}
}
/**
* @param $name
* @return mixed
* @throws Exception
*/
public function clone($name): mixed
{
return clone $this->get($name);
}
/**
*
* @throws Exception
*/
public function initErrorHandler()
{
$this->get('error')->register();
}
/**
* @return mixed
*/
public function getLocalIps(): mixed
{
return swoole_get_local_ip();
}
/**
* @return mixed
*/
public function getFirstLocal(): mixed
{
return current($this->getLocalIps());
}
/**
* @return Logger
* @throws Exception
*/
public function getLogger(): Logger
{
return $this->get('logger');
}
/**
* @return Producer
* @throws Exception
*/
public function getKafka(): Producer
{
return $this->get('kafka');
}
/**
* @return \Redis|Redis
* @throws Exception
*/
public function getRedis(): Redis|\Redis
{
return $this->get('redis');
}
/**
* @param $ip
* @return bool
*/
public function isLocal($ip): bool
{
return $this->getFirstLocal() == $ip;
}
/**
* @return ErrorHandler
* @throws Exception
*/
public function getError(): ErrorHandler
{
return $this->get('error');
}
/**
* @return Connection
* @throws ComponentException
* @throws NotFindClassException
* @throws ReflectionException
*/
public function getMysqlFromPool(): Connection
{
return $this->get('pool')->getDb();
}
/**
* @return SRedis
* @throws NotFindClassException
* @throws ReflectionException
* @throws ComponentException
*/
public function getRedisFromPool(): SRedis
{
return $this->get('pool')->getRedis();
}
/**
* @return Response
* @throws Exception
*/
public function getResponse(): Response
{
return $this->get('response');
}
/**
* @return Request
* @throws Exception
*/
public function getRequest(): Request
{
return $this->get('request');
}
/**
* @param $name
* @return Table
* @throws Exception
*/
public function getTable($name): Table
{
return $this->get($name);
}
/**
* @return Config
* @throws Exception
*/
public function getConfig(): Config
{
return $this->get('config');
}
/**
* @return Router
* @throws Exception
*/
public function getRouter(): Router
{
return $this->get('router');
}
/**
* @return Event
* @throws Exception
*/
public function getEvent(): Event
{
return $this->get('event');
}
/**
* @return Jwt
* @throws Exception
*/
public function getJwt(): Jwt
{
return $this->get('jwt');
}
/**
* @return Server
* @throws Exception
*/
public function getServer(): Server
{
return $this->get('server');
}
/**
* @return Http|Packet|Receive|Websocket|null
* @throws Exception
*/
public function getSwoole(): Packet|Websocket|Receive|Http|null
{
return $this->getServer()->getServer();
}
/**
* @return SAnnotation
* @throws Exception
*/
public function getAttributes(): SAnnotation
{
return $this->get('attributes');
}
/**
* @return Async
* @throws Exception
*/
public function getAsync(): Async
{
return $this->get('async');
}
/**
* @return ObjectPool
* @throws Exception
*/
public function getObject(): ObjectPool
{
return $this->get('object');
}
/**
* @return \Rpc\Producer
* @throws ComponentException
* @throws NotFindClassException
* @throws ReflectionException
*/
public function getRpc(): \Rpc\Producer
{
return $this->get('rpc');
}
/**
* @return Channel
* @throws ComponentException
* @throws NotFindClassException
* @throws ReflectionException
*/
public function getChannel(): Channel
{
return $this->get('channel');
}
/**
* @throws Exception
*/
protected function moreComponents(): void
{
$this->setComponents([
'error' => ['class' => ErrorHandler::class],
'event' => ['class' => Event::class],
'connections' => ['class' => Connection::class],
'redis_connections' => ['class' => SRedis::class],
'pool' => ['class' => SPool::class],
'response' => ['class' => Response::class],
'request' => ['class' => Request::class],
'config' => ['class' => Config::class],
'logger' => ['class' => Logger::class],
'attributes' => ['class' => SAnnotation::class],
'router' => ['class' => Router::class],
'redis' => ['class' => Redis::class],
'jwt' => ['class' => Jwt::class],
'async' => ['class' => Async::class],
'filter' => ['class' => HttpFilter::class],
'object' => ['class' => ObjectPool::class],
'goto' => ['class' => BaseGoto::class],
'channel' => ['class' => Channel::class],
'rpc' => ['class' => \Rpc\Producer::class],
'rpc-service' => ['class' => \Rpc\Service::class],
'http2' => ['class' => Http2::class],
]);
}
use TraitApplication;
/**
* @var string
*/
public string $storage = APP_PATH . 'storage';
public string $envPath = APP_PATH . '.env';
/**
* Init constructor.
*
* @param array $config
*
* @throws
*/
public function __construct(array $config = [])
{
Snowflake::init($this);
$this->moreComponents();
$this->parseInt($config);
$this->parseEvents($config);
$this->initErrorHandler();
$this->enableEnvConfig();
parent::__construct($config);
}
/**
* @return array
*/
public function enableEnvConfig(): array
{
if (!file_exists($this->envPath)) {
return [];
}
$lines = $this->readLinesFromFile($this->envPath);
foreach ($lines as $line) {
if (!$this->isComment($line) && $this->looksLikeSetter($line)) {
[$key, $value] = explode('=', $line);
putenv(trim($key) . '=' . trim($value));
}
}
return $lines;
}
/**
* Read lines from the file, auto detecting line endings.
*
* @param string $filePath
*
* @return array
*/
protected function readLinesFromFile(string $filePath): array
{
// Read file into an array of lines with auto-detected line endings
$autodetect = ini_get('auto_detect_line_endings');
ini_set('auto_detect_line_endings', '1');
$lines = file($filePath, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
ini_set('auto_detect_line_endings', $autodetect);
return $lines;
}
/**
* Determine if the line in the file is a comment, e.g. begins with a #.
*
* @param string $line
*
* @return bool
*/
protected function isComment(string $line): bool
{
$line = ltrim($line);
return isset($line[0]) && $line[0] === '#';
}
/**
* Determine if the given line looks like it's setting a variable.
*
* @param string $line
*
* @return bool
*/
#[Pure] protected function looksLikeSetter(string $line): bool
{
return str_contains($line, '=');
}
/**
* @param $config
*
* @throws
*/
public function parseInt($config)
{
foreach ($config as $key => $value) {
Config::set($key, $value);
}
if ($storage = Config::get('storage', false, 'storage')) {
if (!str_contains($storage, APP_PATH)) {
$storage = APP_PATH . $storage . '/';
}
if (!is_dir($storage)) {
mkdir($storage);
}
if (!is_dir($storage) || !is_writeable($storage)) {
throw new InitException("Directory {$storage} does not have write permission");
}
}
}
/**
* @param $config
*
* @throws
*/
public function parseEvents($config)
{
if (!isset($config['events']) || !is_array($config['events'])) {
return;
}
$event = Snowflake::app()->getEvent();
foreach ($config['events'] as $key => $value) {
if (is_string($value)) {
$value = Snowflake::createObject($value);
}
if (is_array($value) && isset($value[0]) && !($value[0] instanceof \Closure)) {
if (!is_callable($value, true)) {
throw new InitException("Class does not hav callback.");
}
$event->on($key, $value);
} else {
foreach ($value as $item) {
if (!is_callable($item, true)) {
throw new InitException("Class does not hav callback.");
}
$event->on($key, $item);
}
}
}
}
/**
* @param $name
* @return mixed
* @throws Exception
*/
public function clone($name): mixed
{
return clone $this->get($name);
}
/**
*
* @throws Exception
*/
public function initErrorHandler()
{
$this->get('error')->register();
}
/**
* @return mixed
*/
public function getLocalIps(): mixed
{
return swoole_get_local_ip();
}
/**
* @return mixed
*/
public function getFirstLocal(): mixed
{
return current($this->getLocalIps());
}
/**
* @return Logger
* @throws Exception
*/
public function getLogger(): Logger
{
return $this->get('logger');
}
/**
* @return Producer
* @throws Exception
*/
public function getKafka(): Producer
{
return $this->get('kafka');
}
/**
* @return \Redis|Redis
* @throws Exception
*/
public function getRedis(): Redis|\Redis
{
return $this->get('redis');
}
/**
* @param $ip
* @return bool
*/
public function isLocal($ip): bool
{
return $this->getFirstLocal() == $ip;
}
/**
* @return ErrorHandler
* @throws Exception
*/
public function getError(): ErrorHandler
{
return $this->get('error');
}
/**
* @return Connection
* @throws ComponentException
* @throws NotFindClassException
* @throws ReflectionException
*/
public function getMysqlFromPool(): Connection
{
return $this->get('pool')->getDb();
}
/**
* @return SRedis
* @throws NotFindClassException
* @throws ReflectionException
* @throws ComponentException
*/
public function getRedisFromPool(): SRedis
{
return $this->get('pool')->getRedis();
}
/**
* @return Response
* @throws Exception
*/
public function getResponse(): Response
{
return $this->get('response');
}
/**
* @return Request
* @throws Exception
*/
public function getRequest(): Request
{
return $this->get('request');
}
/**
* @param $name
* @return Table
* @throws Exception
*/
public function getTable($name): Table
{
return $this->get($name);
}
/**
* @return Config
* @throws Exception
*/
public function getConfig(): Config
{
return $this->get('config');
}
/**
* @return Router
* @throws Exception
*/
public function getRouter(): Router
{
return $this->get('router');
}
/**
* @return Event
* @throws Exception
*/
public function getEvent(): Event
{
return $this->get('event');
}
/**
* @return Jwt
* @throws Exception
*/
public function getJwt(): Jwt
{
return $this->get('jwt');
}
/**
* @return Server
* @throws Exception
*/
public function getServer(): Server
{
return $this->get('server');
}
/**
* @return Http|Packet|Receive|Websocket|null
* @throws Exception
*/
public function getSwoole(): Packet|Websocket|Receive|Http|null
{
return $this->getServer()->getServer();
}
/**
* @return SAnnotation
* @throws Exception
*/
public function getAttributes(): SAnnotation
{
return $this->get('attributes');
}
/**
* @return Async
* @throws Exception
*/
public function getAsync(): Async
{
return $this->get('async');
}
/**
* @return ObjectPool
* @throws Exception
*/
public function getObject(): ObjectPool
{
return $this->get('object');
}
/**
* @return \Rpc\Producer
* @throws ComponentException
* @throws NotFindClassException
* @throws ReflectionException
*/
public function getRpc(): \Rpc\Producer
{
return $this->get('rpc');
}
/**
* @return Channel
* @throws ComponentException
* @throws NotFindClassException
* @throws ReflectionException
*/
public function getChannel(): Channel
{
return $this->get('channel');
}
/**
* @throws Exception
*/
protected function moreComponents(): void
{
$this->setComponents([
'error' => ['class' => ErrorHandler::class],
'event' => ['class' => Event::class],
'connections' => ['class' => Connection::class],
'redis_connections' => ['class' => SRedis::class],
'pool' => ['class' => SPool::class],
'response' => ['class' => Response::class],
'request' => ['class' => Request::class],
'config' => ['class' => Config::class],
'logger' => ['class' => Logger::class],
'attributes' => ['class' => SAnnotation::class],
'router' => ['class' => Router::class],
'redis' => ['class' => Redis::class],
'jwt' => ['class' => Jwt::class],
'async' => ['class' => Async::class],
'filter' => ['class' => HttpFilter::class],
'object' => ['class' => ObjectPool::class],
'goto' => ['class' => BaseGoto::class],
'channel' => ['class' => Channel::class],
'rpc' => ['class' => \Rpc\Producer::class],
'rpc-service' => ['class' => \Rpc\Service::class],
'http2' => ['class' => Http2::class],
'shutdown' => ['class' => Shutdown::class],
]);
}
}
+2
View File
@@ -14,6 +14,7 @@ use HttpServer\Http\Response;
use HttpServer\HttpFilter;
use HttpServer\Route\Router;
use HttpServer\Server;
use HttpServer\Shutdown;
use Kafka\Producer;
use Snowflake\Async;
use Snowflake\Cache\Redis;
@@ -50,6 +51,7 @@ use Rpc\Producer as RPCProducer;
* @property HttpFilter $filter
* @property RPCProducer $rpc
* @property Channel $channel
* @property Shutdown $shutdown
*/
trait TraitApplication
{
+1 -1
View File
@@ -34,7 +34,7 @@ abstract class Process extends \Swoole\Process implements SProcess
{
parent::__construct([$this, '_load'], false, 1, $enable_coroutine);
$this->application = $application;
Snowflake::setWorkerId($this->pid);
Snowflake::setProcessId($this->pid);
}
/**
+484 -426
View File
@@ -37,432 +37,490 @@ defined('SOCKET_PATH') or define('SOCKET_PATH', APP_PATH . 'app/Websocket/');
class Snowflake
{
/** @var Container */
public static Container $container;
/** @var ?Application */
private static ?Application $service = null;
/**
* @param $service
*
* 初始化服务
*/
public static function init($service)
{
static::$service = $service;
}
/**
* @return Application|null
*/
public static function app(): ?Application
{
return static::$service;
}
/**
* @param $name
* @return bool
*/
public static function has($name): bool
{
return static::$service->has($name);
}
/**
* @param $className
* @param $id
*/
public static function setAlias($className, $id)
{
static::$service->setAlias($className, $id);
}
/**
* @param $port
* @return bool|array
* @throws Exception
*/
public static function port_already($port): bool
{
if (empty($port)) {
return false;
}
if (Snowflake::getPlatform()->isLinux()) {
exec('netstat -tunlp | grep ' . $port, $output);
} else {
exec('lsof -i :' . $port . ' | grep -i "LISTEN"', $output);
}
return !empty($output);
}
/**
* @param $service
* @return string
*/
#[Pure] public static function listen($service): string
{
return sprintf('Check listen %s::%d -> ok', $service['host'], $service['port']);
}
/**
* @param $className
* @param array $construct
* @return mixed
* @throws NotFindClassException
* @throws ReflectionException
* @throws Exception
*/
public static function createObject($className, $construct = []): mixed
{
if (is_object($className)) {
return $className;
}
if (is_string($className)) {
return static::$container->get($className, $construct);
} else if (is_array($className)) {
if (!isset($className['class']) || empty($className['class'])) {
throw new Exception('Object configuration must be an array containing a "class" element.');
}
$class = $className['class'];
unset($className['class']);
return static::$container->get($class, $construct, $className);
} else if (is_callable($className, TRUE)) {
return call_user_func($className, $construct);
} else {
throw new Exception('Unsupported configuration type: ' . gettype($className));
}
}
/**
* @return string
* @throws Exception
*/
public static function getStoragePath(): string
{
$default = APP_PATH . 'storage' . DIRECTORY_SEPARATOR;
$path = Config::get('storage', false, $default);
if (!is_dir($path)) {
mkdir($path);
}
return $path;
}
/**
* @return bool
*/
public static function inCoroutine(): bool
{
return Coroutine::getCid() > 0;
}
/**
* @return Container
*/
public static function getDi(): Container
{
return static::$container;
}
/**
* @param $workerId
* @return mixed
* @throws Exception
*/
public static function setProcessId($workerId): mixed
{
return self::writeFile(storage('socket.sock'), $workerId);
}
/**
* @param $workerId
* @return mixed
* @throws Exception
*/
public static function setWorkerId($workerId): mixed
{
if (empty($workerId)) {
return $workerId;
}
return self::writeFile(storage($workerId . '.sock', 'worker'), $workerId);
}
/**
* @param $fileName
* @param $content
* @param null $is_append
* @return mixed
*/
public static function writeFile($fileName, $content, $is_append = null): mixed
{
$params = [$fileName, (string)$content];
if ($is_append !== null) {
$params[] = $is_append;
}
return !self::inCoroutine() ? file_put_contents(...$params) : Coroutine::writeFile(...$params);
}
/**
* @param $object
* @param $config
* @return mixed
*/
public static function configure($object, $config): mixed
{
foreach ($config as $key => $value) {
if (!property_exists($object, $key)) {
continue;
}
$object->$key = $value;
}
return $object;
}
/**
* @param $workerId
* @throws Exception
*/
public static function clearProcessId($workerId)
{
@unlink(storage($workerId . '.sock', 'worker'));
}
/**
* @return Server|null
* @throws
*/
public static function getWebSocket(): ?Server
{
$server = static::app()->getSwoole();
if (!($server instanceof Server)) {
return null;
}
return $server;
}
/**
* @return false|string
* @throws Exception
*/
public static function getMasterPid(): bool|string
{
$pid = Snowflake::app()->getSwoole()->setting['pid_file'];
return file_get_contents($pid);
}
/**
* @param int $fd
* @param $data
* @return mixed
* @throws Exception
*/
public static function push(int $fd, $data): mixed
{
$server = static::getWebSocket();
if (empty($server)) {
return false;
}
if (!is_string($data)) {
$data = Json::encode($data);
}
return $server->push($fd, $data);
}
/**
* @return mixed
*/
public static function localhost(): mixed
{
return current(swoole_get_local_ip());
}
/**
* @param string $class
* @param array $params
* @throws NotFindClassException
* @throws ReflectionException
* @throws Exception
*/
public static function async(string $class, array $params = [])
{
$server = static::app()->getSwoole();
if (!isset($server->setting['task_worker_num']) || !class_exists($class)) {
return;
}
/** @var Task $class */
$class = static::createObject($class);
$class->setParams($params);
$server->task(swoole_serialize($class));
}
/**
* @param $v1
* @param $v2
* @return float
*/
#[Pure] public static function distance(array $v1, array $v2): float
{
$maxX = max($v1['x'], $v2['x']);
$minX = min($v1['x'], $v2['x']);
$maxZ = max($v1['z'], $v2['z']);
$minZ = min($v1['z'], $v2['z']);
$dx = abs($maxX - $minX);
$dy = abs($maxZ - $minZ);
$sqrt = sqrt($dx * $dx + $dy * $dy);
if ($sqrt < 0) {
$sqrt = abs($sqrt);
}
return (float)$sqrt;
}
/**
* @param $process
* @throws Exception
*/
public static function shutdown($process): void
{
static::app()->getSwoole()->shutdown();
if ($process instanceof Process) {
$process->exit(0);
}
}
/**
* @param $tmp
* @return string
*/
public static function rename($tmp): string
{
$hash = md5_file($tmp['tmp_name']);
$later = '.' . exif_imagetype($tmp['tmp_name']);
$match = '/(\w{12})(\w{5})(\w{9})(\w{6})/';
$tmp = preg_replace($match, '$1-$2-$3-$4', $hash);
return strtoupper($tmp) . $later;
}
/**
* @return Environmental
* @throws Exception
*/
public static function getPlatform(): Environmental
{
return Snowflake::createObject(Environmental::class);
}
/**
* @return mixed
* @throws Exception
*/
public static function reload(): mixed
{
return Snowflake::app()->getSwoole()->reload();
}
private static array $_autoload = [];
const PROCESS = 'process';
const TASK = 'task';
const WORKER = 'worker';
/**
* @return string|null
*/
#[Pure] public static function getEnvironmental(): ?string
{
return env('environmental');
}
/**
* @return bool
*/
#[Pure] public static function isTask(): bool
{
return static::getEnvironmental() == static::TASK;
}
/**
* @return bool
*/
#[Pure] public static function isWorker(): bool
{
return static::getEnvironmental() == static::WORKER;
}
/**
* @return bool
*/
#[Pure] public static function isProcess(): bool
{
return static::getEnvironmental() == static::PROCESS;
}
/**
* @param $class
* @param $file
*/
public static function setAutoload($class, $file)
{
if (isset(static::$_autoload[$class])) {
return;
}
static::$_autoload[$class] = $file;
include_once "$file";
}
/**
* @param $className
*/
public static function autoload($className)
{
if (!isset(static::$_autoload[$className])) {
return;
}
$file = static::$_autoload[$className];
require_once "$file";
}
/** @var Container */
public static Container $container;
/** @var ?Application */
private static ?Application $service = null;
/**
* @param $service
*
* 初始化服务
*/
public static function init($service)
{
static::$service = $service;
}
/**
* @return Application|null
*/
public static function app(): ?Application
{
return static::$service;
}
/**
* @param $name
* @return bool
*/
public static function has($name): bool
{
return static::$service->has($name);
}
/**
* @param $className
* @param $id
*/
public static function setAlias($className, $id)
{
static::$service->setAlias($className, $id);
}
/**
* @param $port
* @return bool|array
* @throws Exception
*/
public static function port_already($port): bool
{
if (empty($port)) {
return false;
}
if (Snowflake::getPlatform()->isLinux()) {
exec('netstat -tunlp | grep ' . $port, $output);
} else {
exec('lsof -i :' . $port . ' | grep -i "LISTEN"', $output);
}
return !empty($output);
}
/**
* @param $service
* @return string
*/
#[Pure] public static function listen($service): string
{
return sprintf('Check listen %s::%d -> ok', $service['host'], $service['port']);
}
/**
* @param $className
* @param array $construct
* @return mixed
* @throws NotFindClassException
* @throws ReflectionException
* @throws Exception
*/
public static function createObject($className, $construct = []): mixed
{
if (is_object($className)) {
return $className;
}
if (is_string($className)) {
return static::$container->get($className, $construct);
} else if (is_array($className)) {
if (!isset($className['class']) || empty($className['class'])) {
throw new Exception('Object configuration must be an array containing a "class" element.');
}
$class = $className['class'];
unset($className['class']);
return static::$container->get($class, $construct, $className);
} else if (is_callable($className, TRUE)) {
return call_user_func($className, $construct);
} else {
throw new Exception('Unsupported configuration type: ' . gettype($className));
}
}
/**
* @return string
* @throws Exception
*/
public static function getStoragePath(): string
{
$default = APP_PATH . 'storage' . DIRECTORY_SEPARATOR;
$path = Config::get('storage', false, $default);
if (!is_dir($path)) {
mkdir($path, 0777, true);
}
return $path;
}
/**
* @return bool
*/
public static function inCoroutine(): bool
{
return Coroutine::getCid() > 0;
}
/**
* @return Container
*/
public static function getDi(): Container
{
return static::$container;
}
/**
* @param $workerId
* @return mixed
* @throws Exception
*/
public static function setManagerId($workerId): mixed
{
return self::writeFile(storage($workerId . '.sock', 'pid/manager'), $workerId);
}
/**
* @param $workerId
* @return mixed
* @throws Exception
*/
public static function setProcessId($workerId): mixed
{
return self::writeFile(storage($workerId . '.sock', 'pid/process'), $workerId);
}
/**
* @param $workerId
* @return mixed
* @throws Exception
*/
public static function setWorkerId($workerId): mixed
{
if (empty($workerId)) {
return $workerId;
}
return self::writeFile(storage($workerId . '.sock', 'pid/worker'), $workerId);
}
/**
* @param $workerId
* @return mixed
* @throws Exception
*/
public static function setTaskId($workerId): mixed
{
if (empty($workerId)) {
return $workerId;
}
return self::writeFile(storage($workerId . '.sock', 'pid/task'), $workerId);
}
/**
* @param $fileName
* @param $content
* @param null $is_append
* @return mixed
*/
public static function writeFile($fileName, $content, $is_append = null): mixed
{
$params = [$fileName, (string)$content];
if ($is_append !== null) {
$params[] = $is_append;
}
return !self::inCoroutine() ? file_put_contents(...$params) : Coroutine::writeFile(...$params);
}
/**
* @param $object
* @param $config
* @return mixed
*/
public static function configure($object, $config): mixed
{
foreach ($config as $key => $value) {
if (!property_exists($object, $key)) {
continue;
}
$object->$key = $value;
}
return $object;
}
/**
* @param $workerId
* @param bool $isWorker
* @throws Exception
*/
public static function clearProcessId($workerId, $isWorker = false)
{
clearstatcache();
$directory = $isWorker === true ? 'pid/worker' : 'pid/task';
if (!file_exists($file = storage($workerId, $directory))) {
return;
}
shell_exec('rm -rf ' . $file);
}
/**
* @param string|null $taskPid
* @throws Exception
*/
public static function clearTaskPid(string $taskPid = null)
{
if (empty($taskPid)) {
exec('rm -rf ' . storage(null, 'pid/task'));
} else {
static::clearProcessId($taskPid);
}
}
/**
* @param $taskPid
* @throws Exception
*/
public static function clearWorkerPid($taskPid = null)
{
if (empty($taskPid)) {
exec('rm -rf ' . storage(null, 'pid/worker'));
} else {
static::clearProcessId($taskPid, true);
}
}
/**
* @return Server|null
* @throws
*/
public static function getWebSocket(): ?Server
{
$server = static::app()->getSwoole();
if (!($server instanceof Server)) {
return null;
}
return $server;
}
/**
* @return false|string
* @throws Exception
*/
public static function getMasterPid(): bool|string
{
$pid = Snowflake::app()->getSwoole()->setting['pid_file'];
return file_get_contents($pid);
}
/**
* @param int $fd
* @param $data
* @return mixed
* @throws Exception
*/
public static function push(int $fd, $data): mixed
{
$server = static::getWebSocket();
if (empty($server)) {
return false;
}
if (!is_string($data)) {
$data = Json::encode($data);
}
return $server->push($fd, $data);
}
/**
* @return mixed
*/
public static function localhost(): mixed
{
return current(swoole_get_local_ip());
}
/**
* @param string $class
* @param array $params
* @throws NotFindClassException
* @throws ReflectionException
* @throws Exception
*/
public static function async(string $class, array $params = [])
{
$server = static::app()->getSwoole();
if (!isset($server->setting['task_worker_num']) || !class_exists($class)) {
return;
}
/** @var Task $class */
$class = static::createObject($class);
$class->setParams($params);
$server->task(swoole_serialize($class));
}
/**
* @param $v1
* @param $v2
* @return float
*/
#[Pure] public static function distance(array $v1, array $v2): float
{
$maxX = max($v1['x'], $v2['x']);
$minX = min($v1['x'], $v2['x']);
$maxZ = max($v1['z'], $v2['z']);
$minZ = min($v1['z'], $v2['z']);
$dx = abs($maxX - $minX);
$dy = abs($maxZ - $minZ);
$sqrt = sqrt($dx * $dx + $dy * $dy);
if ($sqrt < 0) {
$sqrt = abs($sqrt);
}
return (float)$sqrt;
}
/**
* @param $process
* @throws Exception
*/
public static function shutdown($process): void
{
static::app()->getSwoole()->shutdown();
if ($process instanceof Process) {
$process->exit(0);
}
}
/**
* @param $tmp
* @return string
*/
public static function rename($tmp): string
{
$hash = md5_file($tmp['tmp_name']);
$later = '.' . exif_imagetype($tmp['tmp_name']);
$match = '/(\w{12})(\w{5})(\w{9})(\w{6})/';
$tmp = preg_replace($match, '$1-$2-$3-$4', $hash);
return strtoupper($tmp) . $later;
}
/**
* @return Environmental
* @throws Exception
*/
public static function getPlatform(): Environmental
{
return Snowflake::createObject(Environmental::class);
}
/**
* @return mixed
* @throws Exception
*/
public static function reload(): mixed
{
return Snowflake::app()->getSwoole()->reload();
}
private static array $_autoload = [];
const PROCESS = 'process';
const TASK = 'task';
const WORKER = 'worker';
/**
* @return string|null
*/
#[Pure] public static function getEnvironmental(): ?string
{
return env('environmental');
}
/**
* @return bool
*/
#[Pure] public static function isTask(): bool
{
return static::getEnvironmental() == static::TASK;
}
/**
* @return bool
*/
#[Pure] public static function isWorker(): bool
{
return static::getEnvironmental() == static::WORKER;
}
/**
* @return bool
*/
#[Pure] public static function isProcess(): bool
{
return static::getEnvironmental() == static::PROCESS;
}
/**
* @param $class
* @param $file
*/
public static function setAutoload($class, $file)
{
if (isset(static::$_autoload[$class])) {
return;
}
static::$_autoload[$class] = $file;
include_once "$file";
}
/**
* @param $className
*/
public static function autoload($className)
{
if (!isset(static::$_autoload[$className])) {
return;
}
$file = static::$_autoload[$className];
require_once "$file";
}
}