Merge pull request #91 from zhamao-robot/phpstan-level-4

PHPStan Level 4
This commit is contained in:
Jerry Ma
2022-04-03 02:24:27 +08:00
committed by GitHub
19 changed files with 67 additions and 59 deletions

View File

@@ -1,8 +1,10 @@
parameters: parameters:
reportUnmatchedIgnoredErrors: false reportUnmatchedIgnoredErrors: false
level: 2 level: 4
paths: paths:
- ./src/ - ./src/
ignoreErrors: ignoreErrors:
- '#Used constant OS_TYPE_(LINUX|WINDOWS) not found#' - '#Used constant OS_TYPE_(LINUX|WINDOWS) not found#'
- '#Constant .* not found#' - '#Constant .* not found#'
dynamicConstantNames:
- SWOOLE_VERSION

View File

@@ -15,6 +15,7 @@ use ZM\Annotation\Swoole\OnRequestEvent;
use ZM\API\CQ; use ZM\API\CQ;
use ZM\API\OneBotV11; use ZM\API\OneBotV11;
use ZM\API\TuringAPI; use ZM\API\TuringAPI;
use ZM\Config\ZMConfig;
use ZM\ConnectionManager\ConnectionObject; use ZM\ConnectionManager\ConnectionObject;
use ZM\Console\Console; use ZM\Console\Console;
use ZM\Event\EventDispatcher; use ZM\Event\EventDispatcher;
@@ -95,11 +96,11 @@ class Hello
public function turingAPI() public function turingAPI()
{ {
$user_id = ctx()->getUserId(); $user_id = ctx()->getUserId();
$api = ''; // 请在这里填入你的图灵机器人的apikey $api = ZMConfig::get('global', 'custom.turing_apikey') ?? ''; // 请在这里填入你的图灵机器人的apikey
if ($api === '') { if ($api === '') {
return false; return false;
} // 如果没有填入apikey则此功能关闭 } // 如果没有填入apikey则此功能关闭
if (($this->_running_annotation ?? null) instanceof CQCommand) { if (property_exists($this, '_running_annotation') && ($this->_running_annotation instanceof CQCommand)) {
$msg = ctx()->getFullArg('我在!有什么事吗?'); $msg = ctx()->getFullArg('我在!有什么事吗?');
} else { } else {
$msg = ctx()->getMessage(); $msg = ctx()->getMessage();

View File

@@ -379,9 +379,9 @@ class CQ
/** /**
* 获取消息中第一个CQ码 * 获取消息中第一个CQ码
* @param string $msg 消息内容 * @param string $msg 消息内容
* @param bool $is_object 是否以对象形式返回如果为False的话返回数组形式默认为false * @param bool $is_object 是否以对象形式返回如果为False的话返回数组形式默认为false
* @return array|CQObject 返回的CQ码数组或对象 * @return null|array|CQObject 返回的CQ码数组或对象
*/ */
public static function getCQ(string $msg, bool $is_object = false) public static function getCQ(string $msg, bool $is_object = false)
{ {

View File

@@ -4,9 +4,12 @@ declare(strict_types=1);
namespace ZM\Annotation; namespace ZM\Annotation;
use ArrayIterator;
use Closure; use Closure;
use IteratorAggregate;
use Traversable;
abstract class AnnotationBase abstract class AnnotationBase implements IteratorAggregate
{ {
public $method = ''; public $method = '';
@@ -35,4 +38,9 @@ abstract class AnnotationBase
} }
return $str; return $str;
} }
public function getIterator(): Traversable
{
return new ArrayIterator($this);
}
} }

View File

@@ -38,7 +38,7 @@ class AnnotationParser
private $middlewares = []; private $middlewares = [];
/** @var null|AnnotationReader */ /** @var null|AnnotationReader|DualReader */
private $reader; private $reader;
private $req_mapping = []; private $req_mapping = [];

View File

@@ -9,8 +9,6 @@ declare(strict_types=1);
namespace ZM\DB; namespace ZM\DB;
use PDOException; use PDOException;
use PDOStatement;
use Swoole\Database\PDOStatementProxy;
use ZM\Console\Console; use ZM\Console\Console;
use ZM\Exception\DbException; use ZM\Exception\DbException;
use ZM\MySQL\MySQLManager; use ZM\MySQL\MySQLManager;
@@ -102,11 +100,6 @@ class DB
SqlPoolStorage::$sql_pool->putConnection(null); SqlPoolStorage::$sql_pool->putConnection(null);
throw new DbException('SQL语句查询错误' . $line . ',错误信息:' . $conn->errorInfo()[2]); throw new DbException('SQL语句查询错误' . $line . ',错误信息:' . $conn->errorInfo()[2]);
} }
if (!($ps instanceof PDOStatement) && !($ps instanceof PDOStatementProxy)) {
var_dump($ps);
SqlPoolStorage::$sql_pool->putConnection(null);
throw new DbException('语句查询错误!返回的不是 PDOStatement' . $line);
}
if ($params == []) { if ($params == []) {
$result = $ps->execute(); $result = $ps->execute();
} elseif (!is_array($params)) { } elseif (!is_array($params)) {

View File

@@ -47,7 +47,7 @@ class SelectBody
} }
/** /**
* @param int $fetch_mode * @param mixed $fetch_mode
* @throws DbException * @throws DbException
*/ */
public function fetchAll($fetch_mode = ZM_DEFAULT_FETCH_MODE) public function fetchAll($fetch_mode = ZM_DEFAULT_FETCH_MODE)
@@ -66,7 +66,7 @@ class SelectBody
} }
/** /**
* @param null $key * @param null|mixed $key
* @throws DbException * @throws DbException
* @return null|mixed * @return null|mixed
*/ */
@@ -83,10 +83,9 @@ class SelectBody
} }
/** /**
* @param int $fetch_mode
* @throws DbException * @throws DbException
*/ */
public function execute($fetch_mode = ZM_DEFAULT_FETCH_MODE) public function execute(int $fetch_mode = ZM_DEFAULT_FETCH_MODE)
{ {
$str = $this->queryPrepare(); $str = $this->queryPrepare();
$this->result = DB::rawQuery($str[0], $str[1], $fetch_mode); $this->result = DB::rawQuery($str[0], $str[1], $fetch_mode);

View File

@@ -145,10 +145,11 @@ class EventDispatcher
/** /**
* @param mixed $v * @param mixed $v
* @param null $rule_func * @param null|mixed $rule_func
* @param mixed ...$params * @param mixed ...$params
* @throws InterruptException * @throws InterruptException
* @throws AnnotationException * @throws AnnotationException
* @throws Error
* @return bool * @return bool
* @noinspection PhpMissingReturnTypeInspection * @noinspection PhpMissingReturnTypeInspection
*/ */

View File

@@ -1,7 +1,6 @@
<?php <?php
/** /**
* @noinspection PhpPropertyOnlyWrittenInspection
* @noinspection PhpUnusedParameterInspection * @noinspection PhpUnusedParameterInspection
* @noinspection PhpComposerExtensionStubsInspection * @noinspection PhpComposerExtensionStubsInspection
*/ */
@@ -34,7 +33,12 @@ class OnManagerStart implements SwooleEvent
{ {
private static $last_hash = ''; private static $last_hash = '';
private static $watch = -1; private static $watch_tick_id = -1;
public static function getWatchTickId(): int
{
return self::$watch_tick_id;
}
public function onCall(Server $server) public function onCall(Server $server)
{ {
@@ -65,7 +69,7 @@ class OnManagerStart implements SwooleEvent
} }
} }
if (Framework::$argv['polling-watch']) { if (Framework::$argv['polling-watch']) {
self::$watch = swoole_timer_tick(3000, function () use ($server) { self::$watch_tick_id = swoole_timer_tick(3000, function () use ($server) {
$data = (DataProvider::scanDirFiles(DataProvider::getSourceRootDir() . '/src/')); $data = (DataProvider::scanDirFiles(DataProvider::getSourceRootDir() . '/src/'));
$hash = md5(''); $hash = md5('');
foreach ($data as $file) { foreach ($data as $file) {

View File

@@ -4,10 +4,9 @@ declare(strict_types=1);
namespace ZM\Event\SwooleEvent; namespace ZM\Event\SwooleEvent;
use Error;
use Exception;
use Swoole\Coroutine; use Swoole\Coroutine;
use Swoole\WebSocket\Frame; use Swoole\WebSocket\Frame;
use Throwable;
use ZM\Annotation\Swoole\OnMessageEvent; use ZM\Annotation\Swoole\OnMessageEvent;
use ZM\Annotation\Swoole\OnSwooleEvent; use ZM\Annotation\Swoole\OnSwooleEvent;
use ZM\Annotation\Swoole\SwooleHandler; use ZM\Annotation\Swoole\SwooleHandler;
@@ -53,11 +52,7 @@ class OnMessage implements SwooleEvent
$dispatcher1->dispatchEvents($conn); $dispatcher1->dispatchEvents($conn);
$dispatcher->dispatchEvents($conn); $dispatcher->dispatchEvents($conn);
// Console::success("Used ".round((microtime(true) - $starttime) * 1000, 3)." ms!"); // Console::success("Used ".round((microtime(true) - $starttime) * 1000, 3)." ms!");
} catch (Exception $e) { } catch (Throwable $e) {
$error_msg = $e->getMessage() . ' at ' . $e->getFile() . '(' . $e->getLine() . ')';
Console::error(zm_internal_errcode('E00017') . 'Uncaught exception ' . get_class($e) . ' when calling "message": ' . $error_msg);
Console::trace();
} catch (Error $e) {
$error_msg = $e->getMessage() . ' at ' . $e->getFile() . '(' . $e->getLine() . ')'; $error_msg = $e->getMessage() . ' at ' . $e->getFile() . '(' . $e->getLine() . ')';
Console::error(zm_internal_errcode('E00017') . 'Uncaught ' . get_class($e) . ' when calling "message": ' . $error_msg); Console::error(zm_internal_errcode('E00017') . 'Uncaught ' . get_class($e) . ' when calling "message": ' . $error_msg);
Console::trace(); Console::trace();

View File

@@ -6,9 +6,8 @@ declare(strict_types=1);
namespace ZM\Event\SwooleEvent; namespace ZM\Event\SwooleEvent;
use Error;
use Exception;
use Swoole\Server; use Swoole\Server;
use Throwable;
use ZM\Annotation\Swoole\SwooleHandler; use ZM\Annotation\Swoole\SwooleHandler;
use ZM\Console\Console; use ZM\Console\Console;
use ZM\Event\SwooleEvent; use ZM\Event\SwooleEvent;
@@ -25,11 +24,7 @@ class OnPipeMessage implements SwooleEvent
$data = json_decode($data, true); $data = json_decode($data, true);
try { try {
WorkerManager::workerAction($src_worker_id, $data); WorkerManager::workerAction($src_worker_id, $data);
} catch (Exception $e) { } catch (Throwable $e) {
$error_msg = $e->getMessage() . ' at ' . $e->getFile() . '(' . $e->getLine() . ')';
Console::error(zm_internal_errcode('E00021') . 'Uncaught exception ' . get_class($e) . ' when calling "pipeMessage": ' . $error_msg);
Console::trace();
} catch (Error $e) {
$error_msg = $e->getMessage() . ' at ' . $e->getFile() . '(' . $e->getLine() . ')'; $error_msg = $e->getMessage() . ' at ' . $e->getFile() . '(' . $e->getLine() . ')';
Console::error(zm_internal_errcode('E00021') . 'Uncaught ' . get_class($e) . ' when calling "pipeMessage": ' . $error_msg); Console::error(zm_internal_errcode('E00021') . 'Uncaught ' . get_class($e) . ' when calling "pipeMessage": ' . $error_msg);
Console::trace(); Console::trace();

View File

@@ -13,7 +13,7 @@ use ReflectionException;
use Swoole\Coroutine; use Swoole\Coroutine;
use Swoole\Database\PDOConfig; use Swoole\Database\PDOConfig;
use Swoole\Process; use Swoole\Process;
use Swoole\Server; use Swoole\WebSocket\Server;
use ZM\Annotation\AnnotationParser; use ZM\Annotation\AnnotationParser;
use ZM\Annotation\Swoole\OnMessageEvent; use ZM\Annotation\Swoole\OnMessageEvent;
use ZM\Annotation\Swoole\OnStart; use ZM\Annotation\Swoole\OnStart;
@@ -68,12 +68,7 @@ class OnWorkerStart implements SwooleEvent
return; return;
} }
// DataProvider::saveBuffer(); // DataProvider::saveBuffer();
/* @var Server $server */ $server->shutdown();
if (server() === null) {
$server->shutdown();
} else {
server()->shutdown();
}
}); });
Console::verbose("Worker #{$server->worker_id} starting"); Console::verbose("Worker #{$server->worker_id} starting");

View File

@@ -447,7 +447,7 @@ class Framework
} }
/** /**
* @param null $id_or_name * @param null|int|string $id_or_name
* @throws ZMKnownException * @throws ZMKnownException
* @internal * @internal
*/ */

View File

@@ -19,17 +19,16 @@ class StaticFileHandler
if (strpos($full_path, $path) !== 0) { if (strpos($full_path, $path) !== 0) {
$response->status(403); $response->status(403);
$response->end('403 Forbidden'); $response->end('403 Forbidden');
return true; return;
} }
if (is_file($full_path)) { if (is_file($full_path)) {
$exp = strtolower(pathinfo($full_path)['extension'] ?? 'unknown'); $exp = strtolower(pathinfo($full_path)['extension'] ?? 'unknown');
$response->setHeader('Content-Type', ZMConfig::get('file_header')[$exp] ?? 'application/octet-stream'); $response->setHeader('Content-Type', ZMConfig::get('file_header')[$exp] ?? 'application/octet-stream');
$response->end(file_get_contents($full_path)); $response->end(file_get_contents($full_path));
return true; return;
} }
} }
$response->status(404); $response->status(404);
$response->end(HttpUtil::getHttpCodePage(404)); $response->end(HttpUtil::getHttpCodePage(404));
return true;
} }
} }

