diff --git a/docs/guide/quickstart-robot.md b/docs/guide/quickstart-robot.md index f94df246..5c1280d5 100644 --- a/docs/guide/quickstart-robot.md +++ b/docs/guide/quickstart-robot.md @@ -224,5 +224,14 @@ public function repeat() { 这样,一个简易的复读机就做好了!回到 QQ 机器人聊天,向机器人发送 `echo 你好啊`,它会回复你 `你好啊`。 + +) echo 你好啊 +( 你好啊 +) echo +( 请输入你要回复的内容 +) 哦豁,完蛋 +( 哦豁,完蛋 + + > 如果你只回复 `echo` 的话,它会先和你进入一个会话状态,并问你 `请输入你要回复的内容`,这时你再次说一些内容例如 `哦豁`,会回复你 `哦豁`。效果和直接输入 `echo 哦豁` 是一致的,这是炸毛框架内的一个封装好的命令参数对话询问功能。有关参数询问功能,请看后面的进阶模块。 diff --git a/src/ZM/API/CQ.php b/src/ZM/API/CQ.php index ea8908ed..fa7e45e4 100644 --- a/src/ZM/API/CQ.php +++ b/src/ZM/API/CQ.php @@ -130,7 +130,7 @@ class CQ * @return string */ public static function anonymous($ignore = 1) { - return "[CQ:anonymous".($ignore != 1 ? ",ignore=0" : "")."]"; + return "[CQ:anonymous" . ($ignore != 1 ? ",ignore=0" : "") . "]"; } /** @@ -208,7 +208,7 @@ class CQ } public static function node($user_id, $nickname, $content) { - return "[CQ:node,user_id=$user_id,nickname=$nickname,content=".self::escape($content)."]"; + return "[CQ:node,user_id=$user_id,nickname=$nickname,content=" . self::escape($content) . "]"; } /** diff --git a/src/ZM/API/ZMRobot.php b/src/ZM/API/ZMRobot.php index 027fe0ac..d28f6c36 100644 --- a/src/ZM/API/ZMRobot.php +++ b/src/ZM/API/ZMRobot.php @@ -59,7 +59,7 @@ class ZMRobot public static function getAllRobot() { $r = ManagerGM::getAllByName('qq'); $obj = []; - foreach($r as $v) { + foreach ($r as $v) { $obj[] = new ZMRobot($v); } return $obj; diff --git a/src/ZM/Annotation/AnnotationParser.php b/src/ZM/Annotation/AnnotationParser.php index 56e19158..4fdb1d85 100644 --- a/src/ZM/Annotation/AnnotationParser.php +++ b/src/ZM/Annotation/AnnotationParser.php @@ -47,7 +47,7 @@ class AnnotationParser */ public function registerMods() { foreach ($this->path_list as $path) { - Console::debug("parsing annotation in ".$path[0]); + Console::debug("parsing annotation in " . $path[0]); $all_class = getAllClasses($path[0], $path[1]); $this->reader = new AnnotationReader(); foreach ($all_class as $v) { diff --git a/src/ZM/Command/BuildCommand.php b/src/ZM/Command/BuildCommand.php index 956a3c53..9fe3bc99 100644 --- a/src/ZM/Command/BuildCommand.php +++ b/src/ZM/Command/BuildCommand.php @@ -31,7 +31,7 @@ class BuildCommand extends Command $target_dir = $input->getOption("target") ?? (__DIR__ . '/../../../resources/'); if (mb_strpos($target_dir, "../")) $target_dir = realpath($target_dir); if ($target_dir === false) { - $output->writeln(TermColor::color8(31) . "Error: No such file or directory (".__DIR__ . '/../../../resources/'.")" . TermColor::RESET); + $output->writeln(TermColor::color8(31) . "Error: No such file or directory (" . __DIR__ . '/../../../resources/' . ")" . TermColor::RESET); return Command::FAILURE; } $output->writeln("Target: " . $target_dir . " , Version: " . ($version = json_decode(file_get_contents(__DIR__ . "/../../../composer.json"), true)["version"])); @@ -51,7 +51,7 @@ class BuildCommand extends Command return Command::SUCCESS; } - private function build ($target_dir, $filename) { + private function build($target_dir, $filename) { @unlink($target_dir . $filename); $phar = new Phar($target_dir . $filename); $phar->startBuffering(); diff --git a/src/ZM/Command/DaemonStopCommand.php b/src/ZM/Command/DaemonStopCommand.php index 754965b3..b4140eaa 100644 --- a/src/ZM/Command/DaemonStopCommand.php +++ b/src/ZM/Command/DaemonStopCommand.php @@ -18,8 +18,8 @@ class DaemonStopCommand extends DaemonCommand protected function execute(InputInterface $input, OutputInterface $output) { parent::execute($input, $output); - system("kill -TERM ".intval($this->daemon_file["pid"])); - unlink(DataProvider::getWorkingDir()."/.daemon_pid"); + system("kill -TERM " . intval($this->daemon_file["pid"])); + unlink(DataProvider::getWorkingDir() . "/.daemon_pid"); $output->writeln("成功停止!"); return Command::SUCCESS; } diff --git a/src/ZM/Command/PureHttpCommand.php b/src/ZM/Command/PureHttpCommand.php index 99c9114c..f46d41bd 100644 --- a/src/ZM/Command/PureHttpCommand.php +++ b/src/ZM/Command/PureHttpCommand.php @@ -36,8 +36,8 @@ class PureHttpCommand extends Command protected function execute(InputInterface $input, OutputInterface $output) { $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."); + if (realpath($input->getArgument('dir') ?? '.') === false) { + $output->writeln("Directory error(" . ($input->getArgument('dir') ?? '.') . "): no such file or directory."); return self::FAILURE; } $global = ZMConfig::get("global"); @@ -60,15 +60,15 @@ class PureHttpCommand extends Command "document_root" => realpath($input->getArgument('dir') ?? '.'), "document_index" => $index ]); - echo "\r".Coroutine::stats()["coroutine_peak_num"]; + echo "\r" . Coroutine::stats()["coroutine_peak_num"]; }); $server->on("start", function ($server) { Process::signal(SIGINT, function () use ($server) { Console::warning("Server interrupted by keyboard."); for ($i = 0; $i < 32; ++$i) { $num = ZMAtomic::$atomics["request"][$i]->get(); - if($num != 0) - echo "[$i]: ".$num."\n"; + if ($num != 0) + echo "[$i]: " . $num . "\n"; } $server->shutdown(); $server->stop(); diff --git a/src/ZM/DB/DB.php b/src/ZM/DB/DB.php index 8e42e03d..140b9c33 100644 --- a/src/ZM/DB/DB.php +++ b/src/ZM/DB/DB.php @@ -38,7 +38,7 @@ class DB if (Table::getTableInstance($table_name) === null) { if (in_array($table_name, self::$table_list)) return new Table($table_name); - elseif(SqlPoolStorage::$sql_pool !== null){ + elseif (SqlPoolStorage::$sql_pool !== null) { throw new DbException("Table " . $table_name . " not exist in database."); } else { throw new DbException("Database connection not exist or connect failed. Please check sql configuration"); @@ -84,7 +84,7 @@ class DB * @throws DbException */ public static function rawQuery(string $line, $params = [], $fetch_mode = ZM_DEFAULT_FETCH_MODE) { - Console::debug("MySQL: ".$line." | ". implode(", ", $params)); + Console::debug("MySQL: " . $line . " | " . implode(", ", $params)); try { $conn = SqlPoolStorage::$sql_pool->get(); if ($conn === false) { @@ -115,7 +115,7 @@ class DB return $ps->fetchAll($fetch_mode); } } catch (DbException $e) { - if(mb_strpos($e->getMessage(), "has gone away") !== false) { + if (mb_strpos($e->getMessage(), "has gone away") !== false) { zm_sleep(0.2); Console::warning("Gone away of MySQL! retrying!"); return self::rawQuery($line, $params); @@ -123,7 +123,7 @@ class DB Console::warning($e->getMessage()); throw $e; } catch (PDOException $e) { - if(mb_strpos($e->getMessage(), "has gone away") !== false) { + if (mb_strpos($e->getMessage(), "has gone away") !== false) { zm_sleep(0.2); Console::warning("Gone away of MySQL! retrying!"); return self::rawQuery($line, $params); diff --git a/src/ZM/DB/InsertBody.php b/src/ZM/DB/InsertBody.php index 3b866428..d9655d3a 100644 --- a/src/ZM/DB/InsertBody.php +++ b/src/ZM/DB/InsertBody.php @@ -28,6 +28,6 @@ class InsertBody * @throws DbException */ public function save() { - DB::rawQuery('INSERT INTO ' . $this->table->getTableName() . ' VALUES ('.implode(',', array_fill(0, count($this->row), '?')).')', $this->row); + DB::rawQuery('INSERT INTO ' . $this->table->getTableName() . ' VALUES (' . implode(',', array_fill(0, count($this->row), '?')) . ')', $this->row); } } diff --git a/src/ZM/DB/Table.php b/src/ZM/DB/Table.php index 5cf4d0a4..4080d01b 100644 --- a/src/ZM/DB/Table.php +++ b/src/ZM/DB/Table.php @@ -4,7 +4,6 @@ namespace ZM\DB; - class Table { private $table_name; @@ -28,7 +27,7 @@ class Table return new SelectBody($this, $what == [] ? ["*"] : $what); } - public function where($column, $operation_or_value, $value = null){ + public function where($column, $operation_or_value, $value = null) { return (new SelectBody($this, ["*"]))->where($column, $operation_or_value, $value); } @@ -47,7 +46,7 @@ class Table return new DeleteBody($this); } - public function statement(){ + public function statement() { $this->cache = []; //TODO: 无返回的statement语句 } diff --git a/src/ZM/DB/UpdateBody.php b/src/ZM/DB/UpdateBody.php index f9681758..fdbe6fdb 100644 --- a/src/ZM/DB/UpdateBody.php +++ b/src/ZM/DB/UpdateBody.php @@ -18,6 +18,7 @@ class UpdateBody * @var array */ private $set_value; + /** * UpdateBody constructor. * @param Table $table @@ -31,19 +32,19 @@ class UpdateBody /** * @throws DbException */ - public function save(){ + public function save() { $arr = []; $msg = []; - foreach($this->set_value as $k => $v) { - $msg []= $k .' = ?'; - $arr[]=$v; + foreach ($this->set_value as $k => $v) { + $msg [] = $k . ' = ?'; + $arr[] = $v; } - if(($msg ?? []) == []) throw new DbException('update value sets can not be empty!'); - $line = 'UPDATE '.$this->table->getTableName().' SET '.implode(', ', $msg); - if($this->where_thing != []) { + if (($msg ?? []) == []) throw new DbException('update value sets can not be empty!'); + $line = 'UPDATE ' . $this->table->getTableName() . ' SET ' . implode(', ', $msg); + if ($this->where_thing != []) { list($sql, $param) = $this->getWhereSQL(); $arr = array_merge($arr, $param); - $line .= ' WHERE '.$sql; + $line .= ' WHERE ' . $sql; } return DB::rawQuery($line, $arr); } diff --git a/src/ZM/DB/WhereBody.php b/src/ZM/DB/WhereBody.php index c861af9c..d1bbe138 100644 --- a/src/ZM/DB/WhereBody.php +++ b/src/ZM/DB/WhereBody.php @@ -15,17 +15,17 @@ trait WhereBody return $this; } - protected function getWhereSQL(){ + protected function getWhereSQL() { $param = []; $msg = ''; - foreach($this->where_thing as $k => $v) { - foreach($v as $ks => $vs) { - if($param != []) { - $msg .= ' AND '.$ks ." $k ?"; + foreach ($this->where_thing as $k => $v) { + foreach ($v as $ks => $vs) { + if ($param != []) { + $msg .= ' AND ' . $ks . " $k ?"; } else { $msg .= "$ks $k ?"; } - $param []=$vs; + $param [] = $vs; } } if ($msg == '') $msg = 1; diff --git a/src/ZM/Event/EventDispatcher.php b/src/ZM/Event/EventDispatcher.php index 16869701..cdc499fd 100644 --- a/src/ZM/Event/EventDispatcher.php +++ b/src/ZM/Event/EventDispatcher.php @@ -93,13 +93,13 @@ class EventDispatcher foreach ((EventManager::$events[$this->class] ?? []) as $v) { $this->dispatchEvent($v, $this->rule, ...$params); if ($this->log) Console::verbose("[事件分发{$this->eid}] 单一对象 " . $v->class . "::" . $v->method . " 分发结束。"); - if($this->status == self::STATUS_BEFORE_FAILED || $this->status == self::STATUS_RULE_FAILED) continue; + if ($this->status == self::STATUS_BEFORE_FAILED || $this->status == self::STATUS_RULE_FAILED) continue; if (is_callable($this->return_func) && $this->status === self::STATUS_NORMAL) { if ($this->log) Console::verbose("[事件分发{$this->eid}] 单一对象 " . $v->class . "::" . $v->method . " 正在执行返回值处理函数 ..."); ($this->return_func)($this->store); } } - if($this->status === self::STATUS_RULE_FAILED) $this->status = self::STATUS_NORMAL; + if ($this->status === self::STATUS_RULE_FAILED) $this->status = self::STATUS_NORMAL; } catch (InterruptException $e) { $this->store = $e->return_var; $this->status = self::STATUS_INTERRUPTED; @@ -113,9 +113,9 @@ class EventDispatcher * @param mixed $v * @param null $rule_func * @param mixed ...$params - * @throws AnnotationException - * @throws InterruptException * @return bool + * @throws InterruptException + * @throws AnnotationException */ public function dispatchEvent($v, $rule_func = null, ...$params) { $q_c = $v->class; diff --git a/src/ZM/Framework.php b/src/ZM/Framework.php index b3a64ef9..81edebbe 100644 --- a/src/ZM/Framework.php +++ b/src/ZM/Framework.php @@ -94,7 +94,7 @@ class Framework "version" => ZM_VERSION, "config" => $args["env"] === null ? 'global.php' : $args["env"] ]; - if(APP_VERSION !== "unknown") $out["app_version"] = APP_VERSION; + if (APP_VERSION !== "unknown") $out["app_version"] = APP_VERSION; if (isset(ZMConfig::get("global", "swoole")["task_worker_num"])) { $out["task_worker_num"] = ZMConfig::get("global", "swoole")["task_worker_num"]; } diff --git a/src/ZM/Http/Response.php b/src/ZM/Http/Response.php index 24fe266d..be979934 100644 --- a/src/ZM/Http/Response.php +++ b/src/ZM/Http/Response.php @@ -160,7 +160,7 @@ class Response * @return mixed */ public function end($content = null) { - if(!$this->is_end) { + if (!$this->is_end) { $this->is_end = true; return $this->response->end($content); } else { diff --git a/src/ZM/Http/RouteManager.php b/src/ZM/Http/RouteManager.php index 4fd4a0b4..72b127f5 100644 --- a/src/ZM/Http/RouteManager.php +++ b/src/ZM/Http/RouteManager.php @@ -16,7 +16,7 @@ class RouteManager public static $routes = null; public static function importRouteByAnnotation(RequestMapping $vss, $method, $class, $methods_annotations) { - if(self::$routes === null) self::$routes = new RouteCollection(); + if (self::$routes === null) self::$routes = new RouteCollection(); // 拿到所属方法的类上面有没有控制器的注解 $prefix = ''; @@ -27,8 +27,8 @@ class RouteManager } } $tail = trim($vss->route, "/"); - $route_name = $prefix.($tail === "" ? "" : "/").$tail; - Console::debug("添加路由:".$route_name); + $route_name = $prefix . ($tail === "" ? "" : "/") . $tail; + Console::debug("添加路由:" . $route_name); $route = new Route($route_name, ['_class' => $class, '_method' => $method]); $route->setMethods($vss->request_method); diff --git a/src/ZM/Http/StaticFileHandler.php b/src/ZM/Http/StaticFileHandler.php index e31407d0..f6f1d7a8 100644 --- a/src/ZM/Http/StaticFileHandler.php +++ b/src/ZM/Http/StaticFileHandler.php @@ -13,14 +13,14 @@ class StaticFileHandler public function __construct($filename, $path) { $full_path = realpath($path . "/" . $filename); $response = ctx()->getResponse(); - Console::debug("Full path: ".$full_path); + Console::debug("Full path: " . $full_path); if ($full_path !== false) { if (strpos($full_path, $path) !== 0) { $response->status(403); $response->end("403 Forbidden"); return true; } else { - if(is_file($full_path)) { + if (is_file($full_path)) { $exp = strtolower(pathinfo($full_path)['extension'] ?? "unknown"); $response->setHeader("Content-Type", ZMConfig::get("file_header")[$exp] ?? "application/octet-stream"); $response->end(file_get_contents($full_path)); diff --git a/src/ZM/Store/LightCache.php b/src/ZM/Store/LightCache.php index b9ff8cf6..d2c499e0 100644 --- a/src/ZM/Store/LightCache.php +++ b/src/ZM/Store/LightCache.php @@ -184,7 +184,7 @@ class LightCache $r[$k] = self::parseGet($v); } } - if(self::$config["persistence_path"] == "") return; + if (self::$config["persistence_path"] == "") return; if (file_exists(self::$config["persistence_path"])) { $r = file_put_contents(self::$config["persistence_path"], json_encode($r, 128 | 256)); if ($r === false) Console::error("Not saved, please check your \"persistence_path\"!"); diff --git a/src/ZM/Store/Lock/SpinLock.php b/src/ZM/Store/Lock/SpinLock.php index 25b85fa4..b6ccbdf0 100644 --- a/src/ZM/Store/Lock/SpinLock.php +++ b/src/ZM/Store/Lock/SpinLock.php @@ -15,18 +15,16 @@ class SpinLock private static $delay = 1; - public static function init($key_cnt, $delay = 1) - { + public static function init($key_cnt, $delay = 1) { self::$kv_lock = new Table($key_cnt, 0.7); self::$delay = $delay; self::$kv_lock->column('lock_num', Table::TYPE_INT, 8); return self::$kv_lock->create(); } - public static function lock(string $key) - { + public static function lock(string $key) { while (($r = self::$kv_lock->incr($key, 'lock_num')) > 1) { //此资源已经被锁上了 - if(Coroutine::getCid() != -1) System::sleep(self::$delay / 1000); + if (Coroutine::getCid() != -1) System::sleep(self::$delay / 1000); else usleep(self::$delay * 1000); } } diff --git a/src/ZM/Store/Redis/ZMRedis.php b/src/ZM/Store/Redis/ZMRedis.php index 7cde7b6f..7d888242 100644 --- a/src/ZM/Store/Redis/ZMRedis.php +++ b/src/ZM/Store/Redis/ZMRedis.php @@ -16,7 +16,7 @@ class ZMRedis * @throws NotInitializedException */ public static function call(callable $callable) { - if(ZMRedisPool::$pool === null) throw new NotInitializedException("Redis pool is not initialized."); + if (ZMRedisPool::$pool === null) throw new NotInitializedException("Redis pool is not initialized."); $r = ZMRedisPool::$pool->get(); $result = $callable($r); if (isset($r->wasted)) ZMRedisPool::$pool->put(null); @@ -29,7 +29,7 @@ class ZMRedis * @throws NotInitializedException */ public function __construct() { - if(ZMRedisPool::$pool === null) throw new NotInitializedException("Redis pool is not initialized."); + if (ZMRedisPool::$pool === null) throw new NotInitializedException("Redis pool is not initialized."); $this->conn = ZMRedisPool::$pool->get(); } diff --git a/src/ZM/Store/Redis/ZMRedisPool.php b/src/ZM/Store/Redis/ZMRedisPool.php index 2ca1473e..590cc08b 100644 --- a/src/ZM/Store/Redis/ZMRedisPool.php +++ b/src/ZM/Store/Redis/ZMRedisPool.php @@ -24,13 +24,13 @@ class ZMRedisPool ); try { $r = self::$pool->get()->ping('123'); - if(strpos(strtolower($r), "123") !== false) { + if (strpos(strtolower($r), "123") !== false) { Console::debug("成功连接redis连接池!"); } else { var_dump($r); } } catch (RedisException $e) { - Console::error("Redis init failed! ".$e->getMessage()); + Console::error("Redis init failed! " . $e->getMessage()); self::$pool = null; } } diff --git a/src/ZM/Store/WorkerCache.php b/src/ZM/Store/WorkerCache.php index f9e1a4c0..7e7bd2d6 100644 --- a/src/ZM/Store/WorkerCache.php +++ b/src/ZM/Store/WorkerCache.php @@ -38,10 +38,10 @@ class WorkerCache return self::processRemote($action, $async, $config); } } - + private static function processRemote($action, $async, $config) { $ss = server()->sendMessage(json_encode($action, JSON_UNESCAPED_UNICODE), $config["worker"]); - if(!$ss) return false; + if (!$ss) return false; if ($async) return true; zm_yield(); $p = self::$transfer[zm_cid()] ?? null; @@ -63,7 +63,7 @@ class WorkerCache public static function add($key, int $value, $async = false) { $config = self::$config ?? ZMConfig::get("global", "worker_cache") ?? ["worker" => 0]; if ($config["worker"] === server()->worker_id) { - if(!isset(self::$store[$key])) self::$store[$key] = 0; + if (!isset(self::$store[$key])) self::$store[$key] = 0; self::$store[$key] += $value; return true; } else { @@ -75,7 +75,7 @@ class WorkerCache public static function sub($key, int $value, $async = false) { $config = self::$config ?? ZMConfig::get("global", "worker_cache") ?? ["worker" => 0]; if ($config["worker"] === server()->worker_id) { - if(!isset(self::$store[$key])) self::$store[$key] = 0; + if (!isset(self::$store[$key])) self::$store[$key] = 0; self::$store[$key] -= $value; return true; } else { diff --git a/src/ZM/Utils/CoMessage.php b/src/ZM/Utils/CoMessage.php index 3f150086..a2dfdba6 100644 --- a/src/ZM/Utils/CoMessage.php +++ b/src/ZM/Utils/CoMessage.php @@ -55,7 +55,7 @@ class CoMessage SpinLock::lock("wait_api"); $all = LightCacheInside::get("wait_api", "wait_api") ?? []; foreach ($all as $k => $v) { - if(!isset($v["compare"])) continue; + if (!isset($v["compare"])) continue; foreach ($v["compare"] as $vs) { if (!isset($v[$vs], $dat[$vs])) continue 2; if ($v[$vs] != $dat[$vs]) { @@ -64,7 +64,7 @@ class CoMessage } $last = $k; } - if($last !== null) { + if ($last !== null) { $all[$last]["result"] = $dat; LightCacheInside::set("wait_api", "wait_api", $all); SpinLock::unlock("wait_api"); diff --git a/src/ZM/Utils/DataProvider.php b/src/ZM/Utils/DataProvider.php index 04b02738..1d416bf0 100644 --- a/src/ZM/Utils/DataProvider.php +++ b/src/ZM/Utils/DataProvider.php @@ -15,7 +15,7 @@ class DataProvider } public static function getWorkingDir() { - if(LOAD_MODE == 0) return WORKING_DIR; + if (LOAD_MODE == 0) return WORKING_DIR; elseif (LOAD_MODE == 1) return LOAD_MODE_COMPOSER_PATH; elseif (LOAD_MODE == 2) return realpath('.'); return null; diff --git a/src/ZM/global_functions.php b/src/ZM/global_functions.php index 11d6faee..83cd8cd4 100644 --- a/src/ZM/global_functions.php +++ b/src/ZM/global_functions.php @@ -89,10 +89,10 @@ function getAllClasses($dir, $indoor_name) { //echo "At " . $indoor_name . PHP_EOL; if (is_dir($dir . $v)) $classes = array_merge($classes, getAllClasses($dir . $v . "/", $indoor_name . "\\" . $v)); elseif (mb_substr($v, -4) == ".php") { - if(substr(file_get_contents($dir.$v), 6, 6) == "#plain") continue; - $composer = json_decode(file_get_contents(DataProvider::getWorkingDir()."/composer.json"), true); - foreach($composer["autoload"]["files"] as $fi) { - if(realpath(DataProvider::getWorkingDir()."/".$fi) == realpath($dir.$v)) { + if (substr(file_get_contents($dir . $v), 6, 6) == "#plain") continue; + $composer = json_decode(file_get_contents(DataProvider::getWorkingDir() . "/composer.json"), true); + foreach ($composer["autoload"]["files"] as $fi) { + if (realpath(DataProvider::getWorkingDir() . "/" . $fi) == realpath($dir . $v)) { continue 2; } }