From 5e02a79bf014ad16cfcc2fc4e8c2efb6615e6b7a Mon Sep 17 00:00:00 2001 From: as2252258 Date: Sun, 9 Jan 2022 03:50:38 +0800 Subject: [PATCH] e --- .gitee/ISSUE_TEMPLATE.zh-TW.md | 18 +- .gitee/PULL_REQUEST_TEMPLATE.zh-TW.md | 24 +- .gitignore | 74 +- .phpstorm.meta.php | 36 +- LICENSE | 42 +- a.php | 46 +- composer.json | 92 +- error.php | 62 +- function.php | 2468 ++++++++--------- kiri-annotation/Annotation.php | 172 +- kiri-annotation/Aspect.php | 74 +- kiri-annotation/Attribute.php | 54 +- kiri-annotation/Event.php | 92 +- kiri-annotation/IAnnotation.php | 38 +- kiri-annotation/Inject.php | 208 +- kiri-annotation/Loader.php | 450 +-- kiri-annotation/Mapping.php | 62 +- kiri-annotation/Route/Document.php | 68 +- kiri-annotation/Route/Middleware.php | 106 +- kiri-annotation/Route/Route.php | 82 +- kiri-annotation/Route/Socket.php | 62 +- kiri-annotation/Target.php | 56 +- kiri-annotation/Task.php | 88 +- kiri-engine/Abstracts/AbstractServer.php | 24 +- kiri-engine/Abstracts/BaseApplication.php | 902 +++--- kiri-engine/Abstracts/BaseContext.php | 26 +- kiri-engine/Abstracts/BaseGoto.php | 56 +- kiri-engine/Abstracts/Command.php | 20 +- kiri-engine/Abstracts/Component.php | 520 ++-- kiri-engine/Abstracts/Config.php | 256 +- kiri-engine/Abstracts/Configure.php | 36 +- kiri-engine/Abstracts/IListener.php | 52 +- kiri-engine/Abstracts/Input.php | 222 +- kiri-engine/Abstracts/Kernel.php | 30 +- kiri-engine/Abstracts/Listener.php | 36 +- kiri-engine/Abstracts/Logger.php | 458 +-- kiri-engine/Abstracts/Provider.php | 28 +- kiri-engine/Abstracts/Providers.php | 30 +- kiri-engine/Abstracts/TraitApplication.php | 64 +- kiri-engine/Application.php | 506 ++-- kiri-engine/Async.php | 88 +- kiri-engine/Cache/Base/Redis.php | 342 +-- kiri-engine/Cache/File.php | 282 +- kiri-engine/Cache/ICache.php | 130 +- kiri-engine/Cache/Redis.php | 372 +-- kiri-engine/Context.php | 418 +-- kiri-engine/Core/ArrayAccess.php | 200 +- kiri-engine/Core/DateFormat.php | 208 +- kiri-engine/Core/Dtl.php | 116 +- kiri-engine/Core/HashMap.php | 202 +- kiri-engine/Core/Help.php | 438 +-- kiri-engine/Core/Json.php | 242 +- kiri-engine/Core/Network.php | 36 +- kiri-engine/Core/Number.php | 62 +- kiri-engine/Core/Reader.php | 344 +-- kiri-engine/Core/Str.php | 566 ++-- kiri-engine/Core/Xml.php | 114 +- kiri-engine/Di/Container.php | 900 +++--- kiri-engine/Di/LocalService.php | 176 +- kiri-engine/Di/NoteManager.php | 606 ++-- kiri-engine/Environmental.php | 92 +- kiri-engine/Error/ErrorHandler.php | 316 +-- kiri-engine/Error/ErrorInterface.php | 56 +- kiri-engine/Error/Logger.php | 234 +- kiri-engine/Error/LoggerAspect.php | 106 +- kiri-engine/Error/LoggerProcess.php | 168 +- kiri-engine/Event.php | 476 ++-- kiri-engine/Events/OnAfterCommandExecute.php | 32 +- kiri-engine/Events/OnBeforeCommandExecute.php | 16 +- kiri-engine/Exception/AuthException.php | 58 +- kiri-engine/Exception/ComponentException.php | 70 +- kiri-engine/Exception/ConfigException.php | 30 +- kiri-engine/Exception/InitException.php | 28 +- .../Exception/NotFindClassException.php | 72 +- .../Exception/NotFindPropertyException.php | 70 +- .../Exception/RedisConnectException.php | 30 +- kiri-engine/FileListen/HotReload.php | 470 ++-- kiri-engine/FileListen/Inotify.php | 338 +-- kiri-engine/FileListen/Scaner.php | 298 +- kiri-engine/IAspect.php | 54 +- kiri-engine/IProxy.php | 26 +- kiri-engine/Kiri.php | 1272 ++++----- kiri-engine/Pool/Alias.php | 48 +- kiri-engine/Pool/Connection.php | 434 +-- kiri-engine/Pool/Helper/QueueInterface.php | 56 +- kiri-engine/Pool/Helper/SplQueue.php | 202 +- kiri-engine/Pool/Pool.php | 498 ++-- kiri-engine/Pool/Redis.php | 244 +- kiri-engine/Pool/StopHeartbeatCheck.php | 22 +- kiri-engine/Proxy.php | 54 +- kiri-engine/Runtime.php | 202 +- kiri-engine/ToArray.php | 20 +- kiri-gateway/Collector.php | 28 +- kiri-gateway/GatewayServer.php | 46 +- kiri-gateway/HashMap.php | 70 +- kiri-gii/Gii.php | 684 ++--- kiri-gii/GiiBase.php | 822 +++--- kiri-gii/GiiCommand.php | 152 +- kiri-gii/GiiController.php | 1072 +++---- kiri-gii/GiiJsonRpc.php | 226 +- kiri-gii/GiiMiddleware.php | 144 +- kiri-gii/GiiModel.php | 852 +++--- kiri-gii/GiiProviders.php | 68 +- kiri-gii/GiiRpcClient.php | 198 +- kiri-gii/GiiRpcService.php | 156 +- kiri-gii/GiiTask.php | 180 +- kiri-websocket-server/FdCollector.php | 28 +- kiri-websocket-server/Sender.php | 184 +- kiri-websocket-server/Server.php | 330 +-- kiri-websocket-server/WebSocketInterface.php | 94 +- p.php | 180 +- socket.html | 144 +- test.php | 84 +- 113 files changed, 12713 insertions(+), 12703 deletions(-) diff --git a/.gitee/ISSUE_TEMPLATE.zh-TW.md b/.gitee/ISSUE_TEMPLATE.zh-TW.md index 1fa7f02a..77d34702 100644 --- a/.gitee/ISSUE_TEMPLATE.zh-TW.md +++ b/.gitee/ISSUE_TEMPLATE.zh-TW.md @@ -1,9 +1,9 @@ -### 該問題是如何引起的? - - - -### 重現步驟 - - - -### 報錯信息 +### 該問題是如何引起的? + + + +### 重現步驟 + + + +### 報錯信息 diff --git a/.gitee/PULL_REQUEST_TEMPLATE.zh-TW.md b/.gitee/PULL_REQUEST_TEMPLATE.zh-TW.md index 3f3761f6..53114fc4 100644 --- a/.gitee/PULL_REQUEST_TEMPLATE.zh-TW.md +++ b/.gitee/PULL_REQUEST_TEMPLATE.zh-TW.md @@ -1,12 +1,12 @@ -### 該Pull Request關聯的Issue - - -### 修改描述 - - - -### 測試用例 - - - -### 修復效果的截屏 +### 該Pull Request關聯的Issue + + +### 修改描述 + + + +### 測試用例 + + + +### 修復效果的截屏 diff --git a/.gitignore b/.gitignore index 91172367..757bb7d1 100644 --- a/.gitignore +++ b/.gitignore @@ -1,37 +1,37 @@ -# Created by .ignore support plugin (hsz.mobi) -### Yii template -assets/* -!assets/.gitignore -protected/runtime/* -!protected/runtime/.gitignore -protected/data/*.db -themes/classic/views/ - -### Example user template template -### Example user template - -# IntelliJ project files -.idea -*.iml -out -gen - -db/ -async-queue/ - -composer.lock - -*.log -commands/result -config/setting.php -tests/ -vendor/ -runtime/ - -*.xml -*.lock - -oot -d - -composer.lock +# Created by .ignore support plugin (hsz.mobi) +### Yii template +assets/* +!assets/.gitignore +protected/runtime/* +!protected/runtime/.gitignore +protected/data/*.db +themes/classic/views/ + +### Example user template template +### Example user template + +# IntelliJ project files +.idea +*.iml +out +gen + +db/ +async-queue/ + +composer.lock + +*.log +commands/result +config/setting.php +tests/ +vendor/ +runtime/ + +*.xml +*.lock + +oot +d + +composer.lock diff --git a/.phpstorm.meta.php b/.phpstorm.meta.php index 52dfddd6..e1102b5a 100644 --- a/.phpstorm.meta.php +++ b/.phpstorm.meta.php @@ -1,18 +1,18 @@ - 0) { - $shift = (int)array_shift($first); - $endShift = (int)array_shift($end); - if ($endShift == $shift) { - continue; - } - if ($endShift < $shift) { - return true; - } else { - return false; - } - } - return false; -} - -var_dump(version('1.4.4','1.4.3')); + 0) { + $shift = (int)array_shift($first); + $endShift = (int)array_shift($end); + if ($endShift == $shift) { + continue; + } + if ($endShift < $shift) { + return TRUE; + } else { + return FALSE; + } + } + return FALSE; +} + +var_dump(version('1.4.4', '1.4.3')); diff --git a/composer.json b/composer.json index 355a2f38..ee58684d 100644 --- a/composer.json +++ b/composer.json @@ -1,46 +1,46 @@ -{ - "name": "game-worker/kiri-core", - "description": "test framework", - "authors": [ - { - "name": "XiangLin", - "email": "as2252258@163.com" - } - ], - "license": "MIT", - "require": { - "php": ">=8.1", - "ext-json": "*", - "ext-fileinfo": "*", - "ext-pdo": "*", - "ext-redis": "*", - "ext-simplexml": "*", - "ext-libxml": "*", - "ext-iconv": "*", - "ext-mbstring": "*", - "ext-xml": "*", - "ext-curl": "*", - "ext-openssl": "*", - "symfony/console": "~v5.3.10", - "psr/log": "1.*", - "composer-runtime-api": "^2.0", - "psr/container": "^2.0", - "psr/http-server-middleware": "1.0.1", - "game-worker/kiri-event": "~v2.0", - "ext-inotify": "*" - }, - "autoload": { - "psr-4": { - "Kiri\\": "kiri-engine/", - "Kiri\\Gateway\\": "kiri-gateway/", - "Kiri\\Websocket\\": "kiri-websocket-server/", - "Gii\\": "kiri-gii/", - "Kiri\\Annotation\\": "kiri-annotation/", - "Kiri\\Task\\": "kiri-task/" - }, - "files": [ - "error.php", - "function.php" - ] - } -} +{ + "name": "game-worker/kiri-core", + "description": "test framework", + "authors": [ + { + "name": "XiangLin", + "email": "as2252258@163.com" + } + ], + "license": "MIT", + "require": { + "php": ">=8.1", + "ext-json": "*", + "ext-fileinfo": "*", + "ext-pdo": "*", + "ext-redis": "*", + "ext-simplexml": "*", + "ext-libxml": "*", + "ext-iconv": "*", + "ext-mbstring": "*", + "ext-xml": "*", + "ext-curl": "*", + "ext-openssl": "*", + "symfony/console": "~v5.3.10", + "psr/log": "1.*", + "composer-runtime-api": "^2.0", + "psr/container": "^2.0", + "psr/http-server-middleware": "1.0.1", + "game-worker/kiri-event": "~v2.0", + "ext-inotify": "*" + }, + "autoload": { + "psr-4": { + "Kiri\\": "kiri-engine/", + "Kiri\\Gateway\\": "kiri-gateway/", + "Kiri\\Websocket\\": "kiri-websocket-server/", + "Gii\\": "kiri-gii/", + "Kiri\\Annotation\\": "kiri-annotation/", + "Kiri\\Task\\": "kiri-task/" + }, + "files": [ + "error.php", + "function.php" + ] + } +} diff --git a/error.php b/error.php index 22330053..29b442d0 100644 --- a/error.php +++ b/error.php @@ -1,31 +1,31 @@ - 'ok', - NO_AUTH => '' -]); - -if (!function_exists('message')) { - - /** - * @param $code - * @param $replace - * @param string $default - * @return mixed|string - */ - function message($code, $replace, $default = '') - { - if (!isset(ERROR_MESSAGES[$code])) { - if (!empty($default)) { - return $default; - } - return 'unknown error'; - } - return sprintf(ERROR_MESSAGES[$code], $replace); - } - - -} + 'ok', + NO_AUTH => '' +]); + +if (!function_exists('message')) { + + /** + * @param $code + * @param $replace + * @param string $default + * @return mixed|string + */ + function message($code, $replace, $default = '') + { + if (!isset(ERROR_MESSAGES[$code])) { + if (!empty($default)) { + return $default; + } + return 'unknown error'; + } + return sprintf(ERROR_MESSAGES[$code], $replace); + } + + +} diff --git a/function.php b/function.php index e1f304c2..1cd59bd9 100644 --- a/function.php +++ b/function.php @@ -1,1234 +1,1234 @@ -get($name); - } - if (empty($default)) { - throw new Exception("Unknown component ID: $name"); - } - if (Kiri::has($default)) { - return Kiri::app()->get($default); - } - $class = Kiri::createObject($default); - class_alias($name, $default, TRUE); - return $class; - } - - -} - - -if (!function_exists('map')) { - - - /** - * @param array $params - * @param Closure $closure - * @return mixed - */ - function map(array $params, Closure $closure): mixed - { - return array_map($closure, $params); - } - -} - - -if (!function_exists('checkPortIsAlready')) { - - - /** - * @param $port - * @return bool|string - * @throws Exception - */ - function checkPortIsAlready($port): bool|string - { - if (!Kiri::getPlatform()->isLinux()) { - exec("lsof -i :" . $port . " | grep -i 'LISTEN' | awk '{print $2}'", $output); - if (empty($output)) return FALSE; - $output = explode(PHP_EOL, $output[0]); - return $output[0]; - } - - $serverPid = file_get_contents(storage('.swoole.pid')); - if (!empty($serverPid) && shell_exec('ps -ef | grep ' . $serverPid . ' | grep -v grep')) { - Process::kill($serverPid, 0) && Process::kill($serverPid, SIGTERM); - } - - exec('netstat -lnp | grep ' . $port . ' | grep "LISTEN" | awk \'{print $7}\'', $output); - if (empty($output)) { - return FALSE; - } - return explode('/', $output[0])[0]; - } - -} - - -if (!function_exists('done')) { - - /** - * - */ - function done() - { - set_env('state', 'exit'); - } - -} - - -if (!function_exists('set_env')) { - - - /** - * @param $key - * @param $value - */ - function set_env($key, $value) - { - putenv(sprintf('%s=%s', $key, $value)); - } - -} - -if (!function_exists('enable_file_modification_listening')) { - - - function enable_file_modification_listening(): void - { - putenv('enable_file_modification_listening=on'); - } - - -} - - -if (!function_exists('is_enable_file_modification_listening')) { - - - /** - * @return bool - */ - #[Pure] function is_enable_file_modification_listening(): bool - { - return env('enable_file_modification_listening', 'off') == 'on'; - } - - -} - -if (!function_exists('disable_file_modification_listening')) { - - - function disable_file_modification_listening() - { - putenv('enable_file_modification_listening=off'); - } - - -} - - -if (!function_exists('now')) { - - /** - * @return string - */ - function now(): string - { - return date('Y-m-d H:i:s') . '.' . str_replace(time() . '.', '', (string)microtime(TRUE)); - } -} - - -if (!function_exists('workerName')) { - - - /** - * @param $worker_id - * @return string - */ - function workerName($worker_id) - { - return $worker_id >= Kiri::app()->getSwoole()->setting['worker_num'] ? 'Task' : 'Worker'; - } - -} - - -if (!function_exists('Annotation')) { - - - /** - * @return Annotation - * @throws Exception - */ - function annotation(): Annotation - { - return Kiri::getAnnotation(); - } - - -} - - -if (!function_exists('scan_directory')) { - - - /** - * @param $dir - * @param $namespace - * @param array $exclude - * @throws ReflectionException - * @throws Exception - */ - function scan_directory($dir, $namespace, array $exclude = []) - { - $annotation = Kiri::app()->getAnnotation(); - $annotation->read($dir, $namespace, $exclude); - - injectRuntime($dir, $exclude); - } - -} - -if (!class_exists('ReturnTypeWillChange')) { - - /** - * @since 8.1 - */ - #[Attribute(Attribute::TARGET_METHOD)] - final class ReturnTypeWillChange - { - public function __construct() - { - } - } - - -} - - -if (!function_exists('injectRuntime')) { - - - /** - * @param string $path - * @param array $exclude - * @throws ReflectionException - * @throws Exception - */ - function injectRuntime(string $path, array $exclude = []) - { - $fileLists = Kiri::getAnnotation()->runtime($path, $exclude); - $di = Kiri::getDi(); - - $router = []; - foreach ($fileLists as $class) { - foreach (AnnotationManager::getTargetAnnotation($class) as $value) { - if (!method_exists($value, 'execute')) { - continue; - } - $value->execute($class); - } - $methods = $di->getMethodAttribute($class); - foreach ($methods as $method => $attribute) { - if (empty($attribute)) { - continue; - } - foreach ($attribute as $item) { - if ($item instanceof Route) { - $router[] = [$item, $class, $method]; - } else { - if (!method_exists($item, 'execute')) { - continue; - } - $item->execute($class, $method); - } - } - } - } - if (!empty($router)) { - foreach ($router as $class) { - [$item, $class, $method] = $class; - if (!method_exists($item, 'execute')) { - continue; - } - $item->execute($class, $method); - } - } - } - -} - - -if (!function_exists('swoole')) { - - - /** - * @return Server|null - * @throws Exception - */ - function swoole(): ?Server - { - return Kiri::getWebSocket(); - } - - -} - - -if (!function_exists('directory')) { - - /** - * @param $name - * @return string - */ - #[Pure] function directory($name): string - { - return realpath(APP_PATH . $name); - } - - -} - - -if (!function_exists('isUrl')) { - - - /** - * @param $url - * @param bool $get_info - * @return false|array - */ - function isUrl($url, bool $get_info = TRUE): bool|array - { - if (str_starts_with($url, '/')) { - return FALSE; - } - $queryMatch = '/((http[s]?):\/\/)?(([\w\-\_]+\.)+\w+(:\d+)?)(\/.*)?/'; - if (!preg_match($queryMatch, $url, $outPut)) { - return FALSE; - } - - [$scheme, $host, $port, $user, $pass, $query, $path, $fragment] = parse_url($url); - if ($scheme == 'https' && empty($port)) { - $port = 443; - } - - if (!empty($query)) $path .= '?' . $query; - if (!empty($fragment)) $path .= '#' . $fragment; - - - unset($outPut); - - return [$scheme == 'https', $host, $port, $path]; - } - -} - - -if (!function_exists('split_request_uri')) { - - - /** - * @param $url - * @return false|array - */ - function split_request_uri($url): bool|array - { - if (($parse = isUrl($url, NULL)) === FALSE) { - return FALSE; - } - - [$isHttps, $domain, $port, $path] = $parse; - $uri = $isHttps ? 'https://' . $domain : 'http://' . $domain; - if (!empty($port)) { - $uri .= ':' . $port; - } - return [$uri, $path]; - } - -} - - -if (!function_exists('hadDomain')) { - - - /** - * @param $url - * @return false|array - */ - function hadDomain($url): bool|array - { - $param = split_request_uri($url); - return !is_array($param) ? FALSE : $param[0]; - } - -} - - -if (!function_exists('isDomain')) { - - - /** - * @param $url - * @return false|array - */ - function isDomain($url): array|bool - { - return !isIp($url); - } - -} -if (!function_exists('isIp')) { - - - /** - * @param $url - * @return false|array - */ - function isIp($url): bool|array - { - return preg_match('/(\d{1,3}\.){3}\.\d{1,3}(:\d{1,5})?/', $url); - } - -} - - -if (!function_exists('loadByDir')) { - - - /** - * @param $namespace - * @param $dirname - */ - function classAutoload($namespace, $dirname) - { - foreach (glob(rtrim($dirname, '/') . '/*') as $value) { - $value = realpath($value); - if (is_dir($value)) { - classAutoload($namespace, $value); - } else { - $pos = strpos($value, '.php'); - if ($pos === FALSE || strlen($value) - 4 != $pos) { - continue; - } - - $replace = ltrim(str_replace(__DIR__, '', $value), '/'); - $replace = str_replace('.php', '', $replace); - - $first = explode(DIRECTORY_SEPARATOR, $replace); - array_shift($first); - - Kiri::setAutoload($namespace . '\\' . implode('\\', $first), $value); - } - } - } - - -} - - -if (!function_exists('write')) { - - - /** - * @param string $messages - * @param string $category - * @throws Exception - */ - function write(string $messages, string $category = 'app') - { - $logger = Kiri::app()->getLogger(); - $logger->write($messages, $category); - } -} - - -if (!function_exists('redis')) { - - - /** - * @return \Kiri\Cache\Redis|Redis - * @throws Exception - */ - function redis(): \Kiri\Cache\Redis|Redis - { - return Kiri::getDi()->get(\Kiri\Cache\Redis::class); - } -} - -if (!function_exists('fire')) { - - - /** - * @param object $event - */ - function fire(object $event) - { - di(EventDispatch::class)->dispatch($event); - } -} - - -if (!function_exists('app')) { - - - /** - * @return Application|null - */ - #[Pure] function app(): ?Application - { - return Kiri::app(); - } - -} - -if (!function_exists('instance_load')) { - - function instance_load() - { - $content = json_decode(file_get_contents(__DIR__ . '/composer.json'), TRUE); - if (isset($content['autoload']) && isset($content['autoload']['psr-4'])) { - $psr4 = $content['autoload']['psr-4']; - foreach ($psr4 as $namespace => $dirname) { - classAutoload($namespace, __DIR__ . '/' . $dirname); - } - } - } - -} - - -if (!function_exists('exif_imagetype')) { - - /** - * @param $name - * @return string - */ - function exif_imagetype($name): string - { - return get_file_extension($name); - } -} - - -if (!function_exists('logger')) { - - - /** - * @return Logger - * @throws Exception - */ - function logger(): Logger - { - return Kiri::app()->getLogger(); - } -} - - -if (!function_exists('trim_blank')) { - - - /** - * 空白字符替换 - * @param string $content 内容 - * @param int $len 截取长度 - * @param string $encode 编码 - * @param bool $htmlTags - * @return array|string|null - */ - function trim_blank(string $content, int $len = 0, string $encode = 'utf-8', bool $htmlTags = TRUE): array|string|null - { - $str = trim($content); - if ($htmlTags) { - $str = strip_tags($str); - } - $str = preg_replace('/[\n|\r|\t]+/', '', $str); - $str = preg_replace("/(\s|\ \;| |\xc2\xa0)/", '', $str); - if ($len > 0) { - return mb_substr($str, 0, $len, $encode); - } else { - return $str; - } - } -} - - -if (!function_exists('get_file_extension')) { - - function get_file_extension($filename): bool|int|string - { - $mime_types = [ - 'txt' => 'text/plain', - 'htm' => 'text/html', - 'html' => 'text/html', - 'php' => 'text/html', - 'css' => 'text/css', - 'js' => 'application/javascript', - 'json' => 'application/json', - 'xml' => 'application/xml', - 'swf' => 'application/x-shockwave-flash', - 'flv' => 'video/x-flv', - - // images - 'png' => 'image/png', - 'jpeg' => 'image/jpeg', - 'gif' => 'image/gif', - 'bmp' => 'image/bmp', - 'ico' => 'image/vnd.microsoft.icon', - 'tiff' => 'image/tiff', - 'svg' => 'image/svg+xml', - - // archives - 'zip' => 'application/zip', - 'rar' => 'application/x-rar-compressed', - 'exe' => 'application/x-msdownload', - 'msi' => 'application/x-msdownload', - 'cab' => 'application/vnd.ms-cab-compressed', - - // audio/video - 'mp3' => 'audio/mpeg', - 'qt' => 'video/quicktime', - 'mov' => 'video/quicktime', - - // adobe - 'pdf' => 'application/pdf', - 'psd' => 'image/vnd.adobe.photoshop', - 'ai' => 'application/postscript', - 'eps' => 'application/postscript', - 'ps' => 'application/postscript', - - // ms office - 'doc' => 'application/msword', - 'rtf' => 'application/rtf', - 'xls' => 'application/vnd.ms-excel', - 'ppt' => 'application/vnd.ms-powerpoint', - - // open office - 'odt' => 'application/vnd.oasis.opendocument.text', - 'ods' => 'application/vnd.oasis.opendocument.spreadsheet', - - - '323' => 'text / h323', - 'acx' => 'application/internet-property-stream', - 'aif' => 'audio/x-aiff', - 'aifc' => 'audio/x-aiff', - 'aiff' => 'audio/x-aiff', - 'asf' => 'video/x-ms-asf', - 'asr' => 'video/x-ms-asf', - 'asx' => 'video/x-ms-asf', - 'au' => 'audio/basic', - 'avi' => 'video/x-msvideo', - 'axs' => 'application/olescript', - 'bas' => 'text/plain', - 'bcpio' => 'application/x-bcpio', - 'bin' => 'application/octet-stream', - 'c' => 'text/plain', - 'cat' => 'application/vnd.ms-pkiseccat', - 'cdf' => 'application/x-cdf', - 'cer' => 'application/x-x509-ca-cert', - 'class' => 'application/octet-stream', - 'clp' => 'application/x-msclip', - 'cmx' => 'image/x-cmx', - 'cod' => 'image/cis-cod', - 'cpio' => 'application/x-cpio', - 'crd' => 'application/x-mscardfile', - 'crl' => 'application/pkix-crl', - 'crt' => 'application/x-x509-ca-cert', - 'csh' => 'application/x-csh', - 'dcr' => 'application/x-director', - 'der' => 'application/x-x509-ca-cert', - 'dir' => 'application/x-director', - 'dll' => 'application/x-msdownload', - 'dms' => 'application/octet-stream', - 'dot' => 'application/msword', - 'dvi' => 'application/x-dvi', - 'dxr' => 'application/x-director', - 'etx' => 'text/x-setext', - 'evy' => 'application/envoy', - 'fif' => 'application/fractals', - 'flr' => 'x-world/x-vrml', - 'gtar' => 'application/x-gtar', - 'gz' => 'application/x-gzip', - 'h' => 'text/plain', - 'hdf' => 'application/x-hdf', - 'hlp' => 'application/winhlp', - 'hqx' => 'application/mac-binhex40', - 'hta' => 'application/hta', - 'htc' => 'text/x-component', - 'htt' => 'text/webviewhtml', - 'ief' => 'image/ief', - 'iii' => 'application/x-iphone', - 'ins' => 'application/x-internet-signup', - 'isp' => 'application/x-internet-signup', - 'jfif' => 'image/pipeg', - 'jpe' => 'image/jpeg', - 'jpg' => 'image/jpeg', - 'latex' => 'application/x-latex', - 'lha' => 'application/octet-stream', - 'lsf' => 'video/x-la-asf', - 'lsx' => 'video/x-la-asf', - 'lzh' => 'application/octet-stream', - 'm13' => 'application/x-msmediaview', - 'm14' => 'application/x-msmediaview', - 'm3u' => 'audio/x-mpegurl', - 'man' => 'application/x-troff-man', - 'mdb' => 'application/x-msaccess', - 'me' => 'application/x-troff-me', - 'mht' => 'message/rfc822', - 'mhtml' => 'message/rfc822', - 'mid' => 'audio/mid', - 'mny' => 'application/x-msmoney', - 'movie' => 'video/x-sgi-movie', - 'mp2' => 'video/mpeg', - 'mpa' => 'video/mpeg', - 'mpe' => 'video/mpeg', - 'mpeg' => 'video/mpeg', - 'mpg' => 'video/mpeg', - 'mpp' => 'application/vnd.ms-project', - 'mpv2' => 'video/mpeg', - 'ms' => 'application/x-troff-ms', - 'mvb' => 'application/x-msmediaview', - 'nws' => 'message/rfc822', - 'oda' => 'application/oda', - 'p10' => 'application/pkcs10', - 'p12' => 'application/x-pkcs12', - 'p7b' => 'application/x-pkcs7-certificates', - 'p7c' => 'application/x-pkcs7-mime', - 'p7m' => 'application/x-pkcs7-mime', - 'p7r' => 'application/x-pkcs7-certreqresp', - 'p7s' => 'application/x-pkcs7-signature', - 'pbm' => 'image/x-portable-bitmap', - 'pfx' => 'application/x-pkcs12', - 'pgm' => 'image/x-portable-graymap', - 'pko' => 'application/ynd.ms-pkipko', - 'pma' => 'application/x-perfmon', - 'pmc' => 'application/x-perfmon', - 'pml' => 'application/x-perfmon', - 'pmr' => 'application/x-perfmon', - 'pmw' => 'application/x-perfmon', - 'pnm' => 'image/x-portable-anymap', - 'pot' => 'application/vnd.ms-powerpoint', - 'ppm' => 'image/x-portable-pixmap', - 'pps' => 'application/vnd.ms-powerpoint', - 'prf' => 'application/pics-rules', - 'pub' => 'application/x-mspublisher', - 'ra' => 'audio/x-pn-realaudio', - 'ram' => 'audio/x-pn-realaudio', - 'ras' => 'image/x-cmu-raster', - 'rgb' => 'image/x-rgb', - 'rmi' => 'audio/mid', - 'roff' => 'application/x-troff', - 'rtx' => 'text/richtext', - 'scd' => 'application/x-msschedule', - 'sct' => 'text/scriptlet', - 'setpay' => 'application/set-payment-initiation', - 'setreg' => 'application/set-registration-initiation', - 'sh' => 'application/x-sh', - 'shar' => 'application/x-shar', - 'sit' => 'application/x-stuffit', - 'snd' => 'audio/basic', - 'spc' => 'application/x-pkcs7-certificates', - 'spl' => 'application/futuresplash', - 'src' => 'application/x-wais-source', - 'sst' => 'application/vnd.ms-pkicertstore', - 'stl' => 'application/vnd.ms-pkistl', - 'stm' => 'text/html', - 'sv4cpio' => 'application/x-sv4cpio', - 'sv4crc' => 'application/x-sv4crc', - 't' => 'application/x-troff', - 'tar' => 'application/x-tar', - 'tcl' => 'application/x-tcl', - 'tex' => 'application/x-tex', - 'texi' => 'application/x-texinfo', - 'texinfo' => 'application/x-texinfo', - 'tgz' => 'application/x-compressed', - 'tif' => 'image/tiff', - 'tr' => 'application/x-troff', - 'trm' => 'application/x-msterminal', - 'tsv' => 'text/tab-separated-values', - 'uls' => 'text/iuls', - 'ustar' => 'application/x-ustar', - 'vcf' => 'text/x-vcard', - 'vrml' => 'x-world/x-vrml', - 'wav' => 'audio/x-wav', - 'wcm' => 'application/vnd.ms-works', - 'wdb' => 'application/vnd.ms-works', - 'wks' => 'application/vnd.ms-works', - 'wmf' => 'application/x-msmetafile', - 'wps' => 'application/vnd.ms-works', - 'wri' => 'application/x-mswrite', - 'wrl' => 'x-world/x-vrml', - 'wrz' => 'x-world/x-vrml', - 'xaf' => 'x-world/x-vrml', - 'xbm' => 'image/x-xbitmap', - 'xla' => 'application/vnd.ms-excel', - 'xlc' => 'application/vnd.ms-excel', - 'xlm' => 'application/vnd.ms-excel', - 'xlt' => 'application/vnd.ms-excel', - 'xlw' => 'application/vnd.ms-excel', - 'xof' => 'x-world/x-vrml', - 'xpm' => 'image/x-xpixmap', - 'xwd' => 'image/x-xwindowdump', - 'z' => 'application/x-compress', - ]; - - $explode = explode('.', $filename); - $ext = strtolower(array_pop($explode)); - if (array_key_exists($ext, $mime_types)) { - return $ext; - } else if (function_exists('finfo_open')) { - $fInfo = finfo_open(FILEINFO_MIME); - $mimeType = finfo_file($fInfo, $filename); - finfo_close($fInfo); - $mimeType = current(explode('; ', $mimeType)); - if (($search = array_search($mimeType, $mime_types)) == FALSE) { - return $mimeType; - } - return $search; - } else { - return 'application/octet-stream'; - } - } -} - -if (!function_exists('storage')) { - - /** - * @param string|null $fileName - * @param string|null $path - * @return string - * @throws Exception - */ - function storage(?string $fileName = '', ?string $path = ''): string - { - - $basePath = rtrim(Kiri::getStoragePath(), '/'); - if (!empty($path)) { - $path = ltrim($path, '/'); - if (!is_dir($basePath . '/' . $path)) { - mkdir($basePath . '/' . $path, 0777, TRUE); - } - } - if (empty($fileName)) { - return $basePath . '/' . $path; - } - $fileName = $basePath . '/' . $path . $fileName; - if (!file_exists($fileName)) { - touch($fileName); - } - return $fileName; - } -} - - -if (!function_exists('event')) { - - - /** - * @param $name - * @param $callback - * @param bool $isAppend - * @throws Exception - */ - function event($name, $callback, bool $isAppend = TRUE) - { - $pro = di(EventProvider::class); - $pro->on($name, $callback, 0); - } - -} - - -if (!function_exists('name')) { - - /** - * @param int $pid - * @param string|null $prefix - * @throws ConfigException - * @throws Exception - */ - function name(int $pid, string $prefix = NULL) - { - if (Kiri::getPlatform()->isMac()) { - return; - } - - $name = Config::get('id', 'system') . '[' . $pid . ']'; - if (!empty($prefix)) { - $name .= '.' . $prefix; - } - swoole_set_process_name($name); - } - -} - - -if (!function_exists('zero_full')) { - function zero_full(int $data = 1, int $length = 10): string - { - return sprintf('%0' . $length . 'd', $data); - } -} - - -if (!function_exists('env')) { - - /** - * @param $key - * @param null $default - * @return array|string|null - */ - #[Pure] function env($key, $default = NULL): null|array|string - { - $env = getenv($key); - if ($env === FALSE) { - return $default; - } - return $env; - } - -} - - -if (!function_exists('di')) { - - - /** - * @param string $className - * @return mixed - */ - function di(string $className): mixed - { - return Kiri::getDi()->get($className); - } - -} - - -if (!function_exists('interval')) { - - - /** - * @param callable $callback - * @param int $interval - * @param bool $is - */ - function interval(callable $callback, int $interval = 1000, bool $is = FALSE) - { - usleep($interval * 1000); - - $callback(); - - interval($callback, $interval, $is); - } - -} - - -if (!function_exists('duplicate')) { - - - /** - * @param string $className - * @return mixed - * @throws ReflectionException - */ - function duplicate(string $className): mixed - { - $class = di($className); - $clone = clone $class; - if (method_exists($clone, 'clear')) { - $clone->clear(); - } - return $clone; - } - -} - -if (!function_exists('sweep')) { - - /** - * @param string $configPath - * @return array|false|string|null - */ - function sweep(string $configPath = APP_PATH . 'config'): bool|array|string|null - { - $array = []; - foreach (glob($configPath . '/*') as $config) { - $array = array_merge(require_once "$config", $array); - } - return $array; - } - -} - - -if (!function_exists('swoole_serialize')) { - - - /** - * @param $data - * @return string - */ - function swoole_serialize($data): string - { -// if (class_exists('swoole_serialize')) { -// return \swoole_serialize::pack($data); -// } else { - return serialize($data); -// } - } - -} - - -if (!function_exists('swoole_unserialize')) { - - - /** - * @param $data - * @return string - */ - function swoole_unserialize($data): mixed - { - if (empty($data)) { - return NULL; - } -// if (class_exists('swoole_serialize')) { -// return \swoole_serialize::unpack($data); -// } else { - return unserialize($data); -// } - } - -} - - -if (!function_exists('merge')) { - - - /** - * @param $param - * @param $param1 - * @return array - */ - function merge($param, $param1): array - { - return ArrayAccess::merge($param, $param1); - } - -} - - -if (!function_exists('router')) { - - - /** - * @return Router - * @throws Exception - */ - function router(): Router - { - return Kiri::getDi()->get(Router::class); - } - -} - - -if (!function_exists('isService')) { - - - /** - * @param string $name - * @return bool - */ - function isService(string $name): bool - { - return Kiri::app()->has($name); - } - -} - -if (!function_exists('getService')) { - - - /** - * @param string $name - * @return mixed - * @throws Exception - */ - function getService(string $name): mixed - { - return Kiri::app()->get($name); - } - -} - - -if (!function_exists('jTraceEx')) { - - /** - * @param $e - * @param null $seen - * @param bool $toHtml - * @return string - */ - function jTraceEx($e, $seen = NULL, bool $toHtml = FALSE): string - { - $starter = $seen ? 'Caused by: ' : ''; - $result = []; - if (!$seen) $seen = []; - $trace = $e->getTrace(); - $prev = $e->getPrevious(); - $result[] = sprintf('%s%s: %s', $starter, $e::class, $e->getMessage()); - $file = $e->getFile(); - $line = $e->getLine(); - - foreach ($trace as $value) { - $result[] = sprintf(' at %s%s%s(%s%s%s)', - count($value) && array_key_exists('class', $value) ? str_replace('\\', '.', $value['class']) : '', - count($value) && array_key_exists('class', $value) && array_key_exists('function', $value) ? '.' : '', - count($value) && array_key_exists('function', $value) ? str_replace('\\', '.', $value['function']) : '(main)', - $line === NULL ? $file : basename($file), - $line === NULL ? '' : ':', - $line === NULL ? '' : $line); - - $file = array_key_exists('file', $value) ? $value['file'] : 'Unknown Source'; - $line = array_key_exists('file', $value) && array_key_exists('line', $value) && $value['line'] ? $value['line'] : NULL; - } - $result = join($toHtml ? "
" : "\n", $result); - if ($prev) { - $result .= ($toHtml ? "
" : "\n") . jTraceEx($prev, $seen, $toHtml); - } - - return $result; - } - - -} - - -if (!function_exists('swoole_substr_json_decode')) { - - - /** - * @param $packet - * @param int $length - * @return mixed - */ - function swoole_substr_json_decode($packet, int $length = 0): mixed - { - return json_decode($packet, TRUE); - } - -} - - -if (!function_exists('swoole_substr_unserialize')) { - - /** - * @param $packet - * @param int $length - * @return mixed - */ - function swoole_substr_unserialize($packet, int $length = 0): mixed - { - return unserialize($packet); - } - -} - - -if (!function_exists('debug')) { - - /** - * @param mixed $message - * @param string $method - * @throws Exception - */ - function debug(mixed $message, string $method = 'app') - { - Kiri::app()->debug($message, $method); - } - -} - -if (!function_exists('info')) { - - /** - * @param mixed $message - * @param string $method - * @throws Exception - */ - function info(mixed $message, string $method = 'app') - { - Kiri::app()->info($message, $method); - } - -} - -if (!function_exists('error')) { - - /** - * @param mixed $message - * @param string $method - * @throws Exception - */ - function error(mixed $message, string $method = 'error') - { - Kiri::getDi()->get(LoggerInterface::class)->error($method, [$message]); - } -} - -if (!function_exists('success')) { - - /** - * @param mixed $message - * @param string $method - * @throws Exception - */ - function success(mixed $message, string $method = 'app') - { - Kiri::app()->success($message, $method); - } -} - +get($name); + } + if (empty($default)) { + throw new Exception("Unknown component ID: $name"); + } + if (Kiri::has($default)) { + return Kiri::app()->get($default); + } + $class = Kiri::createObject($default); + class_alias($name, $default, TRUE); + return $class; + } + + +} + + +if (!function_exists('map')) { + + + /** + * @param array $params + * @param Closure $closure + * @return mixed + */ + function map(array $params, Closure $closure): mixed + { + return array_map($closure, $params); + } + +} + + +if (!function_exists('checkPortIsAlready')) { + + + /** + * @param $port + * @return bool|string + * @throws Exception + */ + function checkPortIsAlready($port): bool|string + { + if (!Kiri::getPlatform()->isLinux()) { + exec("lsof -i :" . $port . " | grep -i 'LISTEN' | awk '{print $2}'", $output); + if (empty($output)) return FALSE; + $output = explode(PHP_EOL, $output[0]); + return $output[0]; + } + + $serverPid = file_get_contents(storage('.swoole.pid')); + if (!empty($serverPid) && shell_exec('ps -ef | grep ' . $serverPid . ' | grep -v grep')) { + Process::kill($serverPid, 0) && Process::kill($serverPid, SIGTERM); + } + + exec('netstat -lnp | grep ' . $port . ' | grep "LISTEN" | awk \'{print $7}\'', $output); + if (empty($output)) { + return FALSE; + } + return explode('/', $output[0])[0]; + } + +} + + +if (!function_exists('done')) { + + /** + * + */ + function done() + { + set_env('state', 'exit'); + } + +} + + +if (!function_exists('set_env')) { + + + /** + * @param $key + * @param $value + */ + function set_env($key, $value) + { + putenv(sprintf('%s=%s', $key, $value)); + } + +} + +if (!function_exists('enable_file_modification_listening')) { + + + function enable_file_modification_listening(): void + { + putenv('enable_file_modification_listening=on'); + } + + +} + + +if (!function_exists('is_enable_file_modification_listening')) { + + + /** + * @return bool + */ + #[Pure] function is_enable_file_modification_listening(): bool + { + return env('enable_file_modification_listening', 'off') == 'on'; + } + + +} + +if (!function_exists('disable_file_modification_listening')) { + + + function disable_file_modification_listening() + { + putenv('enable_file_modification_listening=off'); + } + + +} + + +if (!function_exists('now')) { + + /** + * @return string + */ + function now(): string + { + return date('Y-m-d H:i:s') . '.' . str_replace(time() . '.', '', (string)microtime(TRUE)); + } +} + + +if (!function_exists('workerName')) { + + + /** + * @param $worker_id + * @return string + */ + function workerName($worker_id) + { + return $worker_id >= Kiri::app()->getSwoole()->setting['worker_num'] ? 'Task' : 'Worker'; + } + +} + + +if (!function_exists('Annotation')) { + + + /** + * @return Annotation + * @throws Exception + */ + function annotation(): Annotation + { + return Kiri::getAnnotation(); + } + + +} + + +if (!function_exists('scan_directory')) { + + + /** + * @param $dir + * @param $namespace + * @param array $exclude + * @throws ReflectionException + * @throws Exception + */ + function scan_directory($dir, $namespace, array $exclude = []) + { + $annotation = Kiri::app()->getAnnotation(); + $annotation->read($dir, $namespace, $exclude); + + injectRuntime($dir, $exclude); + } + +} + +if (!class_exists('ReturnTypeWillChange')) { + + /** + * @since 8.1 + */ + #[Attribute(Attribute::TARGET_METHOD)] + final class ReturnTypeWillChange + { + public function __construct() + { + } + } + + +} + + +if (!function_exists('injectRuntime')) { + + + /** + * @param string $path + * @param array $exclude + * @throws ReflectionException + * @throws Exception + */ + function injectRuntime(string $path, array $exclude = []) + { + $fileLists = Kiri::getAnnotation()->runtime($path, $exclude); + $di = Kiri::getDi(); + + $router = []; + foreach ($fileLists as $class) { + foreach (AnnotationManager::getTargetAnnotation($class) as $value) { + if (!method_exists($value, 'execute')) { + continue; + } + $value->execute($class); + } + $methods = $di->getMethodAttribute($class); + foreach ($methods as $method => $attribute) { + if (empty($attribute)) { + continue; + } + foreach ($attribute as $item) { + if ($item instanceof Route) { + $router[] = [$item, $class, $method]; + } else { + if (!method_exists($item, 'execute')) { + continue; + } + $item->execute($class, $method); + } + } + } + } + if (!empty($router)) { + foreach ($router as $class) { + [$item, $class, $method] = $class; + if (!method_exists($item, 'execute')) { + continue; + } + $item->execute($class, $method); + } + } + } + +} + + +if (!function_exists('swoole')) { + + + /** + * @return Server|null + * @throws Exception + */ + function swoole(): ?Server + { + return Kiri::getWebSocket(); + } + + +} + + +if (!function_exists('directory')) { + + /** + * @param $name + * @return string + */ + #[Pure] function directory($name): string + { + return realpath(APP_PATH . $name); + } + + +} + + +if (!function_exists('isUrl')) { + + + /** + * @param $url + * @param bool $get_info + * @return false|array + */ + function isUrl($url, bool $get_info = TRUE): bool|array + { + if (str_starts_with($url, '/')) { + return FALSE; + } + $queryMatch = '/((http[s]?):\/\/)?(([\w\-\_]+\.)+\w+(:\d+)?)(\/.*)?/'; + if (!preg_match($queryMatch, $url, $outPut)) { + return FALSE; + } + + [$scheme, $host, $port, $user, $pass, $query, $path, $fragment] = parse_url($url); + if ($scheme == 'https' && empty($port)) { + $port = 443; + } + + if (!empty($query)) $path .= '?' . $query; + if (!empty($fragment)) $path .= '#' . $fragment; + + + unset($outPut); + + return [$scheme == 'https', $host, $port, $path]; + } + +} + + +if (!function_exists('split_request_uri')) { + + + /** + * @param $url + * @return false|array + */ + function split_request_uri($url): bool|array + { + if (($parse = isUrl($url, NULL)) === FALSE) { + return FALSE; + } + + [$isHttps, $domain, $port, $path] = $parse; + $uri = $isHttps ? 'https://' . $domain : 'http://' . $domain; + if (!empty($port)) { + $uri .= ':' . $port; + } + return [$uri, $path]; + } + +} + + +if (!function_exists('hadDomain')) { + + + /** + * @param $url + * @return false|array + */ + function hadDomain($url): bool|array + { + $param = split_request_uri($url); + return !is_array($param) ? FALSE : $param[0]; + } + +} + + +if (!function_exists('isDomain')) { + + + /** + * @param $url + * @return false|array + */ + function isDomain($url): array|bool + { + return !isIp($url); + } + +} +if (!function_exists('isIp')) { + + + /** + * @param $url + * @return false|array + */ + function isIp($url): bool|array + { + return preg_match('/(\d{1,3}\.){3}\.\d{1,3}(:\d{1,5})?/', $url); + } + +} + + +if (!function_exists('loadByDir')) { + + + /** + * @param $namespace + * @param $dirname + */ + function classAutoload($namespace, $dirname) + { + foreach (glob(rtrim($dirname, '/') . '/*') as $value) { + $value = realpath($value); + if (is_dir($value)) { + classAutoload($namespace, $value); + } else { + $pos = strpos($value, '.php'); + if ($pos === FALSE || strlen($value) - 4 != $pos) { + continue; + } + + $replace = ltrim(str_replace(__DIR__, '', $value), '/'); + $replace = str_replace('.php', '', $replace); + + $first = explode(DIRECTORY_SEPARATOR, $replace); + array_shift($first); + + Kiri::setAutoload($namespace . '\\' . implode('\\', $first), $value); + } + } + } + + +} + + +if (!function_exists('write')) { + + + /** + * @param string $messages + * @param string $category + * @throws Exception + */ + function write(string $messages, string $category = 'app') + { + $logger = Kiri::app()->getLogger(); + $logger->write($messages, $category); + } +} + + +if (!function_exists('redis')) { + + + /** + * @return \Kiri\Cache\Redis|Redis + * @throws Exception + */ + function redis(): \Kiri\Cache\Redis|Redis + { + return Kiri::getDi()->get(\Kiri\Cache\Redis::class); + } +} + +if (!function_exists('fire')) { + + + /** + * @param object $event + */ + function fire(object $event) + { + di(EventDispatch::class)->dispatch($event); + } +} + + +if (!function_exists('app')) { + + + /** + * @return Application|null + */ + #[Pure] function app(): ?Application + { + return Kiri::app(); + } + +} + +if (!function_exists('instance_load')) { + + function instance_load() + { + $content = json_decode(file_get_contents(__DIR__ . '/composer.json'), TRUE); + if (isset($content['autoload']) && isset($content['autoload']['psr-4'])) { + $psr4 = $content['autoload']['psr-4']; + foreach ($psr4 as $namespace => $dirname) { + classAutoload($namespace, __DIR__ . '/' . $dirname); + } + } + } + +} + + +if (!function_exists('exif_imagetype')) { + + /** + * @param $name + * @return string + */ + function exif_imagetype($name): string + { + return get_file_extension($name); + } +} + + +if (!function_exists('logger')) { + + + /** + * @return Logger + * @throws Exception + */ + function logger(): Logger + { + return Kiri::app()->getLogger(); + } +} + + +if (!function_exists('trim_blank')) { + + + /** + * 空白字符替换 + * @param string $content 内容 + * @param int $len 截取长度 + * @param string $encode 编码 + * @param bool $htmlTags + * @return array|string|null + */ + function trim_blank(string $content, int $len = 0, string $encode = 'utf-8', bool $htmlTags = TRUE): array|string|null + { + $str = trim($content); + if ($htmlTags) { + $str = strip_tags($str); + } + $str = preg_replace('/[\n|\r|\t]+/', '', $str); + $str = preg_replace("/(\s|\ \;| |\xc2\xa0)/", '', $str); + if ($len > 0) { + return mb_substr($str, 0, $len, $encode); + } else { + return $str; + } + } +} + + +if (!function_exists('get_file_extension')) { + + function get_file_extension($filename): bool|int|string + { + $mime_types = [ + 'txt' => 'text/plain', + 'htm' => 'text/html', + 'html' => 'text/html', + 'php' => 'text/html', + 'css' => 'text/css', + 'js' => 'application/javascript', + 'json' => 'application/json', + 'xml' => 'application/xml', + 'swf' => 'application/x-shockwave-flash', + 'flv' => 'video/x-flv', + + // images + 'png' => 'image/png', + 'jpeg' => 'image/jpeg', + 'gif' => 'image/gif', + 'bmp' => 'image/bmp', + 'ico' => 'image/vnd.microsoft.icon', + 'tiff' => 'image/tiff', + 'svg' => 'image/svg+xml', + + // archives + 'zip' => 'application/zip', + 'rar' => 'application/x-rar-compressed', + 'exe' => 'application/x-msdownload', + 'msi' => 'application/x-msdownload', + 'cab' => 'application/vnd.ms-cab-compressed', + + // audio/video + 'mp3' => 'audio/mpeg', + 'qt' => 'video/quicktime', + 'mov' => 'video/quicktime', + + // adobe + 'pdf' => 'application/pdf', + 'psd' => 'image/vnd.adobe.photoshop', + 'ai' => 'application/postscript', + 'eps' => 'application/postscript', + 'ps' => 'application/postscript', + + // ms office + 'doc' => 'application/msword', + 'rtf' => 'application/rtf', + 'xls' => 'application/vnd.ms-excel', + 'ppt' => 'application/vnd.ms-powerpoint', + + // open office + 'odt' => 'application/vnd.oasis.opendocument.text', + 'ods' => 'application/vnd.oasis.opendocument.spreadsheet', + + + '323' => 'text / h323', + 'acx' => 'application/internet-property-stream', + 'aif' => 'audio/x-aiff', + 'aifc' => 'audio/x-aiff', + 'aiff' => 'audio/x-aiff', + 'asf' => 'video/x-ms-asf', + 'asr' => 'video/x-ms-asf', + 'asx' => 'video/x-ms-asf', + 'au' => 'audio/basic', + 'avi' => 'video/x-msvideo', + 'axs' => 'application/olescript', + 'bas' => 'text/plain', + 'bcpio' => 'application/x-bcpio', + 'bin' => 'application/octet-stream', + 'c' => 'text/plain', + 'cat' => 'application/vnd.ms-pkiseccat', + 'cdf' => 'application/x-cdf', + 'cer' => 'application/x-x509-ca-cert', + 'class' => 'application/octet-stream', + 'clp' => 'application/x-msclip', + 'cmx' => 'image/x-cmx', + 'cod' => 'image/cis-cod', + 'cpio' => 'application/x-cpio', + 'crd' => 'application/x-mscardfile', + 'crl' => 'application/pkix-crl', + 'crt' => 'application/x-x509-ca-cert', + 'csh' => 'application/x-csh', + 'dcr' => 'application/x-director', + 'der' => 'application/x-x509-ca-cert', + 'dir' => 'application/x-director', + 'dll' => 'application/x-msdownload', + 'dms' => 'application/octet-stream', + 'dot' => 'application/msword', + 'dvi' => 'application/x-dvi', + 'dxr' => 'application/x-director', + 'etx' => 'text/x-setext', + 'evy' => 'application/envoy', + 'fif' => 'application/fractals', + 'flr' => 'x-world/x-vrml', + 'gtar' => 'application/x-gtar', + 'gz' => 'application/x-gzip', + 'h' => 'text/plain', + 'hdf' => 'application/x-hdf', + 'hlp' => 'application/winhlp', + 'hqx' => 'application/mac-binhex40', + 'hta' => 'application/hta', + 'htc' => 'text/x-component', + 'htt' => 'text/webviewhtml', + 'ief' => 'image/ief', + 'iii' => 'application/x-iphone', + 'ins' => 'application/x-internet-signup', + 'isp' => 'application/x-internet-signup', + 'jfif' => 'image/pipeg', + 'jpe' => 'image/jpeg', + 'jpg' => 'image/jpeg', + 'latex' => 'application/x-latex', + 'lha' => 'application/octet-stream', + 'lsf' => 'video/x-la-asf', + 'lsx' => 'video/x-la-asf', + 'lzh' => 'application/octet-stream', + 'm13' => 'application/x-msmediaview', + 'm14' => 'application/x-msmediaview', + 'm3u' => 'audio/x-mpegurl', + 'man' => 'application/x-troff-man', + 'mdb' => 'application/x-msaccess', + 'me' => 'application/x-troff-me', + 'mht' => 'message/rfc822', + 'mhtml' => 'message/rfc822', + 'mid' => 'audio/mid', + 'mny' => 'application/x-msmoney', + 'movie' => 'video/x-sgi-movie', + 'mp2' => 'video/mpeg', + 'mpa' => 'video/mpeg', + 'mpe' => 'video/mpeg', + 'mpeg' => 'video/mpeg', + 'mpg' => 'video/mpeg', + 'mpp' => 'application/vnd.ms-project', + 'mpv2' => 'video/mpeg', + 'ms' => 'application/x-troff-ms', + 'mvb' => 'application/x-msmediaview', + 'nws' => 'message/rfc822', + 'oda' => 'application/oda', + 'p10' => 'application/pkcs10', + 'p12' => 'application/x-pkcs12', + 'p7b' => 'application/x-pkcs7-certificates', + 'p7c' => 'application/x-pkcs7-mime', + 'p7m' => 'application/x-pkcs7-mime', + 'p7r' => 'application/x-pkcs7-certreqresp', + 'p7s' => 'application/x-pkcs7-signature', + 'pbm' => 'image/x-portable-bitmap', + 'pfx' => 'application/x-pkcs12', + 'pgm' => 'image/x-portable-graymap', + 'pko' => 'application/ynd.ms-pkipko', + 'pma' => 'application/x-perfmon', + 'pmc' => 'application/x-perfmon', + 'pml' => 'application/x-perfmon', + 'pmr' => 'application/x-perfmon', + 'pmw' => 'application/x-perfmon', + 'pnm' => 'image/x-portable-anymap', + 'pot' => 'application/vnd.ms-powerpoint', + 'ppm' => 'image/x-portable-pixmap', + 'pps' => 'application/vnd.ms-powerpoint', + 'prf' => 'application/pics-rules', + 'pub' => 'application/x-mspublisher', + 'ra' => 'audio/x-pn-realaudio', + 'ram' => 'audio/x-pn-realaudio', + 'ras' => 'image/x-cmu-raster', + 'rgb' => 'image/x-rgb', + 'rmi' => 'audio/mid', + 'roff' => 'application/x-troff', + 'rtx' => 'text/richtext', + 'scd' => 'application/x-msschedule', + 'sct' => 'text/scriptlet', + 'setpay' => 'application/set-payment-initiation', + 'setreg' => 'application/set-registration-initiation', + 'sh' => 'application/x-sh', + 'shar' => 'application/x-shar', + 'sit' => 'application/x-stuffit', + 'snd' => 'audio/basic', + 'spc' => 'application/x-pkcs7-certificates', + 'spl' => 'application/futuresplash', + 'src' => 'application/x-wais-source', + 'sst' => 'application/vnd.ms-pkicertstore', + 'stl' => 'application/vnd.ms-pkistl', + 'stm' => 'text/html', + 'sv4cpio' => 'application/x-sv4cpio', + 'sv4crc' => 'application/x-sv4crc', + 't' => 'application/x-troff', + 'tar' => 'application/x-tar', + 'tcl' => 'application/x-tcl', + 'tex' => 'application/x-tex', + 'texi' => 'application/x-texinfo', + 'texinfo' => 'application/x-texinfo', + 'tgz' => 'application/x-compressed', + 'tif' => 'image/tiff', + 'tr' => 'application/x-troff', + 'trm' => 'application/x-msterminal', + 'tsv' => 'text/tab-separated-values', + 'uls' => 'text/iuls', + 'ustar' => 'application/x-ustar', + 'vcf' => 'text/x-vcard', + 'vrml' => 'x-world/x-vrml', + 'wav' => 'audio/x-wav', + 'wcm' => 'application/vnd.ms-works', + 'wdb' => 'application/vnd.ms-works', + 'wks' => 'application/vnd.ms-works', + 'wmf' => 'application/x-msmetafile', + 'wps' => 'application/vnd.ms-works', + 'wri' => 'application/x-mswrite', + 'wrl' => 'x-world/x-vrml', + 'wrz' => 'x-world/x-vrml', + 'xaf' => 'x-world/x-vrml', + 'xbm' => 'image/x-xbitmap', + 'xla' => 'application/vnd.ms-excel', + 'xlc' => 'application/vnd.ms-excel', + 'xlm' => 'application/vnd.ms-excel', + 'xlt' => 'application/vnd.ms-excel', + 'xlw' => 'application/vnd.ms-excel', + 'xof' => 'x-world/x-vrml', + 'xpm' => 'image/x-xpixmap', + 'xwd' => 'image/x-xwindowdump', + 'z' => 'application/x-compress', + ]; + + $explode = explode('.', $filename); + $ext = strtolower(array_pop($explode)); + if (array_key_exists($ext, $mime_types)) { + return $ext; + } else if (function_exists('finfo_open')) { + $fInfo = finfo_open(FILEINFO_MIME); + $mimeType = finfo_file($fInfo, $filename); + finfo_close($fInfo); + $mimeType = current(explode('; ', $mimeType)); + if (($search = array_search($mimeType, $mime_types)) == FALSE) { + return $mimeType; + } + return $search; + } else { + return 'application/octet-stream'; + } + } +} + +if (!function_exists('storage')) { + + /** + * @param string|null $fileName + * @param string|null $path + * @return string + * @throws Exception + */ + function storage(?string $fileName = '', ?string $path = ''): string + { + + $basePath = rtrim(Kiri::getStoragePath(), '/'); + if (!empty($path)) { + $path = ltrim($path, '/'); + if (!is_dir($basePath . '/' . $path)) { + mkdir($basePath . '/' . $path, 0777, TRUE); + } + } + if (empty($fileName)) { + return $basePath . '/' . $path; + } + $fileName = $basePath . '/' . $path . $fileName; + if (!file_exists($fileName)) { + touch($fileName); + } + return $fileName; + } +} + + +if (!function_exists('event')) { + + + /** + * @param $name + * @param $callback + * @param bool $isAppend + * @throws Exception + */ + function event($name, $callback, bool $isAppend = TRUE) + { + $pro = di(EventProvider::class); + $pro->on($name, $callback, 0); + } + +} + + +if (!function_exists('name')) { + + /** + * @param int $pid + * @param string|null $prefix + * @throws ConfigException + * @throws Exception + */ + function name(int $pid, string $prefix = NULL) + { + if (Kiri::getPlatform()->isMac()) { + return; + } + + $name = Config::get('id', 'system') . '[' . $pid . ']'; + if (!empty($prefix)) { + $name .= '.' . $prefix; + } + swoole_set_process_name($name); + } + +} + + +if (!function_exists('zero_full')) { + function zero_full(int $data = 1, int $length = 10): string + { + return sprintf('%0' . $length . 'd', $data); + } +} + + +if (!function_exists('env')) { + + /** + * @param $key + * @param null $default + * @return array|string|null + */ + #[Pure] function env($key, $default = NULL): null|array|string + { + $env = getenv($key); + if ($env === FALSE) { + return $default; + } + return $env; + } + +} + + +if (!function_exists('di')) { + + + /** + * @param string $className + * @return mixed + */ + function di(string $className): mixed + { + return Kiri::getDi()->get($className); + } + +} + + +if (!function_exists('interval')) { + + + /** + * @param callable $callback + * @param int $interval + * @param bool $is + */ + function interval(callable $callback, int $interval = 1000, bool $is = FALSE) + { + usleep($interval * 1000); + + $callback(); + + interval($callback, $interval, $is); + } + +} + + +if (!function_exists('duplicate')) { + + + /** + * @param string $className + * @return mixed + * @throws ReflectionException + */ + function duplicate(string $className): mixed + { + $class = di($className); + $clone = clone $class; + if (method_exists($clone, 'clear')) { + $clone->clear(); + } + return $clone; + } + +} + +if (!function_exists('sweep')) { + + /** + * @param string $configPath + * @return array|false|string|null + */ + function sweep(string $configPath = APP_PATH . 'config'): bool|array|string|null + { + $array = []; + foreach (glob($configPath . '/*') as $config) { + $array = array_merge(require_once "$config", $array); + } + return $array; + } + +} + + +if (!function_exists('swoole_serialize')) { + + + /** + * @param $data + * @return string + */ + function swoole_serialize($data): string + { +// if (class_exists('swoole_serialize')) { +// return \swoole_serialize::pack($data); +// } else { + return serialize($data); +// } + } + +} + + +if (!function_exists('swoole_unserialize')) { + + + /** + * @param $data + * @return string + */ + function swoole_unserialize($data): mixed + { + if (empty($data)) { + return NULL; + } +// if (class_exists('swoole_serialize')) { +// return \swoole_serialize::unpack($data); +// } else { + return unserialize($data); +// } + } + +} + + +if (!function_exists('merge')) { + + + /** + * @param $param + * @param $param1 + * @return array + */ + function merge($param, $param1): array + { + return ArrayAccess::merge($param, $param1); + } + +} + + +if (!function_exists('router')) { + + + /** + * @return Router + * @throws Exception + */ + function router(): Router + { + return Kiri::getDi()->get(Router::class); + } + +} + + +if (!function_exists('isService')) { + + + /** + * @param string $name + * @return bool + */ + function isService(string $name): bool + { + return Kiri::app()->has($name); + } + +} + +if (!function_exists('getService')) { + + + /** + * @param string $name + * @return mixed + * @throws Exception + */ + function getService(string $name): mixed + { + return Kiri::app()->get($name); + } + +} + + +if (!function_exists('jTraceEx')) { + + /** + * @param $e + * @param null $seen + * @param bool $toHtml + * @return string + */ + function jTraceEx($e, $seen = NULL, bool $toHtml = FALSE): string + { + $starter = $seen ? 'Caused by: ' : ''; + $result = []; + if (!$seen) $seen = []; + $trace = $e->getTrace(); + $prev = $e->getPrevious(); + $result[] = sprintf('%s%s: %s', $starter, $e::class, $e->getMessage()); + $file = $e->getFile(); + $line = $e->getLine(); + + foreach ($trace as $value) { + $result[] = sprintf(' at %s%s%s(%s%s%s)', + count($value) && array_key_exists('class', $value) ? str_replace('\\', '.', $value['class']) : '', + count($value) && array_key_exists('class', $value) && array_key_exists('function', $value) ? '.' : '', + count($value) && array_key_exists('function', $value) ? str_replace('\\', '.', $value['function']) : '(main)', + $line === NULL ? $file : basename($file), + $line === NULL ? '' : ':', + $line === NULL ? '' : $line); + + $file = array_key_exists('file', $value) ? $value['file'] : 'Unknown Source'; + $line = array_key_exists('file', $value) && array_key_exists('line', $value) && $value['line'] ? $value['line'] : NULL; + } + $result = join($toHtml ? "
" : "\n", $result); + if ($prev) { + $result .= ($toHtml ? "
" : "\n") . jTraceEx($prev, $seen, $toHtml); + } + + return $result; + } + + +} + + +if (!function_exists('swoole_substr_json_decode')) { + + + /** + * @param $packet + * @param int $length + * @return mixed + */ + function swoole_substr_json_decode($packet, int $length = 0): mixed + { + return json_decode($packet, TRUE); + } + +} + + +if (!function_exists('swoole_substr_unserialize')) { + + /** + * @param $packet + * @param int $length + * @return mixed + */ + function swoole_substr_unserialize($packet, int $length = 0): mixed + { + return unserialize($packet); + } + +} + + +if (!function_exists('debug')) { + + /** + * @param mixed $message + * @param string $method + * @throws Exception + */ + function debug(mixed $message, string $method = 'app') + { + Kiri::app()->debug($message, $method); + } + +} + +if (!function_exists('info')) { + + /** + * @param mixed $message + * @param string $method + * @throws Exception + */ + function info(mixed $message, string $method = 'app') + { + Kiri::app()->info($message, $method); + } + +} + +if (!function_exists('error')) { + + /** + * @param mixed $message + * @param string $method + * @throws Exception + */ + function error(mixed $message, string $method = 'error') + { + Kiri::getDi()->get(LoggerInterface::class)->error($method, [$message]); + } +} + +if (!function_exists('success')) { + + /** + * @param mixed $message + * @param string $method + * @throws Exception + */ + function success(mixed $message, string $method = 'app') + { + Kiri::app()->success($message, $method); + } +} + diff --git a/kiri-annotation/Annotation.php b/kiri-annotation/Annotation.php index a8697c31..0e246796 100644 --- a/kiri-annotation/Annotation.php +++ b/kiri-annotation/Annotation.php @@ -1,86 +1,86 @@ -_loader = new Loader(); - } - - - /** - * @return Loader - */ - public function getLoader(): Loader - { - return $this->_loader; - } - - - /** - * @param Loader $loader - * @return Loader - */ - public function setLoader(Loader $loader): Loader - { - return $this->_loader = $loader; - } - - - /** - * @param object $class - * @throws ReflectionException - */ - public function injectProperty(object $class) - { - $this->_loader->injectProperty($class::class, $class); - } - - - /** - * @param string $path - * @param string $namespace - * @param array $exclude - * @return static - * @throws Exception - */ - public function read(string $path, string $namespace = 'App', array $exclude = []): static - { - $this->_loader->_scanDir(new DirectoryIterator($path), $namespace, $exclude); - return $this; - } - - - /** - * @param string $dir - * @param array $exclude - * @return array - * @throws Exception - */ - public function runtime(string $dir, array $exclude = []): array - { - return $this->_loader->loadByDirectory($dir, $exclude); - } - - -} +_loader = new Loader(); + } + + + /** + * @return Loader + */ + public function getLoader(): Loader + { + return $this->_loader; + } + + + /** + * @param Loader $loader + * @return Loader + */ + public function setLoader(Loader $loader): Loader + { + return $this->_loader = $loader; + } + + + /** + * @param object $class + * @throws ReflectionException + */ + public function injectProperty(object $class) + { + $this->_loader->injectProperty($class::class, $class); + } + + + /** + * @param string $path + * @param string $namespace + * @param array $exclude + * @return static + * @throws Exception + */ + public function read(string $path, string $namespace = 'App', array $exclude = []): static + { + $this->_loader->_scanDir(new DirectoryIterator($path), $namespace, $exclude); + return $this; + } + + + /** + * @param string $dir + * @param array $exclude + * @return array + * @throws Exception + */ + public function runtime(string $dir, array $exclude = []): array + { + return $this->_loader->loadByDirectory($dir, $exclude); + } + + +} diff --git a/kiri-annotation/Aspect.php b/kiri-annotation/Aspect.php index 5218a117..5d91f39c 100644 --- a/kiri-annotation/Aspect.php +++ b/kiri-annotation/Aspect.php @@ -1,37 +1,37 @@ -get(EventProvider::class); - if (is_string($class)) { - $class = Kiri::getDi()->get($class); - } - $pro->on($this->name, [$class, $method]); - return true; - } - -} +get(EventProvider::class); + if (is_string($class)) { + $class = Kiri::getDi()->get($class); + } + $pro->on($this->name, [$class, $method]); + return true; + } + +} diff --git a/kiri-annotation/IAnnotation.php b/kiri-annotation/IAnnotation.php index dca88fdd..ba6e56ce 100644 --- a/kiri-annotation/IAnnotation.php +++ b/kiri-annotation/IAnnotation.php @@ -1,19 +1,19 @@ -getProperty($class, $method))) { - return false; - } - /** @var ReflectionProperty $class */ - $injectValue = static::parseInjectValue(); - if ($method->isPrivate() || $method->isProtected()) { - $this->setter($class, $method, $injectValue); - } else { - $class->{$method->getName()} = $injectValue; - } - return true; - } - - - /** - * @param $class - * @param $method - * @param $injectValue - */ - private function setter($class, $method, $injectValue) - { - $method = 'set' . ucfirst(Str::convertUnderline($method->getName())); - if (!method_exists($class, $method)) { - return; - } - $class->$method($injectValue); - } - - - /** - * @param $class - * @param $method - * @return ReflectionProperty|bool - */ - private function getProperty($class, $method): ReflectionProperty|bool - { - if ($method instanceof ReflectionProperty && !$method->isStatic()) { - return $method; - } - if (is_object($class)) $class = $class::class; - $method = Kiri::getDi()->getClassReflectionProperty($class, $method); - if (!$method || $method->isStatic()) { - return false; - } - return $method; - } - - - /** - * @return mixed - * @throws Exception - */ - private function parseInjectValue(): mixed - { - if (!Kiri::app()->has($this->value)) { - if (!empty($this->construct)) { - return Kiri::getDi()->create($this->value, $this->construct); - } - return Kiri::getDi()->get($this->value); - } else { - return Kiri::app()->get($this->value); - } - } - -} +getProperty($class, $method))) { + return false; + } + /** @var ReflectionProperty $class */ + $injectValue = static::parseInjectValue(); + if ($method->isPrivate() || $method->isProtected()) { + $this->setter($class, $method, $injectValue); + } else { + $class->{$method->getName()} = $injectValue; + } + return true; + } + + + /** + * @param $class + * @param $method + * @param $injectValue + */ + private function setter($class, $method, $injectValue) + { + $method = 'set' . ucfirst(Str::convertUnderline($method->getName())); + if (!method_exists($class, $method)) { + return; + } + $class->$method($injectValue); + } + + + /** + * @param $class + * @param $method + * @return ReflectionProperty|bool + */ + private function getProperty($class, $method): ReflectionProperty|bool + { + if ($method instanceof ReflectionProperty && !$method->isStatic()) { + return $method; + } + if (is_object($class)) $class = $class::class; + $method = Kiri::getDi()->getClassReflectionProperty($class, $method); + if (!$method || $method->isStatic()) { + return false; + } + return $method; + } + + + /** + * @return mixed + * @throws Exception + */ + private function parseInjectValue(): mixed + { + if (!Kiri::app()->has($this->value)) { + if (!empty($this->construct)) { + return Kiri::getDi()->create($this->value, $this->construct); + } + return Kiri::getDi()->get($this->value); + } else { + return Kiri::app()->get($this->value); + } + } + +} diff --git a/kiri-annotation/Loader.php b/kiri-annotation/Loader.php index 30ed7ac5..49d0a46e 100644 --- a/kiri-annotation/Loader.php +++ b/kiri-annotation/Loader.php @@ -1,225 +1,225 @@ -_scanDir(new DirectoryIterator($path), $namespace); - } - - - /** - * @param string $class - * @param object $handler - * @return $this - * @throws ReflectionException - * @throws Exception - */ - public function injectProperty(string $class, object $handler): static - { - $di = Kiri::getDi(); - - $reflect = $di->getReflect($class); - - $di->propertyInject($reflect, $handler); - - return $this; - } - - - /** - * @param string $class - * @param string $method - * @return mixed - */ - public function getMethod(string $class, string $method = ''): array - { - if (!isset($this->_methods[$class])) { - return []; - } - $properties = $this->_methods[$class]; - if (!empty($method) && isset($properties[$method])) { - return $properties[$method]; - } - return $properties; - } - - - /** - * @param DirectoryIterator $paths - * @param $namespace - * @param array $exclude - * @throws Exception - */ - public function _scanDir(DirectoryIterator $paths, $namespace, array $exclude = []) - { - foreach ($paths as $path) { - if ($path->isDot() || str_starts_with($path->getFilename(), '.')) { - continue; - } - if ($this->inExclude($exclude, $path->getRealPath())) { - continue; - } - if ($path->isDir()) { - $iterator = new DirectoryIterator($path->getRealPath()); - $directory = rtrim($path->getRealPath(), '/'); - if (!isset($this->_directory[$directory])) { - $this->_directory[$directory] = []; - } - $this->_scanDir($iterator, $namespace); - } else { - $this->readFile($path, $namespace); - } - } - } - - - /** - * @param DirectoryIterator $path - * @param $namespace - * @throws Exception - */ - private function readFile(DirectoryIterator $path, $namespace) - { - try { - if ($path->getExtension() !== 'php') { - return; - } - $replace = $this->getReflect($path, $namespace); - if (!$replace || !$replace->getAttributes(Target::class)) { - return; - } - $this->appendFileToDirectory($path->getRealPath(), $replace->getName()); - } catch (Throwable $throwable) { - $this->error(jTraceEx($throwable), 'throwable'); - } - } - - - /** - * @param DirectoryIterator $path - * @param string $namespace - * @return ReflectionClass|null - */ - private function getReflect(DirectoryIterator $path, string $namespace): ?ReflectionClass - { - $class = $this->explodeFileName($path, $namespace); - if (!class_exists($class)) { - return null; - } - return Kiri::getDi()->getReflect($class); - } - - - /** - * @param string $path - * @param array $exclude - * @return array - * @throws Exception - */ - public function loadByDirectory(string $path, array $exclude = []): array - { - try { - $path = '/' . trim($path, '/'); - $paths = []; - foreach ($this->_directory as $key => $_path) { - $key = '/' . trim($key, '/'); - if (!str_starts_with($key, $path) || $this->inExclude($exclude, $path)) { - continue; - } - unset($this->_directory[$key]); - foreach ($_path as $item) { - $paths[] = $item; - } - } - return $paths; - } catch (Throwable $exception) { - $this->addError($exception, 'throwable'); - return []; - } - } - - - /** - * @param array $exclude - * @param $path - * @return bool - */ - private function inExclude(array $exclude, $path): bool - { - if (empty($exclude)) { - return false; - } - foreach ($exclude as $value) { - if (str_starts_with($path, $value)) { - return true; - } - } - return false; - } - - - /** - * @param DirectoryIterator $path - * @param string $namespace - * @return string - */ - private function explodeFileName(DirectoryIterator $path, string $namespace): string - { - $replace = str_replace(APP_PATH, '', $path->getRealPath()); - - $replace = str_replace('.php', '', $replace); - $replace = str_replace(DIRECTORY_SEPARATOR, '\\', $replace); - $explode = explode('\\', $replace); - array_shift($explode); - - return $namespace . '\\' . implode('\\', $explode); - } - - - /** - * @param string $filePath - * @param string $className - */ - public function appendFileToDirectory(string $filePath, string $className) - { - $array = explode('/', $filePath); - unset($array[count($array) - 1]); - - $array = '/' . trim(implode('/', $array), '/'); - - $this->_directory[$array][] = $className; - } - - -} +_scanDir(new DirectoryIterator($path), $namespace); + } + + + /** + * @param string $class + * @param object $handler + * @return $this + * @throws ReflectionException + * @throws Exception + */ + public function injectProperty(string $class, object $handler): static + { + $di = Kiri::getDi(); + + $reflect = $di->getReflect($class); + + $di->propertyInject($reflect, $handler); + + return $this; + } + + + /** + * @param string $class + * @param string $method + * @return mixed + */ + public function getMethod(string $class, string $method = ''): array + { + if (!isset($this->_methods[$class])) { + return []; + } + $properties = $this->_methods[$class]; + if (!empty($method) && isset($properties[$method])) { + return $properties[$method]; + } + return $properties; + } + + + /** + * @param DirectoryIterator $paths + * @param $namespace + * @param array $exclude + * @throws Exception + */ + public function _scanDir(DirectoryIterator $paths, $namespace, array $exclude = []) + { + foreach ($paths as $path) { + if ($path->isDot() || str_starts_with($path->getFilename(), '.')) { + continue; + } + if ($this->inExclude($exclude, $path->getRealPath())) { + continue; + } + if ($path->isDir()) { + $iterator = new DirectoryIterator($path->getRealPath()); + $directory = rtrim($path->getRealPath(), '/'); + if (!isset($this->_directory[$directory])) { + $this->_directory[$directory] = []; + } + $this->_scanDir($iterator, $namespace); + } else { + $this->readFile($path, $namespace); + } + } + } + + + /** + * @param DirectoryIterator $path + * @param $namespace + * @throws Exception + */ + private function readFile(DirectoryIterator $path, $namespace) + { + try { + if ($path->getExtension() !== 'php') { + return; + } + $replace = $this->getReflect($path, $namespace); + if (!$replace || !$replace->getAttributes(Target::class)) { + return; + } + $this->appendFileToDirectory($path->getRealPath(), $replace->getName()); + } catch (Throwable $throwable) { + $this->error(jTraceEx($throwable), 'throwable'); + } + } + + + /** + * @param DirectoryIterator $path + * @param string $namespace + * @return ReflectionClass|null + */ + private function getReflect(DirectoryIterator $path, string $namespace): ?ReflectionClass + { + $class = $this->explodeFileName($path, $namespace); + if (!class_exists($class)) { + return null; + } + return Kiri::getDi()->getReflect($class); + } + + + /** + * @param string $path + * @param array $exclude + * @return array + * @throws Exception + */ + public function loadByDirectory(string $path, array $exclude = []): array + { + try { + $path = '/' . trim($path, '/'); + $paths = []; + foreach ($this->_directory as $key => $_path) { + $key = '/' . trim($key, '/'); + if (!str_starts_with($key, $path) || $this->inExclude($exclude, $path)) { + continue; + } + unset($this->_directory[$key]); + foreach ($_path as $item) { + $paths[] = $item; + } + } + return $paths; + } catch (Throwable $exception) { + $this->addError($exception, 'throwable'); + return []; + } + } + + + /** + * @param array $exclude + * @param $path + * @return bool + */ + private function inExclude(array $exclude, $path): bool + { + if (empty($exclude)) { + return false; + } + foreach ($exclude as $value) { + if (str_starts_with($path, $value)) { + return true; + } + } + return false; + } + + + /** + * @param DirectoryIterator $path + * @param string $namespace + * @return string + */ + private function explodeFileName(DirectoryIterator $path, string $namespace): string + { + $replace = str_replace(APP_PATH, '', $path->getRealPath()); + + $replace = str_replace('.php', '', $replace); + $replace = str_replace(DIRECTORY_SEPARATOR, '\\', $replace); + $explode = explode('\\', $replace); + array_shift($explode); + + return $namespace . '\\' . implode('\\', $explode); + } + + + /** + * @param string $filePath + * @param string $className + */ + public function appendFileToDirectory(string $filePath, string $className) + { + $array = explode('/', $filePath); + unset($array[count($array) - 1]); + + $array = '/' . trim(implode('/', $array), '/'); + + $this->_directory[$array][] = $className; + } + + +} diff --git a/kiri-annotation/Mapping.php b/kiri-annotation/Mapping.php index 25d8a4c1..81ad1694 100644 --- a/kiri-annotation/Mapping.php +++ b/kiri-annotation/Mapping.php @@ -1,31 +1,31 @@ -mapping($this->class, $class); - - return parent::execute($class, $method); - } - -} +mapping($this->class, $class); + + return parent::execute($class, $method); + } + +} diff --git a/kiri-annotation/Route/Document.php b/kiri-annotation/Route/Document.php index 4110ba9e..2de1ef26 100644 --- a/kiri-annotation/Route/Document.php +++ b/kiri-annotation/Route/Document.php @@ -1,34 +1,34 @@ - '整数', - self::STRING => '字符串', - self::BOOLEAN => '布尔值', - self::FLOAT => '浮点', - ]; - - - public function __construct(array $request, array $response) - { - } - - -} + '整数', + self::STRING => '字符串', + self::BOOLEAN => '布尔值', + self::FLOAT => '浮点', + ]; + + + public function __construct(array $request, array $response) + { + } + + +} diff --git a/kiri-annotation/Route/Middleware.php b/kiri-annotation/Route/Middleware.php index f03c558f..46d8eda7 100644 --- a/kiri-annotation/Route/Middleware.php +++ b/kiri-annotation/Route/Middleware.php @@ -1,53 +1,53 @@ -middleware)) { - $this->middleware = [$this->middleware]; - } - $array = []; - foreach ($this->middleware as $value) { - if (!in_array(MiddlewareInterface::class, class_implements($value))) { - throw new \Exception('The middleware'); - } - $array[] = $value; - } - $this->middleware = $array; - } - - - /** - * @param mixed $class - * @param mixed|null $method - * @return $this - * @throws \ReflectionException - */ - public function execute(mixed $class, mixed $method = null): mixed - { - MiddlewareManager::add($class, $method, $this->middleware); - return parent::execute($class, $method); - } - - -} +middleware)) { + $this->middleware = [$this->middleware]; + } + $array = []; + foreach ($this->middleware as $value) { + if (!in_array(MiddlewareInterface::class, class_implements($value))) { + throw new \Exception('The middleware'); + } + $array[] = $value; + } + $this->middleware = $array; + } + + + /** + * @param mixed $class + * @param mixed|null $method + * @return $this + * @throws \ReflectionException + */ + public function execute(mixed $class, mixed $method = null): mixed + { + MiddlewareManager::add($class, $method, $this->middleware); + return parent::execute($class, $method); + } + + +} diff --git a/kiri-annotation/Route/Route.php b/kiri-annotation/Route/Route.php index 9e163993..34c94a0d 100644 --- a/kiri-annotation/Route/Route.php +++ b/kiri-annotation/Route/Route.php @@ -1,41 +1,41 @@ -uri = '/' . ltrim($this->uri, '/'); - $this->method = strtoupper($this->method); - } - - - /** - * @param mixed $class - * @param mixed|null $method - * @return bool - * @throws \ReflectionException - */ - public function execute(mixed $class, mixed $method = null): bool - { - $di = Kiri::getDi()->get(Router::class); - $di->addRoute($this->method, $this->uri, $class . '@' . $method); - return parent::execute($class, $method); - } - - -} +uri = '/' . ltrim($this->uri, '/'); + $this->method = strtoupper($this->method); + } + + + /** + * @param mixed $class + * @param mixed|null $method + * @return bool + * @throws \ReflectionException + */ + public function execute(mixed $class, mixed $method = null): bool + { + $di = Kiri::getDi()->get(Router::class); + $di->addRoute($this->method, $this->uri, $class . '@' . $method); + return parent::execute($class, $method); + } + + +} diff --git a/kiri-annotation/Route/Socket.php b/kiri-annotation/Route/Socket.php index 426a61d1..63f0965c 100644 --- a/kiri-annotation/Route/Socket.php +++ b/kiri-annotation/Route/Socket.php @@ -1,31 +1,31 @@ -get(AsyncTaskExecute::class); - $task->reg($this->name, $class); - return true; - } - -} +get(AsyncTaskExecute::class); + $task->reg($this->name, $class); + return true; + } + +} diff --git a/kiri-engine/Abstracts/AbstractServer.php b/kiri-engine/Abstracts/AbstractServer.php index 6b1abb98..7c615ef4 100644 --- a/kiri-engine/Abstracts/AbstractServer.php +++ b/kiri-engine/Abstracts/AbstractServer.php @@ -1,12 +1,12 @@ -moreComponents(); - $this->parseInt($config); - $this->parseEvents($config); - $this->initErrorHandler(); - $this->enableEnvConfig(); - $this->mapping($config['mapping'] ?? []); - - parent::__construct(); - } - - - /** - * @param array $mapping - */ - public function mapping(array $mapping) - { - $di = Kiri::getDi(); - foreach ($mapping as $interface => $class) { - $di->mapping($interface, $class); - } - } - - - /** - * @return array - */ - public function enableEnvConfig(): array - { - if (!file_exists($this->envPath)) { - return []; - } - $lines = $this->readLinesFromFile($this->envPath); - foreach ($lines as $line) { - if (!$this->isComment($line) && $this->looksLikeSetter($line)) { - [$key, $value] = explode('=', $line); - putenv(trim($key) . '=' . trim($value)); - } - } - return $lines; - } - - - /** - * Read lines from the file, auto detecting line endings. - * - * @param string $filePath - * - * @return array - */ - protected function readLinesFromFile(string $filePath): array - { - // Read file into an array of lines with auto-detected line endings - $autodetect = ini_get('auto_detect_line_endings'); - ini_set('auto_detect_line_endings', '1'); - $lines = file($filePath, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES); - ini_set('auto_detect_line_endings', $autodetect); - - return $lines; - } - - /** - * Determine if the line in the file is a comment, e.g. begins with a #. - * - * @param string $line - * - * @return bool - */ - protected function isComment(string $line): bool - { - $line = ltrim($line); - - return isset($line[0]) && $line[0] === '#'; - } - - /** - * Determine if the given line looks like it's setting a variable. - * - * @param string $line - * - * @return bool - */ - protected function looksLikeSetter(string $line): bool - { - return str_contains($line, '='); - } - - - /** - * @param $config - * - * @throws - */ - public function parseInt($config) - { - Config::sets($config); - if ($storage = Config::get('storage', 'storage')) { - if (!str_contains($storage, APP_PATH)) { - $storage = APP_PATH . $storage . '/'; - } - if (!is_dir($storage)) { - mkdir($storage); - } - if (!is_dir($storage) || !is_writeable($storage)) { - throw new InitException("Directory {$storage} does not have write permission"); - } - } - } - - - /** - * @param $name - * @return mixed - * @throws ReflectionException - * @throws NotFindClassException - * @throws Exception - */ - public function __get($name): mixed - { - if ($this->has($name)) { - return $this->get($name); - } - return parent::__get($name); // TODO: Change the autogenerated stub - } - - - /** - * @param $config - * - * @throws - */ - public function parseEvents($config) - { - if (!isset($config['events']) || !is_array($config['events'])) { - return; - } - foreach ($config['events'] as $key => $value) { - if (is_string($value)) { - $value = Kiri::createObject($value); - } - $this->addEvent($key, $value); - } - } - - - /** - * @param OnTaskInterface $execute - * @throws ReflectionException - */ - public function task(OnTaskInterface $execute): void - { - di(AsyncTaskExecute::class)->execute($execute); - } - - - /** - * @param $key - * @param $value - * @throws InitException - * @throws Exception - */ - private function addEvent($key, $value): void - { - if ($value instanceof \Closure || is_object($value)) { - $this->eventProvider->on($key, $value, 0); - return; - } - - - if (is_array($value)) { - if (is_object($value[0]) && !($value[0] instanceof \Closure)) { - $this->eventProvider->on($key, $value, 0); - return; - } - - if (is_string($value[0])) { - $value[0] = Kiri::createObject($value[0]); - $this->eventProvider->on($key, $value, 0); - return; - } - - - foreach ($value as $item) { - if (!is_callable($item, true)) { - throw new InitException("Class does not hav callback."); - } - $this->eventProvider->on($key, $item, 0); - } - } - - } - - - /** - * @param $name - * @return mixed - * @throws Exception - */ - public function clone($name): mixed - { - return clone $this->get($name); - } - - /** - * - * @throws Exception - */ - public function initErrorHandler() - { - $this->get('error')->register(); - } - - - /** - * @param $name - * @return mixed - * @throws - */ - public function get($name): mixed - { - return di(LocalService::class)->get($name); - } - - - /** - * @return mixed - */ - public function getLocalIps(): mixed - { - return swoole_get_local_ip(); - } - - /** - * @return mixed - */ - public function getFirstLocal(): mixed - { - return current($this->getLocalIps()); - } - - - /** - * @return Logger - * @throws - */ - public function getLogger(): Logger - { - return $this->get('logger'); - } - - - /** - * @return \Redis|Redis - * @throws - */ - public function getRedis(): Redis|\Redis - { - return Kiri::getDi()->get(Redis::class); - } - - /** - * @param $ip - * @return bool - */ - public function isLocal($ip): bool - { - return $this->getFirstLocal() == $ip; - } - - - /** - * @return ErrorHandler - * @throws - */ - public function getError(): ErrorHandler - { - return $this->get('error'); - } - - - /** - * @param $name - * @return Table - * @throws - */ - public function getTable($name): Table - { - return $this->get($name); - } - - - /** - * @return Config - * @throws - */ - public function getConfig(): Config - { - return $this->get('config'); - } - - - /** - * @return Router - * @throws - */ - public function getRouter(): Router - { - return Kiri::getDi()->get(Router::class); - } - - - /** - * @return Server - * @throws - */ - public function getServer(): Server - { - return $this->get('server'); - } - - - /** - * @return \Swoole\Http\Server|\Swoole\Server|\Swoole\WebSocket\Server|null - * @throws - */ - public function getSwoole(): \Swoole\Http\Server|\Swoole\Server|\Swoole\WebSocket\Server|null - { - return di(ServerManager::class)->getServer(); - } - - - /** - * @return SAnnotation - * @throws - */ - public function getAnnotation(): SAnnotation - { - return $this->get('Annotation'); - } - - - /** - * @return Async - * @throws - */ - public function getAsync(): Async - { - return $this->get('async'); - } - - - /** - * @param $array - */ - private function setComponents($array): void - { - di(LocalService::class)->setComponents($array); - } - - - /** - * @param $id - * @param $definition - */ - public function set($id, $definition): void - { - di(LocalService::class)->set($id, $definition); - } - - - /** - * @param $id - * @return bool - */ - public function has($id): bool - { - return di(LocalService::class)->has($id); - } - - - /** - * @throws Exception - */ - protected function moreComponents(): void - { - $this->setComponents([ - 'error' => ['class' => ErrorHandler::class], - 'config' => ['class' => Config::class], - 'logger' => ['class' => Logger::class], - 'Annotation' => ['class' => SAnnotation::class], - 'databases' => ['class' => Connection::class], - 'jwt' => ['class' => Jwt::class], - 'async' => ['class' => Async::class], - 'kafka-container' => ['class' => KafkaProvider::class], - ]); - } -} +moreComponents(); + $this->parseInt($config); + $this->parseEvents($config); + $this->initErrorHandler(); + $this->enableEnvConfig(); + $this->mapping($config['mapping'] ?? []); + + parent::__construct(); + } + + + /** + * @param array $mapping + */ + public function mapping(array $mapping) + { + $di = Kiri::getDi(); + foreach ($mapping as $interface => $class) { + $di->mapping($interface, $class); + } + } + + + /** + * @return array + */ + public function enableEnvConfig(): array + { + if (!file_exists($this->envPath)) { + return []; + } + $lines = $this->readLinesFromFile($this->envPath); + foreach ($lines as $line) { + if (!$this->isComment($line) && $this->looksLikeSetter($line)) { + [$key, $value] = explode('=', $line); + putenv(trim($key) . '=' . trim($value)); + } + } + return $lines; + } + + + /** + * Read lines from the file, auto detecting line endings. + * + * @param string $filePath + * + * @return array + */ + protected function readLinesFromFile(string $filePath): array + { + // Read file into an array of lines with auto-detected line endings + $autodetect = ini_get('auto_detect_line_endings'); + ini_set('auto_detect_line_endings', '1'); + $lines = file($filePath, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES); + ini_set('auto_detect_line_endings', $autodetect); + + return $lines; + } + + /** + * Determine if the line in the file is a comment, e.g. begins with a #. + * + * @param string $line + * + * @return bool + */ + protected function isComment(string $line): bool + { + $line = ltrim($line); + + return isset($line[0]) && $line[0] === '#'; + } + + /** + * Determine if the given line looks like it's setting a variable. + * + * @param string $line + * + * @return bool + */ + protected function looksLikeSetter(string $line): bool + { + return str_contains($line, '='); + } + + + /** + * @param $config + * + * @throws + */ + public function parseInt($config) + { + Config::sets($config); + if ($storage = Config::get('storage', 'storage')) { + if (!str_contains($storage, APP_PATH)) { + $storage = APP_PATH . $storage . '/'; + } + if (!is_dir($storage)) { + mkdir($storage); + } + if (!is_dir($storage) || !is_writeable($storage)) { + throw new InitException("Directory {$storage} does not have write permission"); + } + } + } + + + /** + * @param $name + * @return mixed + * @throws ReflectionException + * @throws NotFindClassException + * @throws Exception + */ + public function __get($name): mixed + { + if ($this->has($name)) { + return $this->get($name); + } + return parent::__get($name); // TODO: Change the autogenerated stub + } + + + /** + * @param $config + * + * @throws + */ + public function parseEvents($config) + { + if (!isset($config['events']) || !is_array($config['events'])) { + return; + } + foreach ($config['events'] as $key => $value) { + if (is_string($value)) { + $value = Kiri::createObject($value); + } + $this->addEvent($key, $value); + } + } + + + /** + * @param OnTaskInterface $execute + * @throws ReflectionException + */ + public function task(OnTaskInterface $execute): void + { + di(AsyncTaskExecute::class)->execute($execute); + } + + + /** + * @param $key + * @param $value + * @throws InitException + * @throws Exception + */ + private function addEvent($key, $value): void + { + if ($value instanceof \Closure || is_object($value)) { + $this->eventProvider->on($key, $value, 0); + return; + } + + + if (is_array($value)) { + if (is_object($value[0]) && !($value[0] instanceof \Closure)) { + $this->eventProvider->on($key, $value, 0); + return; + } + + if (is_string($value[0])) { + $value[0] = Kiri::createObject($value[0]); + $this->eventProvider->on($key, $value, 0); + return; + } + + + foreach ($value as $item) { + if (!is_callable($item, true)) { + throw new InitException("Class does not hav callback."); + } + $this->eventProvider->on($key, $item, 0); + } + } + + } + + + /** + * @param $name + * @return mixed + * @throws Exception + */ + public function clone($name): mixed + { + return clone $this->get($name); + } + + /** + * + * @throws Exception + */ + public function initErrorHandler() + { + $this->get('error')->register(); + } + + + /** + * @param $name + * @return mixed + * @throws + */ + public function get($name): mixed + { + return di(LocalService::class)->get($name); + } + + + /** + * @return mixed + */ + public function getLocalIps(): mixed + { + return swoole_get_local_ip(); + } + + /** + * @return mixed + */ + public function getFirstLocal(): mixed + { + return current($this->getLocalIps()); + } + + + /** + * @return Logger + * @throws + */ + public function getLogger(): Logger + { + return $this->get('logger'); + } + + + /** + * @return \Redis|Redis + * @throws + */ + public function getRedis(): Redis|\Redis + { + return Kiri::getDi()->get(Redis::class); + } + + /** + * @param $ip + * @return bool + */ + public function isLocal($ip): bool + { + return $this->getFirstLocal() == $ip; + } + + + /** + * @return ErrorHandler + * @throws + */ + public function getError(): ErrorHandler + { + return $this->get('error'); + } + + + /** + * @param $name + * @return Table + * @throws + */ + public function getTable($name): Table + { + return $this->get($name); + } + + + /** + * @return Config + * @throws + */ + public function getConfig(): Config + { + return $this->get('config'); + } + + + /** + * @return Router + * @throws + */ + public function getRouter(): Router + { + return Kiri::getDi()->get(Router::class); + } + + + /** + * @return Server + * @throws + */ + public function getServer(): Server + { + return $this->get('server'); + } + + + /** + * @return \Swoole\Http\Server|\Swoole\Server|\Swoole\WebSocket\Server|null + * @throws + */ + public function getSwoole(): \Swoole\Http\Server|\Swoole\Server|\Swoole\WebSocket\Server|null + { + return di(ServerManager::class)->getServer(); + } + + + /** + * @return SAnnotation + * @throws + */ + public function getAnnotation(): SAnnotation + { + return $this->get('Annotation'); + } + + + /** + * @return Async + * @throws + */ + public function getAsync(): Async + { + return $this->get('async'); + } + + + /** + * @param $array + */ + private function setComponents($array): void + { + di(LocalService::class)->setComponents($array); + } + + + /** + * @param $id + * @param $definition + */ + public function set($id, $definition): void + { + di(LocalService::class)->set($id, $definition); + } + + + /** + * @param $id + * @return bool + */ + public function has($id): bool + { + return di(LocalService::class)->has($id); + } + + + /** + * @throws Exception + */ + protected function moreComponents(): void + { + $this->setComponents([ + 'error' => ['class' => ErrorHandler::class], + 'config' => ['class' => Config::class], + 'logger' => ['class' => Logger::class], + 'Annotation' => ['class' => SAnnotation::class], + 'databases' => ['class' => Connection::class], + 'jwt' => ['class' => Jwt::class], + 'async' => ['class' => Async::class], + 'kafka-container' => ['class' => KafkaProvider::class], + ]); + } +} diff --git a/kiri-engine/Abstracts/BaseContext.php b/kiri-engine/Abstracts/BaseContext.php index ca21f946..b4b98c39 100644 --- a/kiri-engine/Abstracts/BaseContext.php +++ b/kiri-engine/Abstracts/BaseContext.php @@ -1,13 +1,13 @@ -getContainer()->get(EventProvider::class); - } - - - /** - * @return EventDispatch - */ - protected function getEventDispatch(): EventDispatch - { - return Kiri::getDi()->get(EventDispatch::class); - } - - /** - * @throws Exception - */ - public function init() - { - } - - - /** - * @return string - */ - #[Pure] public static function className(): string - { - return static::class; - } - - /** - * @param $name - * @param $value - * - * @throws Exception - */ - public function __set($name, $value) - { - $method = 'set' . ucfirst($name); - if (method_exists($this, $method)) { - $this->{$method}($value); - } else { - throw new Exception('The set name ' . $name . ' not find in class ' . static::class); - } - } - - /** - * @param $name - * - * @return mixed - * @throws Exception - */ - public function __get($name): mixed - { - $method = 'get' . ucfirst($name); - if (method_exists($this, $method)) { - return $this->$method(); - } else { - throw new Exception('The get name ' . $name . ' not find in class ' . static::class); - } - } - - - /** - * @param $message - * @param string $model - * @return bool - * @throws Exception - */ - public function addError($message, string $model = 'app'): bool - { - if ($message instanceof \Throwable) { - $this->error($message = jTraceEx($message)); - } else { - if (!is_string($message)) { - $message = json_encode($message, JSON_UNESCAPED_UNICODE); - } - $this->error($message); - } - Kiri::app()->getLogger()->fail($message, $model); - return FALSE; - } - - - /** - * @return Logger - * @throws Exception - */ - private function logger(): Logger - { - return Kiri::getDi()->get(Logger::class); - } - - - /** - * @param mixed $message - * @param string $method - * @param string $file - * @throws Exception - */ - public function debug(mixed $message, string $method = '', string $file = '') - { - if (!is_string($message)) { - $message = print_r($message, true); - } - $context = []; - if (!empty($method)) $context['method'] = $method; - if (!empty($file)) $context['file'] = $file; - - $this->logger()->debug($message, $context); - } - - - /** - * @param mixed $message - * @param string $method - * @param string $file - * @throws Exception - */ - public function info(mixed $message, string $method = '', string $file = '') - { - if (!is_string($message)) { - $message = print_r($message, true); - } - $context = []; - if (!empty($method)) $context['method'] = $method; - if (!empty($file)) $context['file'] = $file; - - $this->logger()->info($message, $context); - } - - - /** - * @param mixed $message - * @param string $method - * @param string $file - * @throws Exception - */ - public function success(mixed $message, string $method = '', string $file = '') - { - if (!is_string($message)) { - $message = print_r($message, true); - } - $context = []; - if (!empty($method)) $context['method'] = $method; - if (!empty($file)) $context['file'] = $file; - - $this->logger()->notice($message, $context); - } - - - /** - * @param mixed $message - * @param string $method - * @param string $file - * @throws Exception - */ - public function warning(mixed $message, string $method = '', string $file = '') - { - if (!is_string($message)) { - $message = print_r($message, true); - } - - $context = []; - if (!empty($method)) $context['method'] = $method; - if (!empty($file)) $context['file'] = $file; - - $this->logger()->critical($message, $context); - } - - - /** - * @param mixed $message - * @param null $method - * @param null $file - * @throws Exception - */ - public function error(mixed $message, $method = null, $file = null) - { - if ($message instanceof \Throwable) { - $message = $message->getMessage() . " on line " . $message->getLine() . " at file " . $message->getFile(); - } - - $context = []; - if (is_string($method)) { - $message = (empty($method) ? '' : $method . ': ') . $message; - } else { - if (is_null($method)) { - $method = []; - } - $context = $method; - } - if (!empty($method)) $context['method'] = $method; - if (!empty($file)) $context['file'] = $file; - - $this->logger()->error($message, $context); - } - -} +getContainer()->get(EventProvider::class); + } + + + /** + * @return EventDispatch + */ + protected function getEventDispatch(): EventDispatch + { + return Kiri::getDi()->get(EventDispatch::class); + } + + /** + * @throws Exception + */ + public function init() + { + } + + + /** + * @return string + */ + #[Pure] public static function className(): string + { + return static::class; + } + + /** + * @param $name + * @param $value + * + * @throws Exception + */ + public function __set($name, $value) + { + $method = 'set' . ucfirst($name); + if (method_exists($this, $method)) { + $this->{$method}($value); + } else { + throw new Exception('The set name ' . $name . ' not find in class ' . static::class); + } + } + + /** + * @param $name + * + * @return mixed + * @throws Exception + */ + public function __get($name): mixed + { + $method = 'get' . ucfirst($name); + if (method_exists($this, $method)) { + return $this->$method(); + } else { + throw new Exception('The get name ' . $name . ' not find in class ' . static::class); + } + } + + + /** + * @param $message + * @param string $model + * @return bool + * @throws Exception + */ + public function addError($message, string $model = 'app'): bool + { + if ($message instanceof \Throwable) { + $this->error($message = jTraceEx($message)); + } else { + if (!is_string($message)) { + $message = json_encode($message, JSON_UNESCAPED_UNICODE); + } + $this->error($message); + } + Kiri::app()->getLogger()->fail($message, $model); + return FALSE; + } + + + /** + * @return Logger + * @throws Exception + */ + private function logger(): Logger + { + return Kiri::getDi()->get(Logger::class); + } + + + /** + * @param mixed $message + * @param string $method + * @param string $file + * @throws Exception + */ + public function debug(mixed $message, string $method = '', string $file = '') + { + if (!is_string($message)) { + $message = print_r($message, true); + } + $context = []; + if (!empty($method)) $context['method'] = $method; + if (!empty($file)) $context['file'] = $file; + + $this->logger()->debug($message, $context); + } + + + /** + * @param mixed $message + * @param string $method + * @param string $file + * @throws Exception + */ + public function info(mixed $message, string $method = '', string $file = '') + { + if (!is_string($message)) { + $message = print_r($message, true); + } + $context = []; + if (!empty($method)) $context['method'] = $method; + if (!empty($file)) $context['file'] = $file; + + $this->logger()->info($message, $context); + } + + + /** + * @param mixed $message + * @param string $method + * @param string $file + * @throws Exception + */ + public function success(mixed $message, string $method = '', string $file = '') + { + if (!is_string($message)) { + $message = print_r($message, true); + } + $context = []; + if (!empty($method)) $context['method'] = $method; + if (!empty($file)) $context['file'] = $file; + + $this->logger()->notice($message, $context); + } + + + /** + * @param mixed $message + * @param string $method + * @param string $file + * @throws Exception + */ + public function warning(mixed $message, string $method = '', string $file = '') + { + if (!is_string($message)) { + $message = print_r($message, true); + } + + $context = []; + if (!empty($method)) $context['method'] = $method; + if (!empty($file)) $context['file'] = $file; + + $this->logger()->critical($message, $context); + } + + + /** + * @param mixed $message + * @param null $method + * @param null $file + * @throws Exception + */ + public function error(mixed $message, $method = null, $file = null) + { + if ($message instanceof \Throwable) { + $message = $message->getMessage() . " on line " . $message->getLine() . " at file " . $message->getFile(); + } + + $context = []; + if (is_string($method)) { + $message = (empty($method) ? '' : $method . ': ') . $message; + } else { + if (is_null($method)) { + $method = []; + } + $context = $method; + } + if (!empty($method)) $context['method'] = $method; + if (!empty($file)) $context['file'] = $file; + + $this->logger()->error($message, $context); + } + +} diff --git a/kiri-engine/Abstracts/Config.php b/kiri-engine/Abstracts/Config.php index 049beb4f..a2d50f45 100644 --- a/kiri-engine/Abstracts/Config.php +++ b/kiri-engine/Abstracts/Config.php @@ -1,128 +1,128 @@ -_argv = $this->resolve($argv); - } - - - /** - * @return string - */ - public function getCommandName(): string - { - return $this->_command; - } - - - /** - * @param $key - * @param null $default - * @return mixed - */ - public function get($key, $default = null): mixed - { - return $this->_argv[$key] ?? $default; - } - - - /** - * @param $key - * @return bool - */ - public function exists($key): bool - { - return isset($this->_argv[$key]); - } - - /** - * @param $key - * @param $value - * @return $this - */ - public function set($key, $value): static - { - $this->_argv[$key] = $value; - return $this; - } - - - /** - * @return false|string - */ - public function toJson(): bool|string - { - return json_encode($this->_argv, JSON_UNESCAPED_UNICODE); - } - - - /** - * @param $parameters - * @return array - * @throws Exception - */ - public function resolve($parameters): array - { - $arrays = []; - $parameters = array_slice($parameters, 1); - if (empty($parameters)) { - return $arrays; - } - $this->_command = array_shift($parameters); - foreach ($parameters as $parameter) { - $explode = explode('=', $parameter); - if (count($explode) < 2) { - continue; - } - $arrays[array_shift($explode)] = current($explode); - } - return $arrays; - } - - - /** - * @return string - */ - public function getCommand(): string - { - return $this->_command; - } - -} +_argv = $this->resolve($argv); + } + + + /** + * @return string + */ + public function getCommandName(): string + { + return $this->_command; + } + + + /** + * @param $key + * @param null $default + * @return mixed + */ + public function get($key, $default = null): mixed + { + return $this->_argv[$key] ?? $default; + } + + + /** + * @param $key + * @return bool + */ + public function exists($key): bool + { + return isset($this->_argv[$key]); + } + + /** + * @param $key + * @param $value + * @return $this + */ + public function set($key, $value): static + { + $this->_argv[$key] = $value; + return $this; + } + + + /** + * @return false|string + */ + public function toJson(): bool|string + { + return json_encode($this->_argv, JSON_UNESCAPED_UNICODE); + } + + + /** + * @param $parameters + * @return array + * @throws Exception + */ + public function resolve($parameters): array + { + $arrays = []; + $parameters = array_slice($parameters, 1); + if (empty($parameters)) { + return $arrays; + } + $this->_command = array_shift($parameters); + foreach ($parameters as $parameter) { + $explode = explode('=', $parameter); + if (count($explode) < 2) { + continue; + } + $arrays[array_shift($explode)] = current($explode); + } + return $arrays; + } + + + /** + * @return string + */ + public function getCommand(): string + { + return $this->_command; + } + +} diff --git a/kiri-engine/Abstracts/Kernel.php b/kiri-engine/Abstracts/Kernel.php index 4ecd4559..7fe86f98 100644 --- a/kiri-engine/Abstracts/Kernel.php +++ b/kiri-engine/Abstracts/Kernel.php @@ -1,15 +1,15 @@ -get(EventProvider::class)->on(OnWorkerStop::class, [$this, 'onAfterRequest']); - } - - - /** - * @param string $message - * @param array $context - * @throws ConfigException - * - * 紧急情况 - */ - public function emergency($message, array $context = []) - { - // TODO: Implement emergency() method. - $this->log(Logger::EMERGENCY, $message, $context); - } - - - /** - * @param string $message - * @param array $context - * @throws ConfigException - * - * 应该警惕的 - */ - public function alert($message, array $context = []) - { - // TODO: Implement alert() method. - $this->log(Logger::ALERT, $message, $context); - } - - - /** - * @param string $message - * @param array $context - * @throws ConfigException - * - * 关键性的日志 - */ - public function critical($message, array $context = []) - { - // TODO: Implement critical() method. - $this->log(Logger::CRITICAL, $message, $context); - } - - - /** - * @param string $message - * @param array $context - * @throws ConfigException - */ - public function error($message, array $context = []) - { - // TODO: Implement error() method. - $this->log(Logger::ERROR, $message, $context); - } - - - /** - * @param string $message - * @param array $context - * @throws ConfigException - */ - public function warning($message, array $context = []) - { - // TODO: Implement warning() method. - $this->log(Logger::WARNING, $message, $context); - } - - /** - * @param string $message - * @param array $context - * @throws ConfigException - */ - public function notice($message, array $context = []) - { - // TODO: Implement notice() method. - $this->log(Logger::NOTICE, $message, $context); - } - - - /** - * @param string $message - * @param array $context - * @throws ConfigException - */ - public function info($message, array $context = []) - { - // TODO: Implement info() method. - $this->log(Logger::INFO, $message, $context); - } - - - /** - * @param string $message - * @param array $context - * @throws ConfigException - */ - public function debug($message, array $context = []) - { - // TODO: Implement debug() method. - $this->log(Logger::DEBUG, $message, $context); - } - - - /** - * @param mixed $level - * @param string $message - * @param array $context - * @throws ConfigException - */ - public function log($level, $message, array $context = []) - { - // TODO: Implement log() method. - $levels = Config::get('log.level', Logger::LOGGER_LEVELS); - if (!in_array($level, $levels) || str_contains($message, 'Event::rshutdown')) { - return; - } - - $_string = '[' . now() . '] production.' . $level . ': ' . $this->_string($message, $context); - - file_put_contents('php://output', $_string); - - $this->_loggers[] = $_string; - } - - - /** - * @param OnWorkerStop $param - * @throws Exception - */ - public function onAfterRequest(OnWorkerStop $param) - { - $loggers = implode(PHP_EOL, $this->_loggers); - $this->_loggers = []; - if (!empty($loggers)) { - $filename = storage('log-' . date('Y-m-d') . '.log', 'log/'); - - file_put_contents($filename, $loggers); - } - } - - - /** - * @return void - * @throws Exception - */ - public function flush() - { - $this->removeFile(storage()); - } - - - /** - * @param string $dirname - * @return void - */ - private function removeFile(string $dirname) - { - $paths = new DirectoryIterator($dirname); - /** @var DirectoryIterator $path */ - foreach ($paths as $path) { - if ($path->isDot() || str_starts_with($path->getFilename(), '.')) { - continue; - } - if ($path->isDir()) { - $directory = rtrim($path->getRealPath(), '/'); - $this->removeFile($directory); - } - @unlink($path->getRealPath()); - } - } - - - /** - * @param $message - * @param $context - * @return string - */ - private function _string($message, $context): string - { - if (!empty($context)) { - return $message . ' ' . PHP_EOL . print_r($context, TRUE) . PHP_EOL; - } - return $message . PHP_EOL; - } -} +get(EventProvider::class)->on(OnWorkerStop::class, [$this, 'onAfterRequest']); + } + + + /** + * @param string $message + * @param array $context + * @throws ConfigException + * + * 紧急情况 + */ + public function emergency($message, array $context = []) + { + // TODO: Implement emergency() method. + $this->log(Logger::EMERGENCY, $message, $context); + } + + + /** + * @param string $message + * @param array $context + * @throws ConfigException + * + * 应该警惕的 + */ + public function alert($message, array $context = []) + { + // TODO: Implement alert() method. + $this->log(Logger::ALERT, $message, $context); + } + + + /** + * @param string $message + * @param array $context + * @throws ConfigException + * + * 关键性的日志 + */ + public function critical($message, array $context = []) + { + // TODO: Implement critical() method. + $this->log(Logger::CRITICAL, $message, $context); + } + + + /** + * @param string $message + * @param array $context + * @throws ConfigException + */ + public function error($message, array $context = []) + { + // TODO: Implement error() method. + $this->log(Logger::ERROR, $message, $context); + } + + + /** + * @param string $message + * @param array $context + * @throws ConfigException + */ + public function warning($message, array $context = []) + { + // TODO: Implement warning() method. + $this->log(Logger::WARNING, $message, $context); + } + + /** + * @param string $message + * @param array $context + * @throws ConfigException + */ + public function notice($message, array $context = []) + { + // TODO: Implement notice() method. + $this->log(Logger::NOTICE, $message, $context); + } + + + /** + * @param string $message + * @param array $context + * @throws ConfigException + */ + public function info($message, array $context = []) + { + // TODO: Implement info() method. + $this->log(Logger::INFO, $message, $context); + } + + + /** + * @param string $message + * @param array $context + * @throws ConfigException + */ + public function debug($message, array $context = []) + { + // TODO: Implement debug() method. + $this->log(Logger::DEBUG, $message, $context); + } + + + /** + * @param mixed $level + * @param string $message + * @param array $context + * @throws ConfigException + */ + public function log($level, $message, array $context = []) + { + // TODO: Implement log() method. + $levels = Config::get('log.level', Logger::LOGGER_LEVELS); + if (!in_array($level, $levels) || str_contains($message, 'Event::rshutdown')) { + return; + } + + $_string = '[' . now() . '] production.' . $level . ': ' . $this->_string($message, $context); + + file_put_contents('php://output', $_string); + + $this->_loggers[] = $_string; + } + + + /** + * @param OnWorkerStop $param + * @throws Exception + */ + public function onAfterRequest(OnWorkerStop $param) + { + $loggers = implode(PHP_EOL, $this->_loggers); + $this->_loggers = []; + if (!empty($loggers)) { + $filename = storage('log-' . date('Y-m-d') . '.log', 'log/'); + + file_put_contents($filename, $loggers); + } + } + + + /** + * @return void + * @throws Exception + */ + public function flush() + { + $this->removeFile(storage()); + } + + + /** + * @param string $dirname + * @return void + */ + private function removeFile(string $dirname) + { + $paths = new DirectoryIterator($dirname); + /** @var DirectoryIterator $path */ + foreach ($paths as $path) { + if ($path->isDot() || str_starts_with($path->getFilename(), '.')) { + continue; + } + if ($path->isDir()) { + $directory = rtrim($path->getRealPath(), '/'); + $this->removeFile($directory); + } + @unlink($path->getRealPath()); + } + } + + + /** + * @param $message + * @param $context + * @return string + */ + private function _string($message, $context): string + { + if (!empty($context)) { + return $message . ' ' . PHP_EOL . print_r($context, TRUE) . PHP_EOL; + } + return $message . PHP_EOL; + } +} diff --git a/kiri-engine/Abstracts/Provider.php b/kiri-engine/Abstracts/Provider.php index 9966b6ed..e87c64e7 100644 --- a/kiri-engine/Abstracts/Provider.php +++ b/kiri-engine/Abstracts/Provider.php @@ -1,14 +1,14 @@ -> */ - private array $_process = []; - - - /** - */ - public function init() - { - $this->import(ServerProviders::class); - - $this->register(Runtime::class); - } - - - /** - * @throws - */ - public function withDatabase() - { - $this->import(DatabasesProviders::class); - } - - - /** - * @throws - */ - public function withCrontab() - { - $this->import(CrontabProviders::class); - } - - - /** - * @param string $class - * @param Process $process - */ - public function addProcess(string $class, Process $process) - { - } - - - /** - * @return Process[] - */ - public function getProcess(): array - { - return $this->_process; - } - - - /** - * @param string $class - * @return Process|null - */ - public function getProcessName(string $class): ?Process - { - return $this->_process[$class] ?? null; - } - - - /** - * @throws - */ - public function withFileChangeListen() - { - $container = Kiri::getDi(); - - $console = $container->get(ConsoleApplication::class); - $console->add($container->get(HotReload::class)); - } - - - /** - * @param Closure|array $closure - * @return $this - * @throws Exception - */ - public function middleware(Closure|array $closure): static - { - return $this; - } - - - /** - * @param bool $useTree - * @return $this - * @throws Exception - */ - public function setUseTree(bool $useTree): static - { - return $this; - } - - - /** - * @param string $service - * @return $this - * @throws - */ - public function import(string $service): static - { - if (!class_exists($service)) { - return $this; - } - $class = Kiri::getDi()->get($service); - if (method_exists($class, 'onImport')) { - $class->onImport($this); - } - return $this; - } - - - /** - * @param Kernel $kernel - * @return $this - */ - public function commands(Kernel $kernel): static - { - foreach ($kernel->getCommands() as $command) { - $this->register($command); - } - return $this; - } - - - /** - * @param string $command - * @throws - */ - public function register(string $command) - { - di(ConsoleApplication::class)->add(di($command)); - } - - - /** - * @param array $argv - * @return void - */ - public function execute(array $argv): void - { - ini_set('swoole.enable_preemptive_scheduler', 'On'); - ini_set('swoole.enable_library', 'On'); - [$input, $output] = $this->argument($argv); - try { - $console = di(ConsoleApplication::class); - $command = $input->getFirstArgument(); - if (empty($command)) { - $command = 'sw:server'; - } - $command = $console->find($command); - if ($command instanceof Command) { - $this->enableFileChange($command, $input, $output); - } - } catch (\Throwable $exception) { - $output->writeln(jTraceEx($exception)); - } finally { - Timer::clearAll(); - } - } - - - /** - * @param $argv - * @return array - */ - private function argument($argv): array - { - return [new ArgvInput($argv), new ConsoleOutput()]; - } - - - /** - * @throws ReflectionException - * @throws Exception - */ - private function enableFileChange(Command $class, $input, $output): void - { - fire(new OnBeforeCommandExecute()); - if (!($class instanceof HotReload)) { - scan_directory(directory('app'), 'App'); - } - - $this->container->setBindings(OutputInterface::class, $output); - - $class->run($input, $output); - fire(new OnAfterCommandExecute()); - $output->writeln('ok' . PHP_EOL); - } - - - /** - * @param $className - * @param null $abstracts - * @return stdClass - * @throws Exception - */ - public function make($className, $abstracts = null): stdClass - { - return make($className, $abstracts); - } -} +> */ + private array $_process = []; + + + /** + */ + public function init() + { + $this->import(ServerProviders::class); + + $this->register(Runtime::class); + } + + + /** + * @throws + */ + public function withDatabase() + { + $this->import(DatabasesProviders::class); + } + + + /** + * @throws + */ + public function withCrontab() + { + $this->import(CrontabProviders::class); + } + + + /** + * @param string $class + * @param Process $process + */ + public function addProcess(string $class, Process $process) + { + } + + + /** + * @return Process[] + */ + public function getProcess(): array + { + return $this->_process; + } + + + /** + * @param string $class + * @return Process|null + */ + public function getProcessName(string $class): ?Process + { + return $this->_process[$class] ?? null; + } + + + /** + * @throws + */ + public function withFileChangeListen() + { + $container = Kiri::getDi(); + + $console = $container->get(ConsoleApplication::class); + $console->add($container->get(HotReload::class)); + } + + + /** + * @param Closure|array $closure + * @return $this + * @throws Exception + */ + public function middleware(Closure|array $closure): static + { + return $this; + } + + + /** + * @param bool $useTree + * @return $this + * @throws Exception + */ + public function setUseTree(bool $useTree): static + { + return $this; + } + + + /** + * @param string $service + * @return $this + * @throws + */ + public function import(string $service): static + { + if (!class_exists($service)) { + return $this; + } + $class = Kiri::getDi()->get($service); + if (method_exists($class, 'onImport')) { + $class->onImport($this); + } + return $this; + } + + + /** + * @param Kernel $kernel + * @return $this + */ + public function commands(Kernel $kernel): static + { + foreach ($kernel->getCommands() as $command) { + $this->register($command); + } + return $this; + } + + + /** + * @param string $command + * @throws + */ + public function register(string $command) + { + di(ConsoleApplication::class)->add(di($command)); + } + + + /** + * @param array $argv + * @return void + */ + public function execute(array $argv): void + { + ini_set('swoole.enable_preemptive_scheduler', 'On'); + ini_set('swoole.enable_library', 'On'); + [$input, $output] = $this->argument($argv); + try { + $console = di(ConsoleApplication::class); + $command = $input->getFirstArgument(); + if (empty($command)) { + $command = 'sw:server'; + } + $command = $console->find($command); + if ($command instanceof Command) { + $this->enableFileChange($command, $input, $output); + } + } catch (\Throwable $exception) { + $output->writeln(jTraceEx($exception)); + } finally { + Timer::clearAll(); + } + } + + + /** + * @param $argv + * @return array + */ + private function argument($argv): array + { + return [new ArgvInput($argv), new ConsoleOutput()]; + } + + + /** + * @throws ReflectionException + * @throws Exception + */ + private function enableFileChange(Command $class, $input, $output): void + { + fire(new OnBeforeCommandExecute()); + if (!($class instanceof HotReload)) { + scan_directory(directory('app'), 'App'); + } + + $this->container->setBindings(OutputInterface::class, $output); + + $class->run($input, $output); + fire(new OnAfterCommandExecute()); + $output->writeln('ok' . PHP_EOL); + } + + + /** + * @param $className + * @param null $abstracts + * @return stdClass + * @throws Exception + */ + public function make($className, $abstracts = null): stdClass + { + return make($className, $abstracts); + } +} diff --git a/kiri-engine/Async.php b/kiri-engine/Async.php index 3da691c9..22c0610b 100644 --- a/kiri-engine/Async.php +++ b/kiri-engine/Async.php @@ -1,44 +1,44 @@ -execute(static::$_absences[$name], $params); - } - -} +execute(static::$_absences[$name], $params); + } + +} diff --git a/kiri-engine/Cache/Base/Redis.php b/kiri-engine/Cache/Base/Redis.php index ee1d203a..577c7659 100644 --- a/kiri-engine/Cache/Base/Redis.php +++ b/kiri-engine/Cache/Base/Redis.php @@ -1,171 +1,171 @@ -host = $config['host']; - $this->port = $config['port']; - $this->database = $config['databases']; - $this->auth = $config['auth']; - $this->prefix = $config['prefix']; - $this->timeout = $config['timeout']; - $this->read_timeout = $config['read_timeout']; - $this->pool = $config['pool']; - } - - - public function init() - { - $this->heartbeat_check(); - } - - - /** - * - */ - public function heartbeat_check(): void - { - if (env('state', 'start') == 'exit') { - return; - } - if ($this->_timer === -1) { - $this->_timer = Timer::tick(1000, fn() => $this->waite()); - } - } - - - /** - * @throws Exception - */ - private function waite(): void - { - try { - if (env('state', 'start') == 'exit') { - Kiri::getDi()->get(Logger::class)->critical('timer end'); - $this->stopHeartbeatCheck(); - } - if (time() - $this->_last > intval($this->pool['tick'] ?? 60)) { - $this->stopHeartbeatCheck(); - $this->pdo = null; - } - } catch (\Throwable $throwable) { - error($throwable); - } - } - - - /** - * - */ - public function stopHeartbeatCheck(): void - { - if ($this->_timer > -1) { - Timer::clear($this->_timer); - } - $this->_timer = -1; - } - - - /** - * @param string $name - * @param array $arguments - * @return mixed - * @throws RedisConnectException|RedisException - */ - public function __call(string $name, array $arguments) - { - if (!method_exists($this, $name)) { - return $this->_pdo()->{$name}(...$arguments); - } - return $this->{$name}(...$arguments); - } - - - /** - * @return \Redis - * @throws RedisConnectException - * @throws RedisException - */ - public function _pdo(): \Redis - { - if ($this->_timer === -1) { - $this->heartbeat_check(); - } - if (!($this->pdo instanceof \Redis) || !$this->pdo->ping('isOk')) { - $this->pdo = $this->newClient(); - } - return $this->pdo; - } - - - /** - * @return \Redis - * @throws RedisConnectException - */ - private function newClient(): \Redis - { - $redis = new \Redis(); - if (!$redis->connect($this->host, $this->port, $this->timeout)) { - throw new RedisConnectException(sprintf('The Redis Connect %s::%d Fail.', $this->host, $this->port)); - } - if (!empty($this->auth) && !$redis->auth($this->auth)) { - throw new RedisConnectException(sprintf('Redis Error: %s, Host %s, Auth %s', $redis->getLastError(), $this->host, $this->auth)); - } - if ($this->read_timeout < 0) { - $this->read_timeout = 0; - } - $redis->select($this->database); - if ($this->read_timeout > 0) { - $redis->setOption(\Redis::OPT_READ_TIMEOUT, $this->read_timeout); - } - $redis->setOption(\Redis::OPT_PREFIX, $this->prefix); - return $redis; - - } - -} +host = $config['host']; + $this->port = $config['port']; + $this->database = $config['databases']; + $this->auth = $config['auth']; + $this->prefix = $config['prefix']; + $this->timeout = $config['timeout']; + $this->read_timeout = $config['read_timeout']; + $this->pool = $config['pool']; + } + + + public function init() + { + $this->heartbeat_check(); + } + + + /** + * + */ + public function heartbeat_check(): void + { + if (env('state', 'start') == 'exit') { + return; + } + if ($this->_timer === -1) { + $this->_timer = Timer::tick(1000, fn() => $this->waite()); + } + } + + + /** + * @throws Exception + */ + private function waite(): void + { + try { + if (env('state', 'start') == 'exit') { + Kiri::getDi()->get(Logger::class)->critical('timer end'); + $this->stopHeartbeatCheck(); + } + if (time() - $this->_last > intval($this->pool['tick'] ?? 60)) { + $this->stopHeartbeatCheck(); + $this->pdo = null; + } + } catch (\Throwable $throwable) { + error($throwable); + } + } + + + /** + * + */ + public function stopHeartbeatCheck(): void + { + if ($this->_timer > -1) { + Timer::clear($this->_timer); + } + $this->_timer = -1; + } + + + /** + * @param string $name + * @param array $arguments + * @return mixed + * @throws RedisConnectException|RedisException + */ + public function __call(string $name, array $arguments) + { + if (!method_exists($this, $name)) { + return $this->_pdo()->{$name}(...$arguments); + } + return $this->{$name}(...$arguments); + } + + + /** + * @return \Redis + * @throws RedisConnectException + * @throws RedisException + */ + public function _pdo(): \Redis + { + if ($this->_timer === -1) { + $this->heartbeat_check(); + } + if (!($this->pdo instanceof \Redis) || !$this->pdo->ping('isOk')) { + $this->pdo = $this->newClient(); + } + return $this->pdo; + } + + + /** + * @return \Redis + * @throws RedisConnectException + */ + private function newClient(): \Redis + { + $redis = new \Redis(); + if (!$redis->connect($this->host, $this->port, $this->timeout)) { + throw new RedisConnectException(sprintf('The Redis Connect %s::%d Fail.', $this->host, $this->port)); + } + if (!empty($this->auth) && !$redis->auth($this->auth)) { + throw new RedisConnectException(sprintf('Redis Error: %s, Host %s, Auth %s', $redis->getLastError(), $this->host, $this->auth)); + } + if ($this->read_timeout < 0) { + $this->read_timeout = 0; + } + $redis->select($this->database); + if ($this->read_timeout > 0) { + $redis->setOption(\Redis::OPT_READ_TIMEOUT, $this->read_timeout); + } + $redis->setOption(\Redis::OPT_PREFIX, $this->prefix); + return $redis; + + } + +} diff --git a/kiri-engine/Cache/File.php b/kiri-engine/Cache/File.php index 891a9aef..2f676f8d 100644 --- a/kiri-engine/Cache/File.php +++ b/kiri-engine/Cache/File.php @@ -1,141 +1,141 @@ -getCacheKey($key); - if (!$this->exists($tmpFile)) { - touch($tmpFile); - } - return System::writeFile($tmpFile, $val, LOCK_EX); - } - - /** - * @param $key - * @param array $hashKeys - * @return array|bool - */ - public function hMGet($key, array $hashKeys): array|bool - { - $hash = $this->get($key); - if (!is_array($hash)) { - return false; - } - - $nowHash = []; - foreach ($hashKeys as $hashKey) { - $nowHash[$hashKey] = $hash[$hashKey] ?? null; - } - return $nowHash; - } - - /** - * @param $key - * @param array $val - * @return bool|int|string - */ - public function hMSet($key, array $val): bool|int|string - { - $hash = $this->get($key); - if (!is_array($hash)) { - return false; - } - - $merge = array_merge($hash, $val); - return $this->set($key, $merge); - } - - /** - * @param string $key - * @param string $hashKey - * @return string|int|bool - */ - public function hGet(string $key, string $hashKey): string|int|bool - { - $hash = $this->get($key); - if (!is_array($hash)) { - return false; - } - return $hash[$hashKey] ?? false; - } - - /** - * @param $key - * @param $hashKey - * @param $hashValue - * @return bool|int|string - */ - public function hSet($key, $hashKey, $hashValue): bool|int|string - { - $hash = $this->get($key); - if (!is_array($hash)) { - return false; - } - - $hash[$hashKey] = $hashValue; - - return $this->set($key, $hash); - } - - /** - * @param $key - * @return bool - */ - #[Pure] public function exists($key): bool - { - return file_exists($key); - } - - /** - * @param $key - * @return mixed|bool - */ - public function get($key): string|bool - { - $tmpFile = $this->getCacheKey($key); - if (!$this->exists($tmpFile)) { - return false; - } - $content = file_get_contents($tmpFile); - return swoole_unserialize($content); - } - - /** - * @param $key - * @return string - * @throws - */ - private function getCacheKey($key): string - { - return storage($key, 'cache'); - } -} +getCacheKey($key); + if (!$this->exists($tmpFile)) { + touch($tmpFile); + } + return System::writeFile($tmpFile, $val, LOCK_EX); + } + + /** + * @param $key + * @param array $hashKeys + * @return array|bool + */ + public function hMGet($key, array $hashKeys): array|bool + { + $hash = $this->get($key); + if (!is_array($hash)) { + return false; + } + + $nowHash = []; + foreach ($hashKeys as $hashKey) { + $nowHash[$hashKey] = $hash[$hashKey] ?? null; + } + return $nowHash; + } + + /** + * @param $key + * @param array $val + * @return bool|int|string + */ + public function hMSet($key, array $val): bool|int|string + { + $hash = $this->get($key); + if (!is_array($hash)) { + return false; + } + + $merge = array_merge($hash, $val); + return $this->set($key, $merge); + } + + /** + * @param string $key + * @param string $hashKey + * @return string|int|bool + */ + public function hGet(string $key, string $hashKey): string|int|bool + { + $hash = $this->get($key); + if (!is_array($hash)) { + return false; + } + return $hash[$hashKey] ?? false; + } + + /** + * @param $key + * @param $hashKey + * @param $hashValue + * @return bool|int|string + */ + public function hSet($key, $hashKey, $hashValue): bool|int|string + { + $hash = $this->get($key); + if (!is_array($hash)) { + return false; + } + + $hash[$hashKey] = $hashValue; + + return $this->set($key, $hash); + } + + /** + * @param $key + * @return bool + */ + #[Pure] public function exists($key): bool + { + return file_exists($key); + } + + /** + * @param $key + * @return mixed|bool + */ + public function get($key): string|bool + { + $tmpFile = $this->getCacheKey($key); + if (!$this->exists($tmpFile)) { + return false; + } + $content = file_get_contents($tmpFile); + return swoole_unserialize($content); + } + + /** + * @param $key + * @return string + * @throws + */ + private function getCacheKey($key): string + { + return storage($key, 'cache'); + } +} diff --git a/kiri-engine/Cache/ICache.php b/kiri-engine/Cache/ICache.php index 43c57e49..a9ed1efa 100644 --- a/kiri-engine/Cache/ICache.php +++ b/kiri-engine/Cache/ICache.php @@ -1,65 +1,65 @@ -get(PoolRedis::class); - - $config = $this->get_config(); - - $length = Config::get('cache.redis.pool.max', 10); - - $this->eventProvider->on(OnWorkerExit::class, [$this, 'destroy'], 0); - - $connections->initConnections('Redis:' . $config['host'], true, $length); - } - - - /** - * @param $name - * @param $arguments - * @return mixed - * @throws - */ - public function __call($name, $arguments): mixed - { - $time = microtime(true); - if (method_exists($this, $name)) { - $data = $this->{$name}(...$arguments); - } else { - $data = $this->proxy($name, $arguments); - } - if (microtime(true) - $time >= 0.02) { - $this->warning('Redis:' . Json::encode([$name, $arguments]) . (microtime(true) - $time)); - } - return $data; - } - - - /** - * @param $key - * @param int $timeout - * @return bool - */ - public function waite($key, int $timeout = 5): bool - { - $time = time(); - while (!$this->setNx($key, 1)) { - if (time()- $time >= $timeout) { - return FALSE; - } - usleep(1000); - } - $this->expire($key, $timeout); - return TRUE; - } - - - /** - * @param $key - * @param int $timeout - * @return bool|int - * @throws Exception - */ - public function lock($key, int $timeout = 5): bool|int - { - $script = << - - + + + + + Title + + + + +

+
+
+
diff --git a/test.php b/test.php
index 76c980d2..d97244fb 100644
--- a/test.php
+++ b/test.php
@@ -1,37 +1,47 @@
-get('/v1/agent/services?filter=Service == FriendRpcService');
-	$client->close();
-	var_dump($client->getBody());
-
-});
+get('/v1/agent/services?filter=Service == FriendRpcService');
+//	$client->close();
+//	var_dump($client->getBody());
+//
+//});
+
+function order(int $userId): string
+{
+    $explode = current(explode(' ', str_replace('0.', '', round((float)microtime(),6))));
+
+    return 'N'.sprintf('%09d', $userId) . '.' . date('YmdHis') . '.' . str_pad($explode,6,0);
+}
+var_dump(
+    order(1)
+);
\ No newline at end of file