View File

@@ -10,9 +10,7 @@ use Doctrine\DBAL\Driver\Connection;
use Doctrine\DBAL\ParameterType; use Doctrine\DBAL\ParameterType;
use PDO; use PDO;
use PDOException; use PDOException;
use PDOStatement;
use Swoole\Database\PDOProxy; use Swoole\Database\PDOProxy;
use Swoole\Database\PDOStatementProxy;
use ZM\Console\Console; use ZM\Console\Console;
use ZM\Exception\DbException; use ZM\Exception\DbException;
use ZM\Store\MySQL\SqlPoolStorage; use ZM\Store\MySQL\SqlPoolStorage;
@@ -34,23 +32,31 @@ class MySQLConnection implements Connection
SqlPoolStorage::$sql_pool->putConnection($this->conn); SqlPoolStorage::$sql_pool->putConnection($this->conn);
} }
/**
* @param mixed $sql
* @param mixed $options
* @throws DbException
*/
public function prepare($sql, $options = []) public function prepare($sql, $options = [])
{ {
try { try {
Console::debug('Running SQL prepare: ' . $sql); Console::debug('Running SQL prepare: ' . $sql);
$statement = $this->conn->prepare($sql, $options); $statement = $this->conn->prepare($sql, $options);
assert(($statement instanceof PDOStatementProxy) || ($statement instanceof PDOStatement)); assert($statement !== false);
} catch (PDOException $exception) { } catch (PDOException $exception) {
throw new DbException($exception->getMessage(), $exception->getCode(), $exception); throw new DbException($exception->getMessage(), $exception->getCode(), $exception);
} }
return new MySQLStatement($statement); return new MySQLStatement($statement);
} }
/**
* @throws DbException
*/
public function query(...$args) public function query(...$args)
{ {
try { try {
$statement = $this->conn->query(...$args); $statement = $this->conn->query(...$args);
assert(($statement instanceof PDOStatementProxy) || ($statement instanceof PDOStatement)); assert($statement !== false);
} catch (PDOException $exception) { } catch (PDOException $exception) {
throw new DbException($exception->getMessage(), $exception->getCode(), $exception); throw new DbException($exception->getMessage(), $exception->getCode(), $exception);
} }
@@ -62,6 +68,10 @@ class MySQLConnection implements Connection
return $this->conn->quote($value, $type); return $this->conn->quote($value, $type);
} }
/**
* @param mixed $sql
* @throws DbException
*/
public function exec($sql) public function exec($sql)
{ {
try { try {
@@ -74,6 +84,10 @@ class MySQLConnection implements Connection
} }
} }
/**
* @param null|mixed $name
* @throws DbException
*/
public function lastInsertId($name = null) public function lastInsertId($name = null)
{ {
try { try {

View File

@@ -8,6 +8,6 @@ use ZM\MySQL\MySQLPool;
class SqlPoolStorage class SqlPoolStorage
{ {
/** @var MySQLPool */ /** @var null|MySQLPool */
public static $sql_pool; public static $sql_pool;
} }

View File

@@ -7,6 +7,7 @@ declare(strict_types=1);
namespace ZM\Utils; namespace ZM\Utils;
use Doctrine\Common\Annotations\AnnotationReader; use Doctrine\Common\Annotations\AnnotationReader;
use Error;
use Exception; use Exception;
use ReflectionClass; use ReflectionClass;
use Swoole\Process; use Swoole\Process;
@@ -22,6 +23,7 @@ class Terminal
/** /**
* @throws Exception * @throws Exception
* @throws Error
* @return bool * @return bool
* @noinspection PhpMissingReturnTypeInspection * @noinspection PhpMissingReturnTypeInspection
* @noinspection PhpUnused * @noinspection PhpUnused

View File

@@ -76,13 +76,13 @@ class ZMUtil
/** /**
* 使用Psr-4标准获取目录下的所有类 * 使用Psr-4标准获取目录下的所有类
* @param string $dir 目录 * @param string $dir 目录
* @param string $base_namespace 基础命名空间 * @param string $base_namespace 基础命名空间
* @param null|mixed $rule 规则 * @param null|mixed $rule 规则
* @param bool $return_path_value 是否返回文件路径 * @param bool|string $return_path_value 是否返回文件路径,返回文件路径的话传入字符串
* @return string[] * @return string[]
*/ */
public static function getClassesPsr4(string $dir, string $base_namespace, $rule = null, bool $return_path_value = false): array public static function getClassesPsr4(string $dir, string $base_namespace, $rule = null, $return_path_value = false): array
{ {
// 预先读取下composer的file列表 // 预先读取下composer的file列表
$composer = json_decode(file_get_contents(DataProvider::getSourceRootDir() . '/composer.json'), true); $composer = json_decode(file_get_contents(DataProvider::getSourceRootDir() . '/composer.json'), true);

View File

@@ -409,7 +409,7 @@ function hash_message(array $message): string
* *
* 与 {@link Framework::$server} 一致 * 与 {@link Framework::$server} 一致
*/ */
function server(): ?Server function server(): Server
{ {
return Framework::$server; return Framework::$server;
} }