From e77b9d4970883640bc25419ea7e8a9815cd0be11 Mon Sep 17 00:00:00 2001 From: crazywhalecc Date: Thu, 18 Mar 2021 14:56:35 +0800 Subject: [PATCH] update to 2.3.1 version (build 388) cleanup code and fix a bug --- .entry.sh | 5 - bin/phpunit-swoole | 3 +- src/Custom/global_function.php | 5 + src/Module/Example/Hello.php | 5 +- src/Module/Middleware/TimerMiddleware.php | 2 +- src/ZM/API/CQ.php | 4 +- src/ZM/API/CQAPI.php | 3 +- src/ZM/API/ZMRobot.php | 4 +- src/ZM/Annotation/AnnotationBase.php | 2 +- src/ZM/Annotation/AnnotationParser.php | 13 +- src/ZM/Annotation/CQ/CQAfter.php | 2 +- src/ZM/Annotation/CQ/CQBefore.php | 2 +- src/ZM/Annotation/CQ/CQMessage.php | 2 +- src/ZM/Annotation/CQ/CQMetaEvent.php | 2 +- src/ZM/Annotation/Swoole/OnTask.php | 2 +- src/ZM/Command/BuildCommand.php | 2 +- src/ZM/Command/DaemonCommand.php | 2 +- src/ZM/Command/DaemonReloadCommand.php | 2 +- src/ZM/Command/DaemonStatusCommand.php | 2 +- src/ZM/Command/DaemonStopCommand.php | 2 +- src/ZM/Command/InitCommand.php | 4 +- src/ZM/Command/PureHttpCommand.php | 3 +- src/ZM/Command/RunServerCommand.php | 2 +- src/ZM/Command/SystemdCommand.php | 2 +- src/ZM/ConsoleApplication.php | 10 +- src/ZM/Context/Context.php | 34 ++- src/ZM/Context/ContextInterface.php | 2 +- src/ZM/DB/DB.php | 10 +- src/ZM/DB/SelectBody.php | 8 +- src/ZM/DB/Table.php | 4 +- src/ZM/DB/WhereBody.php | 2 +- src/ZM/Entity/CQObject.php | 2 +- src/ZM/Event/EventDispatcher.php | 18 +- src/ZM/Event/EventManager.php | 2 +- src/ZM/Event/ServerEventHandler.php | 2 +- src/ZM/Framework.php | 4 +- src/ZM/Http/Response.php | 4 +- src/ZM/Module/QQBot.php | 3 +- src/ZM/Store/LightCache.php | 12 +- src/ZM/Store/LightCacheInside.php | 20 +- src/ZM/Store/Lock/SpinLock.php | 4 +- src/ZM/Store/Redis/ZMRedis.php | 6 +- src/ZM/Store/WorkerCache.php | 2 +- src/ZM/Store/ZMAtomic.php | 2 +- src/ZM/Utils/CoMessage.php | 7 +- src/ZM/Utils/DataProvider.php | 4 +- src/ZM/Utils/HttpUtil.php | 3 +- src/ZM/Utils/MessageUtil.php | 7 +- src/ZM/Utils/ProcessManager.php | 2 +- src/ZM/Utils/SingletonTrait.php | 3 +- src/ZM/Utils/TaskManager.php | 9 +- src/ZM/Utils/Terminal.php | 4 +- src/ZM/Utils/ZMUtil.php | 7 + src/ZM/global_functions.php | 41 ++-- test/ZMTest/Mock/Context.php | 256 -------------------- test/ZMTest/Mock/global.php | 111 --------- test/ZMTest/Testing/EventDispatcherTest.php | 5 +- 57 files changed, 179 insertions(+), 508 deletions(-) delete mode 100644 .entry.sh delete mode 100644 test/ZMTest/Mock/Context.php delete mode 100644 test/ZMTest/Mock/global.php diff --git a/.entry.sh b/.entry.sh deleted file mode 100644 index 4e662904..00000000 --- a/.entry.sh +++ /dev/null @@ -1,5 +0,0 @@ -#!/bin/bash -if [ ! -d "/app/zhamao-framework/bin" ]; then - cp -r /app/zhamao-framework-bak/* /app/zhamao-framework/ -fi -php /app/zhamao-framework/bin/start diff --git a/bin/phpunit-swoole b/bin/phpunit-swoole index eec62ac2..b3580fb9 100755 --- a/bin/phpunit-swoole +++ b/bin/phpunit-swoole @@ -1,5 +1,5 @@ #!/usr/bin/env php - @@ -52,6 +52,7 @@ if (!defined('PHPUNIT_COMPOSER_INSTALL')) { } } } +/** @noinspection PhpIncludeInspection */ require PHPUNIT_COMPOSER_INSTALL; $starttime = microtime(true); go(function (){ diff --git a/src/Custom/global_function.php b/src/Custom/global_function.php index 471470ee..40b93e29 100644 --- a/src/Custom/global_function.php +++ b/src/Custom/global_function.php @@ -1,6 +1,11 @@ getRequest()->server['request_uri'] == '/favicon.ico'",level=200) + * @throws InterruptException */ public function onRequest() { EventDispatcher::interrupt(); diff --git a/src/Module/Middleware/TimerMiddleware.php b/src/Module/Middleware/TimerMiddleware.php index 95661b94..c99cb2b0 100644 --- a/src/Module/Middleware/TimerMiddleware.php +++ b/src/Module/Middleware/TimerMiddleware.php @@ -24,7 +24,7 @@ class TimerMiddleware implements MiddlewareInterface * @HandleBefore() * @return bool */ - public function onBefore() { + public function onBefore(): bool { $this->starttime = microtime(true); return true; } diff --git a/src/ZM/API/CQ.php b/src/ZM/API/CQ.php index 77a7da15..99e6f342 100644 --- a/src/ZM/API/CQ.php +++ b/src/ZM/API/CQ.php @@ -1,4 +1,6 @@ - $v) { $str .= "\n\t" . $k . " => "; diff --git a/src/ZM/Annotation/AnnotationParser.php b/src/ZM/Annotation/AnnotationParser.php index 4fdb1d85..a7b8d4d7 100644 --- a/src/ZM/Annotation/AnnotationParser.php +++ b/src/ZM/Annotation/AnnotationParser.php @@ -125,10 +125,7 @@ class AnnotationParser Console::debug("解析注解完毕!"); } - /** - * @return array - */ - public function generateAnnotationEvents() { + public function generateAnnotationEvents(): array { $o = []; foreach ($this->annotation_map as $module => $obj) { foreach (($obj["class_annotations"] ?? []) as $class_annotation) { @@ -151,17 +148,17 @@ class AnnotationParser /** * @return array */ - public function getMiddlewares() { return $this->middlewares; } + public function getMiddlewares(): array { return $this->middlewares; } /** * @return array */ - public function getMiddlewareMap() { return $this->middleware_map; } + public function getMiddlewareMap(): array { return $this->middleware_map; } /** * @return array */ - public function getReqMapping() { return $this->req_mapping; } + public function getReqMapping(): array { return $this->req_mapping; } /** * @param $path @@ -171,7 +168,7 @@ class AnnotationParser //private function below - private function registerMiddleware(MiddlewareClass $vs, ReflectionClass $reflection_class) { + private function registerMiddleware(MiddlewareClass $vs, ReflectionClass $reflection_class): array { $result = [ "class" => "\\" . $reflection_class->getName(), "name" => $vs->name diff --git a/src/ZM/Annotation/CQ/CQAfter.php b/src/ZM/Annotation/CQ/CQAfter.php index 75bfbbfe..e45821a8 100644 --- a/src/ZM/Annotation/CQ/CQAfter.php +++ b/src/ZM/Annotation/CQ/CQAfter.php @@ -26,7 +26,7 @@ class CQAfter extends AnnotationBase implements Level /** * @return mixed */ - public function getLevel() { + public function getLevel(): int { return $this->level; } diff --git a/src/ZM/Annotation/CQ/CQBefore.php b/src/ZM/Annotation/CQ/CQBefore.php index fc0daf75..5ec379b4 100644 --- a/src/ZM/Annotation/CQ/CQBefore.php +++ b/src/ZM/Annotation/CQ/CQBefore.php @@ -28,7 +28,7 @@ class CQBefore extends AnnotationBase implements Level /** * @return mixed */ - public function getLevel() { + public function getLevel(): int { return $this->level; } diff --git a/src/ZM/Annotation/CQ/CQMessage.php b/src/ZM/Annotation/CQ/CQMessage.php index c3906087..e10a7a29 100644 --- a/src/ZM/Annotation/CQ/CQMessage.php +++ b/src/ZM/Annotation/CQ/CQMessage.php @@ -32,7 +32,7 @@ class CQMessage extends AnnotationBase implements Level /** @var int */ public $level = 20; - public function getLevel() { return $this->level; } + public function getLevel(): int { return $this->level; } public function setLevel(int $level) { $this->level = $level; diff --git a/src/ZM/Annotation/CQ/CQMetaEvent.php b/src/ZM/Annotation/CQ/CQMetaEvent.php index 5c6a7526..3466d779 100644 --- a/src/ZM/Annotation/CQ/CQMetaEvent.php +++ b/src/ZM/Annotation/CQ/CQMetaEvent.php @@ -27,7 +27,7 @@ class CQMetaEvent extends AnnotationBase implements Level /** * @return mixed */ - public function getLevel() { return $this->level; } + public function getLevel(): int { return $this->level; } /** * @param int $level diff --git a/src/ZM/Annotation/Swoole/OnTask.php b/src/ZM/Annotation/Swoole/OnTask.php index 83565c09..b0ae0b68 100644 --- a/src/ZM/Annotation/Swoole/OnTask.php +++ b/src/ZM/Annotation/Swoole/OnTask.php @@ -30,7 +30,7 @@ class OnTask extends AnnotationBase implements Rule /** * @return mixed */ - public function getRule() { + public function getRule(): string { return $this->rule; } } \ No newline at end of file diff --git a/src/ZM/Command/BuildCommand.php b/src/ZM/Command/BuildCommand.php index 9fe3bc99..05dd9817 100644 --- a/src/ZM/Command/BuildCommand.php +++ b/src/ZM/Command/BuildCommand.php @@ -26,7 +26,7 @@ class BuildCommand extends Command // ... } - protected function execute(InputInterface $input, OutputInterface $output) { + protected function execute(InputInterface $input, OutputInterface $output): int { $this->output = $output; $target_dir = $input->getOption("target") ?? (__DIR__ . '/../../../resources/'); if (mb_strpos($target_dir, "../")) $target_dir = realpath($target_dir); diff --git a/src/ZM/Command/DaemonCommand.php b/src/ZM/Command/DaemonCommand.php index 6b01c7fc..6fe12460 100644 --- a/src/ZM/Command/DaemonCommand.php +++ b/src/ZM/Command/DaemonCommand.php @@ -13,7 +13,7 @@ abstract class DaemonCommand extends Command { protected $daemon_file = null; - protected function execute(InputInterface $input, OutputInterface $output) { + protected function execute(InputInterface $input, OutputInterface $output): int { $pid_path = DataProvider::getWorkingDir() . "/.daemon_pid"; if (!file_exists($pid_path)) { $output->writeln("没有检测到正在运行的守护进程!"); diff --git a/src/ZM/Command/DaemonReloadCommand.php b/src/ZM/Command/DaemonReloadCommand.php index 931c87c0..9e80385e 100644 --- a/src/ZM/Command/DaemonReloadCommand.php +++ b/src/ZM/Command/DaemonReloadCommand.php @@ -15,7 +15,7 @@ class DaemonReloadCommand extends DaemonCommand $this->setDescription("重载守护进程下的用户代码(仅限--daemon模式可用)"); } - protected function execute(InputInterface $input, OutputInterface $output) { + protected function execute(InputInterface $input, OutputInterface $output): int { parent::execute($input, $output); system("kill -USR1 " . intval($this->daemon_file["pid"])); $output->writeln("成功重载!"); diff --git a/src/ZM/Command/DaemonStatusCommand.php b/src/ZM/Command/DaemonStatusCommand.php index a1c8403f..263b55d2 100644 --- a/src/ZM/Command/DaemonStatusCommand.php +++ b/src/ZM/Command/DaemonStatusCommand.php @@ -15,7 +15,7 @@ class DaemonStatusCommand extends DaemonCommand $this->setDescription("查看守护进程框架的运行状态(仅限--daemon模式可用)"); } - protected function execute(InputInterface $input, OutputInterface $output) { + protected function execute(InputInterface $input, OutputInterface $output): int { parent::execute($input, $output); $output->writeln("框架运行中,pid:" . $this->daemon_file["pid"] . ""); $output->writeln("----- 以下是stdout内容 -----"); diff --git a/src/ZM/Command/DaemonStopCommand.php b/src/ZM/Command/DaemonStopCommand.php index b4140eaa..3a10f45b 100644 --- a/src/ZM/Command/DaemonStopCommand.php +++ b/src/ZM/Command/DaemonStopCommand.php @@ -16,7 +16,7 @@ class DaemonStopCommand extends DaemonCommand $this->setDescription("停止守护进程下运行的框架(仅限--daemon模式可用)"); } - protected function execute(InputInterface $input, OutputInterface $output) { + protected function execute(InputInterface $input, OutputInterface $output): int { parent::execute($input, $output); system("kill -TERM " . intval($this->daemon_file["pid"])); unlink(DataProvider::getWorkingDir() . "/.daemon_pid"); diff --git a/src/ZM/Command/InitCommand.php b/src/ZM/Command/InitCommand.php index 4e837f28..6fa35f7b 100644 --- a/src/ZM/Command/InitCommand.php +++ b/src/ZM/Command/InitCommand.php @@ -30,7 +30,7 @@ class InitCommand extends Command // ... } - protected function execute(InputInterface $input, OutputInterface $output) { + protected function execute(InputInterface $input, OutputInterface $output): int { if (LOAD_MODE === 1) { // 从composer依赖而来的项目模式,最基本的需要初始化的模式 $output->writeln("Initializing files"); $base_path = LOAD_MODE_COMPOSER_PATH; @@ -96,7 +96,7 @@ class InitCommand extends Command return Command::FAILURE; } - private function getExtractFiles() { + private function getExtractFiles(): array { return $this->extract_files; } } diff --git a/src/ZM/Command/PureHttpCommand.php b/src/ZM/Command/PureHttpCommand.php index ccaf70d6..4b246712 100644 --- a/src/ZM/Command/PureHttpCommand.php +++ b/src/ZM/Command/PureHttpCommand.php @@ -5,7 +5,6 @@ namespace ZM\Command; use Swoole\Atomic; -use Swoole\Coroutine; use Swoole\Http\Request; use Swoole\Http\Response; use Swoole\Http\Server; @@ -36,7 +35,7 @@ class PureHttpCommand extends Command // ... } - protected function execute(InputInterface $input, OutputInterface $output) { + protected function execute(InputInterface $input, OutputInterface $output): int { $tty_width = explode(" ", trim(exec("stty size")))[1]; if (realpath($input->getArgument('dir') ?? '.') === false) { $output->writeln("Directory error(" . ($input->getArgument('dir') ?? '.') . "): no such file or directory."); diff --git a/src/ZM/Command/RunServerCommand.php b/src/ZM/Command/RunServerCommand.php index 9b043b2b..c5a93d6d 100644 --- a/src/ZM/Command/RunServerCommand.php +++ b/src/ZM/Command/RunServerCommand.php @@ -33,7 +33,7 @@ class RunServerCommand extends Command $this->setHelp("直接运行可以启动"); } - protected function execute(InputInterface $input, OutputInterface $output) { + protected function execute(InputInterface $input, OutputInterface $output): int { if (($opt = $input->getOption("env")) !== null) { if (!in_array($opt, ["production", "staging", "development", ""])) { $output->writeln(" \"--env\" option only accept production, development, staging and [empty] ! "); diff --git a/src/ZM/Command/SystemdCommand.php b/src/ZM/Command/SystemdCommand.php index 8cea8607..bf6a804f 100644 --- a/src/ZM/Command/SystemdCommand.php +++ b/src/ZM/Command/SystemdCommand.php @@ -13,7 +13,7 @@ class SystemdCommand extends Command // the name of the command (the part after "bin/console") protected static $defaultName = 'systemd:generate'; - protected function execute(InputInterface $input, OutputInterface $output) { + protected function execute(InputInterface $input, OutputInterface $output): int { //TODO: 写一个生成systemd配置的功能,给2.0 return Command::SUCCESS; } diff --git a/src/ZM/ConsoleApplication.php b/src/ZM/ConsoleApplication.php index 446b0c6b..760b0b96 100644 --- a/src/ZM/ConsoleApplication.php +++ b/src/ZM/ConsoleApplication.php @@ -18,8 +18,8 @@ use ZM\Utils\DataProvider; class ConsoleApplication extends Application { - const VERSION_ID = 387; - const VERSION = "2.3.0"; + const VERSION_ID = 388; + const VERSION = "2.3.1"; public function __construct(string $name = 'UNKNOWN') { define("ZM_VERSION_ID", self::VERSION_ID); @@ -27,7 +27,7 @@ class ConsoleApplication extends Application parent::__construct($name, ZM_VERSION); } - public function initEnv() { + public function initEnv(): ConsoleApplication { $this->selfCheck(); if (!is_dir(__DIR__ . '/../../vendor')) { @@ -90,7 +90,7 @@ class ConsoleApplication extends Application * @param OutputInterface|null $output * @return int */ - public function run(InputInterface $input = null, OutputInterface $output = null) { + public function run(InputInterface $input = null, OutputInterface $output = null): int { try { return parent::run($input, $output); } catch (Exception $e) { @@ -98,7 +98,7 @@ class ConsoleApplication extends Application } } - private function selfCheck() { + private function selfCheck(): bool { if (!extension_loaded("swoole")) die("Can not find swoole extension.\nSee: https://github.com/zhamao-robot/zhamao-framework/issues/19\n"); if (version_compare(SWOOLE_VERSION, "4.4.13") == -1) die("You must install swoole version >= 4.4.13 !"); if (version_compare(PHP_VERSION, "7.2") == -1) die("PHP >= 7.2 required."); diff --git a/src/ZM/Context/Context.php b/src/ZM/Context/Context.php index b6feb33c..c40b3443 100644 --- a/src/ZM/Context/Context.php +++ b/src/ZM/Context/Context.php @@ -8,11 +8,12 @@ use Co; use Exception; use Swoole\Http\Request; use Swoole\WebSocket\Frame; -use swoole_server; +use Swoole\WebSocket\Server; use ZM\ConnectionManager\ConnectionObject; use ZM\ConnectionManager\ManagerGM; use ZM\Console\Console; use ZM\Event\EventDispatcher; +use ZM\Exception\InterruptException; use ZM\Exception\InvalidArgumentException; use ZM\Exception\WaitTimeoutException; use ZM\Http\Response; @@ -27,19 +28,19 @@ class Context implements ContextInterface public function __construct($cid) { $this->cid = $cid; } /** - * @return swoole_server|null + * @return Server */ - public function getServer() { return self::$context[$this->cid]["server"] ?? server(); } + public function getServer(): ?Server { return self::$context[$this->cid]["server"] ?? server(); } /** * @return Frame|null */ - public function getFrame() { return self::$context[$this->cid]["frame"] ?? null; } + public function getFrame(): ?Frame { return self::$context[$this->cid]["frame"] ?? null; } - public function getFd() { return self::$context[$this->cid]["fd"] ?? $this->getFrame()->fd ?? null; } + public function getFd(): ?int { return self::$context[$this->cid]["fd"] ?? $this->getFrame()->fd ?? null; } /** - * @return array|null + * @return mixed */ public function getData() { return self::$context[$this->cid]["data"] ?? null; } @@ -48,25 +49,25 @@ class Context implements ContextInterface /** * @return Request|null */ - public function getRequest() { return self::$context[$this->cid]["request"] ?? null; } + public function getRequest(): ?Request { return self::$context[$this->cid]["request"] ?? null; } /** * @return Response|null */ - public function getResponse() { return self::$context[$this->cid]["response"] ?? null; } + public function getResponse(): ?Response { return self::$context[$this->cid]["response"] ?? null; } - /** @return ConnectionObject|null */ + /** @return ConnectionObject|null|Response */ public function getConnection() { return ManagerGM::get($this->getFd()); } /** * @return int|null */ - public function getCid() { return $this->cid; } + public function getCid(): ?int { return $this->cid; } /** * @return ZMRobot|null */ - public function getRobot() { + public function getRobot(): ?ZMRobot { $conn = ManagerGM::get($this->getFrame()->fd); return $conn instanceof ConnectionObject ? new ZMRobot($conn) : null; } @@ -87,7 +88,7 @@ class Context implements ContextInterface public function setDiscussId($id) { self::$context[$this->cid]["data"]["discuss_id"] = $id; } - public function getMessageType() { return $this->getData()["message_type"] ?? null; } + public function getMessageType(): ?string { return $this->getData()["message_type"] ?? null; } public function setMessageType($type) { self::$context[$this->cid]["data"]["message_type"] = $type; } @@ -104,6 +105,7 @@ class Context implements ContextInterface * @param $msg * @param bool $yield * @return mixed + * @noinspection PhpMissingReturnTypeInspection */ public function reply($msg, $yield = false) { $data = $this->getData(); @@ -131,6 +133,12 @@ class Context implements ContextInterface } } + /** + * @param $msg + * @param false $yield + * @return mixed|void + * @throws InterruptException + */ public function finalReply($msg, $yield = false) { self::$context[$this->cid]["cache"]["block_continue"] = true; if ($msg != "") $this->reply($msg, $yield); @@ -144,6 +152,7 @@ class Context implements ContextInterface * @return string * @throws InvalidArgumentException * @throws WaitTimeoutException + * @noinspection PhpMissingReturnTypeInspection */ public function waitMessage($prompt = "", $timeout = 600, $timeout_prompt = "") { if (!isset($this->getData()["user_id"], $this->getData()["message"], $this->getData()["self_id"])) @@ -258,6 +267,7 @@ class Context implements ContextInterface */ public function getNumArg($prompt_msg = "") { return $this->getArgs(ZM_MATCH_NUMBER, $prompt_msg); } + /** @noinspection PhpMissingReturnTypeInspection */ public function cloneFromParent() { set_coroutine_params(self::$context[Co::getPcid()] ?? self::$context[$this->cid]); return context(); diff --git a/src/ZM/Context/ContextInterface.php b/src/ZM/Context/ContextInterface.php index 249cf900..8b7554d8 100644 --- a/src/ZM/Context/ContextInterface.php +++ b/src/ZM/Context/ContextInterface.php @@ -1,4 +1,4 @@ -get(); if ($conn === false) { @@ -134,7 +136,7 @@ class DB } } - public static function isTableExists($table) { + public static function isTableExists($table): bool { return in_array($table, self::$table_list); } } diff --git a/src/ZM/DB/SelectBody.php b/src/ZM/DB/SelectBody.php index 903916db..352397ff 100644 --- a/src/ZM/DB/SelectBody.php +++ b/src/ZM/DB/SelectBody.php @@ -32,7 +32,7 @@ class SelectBody /** * @throws DbException */ - public function count() { + public function count(): int { $this->select_thing = ["count(*)"]; $str = $this->queryPrepare(); $this->result = DB::rawQuery($str[0], $str[1]); @@ -81,7 +81,7 @@ class SelectBody public function getResult() { return $this->result; } - public function equals(SelectBody $body) { + public function equals(SelectBody $body): bool { if ($this->select_thing != $body->getSelectThing()) return false; elseif ($this->where_thing == $body->getWhereThing()) return false; else return true; @@ -95,9 +95,9 @@ class SelectBody /** * @return array */ - public function getWhereThing() { return $this->where_thing; } + public function getWhereThing(): array { return $this->where_thing; } - private function queryPrepare() { + private function queryPrepare(): array { $msg = "SELECT " . implode(", ", $this->select_thing) . " FROM " . $this->table->getTableName(); $sql = $this->table->paintWhereSQL($this->where_thing['='] ?? [], '='); if ($sql[0] != '') { diff --git a/src/ZM/DB/Table.php b/src/ZM/DB/Table.php index 4080d01b..dc2e8155 100644 --- a/src/ZM/DB/Table.php +++ b/src/ZM/DB/Table.php @@ -1,4 +1,6 @@ -class = $class; - try { - $this->eid = ZMAtomic::get("_event_id")->add(1); - $list = LightCacheInside::get("wait_api", "event_trace"); - } catch (ZMException $e) { - $list = []; - } + $this->eid = ZMAtomic::get("_event_id")->add(1); + $list = LightCacheInside::get("wait_api", "event_trace"); if (isset($list[$class])) $this->log = true; if ($this->log) Console::verbose("[事件分发{$this->eid}] 开始分发事件: " . $class); } - public function setRuleFunction(callable $rule = null) { + public function setRuleFunction(callable $rule = null): EventDispatcher { $this->rule = $rule; return $this; } - public function setReturnFunction(callable $return_func) { + public function setReturnFunction(callable $return_func): EventDispatcher { $this->return_func = $return_func; return $this; } @@ -117,6 +112,7 @@ class EventDispatcher * @return bool * @throws InterruptException * @throws AnnotationException + * @noinspection PhpMissingReturnTypeInspection */ public function dispatchEvent($v, $rule_func = null, ...$params) { $q_c = $v->class; diff --git a/src/ZM/Event/EventManager.php b/src/ZM/Event/EventManager.php index 221b649a..e25ea2f4 100644 --- a/src/ZM/Event/EventManager.php +++ b/src/ZM/Event/EventManager.php @@ -9,7 +9,6 @@ use Exception; use Swoole\Timer; use ZM\Annotation\AnnotationBase; use ZM\Annotation\AnnotationParser; -use ZM\Annotation\Swoole\OnSave; use ZM\Annotation\Swoole\OnTick; use ZM\Config\ZMConfig; use ZM\Console\Console; @@ -37,6 +36,7 @@ class EventManager /** * 注册所有计时器给每个进程 + * @throws Exception */ public static function registerTimerTick() { $dispatcher = new EventDispatcher(OnTick::class); diff --git a/src/ZM/Event/ServerEventHandler.php b/src/ZM/Event/ServerEventHandler.php index 2f058a98..1167e61c 100644 --- a/src/ZM/Event/ServerEventHandler.php +++ b/src/ZM/Event/ServerEventHandler.php @@ -127,6 +127,7 @@ class ServerEventHandler * @SwooleHandler("WorkerStop") * @param $server * @param $worker_id + * @throws Exception */ public function onWorkerStop(Server $server, $worker_id) { if ($worker_id == (ZMConfig::get("worker_cache")["worker"] ?? 0)) { @@ -598,7 +599,6 @@ class ServerEventHandler * @param Server|null $server * @param Server\Task $task * @noinspection PhpUnusedParameterInspection - * @return null */ public function onTask(?Server $server, Server\Task $task) { if (isset($task->data["task"])) { diff --git a/src/ZM/Framework.php b/src/ZM/Framework.php index 4f0c8cce..c164aeb0 100644 --- a/src/ZM/Framework.php +++ b/src/ZM/Framework.php @@ -340,7 +340,7 @@ class Framework } else { // 输出很小,写到前面并分片 //Console::info("输出很小,写到前面并分片"); $space = intval($max_border / 2) - 2 - strlen($tmp_line); - $line_data[$current_line] .= str_pad("", $space, " "); + $line_data[$current_line] .= str_pad("", $space); $line_data[$current_line] .= "| "; // 添加分片 $line_width[$current_line] -= (strlen($tmp_line) + 3 + $space); } @@ -392,7 +392,7 @@ class Framework echo str_pad("", $max_border, "=") . PHP_EOL; } - public static function getTtyWidth() { + public static function getTtyWidth(): string { return explode(" ", trim(exec("stty size")))[1]; } } diff --git a/src/ZM/Http/Response.php b/src/ZM/Http/Response.php index be979934..08a6d062 100644 --- a/src/ZM/Http/Response.php +++ b/src/ZM/Http/Response.php @@ -1,4 +1,6 @@ -setRuleFunction(function ($v) use ($data) { return $v->cq_event == $data["post_type"]; @@ -70,6 +70,7 @@ class QQBot /** * @param $data * @throws InterruptException + * @throws Exception */ private function dispatchEvents($data) { //Console::warning("最xia数据包:".json_encode($data)); diff --git a/src/ZM/Store/LightCache.php b/src/ZM/Store/LightCache.php index 373b6bc7..060cc0cf 100644 --- a/src/ZM/Store/LightCache.php +++ b/src/ZM/Store/LightCache.php @@ -27,6 +27,7 @@ class LightCache * @param $config * @return bool|mixed * @throws Exception + * @noinspection PhpMissingReturnTypeInspection */ public static function init($config) { self::$config = $config; @@ -87,6 +88,7 @@ class LightCache * @param int $expire * @return mixed * @throws ZMException + * @noinspection PhpMissingReturnTypeInspection */ public static function set(string $key, $value, int $expire = -1) { if (self::$kv_table === null) throw new ZMException("not initialized LightCache"); @@ -120,6 +122,7 @@ class LightCache * @param $value * @return bool|mixed * @throws ZMException + * @noinspection PhpMissingReturnTypeInspection */ public static function update(string $key, $value) { if (self::$kv_table === null) throw new ZMException("not initialized LightCache."); @@ -154,7 +157,7 @@ class LightCache * @return bool * @throws Exception */ - public static function isset(string $key) { + public static function isset(string $key): bool { return self::get($key) !== null; } @@ -162,7 +165,7 @@ class LightCache return self::$kv_table->del($key); } - public static function getAll() { + public static function getAll(): array { $r = []; $del = []; foreach (self::$kv_table as $k => $v) { @@ -178,8 +181,11 @@ class LightCache return $r; } + /** + * @param false $only_worker + * @throws Exception + */ public static function savePersistence($only_worker = false) { - // 下面将OnSave激活一下 if (server()->worker_id == (ZMConfig::get("global", "worker_cache")["worker"] ?? 0)) { $dispatcher = new EventDispatcher(OnSave::class); diff --git a/src/ZM/Store/LightCacheInside.php b/src/ZM/Store/LightCacheInside.php index 4f10e301..b9bcc81a 100644 --- a/src/ZM/Store/LightCacheInside.php +++ b/src/ZM/Store/LightCacheInside.php @@ -13,12 +13,14 @@ class LightCacheInside /** @var Table[]|null */ private static $kv_table = []; - public static $last_error = ''; - - public static function init() { - self::createTable("wait_api", 3, 65536); //用于存协程等待的状态内容的 - self::createTable("connect", 3, 64); //用于存单机器人模式下的机器人fd的 - self::createTable("static_route", 64, 256);//用于存储 + public static function init(): bool { + try { + self::createTable("wait_api", 3, 65536); + self::createTable("connect", 3, 64); //用于存单机器人模式下的机器人fd的 + self::createTable("static_route", 64, 256);//用于存储 + } catch (ZMException $e) { + return false; + } //用于存协程等待的状态内容的 //self::createTable("worker_start", 2, 1024);//用于存启动服务器时的状态的 return true; } @@ -27,10 +29,8 @@ class LightCacheInside * @param string $table * @param string $key * @return mixed|null - * @throws ZMException */ public static function get(string $table, string $key) { - if (!isset(self::$kv_table[$table])) throw new ZMException("not initialized LightCache"); $r = self::$kv_table[$table]->get($key); return $r === false ? null : json_decode($r["value"], true); } @@ -40,10 +40,8 @@ class LightCacheInside * @param string $key * @param string|array|int $value * @return mixed - * @throws ZMException */ - public static function set(string $table, string $key, $value) { - if (self::$kv_table === null) throw new ZMException("not initialized LightCache"); + public static function set(string $table, string $key, $value): bool { try { return self::$kv_table[$table]->set($key, [ "value" => json_encode($value, 256) diff --git a/src/ZM/Store/Lock/SpinLock.php b/src/ZM/Store/Lock/SpinLock.php index 194e120a..55e632e7 100644 --- a/src/ZM/Store/Lock/SpinLock.php +++ b/src/ZM/Store/Lock/SpinLock.php @@ -1,4 +1,4 @@ -incr($key, 'lock_num')) > 1) { return false; } diff --git a/src/ZM/Store/Redis/ZMRedis.php b/src/ZM/Store/Redis/ZMRedis.php index 7d888242..ad9c53df 100644 --- a/src/ZM/Store/Redis/ZMRedis.php +++ b/src/ZM/Store/Redis/ZMRedis.php @@ -1,4 +1,6 @@ -conn; } diff --git a/src/ZM/Store/WorkerCache.php b/src/ZM/Store/WorkerCache.php index 023ff69a..ce38d2c5 100644 --- a/src/ZM/Store/WorkerCache.php +++ b/src/ZM/Store/WorkerCache.php @@ -1,4 +1,4 @@ -getData(); $last = null; SpinLock::lock("wait_api"); diff --git a/src/ZM/Utils/DataProvider.php b/src/ZM/Utils/DataProvider.php index ccfc6981..23513dc9 100644 --- a/src/ZM/Utils/DataProvider.php +++ b/src/ZM/Utils/DataProvider.php @@ -1,4 +1,4 @@ -setMethod($request->server['request_method']); diff --git a/src/ZM/Utils/MessageUtil.php b/src/ZM/Utils/MessageUtil.php index 22ca5cbc..1396d703 100644 --- a/src/ZM/Utils/MessageUtil.php +++ b/src/ZM/Utils/MessageUtil.php @@ -1,4 +1,4 @@ -type == "image") { @@ -65,7 +64,7 @@ class MessageUtil * @param int $type * @return string */ - public static function getImageCQFromLocal($file, $type = 0) { + public static function getImageCQFromLocal($file, $type = 0): string { switch ($type) { case 0: return CQ::image("base64://" . base64_encode(file_get_contents($file))); diff --git a/src/ZM/Utils/ProcessManager.php b/src/ZM/Utils/ProcessManager.php index 13ef40f8..83b65ac5 100644 --- a/src/ZM/Utils/ProcessManager.php +++ b/src/ZM/Utils/ProcessManager.php @@ -1,4 +1,4 @@ -setting["task_worker_num"])) { Console::warning("未开启 TaskWorker 进程,请先修改 global 配置文件启用!"); diff --git a/src/ZM/Utils/Terminal.php b/src/ZM/Utils/Terminal.php index 9d41eeb2..fc01cc82 100644 --- a/src/ZM/Utils/Terminal.php +++ b/src/ZM/Utils/Terminal.php @@ -1,4 +1,4 @@ -stop(); } + /** + * @param int $delay + * @throws Exception + */ public static function reload($delay = 800) { if (server()->worker_id !== -1) { Console::info(server()->worker_id); diff --git a/src/ZM/global_functions.php b/src/ZM/global_functions.php index fdec70d0..14e790dd 100644 --- a/src/ZM/global_functions.php +++ b/src/ZM/global_functions.php @@ -1,6 +1,8 @@ -getConnection()->getName() == 'qq'; } -function connectIsDefault() { +function connectIsDefault(): bool { return ctx()->getConnection()->getName() == 'default'; } -function connectIs($type) { +function connectIs($type): bool { return ctx()->getConnection()->getName() == $type; } -function getAnnotations() { +function getAnnotations(): array { $s = debug_backtrace()[1]; //echo json_encode($s, 128|256); $list = []; @@ -218,14 +221,14 @@ function set_coroutine_params($array) { /** * @return ContextInterface|null */ -function context() { +function context(): ?ContextInterface { return ctx(); } /** * @return ContextInterface|null */ -function ctx() { +function ctx(): ?ContextInterface { $cid = Co::getCid(); $c_class = ZMConfig::get("global", "context_class"); if (isset(Context::$context[$cid])) { @@ -242,11 +245,11 @@ function ctx() { function zm_debug($msg) { Console::debug($msg); } -function onebot_target_id_name($message_type) { +function onebot_target_id_name($message_type): string { return ($message_type == "group" ? "group_id" : "user_id"); } -function zm_sleep($s = 1) { +function zm_sleep($s = 1): bool { if (Coroutine::getCid() != -1) System::sleep($s); else usleep($s * 1000 * 1000); return true; @@ -291,11 +294,11 @@ function zm_timer_tick($ms, callable $callable) { } } -function zm_data_hash($v) { +function zm_data_hash($v): string { return md5($v["user_id"] . "^" . $v["self_id"] . "^" . $v["message_type"] . "^" . ($v[$v["message_type"] . "_id"] ?? $v["user_id"])); } -function server() { +function server(): ?Server { return Framework::$server; } @@ -304,7 +307,7 @@ function server() { * @throws RobotNotFoundException * @throws ZMException */ -function bot() { +function bot(): ZMRobot { if (($conn = LightCacheInside::get("connect", "conn_fd")) == -2) { return ZMRobot::getRandom(); } elseif ($conn != -1) { @@ -329,11 +332,11 @@ function getAllFdByConnectType(string $type = 'default'): array { return $fds; } -function zm_atomic($name) { - return \ZM\Store\ZMAtomic::get($name); +function zm_atomic($name): ?Atomic { + return ZMAtomic::get($name); } -function uuidgen($uppercase = false) { +function uuidgen($uppercase = false): string { try { $data = random_bytes(16); } catch (Exception $e) { diff --git a/test/ZMTest/Mock/Context.php b/test/ZMTest/Mock/Context.php deleted file mode 100644 index 5992f718..00000000 --- a/test/ZMTest/Mock/Context.php +++ /dev/null @@ -1,256 +0,0 @@ -set参数 */ -$config['swoole'] = [ - 'log_file' => $config['crash_dir'] . 'swoole_error.log', - 'worker_num' => 8, - 'dispatch_mode' => 2, - 'max_coroutine' => 30000, - //'task_worker_num' => 4, - //'task_enable_coroutine' => true -]; - -/** 轻量字符串缓存,默认开启 */ -$config['light_cache'] = [ - "status" => true, - "size" => 2048, //最多允许储存的条数(需要2的倍数) - "max_strlen" => 4096, //单行字符串最大长度(需要2的倍数) - "hash_conflict_proportion" => 0.6 //Hash冲突率(越大越好,但是需要的内存更多) -]; - -/** MySQL数据库连接信息,host留空则启动时不创建sql连接池 */ -$config['sql_config'] = [ - 'sql_host' => '', - 'sql_port' => 3306, - 'sql_username' => 'name', - 'sql_database' => 'db_name', - 'sql_password' => '', - 'sql_enable_cache' => true, - 'sql_reset_cache' => '0300', - 'sql_options' => [ - PDO::ATTR_STRINGIFY_FETCHES => false, - PDO::ATTR_EMULATE_PREPARES => false - ], - 'sql_no_exception' => false, - 'sql_default_fetch_mode' => PDO::FETCH_ASSOC // added in 1.5.6 -]; - -/** CQHTTP连接约定的token */ -$config["access_token"] = ""; - -/** HTTP服务器固定请求头的返回 */ -$config['http_header'] = [ - 'X-Powered-By' => 'zhamao-framework', - 'Content-Type' => 'text/html; charset=utf-8' -]; - -/** HTTP服务器在指定状态码下回复的页面(默认) */ -$config['http_default_code_page'] = [ - '404' => '404.html' -]; - -/** zhamao-framework在框架启动时初始化的atomic们 */ -$config['init_atomics'] = [ - //'custom_atomic_name' => 0, //自定义添加的Atomic -]; - -/** 终端日志显示等级(0-4) */ -$config["info_level"] = 2; - -/** 自动保存计时器的缓存保存时间(秒) */ -$config['auto_save_interval'] = 900; - -/** 上下文接口类 implemented from ContextInterface */ -$config['context_class'] = \ZMTest\Mock\Context::class; - -/** 静态文件访问 */ -$config['static_file_server'] = [ - 'status' => false, - 'document_root' => realpath(__DIR__ . "/../") . '/resources/html', - 'document_index' => [ - 'index.html' - ] -]; - -/** 注册 Swoole Server 事件注解的类列表 */ -$config['server_event_handler_class'] = [ - \ZM\Event\ServerEventHandler::class, -]; - -/** 注册自定义指令的类 */ -$config['command_register_class'] = [ - //\Custom\Command\CustomCommand::class -]; - -/** 服务器启用的外部第三方和内部插件 */ -$config['modules'] = [ - 'onebot' => true, // QQ机器人事件解析器,如果取消此项则默认为 true 开启状态,否则你手动填写 false 才会关闭 -]; - -return $config; diff --git a/test/ZMTest/Testing/EventDispatcherTest.php b/test/ZMTest/Testing/EventDispatcherTest.php index 26984427..49c8e639 100644 --- a/test/ZMTest/Testing/EventDispatcherTest.php +++ b/test/ZMTest/Testing/EventDispatcherTest.php @@ -40,10 +40,7 @@ class EventDispatcherTest extends TestCase $dispatcher->setRuleFunction(function ($v) { return $v->match == "你好"; }); //$dispatcher->setRuleFunction(fn ($v) => $v->match == "qwe"); ob_start(); - try { - $dispatcher->dispatchEvents(); - } catch (AnnotationException $e) { - } + $dispatcher->dispatchEvents(); $r = ob_get_clean(); echo $r; $this->assertStringContainsString("你好啊", $r);