add cs fixer and PHPStan and activate it (build 436)

This commit is contained in:
crazywhalecc
2022-03-15 18:05:33 +08:00
parent d01bd69aa5
commit 1706afbcd0
163 changed files with 4572 additions and 3588 deletions

View File

@@ -1,9 +1,9 @@
<?php
declare(strict_types=1);
namespace ZM\Utils\Manager;
use ZM\Config\ZMConfig;
use ZM\Console\Console;
use ZM\Exception\ModulePackException;
@@ -16,67 +16,80 @@ use ZM\Utils\DataProvider;
/**
* 模块管理器,负责打包解包模块
* Class ModuleManager
* @package ZM\Utils\Manager
* @since 2.5
*/
class ModuleManager
{
/**
* 扫描src目录下的所有已经被标注的模块
* @return array
* @throws ZMException
*/
public static function getConfiguredModules(): array {
$dir = DataProvider::getSourceRootDir() . "/src/";
public static function getConfiguredModules(): array
{
$dir = DataProvider::getSourceRootDir() . '/src/';
$ls = DataProvider::scanDirFiles($dir, true, true);
$modules = [];
foreach ($ls as $v) {
$pathinfo = pathinfo($v);
if ($pathinfo["basename"] == "zm.json") {
$json = json_decode(file_get_contents(realpath($dir . "/" . $v)), true);
if ($json === null) continue;
if (!isset($json["name"])) continue;
if ($pathinfo["dirname"] == ".") {
throw new ZMKnownException("E00052", "在/src/目录下不可以直接标记为模块(zm.json),因为命名空间不能为根空间!");
if ($pathinfo['basename'] == 'zm.json') {
$json = json_decode(file_get_contents(realpath($dir . '/' . $v)), true);
if ($json === null) {
continue;
}
$json["module-path"] = realpath($dir . "/" . $pathinfo["dirname"]);
$json["namespace"] = str_replace("/", "\\", $pathinfo["dirname"]);
if (isset($modules[$json["name"]])) {
throw new ZMKnownException("E00053", "重名模块:" . $json["name"]);
if (!isset($json['name'])) {
continue;
}
$modules[$json["name"]] = $json;
if ($pathinfo['dirname'] == '.') {
throw new ZMKnownException('E00052', '在/src/目录下不可以直接标记为模块(zm.json),因为命名空间不能为根空间!');
}
$json['module-path'] = realpath($dir . '/' . $pathinfo['dirname']);
$json['namespace'] = str_replace('/', '\\', $pathinfo['dirname']);
if (isset($modules[$json['name']])) {
throw new ZMKnownException('E00053', '重名模块:' . $json['name']);
}
$modules[$json['name']] = $json;
}
}
return $modules;
}
public static function getPackedModules(): array {
$dir = ZMConfig::get("global", "module_loader")["load_path"] ?? (ZM_DATA . "modules");
public static function getPackedModules(): array
{
$dir = ZMConfig::get('global', 'module_loader')['load_path'] ?? (ZM_DATA . 'modules');
$ls = DataProvider::scanDirFiles($dir, true, false);
if ($ls === false) return [];
if ($ls === false) {
return [];
}
$modules = [];
foreach ($ls as $v) {
$pathinfo = pathinfo($v);
if (($pathinfo["extension"] ?? "") != "phar") continue;
$file = "phar://" . $v;
if (!is_file($file . "/module_entry.php") || !is_file($file . "/zmplugin.json")) continue;
$module_config = json_decode(file_get_contents($file . "/zmplugin.json"), true);
if ($module_config === null) continue;
if (!is_file($file . "/" . $module_config["module-root-path"] . "/zm.json")) {
Console::warning(zm_internal_errcode("E00054") . "模块(插件)文件 " . $pathinfo["basename"] . " 无法找到模块配置文件zm.json");
if (($pathinfo['extension'] ?? '') != 'phar') {
continue;
}
$module_file = json_decode(file_get_contents($file . "/" . $module_config["module-root-path"] . "/zm.json"), true);
$file = 'phar://' . $v;
if (!is_file($file . '/module_entry.php') || !is_file($file . '/zmplugin.json')) {
continue;
}
$module_config = json_decode(file_get_contents($file . '/zmplugin.json'), true);
if ($module_config === null) {
continue;
}
if (!is_file($file . '/' . $module_config['module-root-path'] . '/zm.json')) {
Console::warning(zm_internal_errcode('E00054') . '模块(插件)文件 ' . $pathinfo['basename'] . ' 无法找到模块配置文件zm.json');
continue;
}
$module_file = json_decode(file_get_contents($file . '/' . $module_config['module-root-path'] . '/zm.json'), true);
if ($module_file === null) {
Console::warning(zm_internal_errcode("E000555") . "模块(插件)文件 " . $pathinfo["basename"] . " 无法正常读取模块配置文件zm.json");
Console::warning(zm_internal_errcode('E000555') . '模块(插件)文件 ' . $pathinfo['basename'] . ' 无法正常读取模块配置文件zm.json');
continue;
}
$module_config["phar-path"] = $v;
$module_config["name"] = $module_file["name"] ?? null;
if ($module_config["name"] === null) continue;
$module_config["module-config"] = $module_file;
$modules[$module_config["name"]] = $module_config;
$module_config['phar-path'] = $v;
$module_config['name'] = $module_file['name'] ?? null;
if ($module_config['name'] === null) {
continue;
}
$module_config['module-config'] = $module_file;
$modules[$module_config['name']] = $module_config;
}
return $modules;
}
@@ -84,15 +97,19 @@ class ModuleManager
/**
* 打包模块
* @param $module
* @return bool
* @throws ZMException
*/
public static function packModule($module): bool {
public static function packModule($module): bool
{
try {
$packer = new ModulePacker($module);
if (!is_dir(DataProvider::getDataFolder())) throw new ModulePackException(zm_internal_errcode("E00070") . "zm_data dir not found!");
$path = realpath(DataProvider::getDataFolder() . "/output");
if ($path === false) mkdir($path = DataProvider::getDataFolder() . "/output");
if (!is_dir(DataProvider::getDataFolder())) {
throw new ModulePackException(zm_internal_errcode('E00070') . 'zm_data dir not found!');
}
$path = realpath(DataProvider::getDataFolder() . '/output');
if ($path === false) {
mkdir($path = DataProvider::getDataFolder() . '/output');
}
$packer->setOutputPath($path);
$packer->setOverride();
$packer->pack();
@@ -106,16 +123,16 @@ class ModuleManager
/**
* 解包模块
* @param $module
* @param array $options
* @return array|false
*/
public static function unpackModule($module, array $options = []) {
public static function unpackModule($module, array $options = [])
{
try {
$packer = new ModuleUnpacker($module);
return $packer->unpack((bool)$options["overwrite-light-cache"], (bool)$options["overwrite-zm-data"], (bool)$options["overwrite-source"], (bool)$options["ignore-depends"]);
return $packer->unpack((bool) $options['overwrite-light-cache'], (bool) $options['overwrite-zm-data'], (bool) $options['overwrite-source'], (bool) $options['ignore-depends']);
} catch (ZMException $e) {
Console::error($e->getMessage());
return false;
}
}
}
}

View File

@@ -1,9 +1,11 @@
<?php /** @noinspection PhpUnused */
<?php
/** @noinspection PhpUnused */
declare(strict_types=1);
namespace ZM\Utils\Manager;
use Swoole\Process;
class ProcessManager
@@ -11,22 +13,13 @@ class ProcessManager
/** @var Process[] */
public static $user_process = [];
/**
* @param string $name
* @param callable $callable
* @return Process
*/
public static function createUserProcess(string $name, callable $callable): Process
{
return self::$user_process[$name] = new Process($callable);
}
/**
* @param string $string
* @return Process|null
*/
public static function getUserProcess(string $string): ?Process
{
return self::$user_process[$string] ?? null;
}
}
}

View File

@@ -1,9 +1,9 @@
<?php
declare(strict_types=1);
namespace ZM\Utils\Manager;
use Symfony\Component\Routing\Route;
use Symfony\Component\Routing\RouteCollection;
use ZM\Annotation\Http\Controller;
@@ -15,16 +15,18 @@ use ZM\Store\LightCacheInside;
/**
* 路由管理器2.5版本更改了命名空间
* Class RouteManager
* @package ZM\Utils\Manager
* @since 2.3.0
*/
class RouteManager
{
/** @var null|RouteCollection */
public static $routes = null;
public static $routes;
public static function importRouteByAnnotation(RequestMapping $vss, $method, $class, $methods_annotations) {
if (self::$routes === null) self::$routes = new RouteCollection();
public static function importRouteByAnnotation(RequestMapping $vss, $method, $class, $methods_annotations)
{
if (self::$routes === null) {
self::$routes = new RouteCollection();
}
// 拿到所属方法的类上面有没有控制器的注解
$prefix = '';
@@ -34,34 +36,36 @@ class RouteManager
break;
}
}
$tail = trim($vss->route, "/");
$route_name = $prefix . ($tail === "" ? "" : "/") . $tail;
Console::debug("添加路由:" . $route_name);
$tail = trim($vss->route, '/');
$route_name = $prefix . ($tail === '' ? '' : '/') . $tail;
Console::debug('添加路由:' . $route_name);
$route = new Route($route_name, ['_class' => $class, '_method' => $method]);
$route->setMethods($vss->request_method);
self::$routes->add(md5($route_name), $route);
}
public static function addStaticFileRoute($route, $path) {
$tail = trim($route, "/");
$route_name = ($tail === "" ? "" : "/") . $tail . "/{filename}";
Console::debug("添加静态文件路由:" . $route_name);
$route = new Route($route_name, ['_class' => RouteManager::class, '_method' => "onStaticRoute"]);
public static function addStaticFileRoute($route, $path)
{
$tail = trim($route, '/');
$route_name = ($tail === '' ? '' : '/') . $tail . '/{filename}';
Console::debug('添加静态文件路由:' . $route_name);
$route = new Route($route_name, ['_class' => RouteManager::class, '_method' => 'onStaticRoute']);
//echo $path.PHP_EOL;
LightCacheInside::set("static_route", $route->getPath(), $path);
LightCacheInside::set('static_route', $route->getPath(), $path);
self::$routes->add(md5($route_name), $route);
}
public function onStaticRoute($params) {
$route_path = self::$routes->get($params["_route"])->getPath();
if(($path = LightCacheInside::get("static_route", $route_path)) === null) {
public function onStaticRoute($params)
{
$route_path = self::$routes->get($params['_route'])->getPath();
if (($path = LightCacheInside::get('static_route', $route_path)) === null) {
ctx()->getResponse()->endWithStatus(404);
return false;
}
unset($params["_route"]);
unset($params['_route']);
$obj = array_shift($params);
return new StaticFileHandler($obj, $path);
}
}
}

View File

@@ -1,25 +1,27 @@
<?php /** @noinspection PhpUnused */
<?php
/** @noinspection PhpUnused */
declare(strict_types=1);
namespace ZM\Utils\Manager;
use ZM\Console\Console;
class TaskManager
{
/**
* @param $task_name
* @param int $timeout
* @param mixed ...$params
* @param mixed ...$params
* @return false|mixed
*/
public static function runTask($task_name, int $timeout = -1, ...$params) {
if (!isset(server()->setting["task_worker_num"])) {
Console::warning(zm_internal_errcode("E00056") . "未开启 TaskWorker 进程,请先修改 global 配置文件启用!");
public static function runTask($task_name, int $timeout = -1, ...$params)
{
if (!isset(server()->setting['task_worker_num'])) {
Console::warning(zm_internal_errcode('E00056') . '未开启 TaskWorker 进程,请先修改 global 配置文件启用!');
return false;
}
$r = server()->taskwait(["task" => $task_name, "params" => $params], $timeout);
return $r === false ? false : $r["result"];
$r = server()->taskwait(['task' => $task_name, 'params' => $params], $timeout);
return $r === false ? false : $r['result'];
}
}
}

View File

@@ -1,5 +1,7 @@
<?php
declare(strict_types=1);
namespace ZM\Utils\Manager;
use Exception;
@@ -24,78 +26,78 @@ class WorkerManager
public static function workerAction($src_worker_id, $data)
{
$server = server();
switch ($data["action"] ?? '') {
switch ($data['action'] ?? '') {
case 'add_short_command':
Console::verbose("Adding short command " . $data["data"][0]);
Console::verbose('Adding short command ' . $data['data'][0]);
$obj = new CQCommand();
$obj->method = quick_reply_closure($data["data"][1]);
$obj->match = $data["data"][0];
$obj->class = "";
$obj->method = quick_reply_closure($data['data'][1]);
$obj->match = $data['data'][0];
$obj->class = '';
EventManager::addEvent(CQCommand::class, $obj);
break;
case "eval":
eval($data["data"]);
case 'eval':
eval($data['data']);
break;
case "call_static":
call_user_func_array([$data["data"]["class"], $data["data"]["method"]], $data["data"]["params"]);
case 'call_static':
call_user_func_array([$data['data']['class'], $data['data']['method']], $data['data']['params']);
break;
case "save_persistence":
case 'save_persistence':
LightCache::savePersistence();
break;
case "resume_ws_message":
$obj = $data["data"];
Coroutine::resume($obj["coroutine"]);
case 'resume_ws_message':
$obj = $data['data'];
Coroutine::resume($obj['coroutine']);
break;
case "getWorkerCache":
$r = WorkerCache::get($data["key"]);
$action = ["action" => "returnWorkerCache", "cid" => $data["cid"], "value" => $r];
case 'getWorkerCache':
$r = WorkerCache::get($data['key']);
$action = ['action' => 'returnWorkerCache', 'cid' => $data['cid'], 'value' => $r];
$server->sendMessage(json_encode($action, 256), $src_worker_id);
break;
case "setWorkerCache":
$r = WorkerCache::set($data["key"], $data["value"]);
$action = ["action" => "returnWorkerCache", "cid" => $data["cid"], "value" => $r];
case 'setWorkerCache':
$r = WorkerCache::set($data['key'], $data['value']);
$action = ['action' => 'returnWorkerCache', 'cid' => $data['cid'], 'value' => $r];
$server->sendMessage(json_encode($action, 256), $src_worker_id);
break;
case "unsetWorkerCache":
$r = WorkerCache::unset($data["key"]);
$action = ["action" => "returnWorkerCache", "cid" => $data["cid"], "value" => $r];
case 'unsetWorkerCache':
$r = WorkerCache::unset($data['key']);
$action = ['action' => 'returnWorkerCache', 'cid' => $data['cid'], 'value' => $r];
$server->sendMessage(json_encode($action, 256), $src_worker_id);
break;
case "hasKeyWorkerCache":
$r = WorkerCache::hasKey($data["key"], $data["subkey"]);
$action = ["action" => "returnWorkerCache", "cid" => $data["cid"], "value" => $r];
case 'hasKeyWorkerCache':
$r = WorkerCache::hasKey($data['key'], $data['subkey']);
$action = ['action' => 'returnWorkerCache', 'cid' => $data['cid'], 'value' => $r];
$server->sendMessage(json_encode($action, 256), $src_worker_id);
break;
case "asyncAddWorkerCache":
WorkerCache::add($data["key"], $data["value"], true);
case 'asyncAddWorkerCache':
WorkerCache::add($data['key'], $data['value'], true);
break;
case "asyncSubWorkerCache":
WorkerCache::sub($data["key"], $data["value"], true);
case 'asyncSubWorkerCache':
WorkerCache::sub($data['key'], $data['value'], true);
break;
case "asyncSetWorkerCache":
WorkerCache::set($data["key"], $data["value"], true);
case 'asyncSetWorkerCache':
WorkerCache::set($data['key'], $data['value'], true);
break;
case "asyncUnsetWorkerCache":
WorkerCache::unset($data["key"], true);
case 'asyncUnsetWorkerCache':
WorkerCache::unset($data['key'], true);
break;
case "addWorkerCache":
$r = WorkerCache::add($data["key"], $data["value"]);
$action = ["action" => "returnWorkerCache", "cid" => $data["cid"], "value" => $r];
case 'addWorkerCache':
$r = WorkerCache::add($data['key'], $data['value']);
$action = ['action' => 'returnWorkerCache', 'cid' => $data['cid'], 'value' => $r];
$server->sendMessage(json_encode($action, 256), $src_worker_id);
break;
case "subWorkerCache":
$r = WorkerCache::sub($data["key"], $data["value"]);
$action = ["action" => "returnWorkerCache", "cid" => $data["cid"], "value" => $r];
case 'subWorkerCache':
$r = WorkerCache::sub($data['key'], $data['value']);
$action = ['action' => 'returnWorkerCache', 'cid' => $data['cid'], 'value' => $r];
$server->sendMessage(json_encode($action, 256), $src_worker_id);
break;
case "returnWorkerCache":
WorkerCache::$transfer[$data["cid"]] = $data["value"];
zm_resume($data["cid"]);
case 'returnWorkerCache':
WorkerCache::$transfer[$data['cid']] = $data['value'];
zm_resume($data['cid']);
break;
default:
$dispatcher = new EventDispatcher(OnPipeMessageEvent::class);
$dispatcher->setRuleFunction(function (OnPipeMessageEvent $v) use ($data) {
return $v->action == $data["action"];
return $v->action == $data['action'];
});
$dispatcher->dispatchEvents($data);
break;
@@ -111,9 +113,9 @@ class WorkerManager
*/
public static function sendActionToWorker($worker_id, $action, $data)
{
$obj = ["action" => $action, "data" => $data];
$obj = ['action' => $action, 'data' => $data];
if (server()->worker_id === -1 && server()->getManagerPid() != posix_getpid()) {
Console::warning(zm_internal_errcode("E00022") . "Cannot send worker action from master or manager process!");
Console::warning(zm_internal_errcode('E00022') . 'Cannot send worker action from master or manager process!');
return;
}
if (server()->worker_id == $worker_id) {
@@ -132,10 +134,12 @@ class WorkerManager
Console::warning("Cannot call '" . __FUNCTION__ . "' in non-worker process!");
return;
}
foreach ((LightCacheInside::get("wait_api", "wait_api") ?? []) as $v) {
if (isset($v["coroutine"], $v["worker_id"])) {
if (server()->worker_id == $v["worker_id"]) Coroutine::resume($v["coroutine"]);
foreach ((LightCacheInside::get('wait_api', 'wait_api') ?? []) as $v) {
if (isset($v['coroutine'], $v['worker_id'])) {
if (server()->worker_id == $v['worker_id']) {
Coroutine::resume($v['coroutine']);
}
}
}
}
}
}