This commit is contained in:
2021-03-29 17:29:39 +08:00
parent c112fc839c
commit 9e54e20dae
6 changed files with 512 additions and 496 deletions
+1
View File
@@ -52,6 +52,7 @@ abstract class AbstractCollection extends Component implements \IteratorAggregat
* @param $query * @param $query
* @param array $array * @param array $array
* @param null $model * @param null $model
* @throws Exception
*/ */
public function __construct($query, array $array = [], $model = null) public function __construct($query, array $array = [], $model = null)
{ {
+2 -1
View File
@@ -157,7 +157,8 @@ abstract class BaseActiveRecord extends Component implements IOrm, ArrayAccess
*/ */
public function createAnnotation() public function createAnnotation()
{ {
$annotation = Snowflake::app()->getAttributes(); $annotation = Snowflake::getAnnotation();
$annotation->injectProperty($this);
$methods = $annotation->getMethods(get_called_class()); $methods = $annotation->getMethods(get_called_class());
foreach ($methods as $method => $attributes) { foreach ($methods as $method => $attributes) {
foreach ($attributes as $attribute) { foreach ($attributes as $attribute) {
+12
View File
@@ -39,12 +39,24 @@ class Controller extends HttpService
/** /**
* Controller constructor. * Controller constructor.
* @param array $config * @param array $config
* @throws Exception
*/ */
public function __construct($config = []) public function __construct($config = [])
{ {
parent::__construct($config); parent::__construct($config);
} }
/**
* @throws Exception
*/
public function init()
{
$annotation = Snowflake::getAnnotation();
$annotation->injectProperty($this);
}
/** /**
* @param null|HttpParams $input * @param null|HttpParams $input
*/ */
-9
View File
@@ -45,15 +45,6 @@ class BaseObject implements Configure
*/ */
public function init() public function init()
{ {
$app = Snowflake::app();
if (!($app instanceof Application)) {
return;
}
if (!$app->has('attributes')) {
return;
}
$attributes = $app->getAttributes();
$attributes->injectProperty($this);
} }
+495 -484
View File
@@ -5,6 +5,7 @@ declare(strict_types=1);
namespace Snowflake; namespace Snowflake;
use Annotation\Annotation;
use Exception; use Exception;
use HttpServer\IInterface\Task; use HttpServer\IInterface\Task;
@@ -37,490 +38,500 @@ defined('SOCKET_PATH') or define('SOCKET_PATH', APP_PATH . 'app/Websocket/');
class Snowflake class Snowflake
{ {
/** @var Container */ /** @var Container */
public static Container $container; public static Container $container;
/** @var ?Application */ /** @var ?Application */
private static ?Application $service = null; private static ?Application $service = null;
/** /**
* @param $service * @param $service
* *
* 初始化服务 * 初始化服务
*/ */
public static function init($service) public static function init($service)
{ {
static::$service = $service; static::$service = $service;
} }
/** /**
* @return Application|null * @return Application|null
*/ */
public static function app(): ?Application public static function app(): ?Application
{ {
return static::$service; return static::$service;
} }
/** /**
* @param $name * @param $name
* @return bool * @return bool
*/ */
public static function has($name): bool public static function has($name): bool
{ {
return static::$service->has($name); return static::$service->has($name);
} }
/** /**
* @param $className * @param $className
* @param $id * @param $id
*/ */
public static function setAlias($className, $id) public static function setAlias($className, $id)
{ {
static::$service->setAlias($className, $id); static::$service->setAlias($className, $id);
} }
/** /**
* @param $port * @param $port
* @return bool|array * @return bool
* @throws Exception * @throws Exception
*/ */
public static function port_already($port): bool public static function port_already($port): bool
{ {
if (empty($port)) { if (empty($port)) {
return false; return false;
} }
if (Snowflake::getPlatform()->isLinux()) { if (Snowflake::getPlatform()->isLinux()) {
exec('netstat -tunlp | grep ' . $port, $output); exec('netstat -tunlp | grep ' . $port, $output);
} else { } else {
exec('lsof -i :' . $port . ' | grep -i "LISTEN"', $output); exec('lsof -i :' . $port . ' | grep -i "LISTEN"', $output);
} }
return !empty($output); return !empty($output);
} }
/** /**
* @param $service * @return Annotation
* @return string * @throws Exception
*/ */
#[Pure] public static function listen($service): string public static function getAnnotation(): Annotation
{ {
return sprintf('Check listen %s::%d -> ok', $service['host'], $service['port']); return static::app()->getAttributes();
} }
/** /**
* @param $className * @param $service
* @param array $construct * @return string
* @return mixed */
* @throws NotFindClassException #[Pure] public static function listen($service): string
* @throws ReflectionException {
* @throws Exception return sprintf('Check listen %s::%d -> ok', $service['host'], $service['port']);
*/ }
public static function createObject($className, $construct = []): mixed
{
if (is_object($className)) { /**
return $className; * @param $className
} * @param array $construct
if (is_string($className)) { * @return mixed
return static::$container->get($className, $construct); * @throws NotFindClassException
} else if (is_array($className)) { * @throws ReflectionException
if (!isset($className['class']) || empty($className['class'])) { * @throws Exception
throw new Exception('Object configuration must be an array containing a "class" element.'); */
} public static function createObject($className, $construct = []): mixed
{
$class = $className['class']; if (is_object($className)) {
unset($className['class']); return $className;
}
return static::$container->get($class, $construct, $className); if (is_string($className)) {
} else if (is_callable($className, TRUE)) { return static::$container->get($className, $construct);
return call_user_func($className, $construct); } else if (is_array($className)) {
} else { if (!isset($className['class']) || empty($className['class'])) {
throw new Exception('Unsupported configuration type: ' . gettype($className)); throw new Exception('Object configuration must be an array containing a "class" element.');
} }
}
$class = $className['class'];
/** unset($className['class']);
* @return string
* @throws Exception return static::$container->get($class, $construct, $className);
*/ } else if (is_callable($className, TRUE)) {
public static function getStoragePath(): string return call_user_func($className, $construct);
{ } else {
$default = APP_PATH . 'storage' . DIRECTORY_SEPARATOR; throw new Exception('Unsupported configuration type: ' . gettype($className));
$path = Config::get('storage', false, $default); }
if (!is_dir($path)) { }
mkdir($path, 0777, true);
} /**
return $path; * @return string
} * @throws Exception
*/
public static function getStoragePath(): string
/** {
* @return bool $default = APP_PATH . 'storage' . DIRECTORY_SEPARATOR;
*/ $path = Config::get('storage', false, $default);
public static function inCoroutine(): bool if (!is_dir($path)) {
{ mkdir($path, 0777, true);
return Coroutine::getCid() > 0; }
} return $path;
}
/**
* @return Container /**
*/ * @return bool
public static function getDi(): Container */
{ public static function inCoroutine(): bool
return static::$container; {
} return Coroutine::getCid() > 0;
}
/**
* @param $workerId /**
* @return mixed * @return Container
* @throws Exception */
*/ public static function getDi(): Container
public static function setManagerId($workerId): mixed {
{ return static::$container;
return self::writeFile(storage($workerId . '.sock', 'pid/manager'), $workerId); }
}
/**
/** * @param $workerId
* @param $workerId * @return mixed
* @return mixed * @throws Exception
* @throws Exception */
*/ public static function setManagerId($workerId): mixed
public static function setProcessId($workerId): mixed {
{ return self::writeFile(storage($workerId . '.sock', 'pid/manager'), $workerId);
return self::writeFile(storage($workerId . '.sock', 'pid/process'), $workerId); }
}
/**
/** * @param $workerId
* @param $workerId * @return mixed
* @return mixed * @throws Exception
* @throws Exception */
*/ public static function setProcessId($workerId): mixed
public static function setWorkerId($workerId): mixed {
{ return self::writeFile(storage($workerId . '.sock', 'pid/process'), $workerId);
if (empty($workerId)) { }
return $workerId;
}
return self::writeFile(storage($workerId . '.sock', 'pid/worker'), $workerId); /**
} * @param $workerId
* @return mixed
* @throws Exception
/** */
* @param $workerId public static function setWorkerId($workerId): mixed
* @return mixed {
* @throws Exception if (empty($workerId)) {
*/ return $workerId;
public static function setTaskId($workerId): mixed }
{ return self::writeFile(storage($workerId . '.sock', 'pid/worker'), $workerId);
if (empty($workerId)) { }
return $workerId;
}
return self::writeFile(storage($workerId . '.sock', 'pid/task'), $workerId); /**
} * @param $workerId
* @return mixed
/** * @throws Exception
* @param $fileName */
* @param $content public static function setTaskId($workerId): mixed
* @param null $is_append {
* @return mixed if (empty($workerId)) {
*/ return $workerId;
public static function writeFile($fileName, $content, $is_append = null): mixed }
{ return self::writeFile(storage($workerId . '.sock', 'pid/task'), $workerId);
$params = [$fileName, (string)$content]; }
if ($is_append !== null) {
$params[] = $is_append; /**
} * @param $fileName
return !self::inCoroutine() ? file_put_contents(...$params) : Coroutine::writeFile(...$params); * @param $content
} * @param null $is_append
* @return mixed
*/
/** public static function writeFile($fileName, $content, $is_append = null): mixed
* @param $object {
* @param $config $params = [$fileName, (string)$content];
* @return mixed if ($is_append !== null) {
*/ $params[] = $is_append;
public static function configure($object, $config): mixed }
{ return !self::inCoroutine() ? file_put_contents(...$params) : Coroutine::writeFile(...$params);
foreach ($config as $key => $value) { }
if (!property_exists($object, $key)) {
continue;
} /**
$object->$key = $value; * @param $object
} * @param $config
return $object; * @return mixed
} */
public static function configure($object, $config): mixed
{
/** foreach ($config as $key => $value) {
* @param $workerId if (!property_exists($object, $key)) {
* @param bool $isWorker continue;
* @throws Exception }
*/ $object->$key = $value;
public static function clearProcessId($workerId, $isWorker = false) }
{ return $object;
clearstatcache(); }
$directory = $isWorker === true ? 'pid/worker' : 'pid/task';
if (!file_exists($file = storage($workerId, $directory))) {
return; /**
} * @param $workerId
shell_exec('rm -rf ' . $file); * @param bool $isWorker
} * @throws Exception
*/
public static function clearProcessId($workerId, $isWorker = false)
/** {
* @param string|null $taskPid clearstatcache();
* @throws Exception $directory = $isWorker === true ? 'pid/worker' : 'pid/task';
*/ if (!file_exists($file = storage($workerId, $directory))) {
public static function clearTaskPid(string $taskPid = null) return;
{ }
if (empty($taskPid)) { shell_exec('rm -rf ' . $file);
exec('rm -rf ' . storage(null, 'pid/task')); }
} else {
static::clearProcessId($taskPid);
} /**
} * @param string|null $taskPid
* @throws Exception
*/
/** public static function clearTaskPid(string $taskPid = null)
* @param $taskPid {
* @throws Exception if (empty($taskPid)) {
*/ exec('rm -rf ' . storage(null, 'pid/task'));
public static function clearWorkerPid($taskPid = null) } else {
{ static::clearProcessId($taskPid);
if (empty($taskPid)) { }
exec('rm -rf ' . storage(null, 'pid/worker')); }
} else {
static::clearProcessId($taskPid, true);
} /**
} * @param $taskPid
* @throws Exception
*/
/** public static function clearWorkerPid($taskPid = null)
* @return Server|null {
* @throws if (empty($taskPid)) {
*/ exec('rm -rf ' . storage(null, 'pid/worker'));
public static function getWebSocket(): ?Server } else {
{ static::clearProcessId($taskPid, true);
$server = static::app()->getSwoole(); }
if (!($server instanceof Server)) { }
return null;
}
return $server; /**
} * @return Server|null
* @throws
*/
/** public static function getWebSocket(): ?Server
* @return false|string {
* @throws Exception $server = static::app()->getSwoole();
*/ if (!($server instanceof Server)) {
public static function getMasterPid(): bool|string return null;
{ }
$pid = Snowflake::app()->getSwoole()->setting['pid_file']; return $server;
}
return file_get_contents($pid);
}
/**
* @return false|string
/** * @throws Exception
* @param int $fd */
* @param $data public static function getMasterPid(): bool|string
* @return mixed {
* @throws Exception $pid = Snowflake::app()->getSwoole()->setting['pid_file'];
*/
public static function push(int $fd, $data): mixed return file_get_contents($pid);
{ }
$server = static::getWebSocket();
if (empty($server)) {
return false; /**
} * @param int $fd
if (!is_string($data)) { * @param $data
$data = Json::encode($data); * @return mixed
} * @throws Exception
return $server->push($fd, $data); */
} public static function push(int $fd, $data): mixed
{
$server = static::getWebSocket();
/** if (empty($server)) {
* @return mixed return false;
*/ }
public static function localhost(): mixed if (!is_string($data)) {
{ $data = Json::encode($data);
return current(swoole_get_local_ip()); }
} return $server->push($fd, $data);
}
/**
* @param string $class /**
* @param array $params * @return mixed
* @throws NotFindClassException */
* @throws ReflectionException public static function localhost(): mixed
* @throws Exception {
*/ return current(swoole_get_local_ip());
public static function async(string $class, array $params = []) }
{
$server = static::app()->getSwoole();
if (!isset($server->setting['task_worker_num']) || !class_exists($class)) { /**
return; * @param string $class
} * @param array $params
* @throws NotFindClassException
/** @var Task $class */ * @throws ReflectionException
$class = static::createObject($class); * @throws Exception
$class->setParams($params); */
public static function async(string $class, array $params = [])
$server->task(swoole_serialize($class)); {
} $server = static::app()->getSwoole();
if (!isset($server->setting['task_worker_num']) || !class_exists($class)) {
return;
/** }
* @param $v1
* @param $v2 /** @var Task $class */
* @return float $class = static::createObject($class);
*/ $class->setParams($params);
#[Pure] public static function distance(array $v1, array $v2): float
{ $server->task(swoole_serialize($class));
$maxX = max($v1['x'], $v2['x']); }
$minX = min($v1['x'], $v2['x']);
$maxZ = max($v1['z'], $v2['z']); /**
$minZ = min($v1['z'], $v2['z']); * @param $v1
* @param $v2
$dx = abs($maxX - $minX); * @return float
$dy = abs($maxZ - $minZ); */
#[Pure] public static function distance(array $v1, array $v2): float
$sqrt = sqrt($dx * $dx + $dy * $dy); {
if ($sqrt < 0) { $maxX = max($v1['x'], $v2['x']);
$sqrt = abs($sqrt); $minX = min($v1['x'], $v2['x']);
}
return (float)$sqrt; $maxZ = max($v1['z'], $v2['z']);
} $minZ = min($v1['z'], $v2['z']);
$dx = abs($maxX - $minX);
/** $dy = abs($maxZ - $minZ);
* @param $process
* @throws Exception $sqrt = sqrt($dx * $dx + $dy * $dy);
*/ if ($sqrt < 0) {
public static function shutdown($process): void $sqrt = abs($sqrt);
{ }
static::app()->getSwoole()->shutdown(); return (float)$sqrt;
if ($process instanceof Process) { }
$process->exit(0);
}
} /**
* @param $process
* @throws Exception
/** */
* @param $tmp public static function shutdown($process): void
* @return string {
*/ static::app()->getSwoole()->shutdown();
public static function rename($tmp): string if ($process instanceof Process) {
{ $process->exit(0);
$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); * @param $tmp
* @return string
return strtoupper($tmp) . $later; */
} public static function rename($tmp): string
{
$hash = md5_file($tmp['tmp_name']);
/**
* @return Environmental $later = '.' . exif_imagetype($tmp['tmp_name']);
* @throws Exception
*/ $match = '/(\w{12})(\w{5})(\w{9})(\w{6})/';
public static function getPlatform(): Environmental $tmp = preg_replace($match, '$1-$2-$3-$4', $hash);
{
return Snowflake::createObject(Environmental::class); return strtoupper($tmp) . $later;
} }
/** /**
* @return mixed * @return Environmental
* @throws Exception * @throws Exception
*/ */
public static function reload(): mixed public static function getPlatform(): Environmental
{ {
return Snowflake::app()->getSwoole()->reload(); return Snowflake::createObject(Environmental::class);
} }
private static array $_autoload = []; /**
* @return mixed
* @throws Exception
const PROCESS = 'process'; */
const TASK = 'task'; public static function reload(): mixed
const WORKER = 'worker'; {
return Snowflake::app()->getSwoole()->reload();
}
/**
* @return string|null
*/ private static array $_autoload = [];
#[Pure] public static function getEnvironmental(): ?string
{
return env('environmental'); const PROCESS = 'process';
} const TASK = 'task';
const WORKER = 'worker';
/**
* @return bool /**
*/ * @return string|null
#[Pure] public static function isTask(): bool */
{ #[Pure] public static function getEnvironmental(): ?string
return static::getEnvironmental() == static::TASK; {
} return env('environmental');
}
/**
* @return bool /**
*/ * @return bool
#[Pure] public static function isWorker(): bool */
{ #[Pure] public static function isTask(): bool
return static::getEnvironmental() == static::WORKER; {
} return static::getEnvironmental() == static::TASK;
}
/**
* @return bool /**
*/ * @return bool
#[Pure] public static function isProcess(): bool */
{ #[Pure] public static function isWorker(): bool
return static::getEnvironmental() == static::PROCESS; {
} return static::getEnvironmental() == static::WORKER;
}
/**
* @param $class /**
* @param $file * @return bool
*/ */
public static function setAutoload($class, $file) #[Pure] public static function isProcess(): bool
{ {
if (isset(static::$_autoload[$class])) { return static::getEnvironmental() == static::PROCESS;
return; }
}
static::$_autoload[$class] = $file;
include_once "$file"; /**
} * @param $class
* @param $file
*/
/** public static function setAutoload($class, $file)
* @param $className {
*/ if (isset(static::$_autoload[$class])) {
public static function autoload($className) return;
{ }
if (!isset(static::$_autoload[$className])) { static::$_autoload[$class] = $file;
return; include_once "$file";
} }
$file = static::$_autoload[$className];
require_once "$file";
} /**
* @param $className
*/
public static function autoload($className)
{
if (!isset(static::$_autoload[$className])) {
return;
}
$file = static::$_autoload[$className];
require_once "$file";
}
} }
+2 -2
View File
@@ -65,7 +65,7 @@ if (!function_exists('annotation')) {
*/ */
function annotation(): Annotation function annotation(): Annotation
{ {
return Snowflake::app()->getAttributes(); return Snowflake::getAnnotation();
} }
@@ -81,7 +81,7 @@ if (!function_exists('recursive_directory')) {
*/ */
function recursive_callback(DirectoryIterator $file) function recursive_callback(DirectoryIterator $file)
{ {
$attributes = Snowflake::app()->getAttributes(); $attributes = Snowflake::getAnnotation();
$annotations = $attributes->getFilename($file->getRealPath()); $annotations = $attributes->getFilename($file->getRealPath());
if (empty($annotations)) { if (empty($annotations)) {