From abd043ee15269973d58efe7fe43202fc38d51278 Mon Sep 17 00:00:00 2001 From: "as2252258@163.com" Date: Sat, 4 Sep 2021 00:08:34 +0800 Subject: [PATCH] 111 --- core/Cache/Base/Redis.php | 4 +- core/Di/Attributes.php | 272 ----- core/Di/Container.php | 16 +- core/Di/NoteManager.php | 272 +++++ function.php | 1593 +++++++++++++------------ http-server/ApplicationStore.php | 2 +- http-server/ServerManager.php | 820 ++++++------- http-server/Worker/OnServerWorker.php | 9 +- http-server/Worker/OnWorkerStart.php | 7 +- note/Route/Socket.php | 19 - 10 files changed, 1503 insertions(+), 1511 deletions(-) delete mode 100644 core/Di/Attributes.php create mode 100644 core/Di/NoteManager.php diff --git a/core/Cache/Base/Redis.php b/core/Cache/Base/Redis.php index be38dfe3..2567fe1e 100644 --- a/core/Cache/Base/Redis.php +++ b/core/Cache/Base/Redis.php @@ -66,13 +66,13 @@ class Redis implements StopHeartbeatCheck */ public function heartbeat_check(): void { - if (env('state') == 'exit') { + if (env('state','start') == 'exit') { return; } if ($this->_timer === -1 && Context::inCoroutine()) { $this->_timer = Timer::tick(1000, function () { try { - if (env('state') == 'exit') { + if (env('state','start') == 'exit') { echo 'timer end.' . PHP_EOL; } if (time() - $this->_last > 10 * 60) { diff --git a/core/Di/Attributes.php b/core/Di/Attributes.php deleted file mode 100644 index d008bb10..00000000 --- a/core/Di/Attributes.php +++ /dev/null @@ -1,272 +0,0 @@ -getName(); - if (!isset($this->_classTarget[$className])) { - $this->_classTarget[$className] = []; - } - foreach ($class->getAttributes() as $attribute) { - if (!class_exists($attribute->getName())) { - continue; - } - - $instance = $attribute->newInstance(); - - $this->_classTarget[$className][] = $instance; - - $this->setMappingClass($attribute, $className); - } - } - - - /** - * @param ReflectionAttribute $attribute - * @param string $class - */ - private function setMappingClass(ReflectionAttribute $attribute, string $class) - { - if (!isset($this->_mapping[$attribute->getName()])) { - $this->_mapping[$attribute->getName()] = []; - } - if (!isset($this->_mapping[$attribute->getName()][$class])) { - $this->_mapping[$attribute->getName()][$class] = []; - } - } - - - /** - * @param ReflectionAttribute $attribute - * @param string $class - * @param string $method - * @param mixed $instance - */ - private function setMappingMethod(ReflectionAttribute $attribute, string $class, string $method, mixed $instance) - { - $this->setMappingClass($attribute, $class); - - if (!isset($this->_mapping[$attribute->getName()][$class]['method'])) { - $this->_mapping[$attribute->getName()][$class]['method'] = []; - } - $this->_mapping[$attribute->getName()][$class]['method'][] = [$method => $instance]; - } - - - /** - * @param ReflectionAttribute $attribute - * @param string $class - * @param string $property - * @param $instance - */ - private function setMappingProperty(ReflectionAttribute $attribute, string $class, string $property, $instance) - { - $this->setMappingClass($attribute, $class); - - $mapping = $this->_mapping[$attribute->getName()][$class]; - if (!isset($mapping['property'])) { - $mapping['property'] = []; - } - $mapping['property'][] = [$property => $instance]; - $this->_mapping[$attribute->getName()][$class] = $mapping; - } - - - /** - * @param mixed $class - * @return array - */ - public function getTargetNote(mixed $class): array - { - if (!is_string($class)) { - $class = $class::class; - } - return $this->_classTarget[$class] ?? []; - } - - - /** - * @param ReflectionClass $class - */ - protected function setMethodNote(ReflectionClass $class) - { - $className = $class->getName(); - $this->_classMethodNote[$className] = $this->_classMethod[$className] = []; - foreach ($class->getMethods() as $ReflectionMethod) { - $this->_classMethod[$className][$ReflectionMethod->getName()] = $ReflectionMethod; - $this->_classMethodNote[$className][$ReflectionMethod->getName()] = []; - foreach ($ReflectionMethod->getAttributes() as $attribute) { - if (!class_exists($attribute->getName())) { - continue; - } - $instance = $attribute->newInstance(); - - $this->_classMethodNote[$className][$ReflectionMethod->getName()][] = $instance; - - $this->setMappingMethod($attribute, $className, $ReflectionMethod->getName(), $instance); - } - } - } - - - /** - * @param string $class - * @param string $method - * @return bool - */ - public function hasMethod(string $class, string $method): bool - { - return isset($this->_classMethod[$class]) && isset($this->_classMethod[$class][$method]); - } - - - /** - * @param ReflectionClass $class - * @return array - */ - #[Pure] public function getMethodNote(ReflectionClass $class): array - { - return $this->_classMethodNote[$class->getName()] ?? []; - } - - - /** - * @param ReflectionClass $class - */ - protected function setPropertyNote(ReflectionClass $class) - { - $className = $class->getName(); - $this->_classProperty[$className] = $this->_classPropertyNote[$className] = []; - foreach ($class->getProperties(ReflectionProperty::IS_PRIVATE | ReflectionProperty::IS_PUBLIC | - ReflectionProperty::IS_PROTECTED) as $ReflectionMethod) { - $this->_classProperty[$className][$ReflectionMethod->getName()] = $ReflectionMethod; - foreach ($ReflectionMethod->getAttributes() as $attribute) { - if (!class_exists($attribute->getName())) { - continue; - } - - $instance = $attribute->newInstance(); - - $this->_classPropertyNote[$className][$ReflectionMethod->getName()] = $instance; - - $this->setMappingProperty($attribute, $className, $ReflectionMethod->getName(), $instance); - } - } - } - - - /** - * @param string $attribute - * @param string|null $class - * @return array[] - */ - public function getAttributeTrees(string $attribute, string $class = null): array - { - $mapping = $this->_mapping[$attribute] ?? []; - if (empty($mapping) || empty($class)) { - return $mapping; - } - return $mapping[$class] ?? []; - } - - - /** - * @param string $attribute - * @param string $class - * @param string|null $method - * @return array - */ - public function getMethodByAnnotation(string $attribute, string $class, string $method = null): mixed - { - $class = $this->getAttributeTrees($attribute, $class); - if (empty($class) || !isset($class['method']) || empty($method)) { - return $class['method'] ?? []; - } - foreach ($class['method'] as $value) { - $key = key($value); - if ($method == $key) { - return $value[$key]; - } - } - return null; - } - - - /** - * @param string $attribute - * @param string $class - * @param string $method - * @return mixed - */ - public function getPropertyByAnnotation(string $attribute, string $class, string $method): mixed - { - $class = $this->getAttributeTrees($attribute, $class); - if (empty($class) || !isset($class['property'])) { - return []; - } - foreach ($class['property'] as $value) { - $key = key($value); - if ($method == $key) { - return $value[$key]; - } - } - return null; - } - - - /** - * @param ReflectionClass|string $class - * @return array - * @throws \ReflectionException - */ - public function getMethods(ReflectionClass|string $class): array - { - if (is_string($class)) { - $class = $this->getReflect($class); - } - return $this->_classMethod[$class->getName()] ?? []; - } - - - /** - * @param ReflectionClass $class - * @return ReflectionProperty[] - */ - #[Pure] public function getProperty(ReflectionClass $class): array - { - return $this->_classProperty[$class->getName()] ?? []; - } - - - /** - * @param ReflectionClass $class - * @return array - */ - #[Pure] public function getPropertyNote(ReflectionClass $class): array - { - return $this->_classPropertyNote[$class->getName()] ?? []; - } - - -} diff --git a/core/Di/Container.php b/core/Di/Container.php index 488b5a1f..9218858e 100644 --- a/core/Di/Container.php +++ b/core/Di/Container.php @@ -34,8 +34,6 @@ use Server\ResponseInterface; class Container extends BaseObject implements ContainerInterface { - use Attributes; - /** * @var array * @@ -200,7 +198,7 @@ class Container extends BaseObject implements ContainerInterface */ public function propertyInject(ReflectionClass $reflect, $object): mixed { - foreach ($this->getPropertyNote($reflect) as $property => $inject) { + foreach (NoteManager::getPropertyNote($reflect) as $property => $inject) { /** @var Inject $inject */ $inject->execute($object, $property); } @@ -216,7 +214,7 @@ class Container extends BaseObject implements ContainerInterface */ public function getMethodAttribute($className, $method = null): array { - $methods = $this->getMethodNote($this->getReflect($className)); + $methods = NoteManager::getMethodNote($this->getReflect($className)); if (!empty($method)) { return $methods[$method] ?? []; } @@ -232,7 +230,7 @@ class Container extends BaseObject implements ContainerInterface */ public function getClassReflectionProperty(string $class, string $property = null): ReflectionProperty|null|array { - $lists = $this->getProperty($this->getReflect($class)); + $lists = NoteManager::getProperty($this->getReflect($class)); if (empty($lists)) { return null; } @@ -272,9 +270,9 @@ class Container extends BaseObject implements ContainerInterface if ($reflect->isAbstract() || $reflect->isTrait() || $reflect->isInterface()) { return $this->_reflection[$class] = $reflect; } - $this->setPropertyNote($reflect); - $this->setTargetNote($reflect); - $this->setMethodNote($reflect); + NoteManager::setPropertyNote($reflect); + NoteManager::setTargetNote($reflect); + NoteManager::setMethodNote($reflect); $construct = $reflect->getConstructor(); if (!empty($construct) && $construct->getNumberOfParameters() > 0) { $this->_constructs[$class] = $construct; @@ -293,7 +291,7 @@ class Container extends BaseObject implements ContainerInterface if (is_string($class)) { $class = $this->getReflect($class); } - return $this->getMethods($class); + return NoteManager::getMethods($class); } diff --git a/core/Di/NoteManager.php b/core/Di/NoteManager.php new file mode 100644 index 00000000..ba5f4dd8 --- /dev/null +++ b/core/Di/NoteManager.php @@ -0,0 +1,272 @@ +getName(); + if (!isset(static::$_classTarget[$className])) { + static::$_classTarget[$className] = []; + } + foreach ($class->getAttributes() as $attribute) { + if (!class_exists($attribute->getName())) { + continue; + } + + $instance = $attribute->newInstance(); + + static::$_classTarget[$className][] = $instance; + + self::setMappingClass($attribute, $className); + } + } + + + /** + * @param ReflectionAttribute $attribute + * @param string $class + */ + public static function setMappingClass(ReflectionAttribute $attribute, string $class) + { + if (!isset(static::$_mapping[$attribute->getName()])) { + static::$_mapping[$attribute->getName()] = []; + } + if (!isset(static::$_mapping[$attribute->getName()][$class])) { + static::$_mapping[$attribute->getName()][$class] = []; + } + } + + + /** + * @param ReflectionAttribute $attribute + * @param string $class + * @param string $method + * @param mixed $instance + */ + public static function setMappingMethod(ReflectionAttribute $attribute, string $class, string $method, mixed $instance) + { + self::setMappingClass($attribute, $class); + + if (!isset(static::$_mapping[$attribute->getName()][$class]['method'])) { + static::$_mapping[$attribute->getName()][$class]['method'] = []; + } + static::$_mapping[$attribute->getName()][$class]['method'][] = [$method => $instance]; + } + + + /** + * @param ReflectionAttribute $attribute + * @param string $class + * @param string $property + * @param $instance + */ + public static function setMappingProperty(ReflectionAttribute $attribute, string $class, string $property, $instance) + { + self::setMappingClass($attribute, $class); + + $mapping = static::$_mapping[$attribute->getName()][$class]; + if (!isset($mapping['property'])) { + $mapping['property'] = []; + } + $mapping['property'][] = [$property => $instance]; + static::$_mapping[$attribute->getName()][$class] = $mapping; + } + + + /** + * @param mixed $class + * @return array + */ + public static function getTargetNote(mixed $class): array + { + if (!is_string($class)) { + $class = $class::class; + } + return static::$_classTarget[$class] ?? []; + } + + + /** + * @param ReflectionClass $class + */ + public static function setMethodNote(ReflectionClass $class) + { + $className = $class->getName(); + static::$_classMethodNote[$className] = static::$_classMethod[$className] = []; + foreach ($class->getMethods() as $ReflectionMethod) { + static::$_classMethod[$className][$ReflectionMethod->getName()] = $ReflectionMethod; + static::$_classMethodNote[$className][$ReflectionMethod->getName()] = []; + foreach ($ReflectionMethod->getAttributes() as $attribute) { + if (!class_exists($attribute->getName())) { + continue; + } + $instance = $attribute->newInstance(); + + static::$_classMethodNote[$className][$ReflectionMethod->getName()][] = $instance; + + self::setMappingMethod($attribute, $className, $ReflectionMethod->getName(), $instance); + } + } + } + + + /** + * @param string $class + * @param string $method + * @return bool + */ + public static function hasMethod(string $class, string $method): bool + { + return isset(static::$_classMethod[$class]) && isset(static::$_classMethod[$class][$method]); + } + + + /** + * @param ReflectionClass $class + * @return array + */ + #[Pure] public static function getMethodNote(ReflectionClass $class): array + { + return static::$_classMethodNote[$class->getName()] ?? []; + } + + + /** + * @param ReflectionClass $class + */ + public static function setPropertyNote(ReflectionClass $class) + { + $className = $class->getName(); + static::$_classProperty[$className] = static::$_classPropertyNote[$className] = []; + foreach ($class->getProperties(ReflectionProperty::IS_PRIVATE | ReflectionProperty::IS_PUBLIC | + ReflectionProperty::IS_PROTECTED) as $ReflectionMethod) { + static::$_classProperty[$className][$ReflectionMethod->getName()] = $ReflectionMethod; + foreach ($ReflectionMethod->getAttributes() as $attribute) { + if (!class_exists($attribute->getName())) { + continue; + } + + $instance = $attribute->newInstance(); + + static::$_classPropertyNote[$className][$ReflectionMethod->getName()] = $instance; + + self::setMappingProperty($attribute, $className, $ReflectionMethod->getName(), $instance); + } + } + } + + + /** + * @param string $attribute + * @param string|null $class + * @return array[] + */ + public static function getAttributeTrees(string $attribute, string $class = null): array + { + $mapping = static::$_mapping[$attribute] ?? []; + if (empty($mapping) || empty($class)) { + return $mapping; + } + return $mapping[$class] ?? []; + } + + + /** + * @param string $attribute + * @param string $class + * @param string|null $method + * @return array + */ + public static function getMethodByAnnotation(string $attribute, string $class, string $method = null): mixed + { + $class = self::getAttributeTrees($attribute, $class); + if (empty($class) || !isset($class['method']) || empty($method)) { + return $class['method'] ?? []; + } + foreach ($class['method'] as $value) { + $key = key($value); + if ($method == $key) { + return $value[$key]; + } + } + return null; + } + + + /** + * @param string $attribute + * @param string $class + * @param string $method + * @return mixed + */ + public static function getPropertyByAnnotation(string $attribute, string $class, string $method): mixed + { + $class = self::getAttributeTrees($attribute, $class); + if (empty($class) || !isset($class['property'])) { + return []; + } + foreach ($class['property'] as $value) { + $key = key($value); + if ($method == $key) { + return $value[$key]; + } + } + return null; + } + + + /** + * @param ReflectionClass|string $class + * @return array + * @throws \ReflectionException + */ + public static function getMethods(ReflectionClass|string $class): array + { + if (is_string($class)) { + $class = self::getReflect($class); + } + return static::$_classMethod[$class->getName()] ?? []; + } + + + /** + * @param ReflectionClass $class + * @return ReflectionProperty[] + */ + #[Pure] public static function getProperty(ReflectionClass $class): array + { + return static::$_classProperty[$class->getName()] ?? []; + } + + + /** + * @param ReflectionClass $class + * @return array + */ + #[Pure] public static function getPropertyNote(ReflectionClass $class): array + { + return static::$_classPropertyNote[$class->getName()] ?? []; + } + + +} diff --git a/function.php b/function.php index 21c5b36d..6920577a 100644 --- a/function.php +++ b/function.php @@ -21,35 +21,36 @@ use Kiri\Kiri; use Psr\Log\LoggerInterface; use Server\Constrict\Request; use Server\Constrict\Response; +use Server\ServerManager; use Swoole\WebSocket\Server; if (!function_exists('make')) { - /** - * @param $name - * @param $default - * @return mixed - * @throws - */ - function make($name, $default = null): mixed - { - if (class_exists($name)) { - return Kiri::createObject($name); - } - if (Kiri::has($name)) { - return Kiri::app()->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; - } + /** + * @param $name + * @param $default + * @return mixed + * @throws + */ + function make($name, $default = null): mixed + { + if (class_exists($name)) { + return Kiri::createObject($name); + } + if (Kiri::has($name)) { + return Kiri::app()->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; + } } @@ -57,13 +58,13 @@ if (!function_exists('make')) { if (!function_exists('done')) { - /** - * - */ - function done() - { - putenv('state=exit'); - } + /** + * + */ + function done() + { + ServerManager::setEnv('state', 'exit'); + } } @@ -71,10 +72,10 @@ if (!function_exists('done')) { if (!function_exists('enable_file_modification_listening')) { - function enable_file_modification_listening(): void - { - putenv('enable_file_modification_listening=on'); - } + function enable_file_modification_listening(): void + { + putenv('enable_file_modification_listening=on'); + } } @@ -83,13 +84,13 @@ if (!function_exists('enable_file_modification_listening')) { if (!function_exists('is_enable_file_modification_listening')) { - /** - * @return bool - */ - function is_enable_file_modification_listening(): bool - { - return env('enable_file_modification_listening', 'off') == 'off'; - } + /** + * @return bool + */ + function is_enable_file_modification_listening(): bool + { + return env('enable_file_modification_listening', 'off') == 'off'; + } } @@ -97,10 +98,10 @@ if (!function_exists('is_enable_file_modification_listening')) { if (!function_exists('disable_file_modification_listening')) { - function disable_file_modification_listening() - { - putenv('enable_file_modification_listening=off'); - } + function disable_file_modification_listening() + { + putenv('enable_file_modification_listening=off'); + } } @@ -108,27 +109,27 @@ if (!function_exists('disable_file_modification_listening')) { if (!function_exists('now')) { - /** - * @return string - */ - function now(): string - { - return date('Y-m-d H:i:s') . '.' . str_replace('0.', '', (string)microtime(true)); - } + /** + * @return string + */ + function now(): string + { + return date('Y-m-d H:i:s') . '.' . str_replace('0.', '', (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'; - } + /** + * @param $worker_id + * @return string + */ + function workerName($worker_id) + { + return $worker_id >= Kiri::app()->getSwoole()->setting['worker_num'] ? 'Task' : 'Worker'; + } } @@ -136,14 +137,14 @@ if (!function_exists('workerName')) { if (!function_exists('annotation')) { - /** - * @return Annotation - * @throws Exception - */ - function annotation(): Annotation - { - return Kiri::getAnnotation(); - } + /** + * @return Annotation + * @throws Exception + */ + function annotation(): Annotation + { + return Kiri::getAnnotation(); + } } @@ -152,21 +153,21 @@ if (!function_exists('annotation')) { if (!function_exists('scan_directory')) { - /** - * @param $dir - * @param $namespace - * @param array $exclude - * @throws NotFindClassException - * @throws ReflectionException - * @throws Exception - */ - function scan_directory($dir, $namespace, array $exclude = []) - { - $annotation = Kiri::app()->getAnnotation(); - $annotation->read($dir, $namespace, $exclude); + /** + * @param $dir + * @param $namespace + * @param array $exclude + * @throws NotFindClassException + * @throws ReflectionException + * @throws Exception + */ + function scan_directory($dir, $namespace, array $exclude = []) + { + $annotation = Kiri::app()->getAnnotation(); + $annotation->read($dir, $namespace, $exclude); - injectRuntime($dir, $exclude); - } + injectRuntime($dir, $exclude); + } } @@ -174,32 +175,32 @@ if (!function_exists('scan_directory')) { if (!function_exists('injectRuntime')) { - /** - * @param string $path - * @param array $exclude - * @throws NotFindClassException - * @throws ReflectionException - * @throws Exception - */ - function injectRuntime(string $path, array $exclude = []) - { - $fileLists = Kiri::getAnnotation()->runtime($path, $exclude); - $di = Kiri::getDi(); - foreach ($fileLists as $class) { - foreach ($di->getTargetNote($class) as $value) { - $value->execute($class); - } - $methods = $di->getMethodAttribute($class); - foreach ($methods as $method => $attribute) { - if (empty($attribute)) { - continue; - } - foreach ($attribute as $item) { - $item->execute($class, $method); - } - } - } - } + /** + * @param string $path + * @param array $exclude + * @throws NotFindClassException + * @throws ReflectionException + * @throws Exception + */ + function injectRuntime(string $path, array $exclude = []) + { + $fileLists = Kiri::getAnnotation()->runtime($path, $exclude); + $di = Kiri::getDi(); + foreach ($fileLists as $class) { + foreach ($di->getTargetNote($class) as $value) { + $value->execute($class); + } + $methods = $di->getMethodAttribute($class); + foreach ($methods as $method => $attribute) { + if (empty($attribute)) { + continue; + } + foreach ($attribute as $item) { + $item->execute($class, $method); + } + } + } + } } @@ -207,14 +208,14 @@ if (!function_exists('injectRuntime')) { if (!function_exists('swoole')) { - /** - * @return Server|null - * @throws Exception - */ - function swoole(): ?Server - { - return Kiri::getWebSocket(); - } + /** + * @return Server|null + * @throws Exception + */ + function swoole(): ?Server + { + return Kiri::getWebSocket(); + } } @@ -222,14 +223,14 @@ if (!function_exists('swoole')) { if (!function_exists('directory')) { - /** - * @param $name - * @return string - */ - #[Pure] function directory($name): string - { - return realpath(APP_PATH . $name); - } + /** + * @param $name + * @return string + */ + #[Pure] function directory($name): string + { + return realpath(APP_PATH . $name); + } } @@ -238,28 +239,28 @@ if (!function_exists('directory')) { if (!function_exists('isUrl')) { - /** - * @param $url - * @param bool $get_info - * @return false|array - */ - function isUrl($url, $get_info = true): bool|array - { - $queryMatch = '/((http[s]?):\/\/)?(([\w\-\_]+\.)+\w+(:\d+)?)(\/.*)?/'; - if (!preg_match($queryMatch, $url, $outPut)) { - return false; - } - $port = str_replace(':', '', $outPut[5]); + /** + * @param $url + * @param bool $get_info + * @return false|array + */ + function isUrl($url, $get_info = true): bool|array + { + $queryMatch = '/((http[s]?):\/\/)?(([\w\-\_]+\.)+\w+(:\d+)?)(\/.*)?/'; + if (!preg_match($queryMatch, $url, $outPut)) { + return false; + } + $port = str_replace(':', '', $outPut[5]); - [$isHttps, $domain, $port, $path] = [$outPut[2] == 'https', $outPut[3], $port, $outPut[6] ?? '']; - if ($isHttps && empty($port)) { - $port = 443; - } + [$isHttps, $domain, $port, $path] = [$outPut[2] == 'https', $outPut[3], $port, $outPut[6] ?? '']; + if ($isHttps && empty($port)) { + $port = 443; + } - unset($outPut); + unset($outPut); - return [$isHttps == 'https', $domain, $port, $path]; - } + return [$isHttps == 'https', $domain, $port, $path]; + } } @@ -267,23 +268,23 @@ if (!function_exists('isUrl')) { 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; - } + /** + * @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]; - } + [$isHttps, $domain, $port, $path] = $parse; + $uri = $isHttps ? 'https://' . $domain : 'http://' . $domain; + if (!empty($port)) { + $uri .= ':' . $port; + } + return [$uri, $path]; + } } @@ -291,15 +292,15 @@ if (!function_exists('split_request_uri')) { 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]; - } + /** + * @param $url + * @return false|array + */ + function hadDomain($url): bool|array + { + $param = split_request_uri($url); + return !is_array($param) ? false : $param[0]; + } } @@ -307,27 +308,27 @@ if (!function_exists('hadDomain')) { if (!function_exists('isDomain')) { - /** - * @param $url - * @return false|array - */ - function isDomain($url): array|bool - { - return !isIp($url); - } + /** + * @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); - } + /** + * @param $url + * @return false|array + */ + function isIp($url): bool|array + { + return preg_match('/(\d{1,3}\.){3}\.\d{1,3}(:\d{1,5})?/', $url); + } } @@ -335,32 +336,32 @@ if (!function_exists('isIp')) { 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; - } + /** + * @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); + $replace = ltrim(str_replace(__DIR__, '', $value), '/'); + $replace = str_replace('.php', '', $replace); - $first = explode(DIRECTORY_SEPARATOR, $replace); - array_shift($first); + $first = explode(DIRECTORY_SEPARATOR, $replace); + array_shift($first); - Kiri::setAutoload($namespace . '\\' . implode('\\', $first), $value); - } - } - } + Kiri::setAutoload($namespace . '\\' . implode('\\', $first), $value); + } + } + } } @@ -369,523 +370,523 @@ if (!function_exists('loadByDir')) { 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); - } + /** + * @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::app()->getRedis(); - } + /** + * @return \Kiri\Cache\Redis|Redis + * @throws Exception + */ + function redis(): \Kiri\Cache\Redis|Redis + { + return Kiri::app()->getRedis(); + } } if (!function_exists('fire')) { - /** - * @param object $event - * @throws NotFindClassException - * @throws ReflectionException - */ - function fire(object $event) - { - di(EventDispatch::class)->dispatch($event); - } + /** + * @param object $event + * @throws NotFindClassException + * @throws ReflectionException + */ + function fire(object $event) + { + di(EventDispatch::class)->dispatch($event); + } } if (!function_exists('aop')) { - /** - * @param mixed $handler - * @param array $params - * @return mixed - * @throws Exception - */ - function aop(mixed $handler, array $params = []): mixed - { - return Kiri::getDi()->get(AspectManager::class)->dispatch($handler, $params); - } + /** + * @param mixed $handler + * @param array $params + * @return mixed + * @throws Exception + */ + function aop(mixed $handler, array $params = []): mixed + { + return Kiri::getDi()->get(AspectManager::class)->dispatch($handler, $params); + } } if (!function_exists('app')) { - /** - * @return Application|null - */ - #[Pure] function app(): ?Application - { - return Kiri::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); - } - } - } + 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); - } + /** + * @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(); - } + /** + * @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; - } - } + /** + * 空白字符替换 + * @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) - { - $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', + function get_file_extension($filename) + { + $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', + // 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', + // 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', + // 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', + // 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', + // 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', + // 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', - ]; + '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; - } elseif (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'; - } - } + $explode = explode('.', $filename); + $ext = strtolower(array_pop($explode)); + if (array_key_exists($ext, $mime_types)) { + return $ext; + } elseif (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('request')) { - /** - * @return Request - * @throws Exception - */ - function request(): Request - { - return Kiri::getDi()->get(Request::class); - } + /** + * @return Request + * @throws Exception + */ + function request(): Request + { + return Kiri::getDi()->get(Request::class); + } } if (!function_exists('storage')) { - /** - * @param string|null $fileName - * @param string|null $path - * @return string - * @throws Exception - */ - function storage(?string $fileName = '', ?string $path = ''): string - { + /** + * @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; - } + $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); - } + /** + * @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; - } + /** + * @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); - } + $name = Config::get('id', 'system') . '[' . $pid . ']'; + if (!empty($prefix)) { + $name .= '.' . $prefix; + } + swoole_set_process_name($name); + } } if (!function_exists('response')) { - /** - * @return Response - * @throws - */ - function response(): Response - { - if (!Context::hasContext(HttpResponse::class)) { - Context::setContext(HttpResponse::class, new HttpResponse()); - } - return di(Response::class); - } + /** + * @return Response + * @throws + */ + function response(): Response + { + if (!Context::hasContext(HttpResponse::class)) { + Context::setContext(HttpResponse::class, new HttpResponse()); + } + return di(Response::class); + } } if (!function_exists('zero_full')) { - function zero_full(int $data = 1, int $length = 10): string - { - return sprintf('%0' . $length . 'd', $data); - } + function zero_full(int $data = 1, int $length = 10): string + { + return sprintf('%0' . $length . 'd', $data); + } } if (!function_exists('redirect')) { - /** - * @param $url - * @return int - */ - function redirect($url): int - { - return response()->redirect($url); - } + /** + * @param $url + * @return int + */ + function redirect($url): int + { + return response()->redirect($url); + } } 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; - } + /** + * @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; + } } @@ -893,50 +894,50 @@ if (!function_exists('env')) { if (!function_exists('di')) { - /** - * @param string $className - * @return mixed - * @throws ReflectionException - * @throws NotFindClassException - */ - function di(string $className): mixed - { - return Kiri::getDi()->get($className); - } + /** + * @param string $className + * @return mixed + * @throws ReflectionException + * @throws NotFindClassException + */ + function di(string $className): mixed + { + return Kiri::getDi()->get($className); + } } if (!function_exists('duplicate')) { - /** - * @param string $className - * @return mixed - * @throws ReflectionException - * @throws NotFindClassException - */ - function duplicate(string $className): mixed - { - $class = di($className); - return clone $class; - } + /** + * @param string $className + * @return mixed + * @throws ReflectionException + * @throws NotFindClassException + */ + function duplicate(string $className): mixed + { + $class = di($className); + return clone $class; + } } 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; - } + /** + * @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; + } } @@ -944,18 +945,18 @@ if (!function_exists('sweep')) { if (!function_exists('swoole_serialize')) { - /** - * @param $data - * @return string - */ - function swoole_serialize($data): string - { + /** + * @param $data + * @return string + */ + function swoole_serialize($data): string + { // if (class_exists('swoole_serialize')) { // return \swoole_serialize::pack($data); // } else { - return serialize($data); + return serialize($data); // } - } + } } @@ -963,21 +964,21 @@ if (!function_exists('swoole_serialize')) { if (!function_exists('swoole_unserialize')) { - /** - * @param $data - * @return string - */ - function swoole_unserialize($data): mixed - { - if (empty($data)) { - return null; - } + /** + * @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); + return unserialize($data); // } - } + } } @@ -985,15 +986,15 @@ if (!function_exists('swoole_unserialize')) { if (!function_exists('merge')) { - /** - * @param $param - * @param $param1 - * @return array - */ - function merge($param, $param1): array - { - return ArrayAccess::merge($param, $param1); - } + /** + * @param $param + * @param $param1 + * @return array + */ + function merge($param, $param1): array + { + return ArrayAccess::merge($param, $param1); + } } @@ -1001,14 +1002,14 @@ if (!function_exists('merge')) { if (!function_exists('router')) { - /** - * @return Router - * @throws Exception - */ - function router(): Router - { - return Kiri::app()->getRouter(); - } + /** + * @return Router + * @throws Exception + */ + function router(): Router + { + return Kiri::app()->getRouter(); + } } @@ -1016,73 +1017,73 @@ if (!function_exists('router')) { if (!function_exists('isService')) { - /** - * @param string $name - * @return bool - * @throws NotFindClassException - * @throws ReflectionException - */ - function isService(string $name): bool - { - return Kiri::app()->has($name); - } + /** + * @param string $name + * @return bool + * @throws NotFindClassException + * @throws ReflectionException + */ + 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); - } + /** + * @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 = array(); - if (!$seen) $seen = array(); - $trace = $e->getTrace(); - $prev = $e->getPrevious(); - $result[] = sprintf('%s%s: %s', $starter, $e::class, $e->getMessage()); - $file = $e->getFile(); - $line = $e->getLine(); + /** + * @param $e + * @param null $seen + * @param bool $toHtml + * @return string + */ + function jTraceEx($e, $seen = null, bool $toHtml = false): string + { + $starter = $seen ? 'Caused by: ' : ''; + $result = array(); + if (!$seen) $seen = array(); + $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); + 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); - } + $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; - } + return $result; + } } @@ -1091,85 +1092,85 @@ if (!function_exists('jTraceEx')) { 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); - } + /** + * @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); - } + /** + * @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); - } + /** + * @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); - } + /** + * @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]); - } + /** + * @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); - } + /** + * @param mixed $message + * @param string $method + * @throws Exception + */ + function success(mixed $message, string $method = 'app') + { + Kiri::app()->success($message, $method); + } } diff --git a/http-server/ApplicationStore.php b/http-server/ApplicationStore.php index 951c306f..c1117099 100644 --- a/http-server/ApplicationStore.php +++ b/http-server/ApplicationStore.php @@ -89,7 +89,7 @@ class ApplicationStore */ #[Pure] public function getStatus(): string { - return env('state'); + return env('state','start'); } } diff --git a/http-server/ServerManager.php b/http-server/ServerManager.php index a30c6cd8..aa702d8f 100644 --- a/http-server/ServerManager.php +++ b/http-server/ServerManager.php @@ -27,466 +27,476 @@ use Swoole\WebSocket\Server as WServer; class ServerManager { - /** @var string */ - public string $host = ''; + /** @var string */ + public string $host = ''; - public int $port = 0; + public int $port = 0; - /** @var array */ - public array $ports = []; + /** @var array */ + public array $ports = []; - public int $mode = SWOOLE_TCP; + public int $mode = SWOOLE_TCP; - private Server|null $server = null; + private Server|null $server = null; - /** - * @return Server|WServer|HServer|null - */ - public function getServer(): Server|WServer|HServer|null - { - return $this->server; - } + /** + * @return Server|WServer|HServer|null + */ + public function getServer(): Server|WServer|HServer|null + { + return $this->server; + } - /** - * @param string $type - * @param string $host - * @param int $port - * @param int $mode - * @param array $settings - * @throws ReflectionException - * @throws ConfigException - * @throws Exception - */ - public function addListener(string $type, string $host, int $port, int $mode, array $settings = []) - { - if ($this->checkPortIsAlready($port)) $this->stopServer($port); - if (!$this->server) { - $this->createBaseServer($type, $host, $port, $mode, $settings); - } else { - if (!isset($settings['settings'])) { - $settings['settings'] = []; - } - $this->addNewListener($type, $host, $port, $mode, $settings); - } - } + /** + * @param string $type + * @param string $host + * @param int $port + * @param int $mode + * @param array $settings + * @throws ReflectionException + * @throws ConfigException + * @throws Exception + */ + public function addListener(string $type, string $host, int $port, int $mode, array $settings = []) + { + if ($this->checkPortIsAlready($port)) $this->stopServer($port); + if (!$this->server) { + $this->createBaseServer($type, $host, $port, $mode, $settings); + } else { + if (!isset($settings['settings'])) { + $settings['settings'] = []; + } + $this->addNewListener($type, $host, $port, $mode, $settings); + } + } - /** - * @throws NotFindClassException - * @throws ReflectionException - * @throws ConfigException - */ - public function initBaseServer($configs, int $daemon = 0): void - { - $context = di(ServerManager::class); - foreach ($this->sortService($configs['ports']) as $config) { - $this->startListenerHandler($context, $config, $daemon); - } - $this->bindCallback($this->server, [Constant::PIPE_MESSAGE => [OnPipeMessage::class, 'onPipeMessage']]); - $this->bindCallback($this->server, $this->getSystemEvents($configs)); - } + /** + * @throws NotFindClassException + * @throws ReflectionException + * @throws ConfigException + */ + public function initBaseServer($configs, int $daemon = 0): void + { + $context = di(ServerManager::class); + foreach ($this->sortService($configs['ports']) as $config) { + $this->startListenerHandler($context, $config, $daemon); + } + $this->bindCallback($this->server, [Constant::PIPE_MESSAGE => [OnPipeMessage::class, 'onPipeMessage']]); + $this->bindCallback($this->server, $this->getSystemEvents($configs)); + } - /** - * @return bool - * @throws ConfigException - * @throws Exception - */ - public function isRunner(): bool - { - $configs = Config::get('server', [], true); - foreach ($this->sortService($configs['ports']) as $config) { - if ($this->checkPortIsAlready($config['port'])) { - return true; - } - } - return false; - } + /** + * @return bool + * @throws ConfigException + * @throws Exception + */ + public function isRunner(): bool + { + $configs = Config::get('server', [], true); + foreach ($this->sortService($configs['ports']) as $config) { + if ($this->checkPortIsAlready($config['port'])) { + return true; + } + } + return false; + } - /** - * @param string|CustomProcess $customProcess - * @param null $redirect_stdin_and_stdout - * @param int|null $pipe_type - * @param bool $enable_coroutine - * @throws Exception - */ - public function addProcess(string|CustomProcess $customProcess, $redirect_stdin_and_stdout = null, ?int $pipe_type = SOCK_DGRAM, bool $enable_coroutine = true) - { - $process = $this->initProcess($customProcess, $redirect_stdin_and_stdout, $pipe_type, $enable_coroutine); - $this->server->addProcess($process); - if ($customProcess instanceof CustomProcess) { - Kiri::app()->addProcess($customProcess::class, $process); - } else { - Kiri::app()->addProcess($customProcess, $process); - } - } + /** + * @param string|CustomProcess $customProcess + * @param null $redirect_stdin_and_stdout + * @param int|null $pipe_type + * @param bool $enable_coroutine + * @throws Exception + */ + public function addProcess(string|CustomProcess $customProcess, $redirect_stdin_and_stdout = null, ?int $pipe_type = SOCK_DGRAM, bool $enable_coroutine = true) + { + $process = $this->initProcess($customProcess, $redirect_stdin_and_stdout, $pipe_type, $enable_coroutine); + $this->server->addProcess($process); + if ($customProcess instanceof CustomProcess) { + Kiri::app()->addProcess($customProcess::class, $process); + } else { + Kiri::app()->addProcess($customProcess, $process); + } + } - /** - * @param $customProcess - * @param $redirect_stdin_and_stdout - * @param $pipe_type - * @param $enable_coroutine - * @return Process - */ - private function initProcess($customProcess, $redirect_stdin_and_stdout, $pipe_type, $enable_coroutine): Process - { - $server = $this->server; - return new Process(function (Process $soloProcess) use ($customProcess, $server) { - if (is_string($customProcess)) { - $customProcess = Kiri::createObject($customProcess, [$server]); - } + /** + * @param $customProcess + * @param $redirect_stdin_and_stdout + * @param $pipe_type + * @param $enable_coroutine + * @return Process + */ + private function initProcess($customProcess, $redirect_stdin_and_stdout, $pipe_type, $enable_coroutine): Process + { + $server = $this->server; + return new Process(function (Process $soloProcess) use ($customProcess, $server) { + if (is_string($customProcess)) { + $customProcess = Kiri::createObject($customProcess, [$server]); + } - $name = $customProcess->getProcessName($soloProcess); - info(sprintf("Process %s start.", $name)); + $name = $customProcess->getProcessName($soloProcess); + info(sprintf("Process %s start.", $name)); - scan_directory(directory('app'), 'App'); + scan_directory(directory('app'), 'App'); - $system = sprintf('%s.process[%d]', Config::get('id', 'system-service'), $soloProcess->pid); - if (Kiri::getPlatform()->isLinux()) { - $soloProcess->name($system . '.' . $name . ' start.'); - } - $customProcess->signListen($soloProcess); - $customProcess->onHandler($soloProcess); - }, - $redirect_stdin_and_stdout, - $pipe_type, - $enable_coroutine - ); - } + $system = sprintf('%s.process[%d]', Config::get('id', 'system-service'), $soloProcess->pid); + if (Kiri::getPlatform()->isLinux()) { + $soloProcess->name($system . '.' . $name . ' start.'); + } + $customProcess->signListen($soloProcess); + $customProcess->onHandler($soloProcess); + }, + $redirect_stdin_and_stdout, + $pipe_type, + $enable_coroutine + ); + } - /** - * @return array - */ - public function getSetting(): array - { - return $this->server->setting; - } + /** + * @return array + */ + public function getSetting(): array + { + return $this->server->setting; + } - /** - * @param array $ports - * @return array - */ - public function sortService(array $ports): array - { - $array = []; - foreach ($ports as $port) { - if ($port['type'] == Constant::SERVER_TYPE_WEBSOCKET) { - array_unshift($array, $port); - } else if ($port['type'] == Constant::SERVER_TYPE_HTTP) { - if (!empty($array) && $array[0]['type'] == Constant::SERVER_TYPE_WEBSOCKET) { - $array[] = $port; - } else { - array_unshift($array, $port); - } - } else { - $array[] = $port; - } - } - return $array; - } + /** + * @param array $ports + * @return array + */ + public function sortService(array $ports): array + { + $array = []; + foreach ($ports as $port) { + if ($port['type'] == Constant::SERVER_TYPE_WEBSOCKET) { + array_unshift($array, $port); + } else if ($port['type'] == Constant::SERVER_TYPE_HTTP) { + if (!empty($array) && $array[0]['type'] == Constant::SERVER_TYPE_WEBSOCKET) { + $array[] = $port; + } else { + array_unshift($array, $port); + } + } else { + $array[] = $port; + } + } + return $array; + } - /** - * @param array $configs - * @return array - */ - private function getSystemEvents(array $configs): array - { - return array_intersect_key($configs['events'] ?? [], [ - Constant::SHUTDOWN => '', - Constant::WORKER_START => '', - Constant::WORKER_ERROR => '', - Constant::WORKER_EXIT => '', - Constant::WORKER_STOP => '', - Constant::MANAGER_START => '', - Constant::MANAGER_STOP => '', - Constant::BEFORE_RELOAD => '', - Constant::AFTER_RELOAD => '', - Constant::START => '', - ]); - } + /** + * @param $key + * @param $value + */ + public static function setEnv(string $key, string|int $value): void + { + putenv(sprintf('%s=%s', $key, (string)$value)); + } - /** - * @param ServerManager $context - * @param array $config - * @param int $daemon - * @throws ConfigException - * @throws ReflectionException - * @throws Exception - */ - private function startListenerHandler(ServerManager $context, array $config, int $daemon = 0) - { - if (!$this->server) { - $config = $this->mergeConfig($config, $daemon); - } - $context->addListener( - $config['type'], $config['host'], $config['port'], $config['mode'], - $config); - } + /** + * @param array $configs + * @return array + */ + private function getSystemEvents(array $configs): array + { + return array_intersect_key($configs['events'] ?? [], [ + Constant::SHUTDOWN => '', + Constant::WORKER_START => '', + Constant::WORKER_ERROR => '', + Constant::WORKER_EXIT => '', + Constant::WORKER_STOP => '', + Constant::MANAGER_START => '', + Constant::MANAGER_STOP => '', + Constant::BEFORE_RELOAD => '', + Constant::AFTER_RELOAD => '', + Constant::START => '', + ]); + } - /** - * @param $config - * @param $daemon - * @return array - * @throws Exception - */ - private function mergeConfig($config, $daemon): array - { - $config['settings'] = $config['settings'] ?? []; - if (!isset($config['settings']['daemonize']) || !$config['settings']['daemonize'] != $daemon) { - $config['settings']['daemonize'] = $daemon; - } - if (!isset($config['settings']['log_file'])) { - $config['settings']['log_file'] = storage('system.log'); - } - $config['settings']['pid_file'] = storage('.swoole.pid'); - $config['events'] = $config['events'] ?? []; - return $config; - } + /** + * @param ServerManager $context + * @param array $config + * @param int $daemon + * @throws ConfigException + * @throws ReflectionException + * @throws Exception + */ + private function startListenerHandler(ServerManager $context, array $config, int $daemon = 0) + { + if (!$this->server) { + $config = $this->mergeConfig($config, $daemon); + } + $context->addListener( + $config['type'], $config['host'], $config['port'], $config['mode'], + $config); + } - /** - * @param string $type - * @param string $host - * @param int $port - * @param int $mode - * @param array $settings - * @throws ReflectionException - * @throws Exception - */ - private function addNewListener(string $type, string $host, int $port, int $mode, array $settings = []) - { - echo sprintf("\033[36m[" . date('Y-m-d H:i:s') . "]\033[0m $type service %s::%d start.", $host, $port) . PHP_EOL; - /** @var Server\Port $service */ - $this->ports[$port] = $this->server->addlistener($host, $port, $mode); - if ($this->ports[$port] === false) { - throw new Exception("The port is already in use[$host::$port]"); - } - $this->ports[$port]->set($settings['settings'] ?? []); - $this->addServiceEvents($settings['events'] ?? [], $this->ports[$port]); - } + /** + * @param $config + * @param $daemon + * @return array + * @throws Exception + */ + private function mergeConfig($config, $daemon): array + { + $config['settings'] = $config['settings'] ?? []; + if (!isset($config['settings']['daemonize']) || !$config['settings']['daemonize'] != $daemon) { + $config['settings']['daemonize'] = $daemon; + } + if (!isset($config['settings']['log_file'])) { + $config['settings']['log_file'] = storage('system.log'); + } + $config['settings']['pid_file'] = storage('.swoole.pid'); + $config['events'] = $config['events'] ?? []; + return $config; + } - /** - * @param int $port - * @param string $event - * @return Closure|array|null - */ - public function getPortCallback(int $port, string $event): Closure|array|null - { - /** @var Server\Port $_port */ - $_port = $this->ports[$port] ?? null; - if (is_null($_port)) { - return null; - } - return $_port->getCallback($event); - } + /** + * @param string $type + * @param string $host + * @param int $port + * @param int $mode + * @param array $settings + * @throws ReflectionException + * @throws Exception + */ + private function addNewListener(string $type, string $host, int $port, int $mode, array $settings = []) + { + echo sprintf("\033[36m[" . date('Y-m-d H:i:s') . "]\033[0m $type service %s::%d start.", $host, $port) . PHP_EOL; + /** @var Server\Port $service */ + $this->ports[$port] = $this->server->addlistener($host, $port, $mode); + if ($this->ports[$port] === false) { + throw new Exception("The port is already in use[$host::$port]"); + } + $this->ports[$port]->set($settings['settings'] ?? []); + $this->addServiceEvents($settings['events'] ?? [], $this->ports[$port]); + } - /** - * @param string $type - * @param string $host - * @param int $port - * @param int $mode - * @param array $settings - * @throws ReflectionException - * @throws ConfigException - */ - private function createBaseServer(string $type, string $host, int $port, int $mode, array $settings = []) - { - $match = match ($type) { - Constant::SERVER_TYPE_BASE, Constant::SERVER_TYPE_TCP, - Constant::SERVER_TYPE_UDP => Server::class, - Constant::SERVER_TYPE_HTTP => HServer::class, - Constant::SERVER_TYPE_WEBSOCKET => WServer::class - }; - $this->server = new $match($host, $port, SWOOLE_PROCESS, $mode); - $this->server->set(array_merge(Config::get('server.settings', []), $settings['settings'])); - - echo sprintf("\033[36m[" . date('Y-m-d H:i:s') . "]\033[0m $type service %s::%d start.", $host, $port) . PHP_EOL; - - $this->addDefaultListener($type, $settings); - } + /** + * @param int $port + * @param string $event + * @return Closure|array|null + */ + public function getPortCallback(int $port, string $event): Closure|array|null + { + /** @var Server\Port $_port */ + $_port = $this->ports[$port] ?? null; + if (is_null($_port)) { + return null; + } + return $_port->getCallback($event); + } - /** - * @param int $port - * @throws Exception - */ - public function stopServer(int $port) - { - if (!($pid = $this->checkPortIsAlready($port))) { - return; - } - while ($this->checkPortIsAlready($port)) { - Process::kill($pid, SIGTERM); - usleep(300); - } - } + /** + * @param string $type + * @param string $host + * @param int $port + * @param int $mode + * @param array $settings + * @throws ReflectionException + * @throws ConfigException + */ + private function createBaseServer(string $type, string $host, int $port, int $mode, array $settings = []) + { + $match = match ($type) { + Constant::SERVER_TYPE_BASE, Constant::SERVER_TYPE_TCP, + Constant::SERVER_TYPE_UDP => Server::class, + Constant::SERVER_TYPE_HTTP => HServer::class, + Constant::SERVER_TYPE_WEBSOCKET => WServer::class + }; + $this->server = new $match($host, $port, SWOOLE_PROCESS, $mode); + $this->server->set(array_merge(Config::get('server.settings', []), $settings['settings'])); + + echo sprintf("\033[36m[" . date('Y-m-d H:i:s') . "]\033[0m $type service %s::%d start.", $host, $port) . PHP_EOL; + + $this->addDefaultListener($type, $settings); + } - /** - * @param $port - * @return bool|string - * @throws Exception - */ - private 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, SIGTERM); - } - - exec('netstat -lnp | grep ' . $port . ' | grep "LISTEN" | awk \'{print $7}\'', $output); - if (empty($output)) { - return false; - } - return explode('/', $output[0])[0]; - } + /** + * @param int $port + * @throws Exception + */ + public function stopServer(int $port) + { + if (!($pid = $this->checkPortIsAlready($port))) { + return; + } + while ($this->checkPortIsAlready($port)) { + Process::kill($pid, SIGTERM); + usleep(300); + } + } - /** - * @param string $type - * @param array $settings - * @throws ReflectionException - * @throws Exception - */ - private function addDefaultListener(string $type, array $settings): void - { - if (($this->server->setting['task_worker_num'] ?? 0) > 0) { - $this->addTaskListener($settings['events']); - } - $this->addServiceEvents($settings['events'] ?? [], $this->server); - Kiri::getDi()->setBindings(SwooleServerInterface::class, - $this->server); - } + /** + * @param $port + * @return bool|string + * @throws Exception + */ + private 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, SIGTERM); + } + + exec('netstat -lnp | grep ' . $port . ' | grep "LISTEN" | awk \'{print $7}\'', $output); + if (empty($output)) { + return false; + } + return explode('/', $output[0])[0]; + } - /** - * @param array $events - * @param Server|Port $server - * @throws ReflectionException - */ - private function addServiceEvents(array $events, Server|Port $server) - { - foreach ($events as $name => $event) { - if (is_array($event) && is_string($event[0])) { - $event[0] = Kiri::getDi()->get($event[0], [$server]); - } - $server->on($name, $event); - } - } + /** + * @param string $type + * @param array $settings + * @throws ReflectionException + * @throws Exception + */ + private function addDefaultListener(string $type, array $settings): void + { + if (($this->server->setting['task_worker_num'] ?? 0) > 0) { + $this->addTaskListener($settings['events']); + } + $this->addServiceEvents($settings['events'] ?? [], $this->server); + Kiri::getDi()->setBindings(SwooleServerInterface::class, + $this->server); + } - /** - * - */ - public function start() - { - $this->server->start(); - } + /** + * @param array $events + * @param Server|Port $server + * @throws ReflectionException + */ + private function addServiceEvents(array $events, Server|Port $server) + { + foreach ($events as $name => $event) { + if (is_array($event) && is_string($event[0])) { + $event[0] = Kiri::getDi()->get($event[0], [$server]); + } + $server->on($name, $event); + } + } - /** - * @param string $class - * @return object - * @throws NotFindClassException - * @throws ReflectionException - */ - private function getNewInstance(string $class): object - { - return Kiri::getDi()->newObject($class); - } + /** + * + */ + public function start() + { + $this->server->start(); + } - /** - * @param TaskExecute|string $handler - * @param array $params - * @param int|null $workerId - * @throws ReflectionException - * @throws Exception - */ - public function task(TaskExecute|string $handler, array $params = [], int $workerId = null) - { - if ($workerId === null || $workerId <= $this->server->setting['worker_num']) { - $workerId = random_int($this->server->setting['worker_num'] + 1, - $this->server->setting['worker_num'] + 1 + $this->server->setting['task_worker_num']); - } - if (is_string($handler)) { - $implements = Kiri::getDi()->getReflect($handler); - if (!in_array(TaskExecute::class, $implements->getInterfaceNames())) { - throw new Exception('Task must instance ' . TaskExecute::class); - } - $handler = $implements->newInstanceArgs($params); - } - $this->server->task(serialize($handler), $workerId); - } + /** + * @param string $class + * @return object + * @throws NotFindClassException + * @throws ReflectionException + */ + private function getNewInstance(string $class): object + { + return Kiri::getDi()->newObject($class); + } - /** - * @param mixed $message - * @param int $workerId - * @return mixed - */ - public function sendMessage(mixed $message, int $workerId): mixed - { - return $this->server?->sendMessage($message, $workerId); - } + /** + * @param TaskExecute|string $handler + * @param array $params + * @param int|null $workerId + * @throws ReflectionException + * @throws Exception + */ + public function task(TaskExecute|string $handler, array $params = [], int $workerId = null) + { + if ($workerId === null || $workerId <= $this->server->setting['worker_num']) { + $workerId = random_int($this->server->setting['worker_num'] + 1, + $this->server->setting['worker_num'] + 1 + $this->server->setting['task_worker_num']); + } + if (is_string($handler)) { + $implements = Kiri::getDi()->getReflect($handler); + if (!in_array(TaskExecute::class, $implements->getInterfaceNames())) { + throw new Exception('Task must instance ' . TaskExecute::class); + } + $handler = $implements->newInstanceArgs($params); + } + $this->server->task(serialize($handler), $workerId); + } - /** - * @param array $events - * @throws ReflectionException - */ - private function addTaskListener(array $events = []): void - { - $task_use_object = $this->server->setting['task_object'] ?? $this->server->setting['task_use_object'] ?? false; - $reflect = Kiri::getDi()->getReflect(OnServerTask::class)?->newInstance(); - if ($task_use_object || $this->server->setting['task_enable_coroutine']) { - $this->server->on('task', $events[Constant::TASK] ?? [$reflect, 'onCoroutineTask']); - } else { - $this->server->on('task', $events[Constant::TASK] ?? [$reflect, 'onTask']); - } - $this->server->on('finish', $events[Constant::FINISH] ?? [$reflect, 'onFinish']); - } + /** + * @param mixed $message + * @param int $workerId + * @return mixed + */ + public function sendMessage(mixed $message, int $workerId): mixed + { + return $this->server?->sendMessage($message, $workerId); + } - /** - * @param Port|Server $server - * @param array|null $settings - * @throws ReflectionException - */ - public function bindCallback(Port|Server $server, ?array $settings = []) - { - // TODO: Implement bindCallback() method. - if (count($settings) < 1) { - return; - } - foreach ($settings as $event_type => $callback) { - if ($this->server->getCallback($event_type) !== null) { - continue; - } - if (is_array($callback) && !is_object($callback[0])) { - $callback[0] = Kiri::getDi()->get($callback[0]); - } - $this->server->on($event_type, $callback); - } - } + /** + * @param array $events + * @throws ReflectionException + */ + private function addTaskListener(array $events = []): void + { + $task_use_object = $this->server->setting['task_object'] ?? $this->server->setting['task_use_object'] ?? false; + $reflect = Kiri::getDi()->getReflect(OnServerTask::class)?->newInstance(); + if ($task_use_object || $this->server->setting['task_enable_coroutine']) { + $this->server->on('task', $events[Constant::TASK] ?? [$reflect, 'onCoroutineTask']); + } else { + $this->server->on('task', $events[Constant::TASK] ?? [$reflect, 'onTask']); + } + $this->server->on('finish', $events[Constant::FINISH] ?? [$reflect, 'onFinish']); + } + + + /** + * @param Port|Server $server + * @param array|null $settings + * @throws ReflectionException + */ + public function bindCallback(Port|Server $server, ?array $settings = []) + { + // TODO: Implement bindCallback() method. + if (count($settings) < 1) { + return; + } + foreach ($settings as $event_type => $callback) { + if ($this->server->getCallback($event_type) !== null) { + continue; + } + if (is_array($callback) && !is_object($callback[0])) { + $callback[0] = Kiri::getDi()->get($callback[0]); + } + $this->server->on($event_type, $callback); + } + } } diff --git a/http-server/Worker/OnServerWorker.php b/http-server/Worker/OnServerWorker.php index cf41724a..72fa9c8f 100644 --- a/http-server/Worker/OnServerWorker.php +++ b/http-server/Worker/OnServerWorker.php @@ -14,6 +14,7 @@ use Server\Events\OnWorkerError; use Server\Events\OnWorkerExit; use Server\Events\OnWorkerStart; use Server\Events\OnWorkerStop; +use Server\ServerManager; use Swoole\Server; use Swoole\Timer; @@ -54,8 +55,7 @@ class OnServerWorker extends \Server\Abstracts\Server */ public function setConfigure(OnBeforeWorkerStart $worker) { - putenv('state=start'); - putenv('worker=' . $worker->workerId); + ServerManager::setEnv('worker', $worker->workerId); $serialize = file_get_contents(storage(Runtime::CONFIG_NAME)); if (!empty($serialize)) { Config::sets(unserialize($serialize)); @@ -83,7 +83,7 @@ class OnServerWorker extends \Server\Abstracts\Server */ public function onWorkerExit(Server $server, int $workerId) { - putenv('state=exit'); + ServerManager::setEnv('state', 'exit'); $this->eventDispatch->dispatch(new OnWorkerExit($server, $workerId)); } @@ -104,7 +104,8 @@ class OnServerWorker extends \Server\Abstracts\Server $message = sprintf('Worker#%d::%d error stop. signal %d, exit_code %d, msg %s', $worker_id, $worker_pid, $signal, $exit_code, swoole_strerror(swoole_last_error(), 9) ); - write($message, 'worker-exit'); + + $this->logger->error($message); $this->system_mail($message); } diff --git a/http-server/Worker/OnWorkerStart.php b/http-server/Worker/OnWorkerStart.php index 4e6ab22d..37fbb2b0 100644 --- a/http-server/Worker/OnWorkerStart.php +++ b/http-server/Worker/OnWorkerStart.php @@ -12,6 +12,7 @@ use Kiri\Kiri; use Kiri\Runtime; use Psr\EventDispatcher\EventDispatcherInterface; use ReflectionException; +use Server\ServerManager; class OnWorkerStart implements EventDispatcherInterface { @@ -35,17 +36,17 @@ class OnWorkerStart implements EventDispatcherInterface { $isWorker = $event->workerId < $event->server->setting['worker_num']; - $this->annotation->read(APP_PATH . 'app','App', $isWorker ? [] : [CONTROLLER_PATH]); + $this->annotation->read(APP_PATH . 'app', 'App', $isWorker ? [] : [CONTROLLER_PATH]); $this->interpretDirectory(); if ($isWorker) { - putenv('environmental=' . Kiri::WORKER); + ServerManager::setEnv('environmental', Kiri::WORKER); Kiri::getFactory()->getRouter()->_loader(); echo sprintf("\033[36m[" . date('Y-m-d H:i:s') . "]\033[0m Worker[%d].%d start.", $event->server->worker_pid, $event->workerId) . PHP_EOL; $this->setProcessName(sprintf('Worker[%d].%d', $event->server->worker_pid, $event->workerId)); } else { - putenv('environmental=' . Kiri::TASK); + ServerManager::setEnv('environmental', Kiri::TASK); echo sprintf("\033[36m[" . date('Y-m-d H:i:s') . "]\033[0m Tasker[%d].%d start.", $event->server->worker_pid, $event->workerId) . PHP_EOL; diff --git a/note/Route/Socket.php b/note/Route/Socket.php index 0caf2741..3a04cfe4 100644 --- a/note/Route/Socket.php +++ b/note/Route/Socket.php @@ -31,23 +31,4 @@ use Kiri\Kiri; } - /** - * @param static $params - * @param mixed $class - * @param mixed|null $method - * @return Router - * @throws Exception - */ - public static function execute(mixed $params, mixed $class, mixed $method = null): Router - { - // TODO: Implement setHandler() method. - $router = Kiri::app()->getRouter(); - - $path = $params->event . '::' . (is_null($params->uri) ? 'event' : $params->uri); - - $router->addRoute($path, [di($class), $method], 'sw::socket'); - - return $router; - } - }