This commit is contained in:
2023-07-31 23:09:00 +08:00
parent c062a8f6a3
commit 0fbb08ed58
7 changed files with 94 additions and 422 deletions
+22 -386
View File
@@ -39,20 +39,6 @@ if (!function_exists('make')) {
} }
if (!function_exists('service')) {
/**
* @param string $name
* @return mixed|null
* @throws Exception
*/
function service(string $name): mixed
{
return Kiri::service()->get($name);
}
}
if (!function_exists('isJson')) { if (!function_exists('isJson')) {
@@ -87,6 +73,7 @@ if (!function_exists('instance')) {
if (!function_exists('call')) { if (!function_exists('call')) {
/** /**
* @param $handler * @param $handler
* @param mixed ...$params * @param mixed ...$params
@@ -155,19 +142,6 @@ if (!function_exists('checkPortIsAlready')) {
} }
if (!function_exists('done')) {
/**
*
*/
function done()
{
set_env('state', 'exit');
}
}
if (!function_exists('set_env')) { if (!function_exists('set_env')) {
@@ -175,7 +149,7 @@ if (!function_exists('set_env')) {
* @param $key * @param $key
* @param $value * @param $value
*/ */
function set_env($key, $value) function set_env($key, $value): void
{ {
putenv(sprintf('%s=%s', $key, $value)); putenv(sprintf('%s=%s', $key, $value));
} }
@@ -211,7 +185,7 @@ if (!function_exists('is_enable_file_modification_listening')) {
if (!function_exists('disable_file_modification_listening')) { if (!function_exists('disable_file_modification_listening')) {
function disable_file_modification_listening() function disable_file_modification_listening(): void
{ {
putenv('enable_file_modification_listening=off'); putenv('enable_file_modification_listening=off');
} }
@@ -230,86 +204,6 @@ if (!function_exists('now')) {
return date('Y-m-d H:i:s') . '.' . str_replace(time() . '.', '', (string)microtime(TRUE)); return date('Y-m-d H:i:s') . '.' . str_replace(time() . '.', '', (string)microtime(TRUE));
} }
} }
//
//
//if (!function_exists('scan_directory')) {
//
//
// /**
// * @param $dir
// * @param $namespace
// * @param array $exclude
// * @throws ReflectionException
// * @throws Exception
// */
// function scan_directory($dir, $namespace, array $exclude = []): void
// {
// $annotation = Kiri::getDi()->get(Annotation::class);
// $annotation->read($dir, $namespace, $exclude);
//
// injectRuntime($dir, $exclude);
// }
//
//}
//
//
//if (!function_exists('injectRuntime')) {
//
//
// /**
// * @param string $path
// * @param array $exclude
// * @throws ReflectionException
// * @throws Exception
// */
// function injectRuntime(string $path, array $exclude = []): void
// {
// $fileLists = Kiri::getAnnotation()->runtime($path, $exclude);
//
// $router = [];
// foreach ($fileLists as $class) {
// $target = TargetManager::get($class);
// $targetAttributes = $target->getAttributes();
// foreach ($targetAttributes as $value) {
// $value = $value->newInstance();
// if (!method_exists($value, 'execute')) {
// continue;
// }
// $value->execute($class);
// }
//
//
// $methods = $target->getMethodsAttribute();
// foreach ($methods as $method => $attribute) {
// /** @var ReflectionAttribute $item */
// foreach ($attribute as $item) {
// if (!class_exists($item->getName())) {
// continue;
// }
// $item = $item->newInstance();
// 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('directory')) { if (!function_exists('directory')) {
@@ -318,7 +212,7 @@ if (!function_exists('directory')) {
* @param $name * @param $name
* @return string * @return string
*/ */
#[Pure] function directory($name): string function directory($name): string
{ {
return realpath(APP_PATH . $name); return realpath(APP_PATH . $name);
} }
@@ -413,83 +307,6 @@ 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];
}
}
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('redis')) { if (!function_exists('redis')) {
@@ -509,33 +326,16 @@ if (!function_exists('fire')) {
/** /**
* @param object $event * @param object $event
* @throws ContainerExceptionInterface
* @throws NotFoundExceptionInterface
* @throws ReflectionException
*/ */
function fire(object $event) function fire(object $event): void
{ {
di(EventDispatch::class)->dispatch($event); di(EventDispatch::class)->dispatch($event);
} }
} }
if (!function_exists('instance_load')) {
/**
* @return void
*/
function instance_load(): void
{
$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')) { if (!function_exists('exif_imagetype')) {
/** /**
@@ -549,19 +349,6 @@ if (!function_exists('exif_imagetype')) {
} }
if (!function_exists('logger')) {
/**
* @throws Exception
*/
function logger(): StdoutLogger
{
return Kiri::getDi()->get(StdoutLogger::class);
}
}
if (!function_exists('trim_blank')) { if (!function_exists('trim_blank')) {
@@ -818,7 +605,7 @@ if (!function_exists('get_file_extension')) {
$mimeType = finfo_file($fInfo, $filename); $mimeType = finfo_file($fInfo, $filename);
finfo_close($fInfo); finfo_close($fInfo);
$mimeType = current(explode('; ', $mimeType)); $mimeType = current(explode('; ', $mimeType));
if (($search = array_search($mimeType, $mime_types)) == FALSE) { if (!($search = array_search($mimeType, $mime_types))) {
return $mimeType; return $mimeType;
} }
return $search; return $search;
@@ -876,15 +663,14 @@ if (!function_exists('on')) {
} }
if (!function_exists('name')) { if (!function_exists('process_name_set')) {
/** /**
* @param int $pid * @param int $pid
* @param string|null $prefix * @param string|null $prefix
* @throws ConfigException
* @throws Exception * @throws Exception
*/ */
function name(int $pid, string $prefix = NULL) function process_name_set(int $pid, string $prefix = NULL): void
{ {
if (Kiri::getPlatform()->isMac()) { if (Kiri::getPlatform()->isMac()) {
return; return;
@@ -901,6 +687,12 @@ if (!function_exists('name')) {
if (!function_exists('zero_full')) { if (!function_exists('zero_full')) {
/**
* @param int $data
* @param int $length
* @return string
*/
function zero_full(int $data = 1, int $length = 10): string function zero_full(int $data = 1, int $length = 10): string
{ {
return sprintf('%0' . $length . 'd', $data); return sprintf('%0' . $length . 'd', $data);
@@ -915,7 +707,7 @@ if (!function_exists('env')) {
* @param null $default * @param null $default
* @return array|string|null * @return array|string|null
*/ */
#[Pure] function env($key, $default = NULL): null|array|string function env($key, $default = NULL): null|array|string
{ {
$env = getenv($key); $env = getenv($key);
if ($env === FALSE) { if ($env === FALSE) {
@@ -978,26 +770,6 @@ if (!function_exists('di')) {
} }
if (!function_exists('interval')) {
/**
* @param callable $callback
* @param int $interval
* @param bool $is
*/
function interval(callable $callback, int $interval = 1000, bool $is = FALSE): void
{
usleep($interval * 1000);
$callback();
interval($callback, $interval, $is);
}
}
if (!function_exists('sweep')) { if (!function_exists('sweep')) {
/** /**
@@ -1015,48 +787,6 @@ if (!function_exists('sweep')) {
} }
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')) { if (!function_exists('merge')) {
@@ -1073,21 +803,6 @@ if (!function_exists('merge')) {
} }
if (!function_exists('router')) {
/**
* @return Router
* @throws Exception
*/
function router(): Router
{
return Kiri::getDi()->get(Rout::class);
}
}
if (!function_exists('jTraceEx')) { if (!function_exists('jTraceEx')) {
/** /**
@@ -1130,66 +845,6 @@ 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);
}
}
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'): void
{
Kiri::getLogger()->debug($method, [$message]);
}
}
if (!function_exists('info')) {
/**
* @param mixed $message
* @param string $method
* @throws
*/
function info(mixed $message, string $method = 'app'): void
{
Kiri::getLogger()->info($method, [$message]);
}
}
if (!function_exists('error')) { if (!function_exists('error')) {
/** /**
@@ -1200,15 +855,12 @@ if (!function_exists('error')) {
*/ */
function error(mixed $message, array $method = []): void function error(mixed $message, array $method = []): void
{ {
if ($message instanceof Throwable) { Kiri::getLogger()->failure($message);
$message = throwable($message);
}
Kiri::getLogger()->error($message, $method);
} }
} }
if (!function_exists('addError')) { if (!function_exists('trigger_print_error')) {
/** /**
* @param mixed $message * @param mixed $message
@@ -1216,28 +868,12 @@ if (!function_exists('addError')) {
* @return bool * @return bool
* @throws * @throws
*/ */
function addError(mixed $message, string $method = 'app'): bool function trigger_print_error(mixed $message, string $method = 'app'): bool
{ {
$logger = Kiri::getLogger(); return Kiri::getLogger()->failure($message, $method);
if ($message instanceof Throwable) {
$logger->error($message, [$message]);
}
return $logger->addError($message, $method);
} }
} }
if (!function_exists('success')) {
/**
* @param mixed $message
* @param string $method
* @throws
*/
function success(mixed $message, string $method = 'app'): void
{
Kiri::getLogger()->critical($method, [$message]);
}
}
if (!function_exists('event')) { if (!function_exists('event')) {
+29 -12
View File
@@ -17,6 +17,7 @@ use Kiri\Di\LocalService;
use Kiri\Config\ConfigProvider; use Kiri\Config\ConfigProvider;
use Kiri\Error\StdoutLogger; use Kiri\Error\StdoutLogger;
use Kiri\Exception\{InitException}; use Kiri\Exception\{InitException};
use Psr\Container\ContainerInterface;
use Psr\Log\LoggerInterface; use Psr\Log\LoggerInterface;
use Kiri\Events\EventProvider; use Kiri\Events\EventProvider;
@@ -34,8 +35,24 @@ abstract class BaseApplication extends Component
*/ */
public string $storage = APP_PATH . 'storage'; public string $storage = APP_PATH . 'storage';
/**
* @var LocalService|mixed
*/
public LocalService $localService; public LocalService $localService;
/**
* @var ContainerInterface
*/
public ContainerInterface $container;
/**
* @var EventProvider
*/
public EventProvider $provider;
/** /**
* Init constructor. * Init constructor.
* *
@@ -44,10 +61,12 @@ abstract class BaseApplication extends Component
*/ */
public function __construct() public function __construct()
{ {
$this->localService = make(LocalService::class); $this->container = Kiri::getContainer();
$this->localService = $this->container->get(LocalService::class);
/** @var ConfigProvider $config */ $this->provider = $this->container->get(EventProvider::class);
$config = make(ConfigProvider::class);
$config = $this->container->get(ConfigProvider::class);
$this->mapping($config); $this->mapping($config);
$this->parseStorage($config); $this->parseStorage($config);
@@ -62,14 +81,13 @@ abstract class BaseApplication extends Component
*/ */
public function mapping(ConfigProvider $config): void public function mapping(ConfigProvider $config): void
{ {
$di = Kiri::getDi(); $this->container->set(LoggerInterface::class, StdoutLogger::class);
$di->set(LoggerInterface::class, StdoutLogger::class);
foreach ($config->get('mapping', []) as $interface => $class) { foreach ($config->get('mapping', []) as $interface => $class) {
$di->set($interface, $class); $this->container->set($interface, $class);
} }
foreach ($config->get('components', []) as $id => $component) { foreach ($config->get('components', []) as $id => $component) {
$this->set($id, $component); $this->container->set($id, $component);
} }
} }
@@ -121,27 +139,26 @@ abstract class BaseApplication extends Component
*/ */
private function addEvent($key, $value): void private function addEvent($key, $value): void
{ {
$provider = Kiri::getDi()->get(EventProvider::class);
if ($value instanceof \Closure || is_object($value)) { if ($value instanceof \Closure || is_object($value)) {
$provider->on($key, $value, 0); $this->provider->on($key, $value, 0);
return; return;
} }
if (!is_array($value)) { if (!is_array($value)) {
return; return;
} }
if (is_object($value[0]) && !($value[0] instanceof \Closure)) { if (is_object($value[0]) && !($value[0] instanceof \Closure)) {
$provider->on($key, $value, 0); $this->provider->on($key, $value, 0);
return; return;
} else if (is_string($value[0])) { } else if (is_string($value[0])) {
$value[0] = Kiri::createObject($value[0]); $value[0] = Kiri::createObject($value[0]);
$provider->on($key, $value, 0); $this->provider->on($key, $value, 0);
return; return;
} }
foreach ($value as $item) { foreach ($value as $item) {
if (!is_callable($item, true)) { if (!is_callable($item, true)) {
throw new InitException("Class does not hav callback."); throw new InitException("Class does not hav callback.");
} }
$provider->on($key, $item, 0); $this->provider->on($key, $item, 0);
} }
} }
+2 -2
View File
@@ -4,7 +4,7 @@ declare(strict_types=1);
namespace Kiri\Abstracts; namespace Kiri\Abstracts;
use Kiri\Di\Inject\Container; use Kiri;
use Psr\Container\ContainerInterface; use Psr\Container\ContainerInterface;
/** /**
@@ -21,7 +21,7 @@ abstract class Providers extends Component implements Provider
*/ */
public function getContainer(): ContainerInterface public function getContainer(): ContainerInterface
{ {
return \Kiri::getDi(); return Kiri::getDi();
} }
} }
+14 -5
View File
@@ -18,6 +18,7 @@ use Kiri\Di\Scanner;
use Kiri\Error\ErrorHandler; use Kiri\Error\ErrorHandler;
use Kiri\Events\{OnAfterCommandExecute, OnBeforeCommandExecute}; use Kiri\Events\{OnAfterCommandExecute, OnBeforeCommandExecute};
use Psr\Container\ContainerExceptionInterface; use Psr\Container\ContainerExceptionInterface;
use Psr\Container\ContainerInterface;
use Psr\Container\NotFoundExceptionInterface; use Psr\Container\NotFoundExceptionInterface;
use ReflectionException; use ReflectionException;
use Symfony\Component\Console\{Application as ConsoleApplication, use Symfony\Component\Console\{Application as ConsoleApplication,
@@ -44,16 +45,24 @@ class Application extends BaseApplication
public string $state = ''; public string $state = '';
/**
* @param ErrorHandler $errorHandler
*/
public function __construct(public ErrorHandler $errorHandler)
{
parent::__construct();
}
/** /**
* @return void * @return void
* @throws ReflectionException * @throws ReflectionException
*/ */
public function init(): void public function init(): void
{ {
$error = Kiri::getDi()->get(ErrorHandler::class); $this->errorHandler->registerShutdownHandler(\config('error.shutdown', []));
$error->registerShutdownHandler(\config('error.shutdown', [])); $this->errorHandler->registerExceptionHandler(\config('error.exception', []));
$error->registerExceptionHandler(\config('error.exception', [])); $this->errorHandler->registerErrorHandler(\config('error.error', []));
$error->registerErrorHandler(\config('error.error', []));
$this->id = \config('id', uniqid('id.')); $this->id = \config('id', uniqid('id.'));
} }
@@ -69,7 +78,7 @@ class Application extends BaseApplication
} }
$class = Kiri::getDi()->get($service); $class = Kiri::getDi()->get($service);
if (method_exists($class, 'onImport')) { if (method_exists($class, 'onImport')) {
$class->onImport(Kiri::getDi()->get(LocalService::class)); $class->onImport($this->localService);
} }
return $this; return $this;
} }
+22 -13
View File
@@ -13,12 +13,12 @@ use Closure;
use Exception; use Exception;
use Kiri; use Kiri;
use Kiri\Abstracts\Component; use Kiri\Abstracts\Component;
use Kiri\Core\Json;
use Kiri\Events\EventDispatch;
use Psr\Container\ContainerExceptionInterface; use Psr\Container\ContainerExceptionInterface;
use Psr\Container\ContainerInterface;
use Psr\Container\NotFoundExceptionInterface; use Psr\Container\NotFoundExceptionInterface;
use ReflectionException; use ReflectionException;
use Kiri\Di\Inject\Container; use Kiri\Abstracts\Logger;
use Kiri\Events\OnSystemError;
/** /**
* Class ErrorHandler * Class ErrorHandler
@@ -35,17 +35,26 @@ class ErrorHandler extends Component implements ErrorInterface
public string $category = 'app'; public string $category = 'app';
/**
* @param ContainerInterface $container
*/
public function __construct(public ContainerInterface $container)
{
parent::__construct();
}
/** /**
* @param array|Closure|null $callback * @param array|Closure|null $callback
* @return void * @return void
* @throws ReflectionException * @throws
*/ */
public function registerExceptionHandler(null|array|Closure $callback): void public function registerExceptionHandler(null|array|Closure $callback): void
{ {
if (empty($callback)) { if (empty($callback)) {
$callback = [$this, 'exceptionHandler']; $callback = [$this, 'exceptionHandler'];
} else if (is_array($callback) && is_string($callback[0])) { } else if (is_array($callback) && is_string($callback[0])) {
$callback[0] = Kiri::getDi()->get($callback[0]); $callback[0] = $this->container->get($callback[0]);
} }
set_exception_handler($callback); set_exception_handler($callback);
} }
@@ -54,14 +63,14 @@ class ErrorHandler extends Component implements ErrorInterface
/** /**
* @param array|Closure|null $callback * @param array|Closure|null $callback
* @return void * @return void
* @throws ReflectionException * @throws
*/ */
public function registerErrorHandler(null|array|Closure $callback): void public function registerErrorHandler(null|array|Closure $callback): void
{ {
if (empty($callback)) { if (empty($callback)) {
$callback = [$this, 'errorHandler']; $callback = [$this, 'errorHandler'];
} else if (is_array($callback) && is_string($callback[0])) { } else if (is_array($callback) && is_string($callback[0])) {
$callback[0] = Kiri::getDi()->get($callback[0]); $callback[0] = $this->container->get($callback[0]);
} }
set_error_handler($callback); set_error_handler($callback);
} }
@@ -70,14 +79,14 @@ class ErrorHandler extends Component implements ErrorInterface
/** /**
* @param array|Closure|null $callback * @param array|Closure|null $callback
* @return void * @return void
* @throws ReflectionException * @throws
*/ */
public function registerShutdownHandler(null|array|Closure $callback): void public function registerShutdownHandler(null|array|Closure $callback): void
{ {
if (empty($callback)) { if (empty($callback)) {
$callback = [$this, 'shutdown']; $callback = [$this, 'shutdown'];
} else if (is_array($callback) && is_string($callback[0])) { } else if (is_array($callback) && is_string($callback[0])) {
$callback[0] = Kiri::getDi()->get($callback[0]); $callback[0] = $this->container->get($callback[0]);
} }
register_shutdown_function($callback); register_shutdown_function($callback);
} }
@@ -99,7 +108,7 @@ class ErrorHandler extends Component implements ErrorInterface
error("\033[31m" . $lastError['message'] . "\033[0m" . $lastError['file'] . " at line " . $lastError['line'] . PHP_EOL); error("\033[31m" . $lastError['message'] . "\033[0m" . $lastError['file'] . " at line " . $lastError['line'] . PHP_EOL);
event(new Kiri\Events\OnSystemError()); event(new OnSystemError());
} }
@@ -114,9 +123,9 @@ class ErrorHandler extends Component implements ErrorInterface
{ {
$this->category = 'exception'; $this->category = 'exception';
Kiri::getLogger()->error($exception, []); Logger::_error(jTraceEx($exception), []);
event(new Kiri\Events\OnSystemError()); event(new OnSystemError());
$this->sendError($exception->getMessage(), $exception->getFile(), $exception->getLine()); $this->sendError($exception->getMessage(), $exception->getFile(), $exception->getLine());
} }
@@ -134,7 +143,7 @@ class ErrorHandler extends Component implements ErrorInterface
error("\033[31m" . $error[1] . "\033[0m" . $error[2] . " at line " . $error[3] . PHP_EOL); error("\033[31m" . $error[1] . "\033[0m" . $error[2] . " at line " . $error[3] . PHP_EOL);
event(new Kiri\Events\OnSystemError()); event(new OnSystemError());
throw new \ErrorException($error[1], $error[0], 1, $error[2], $error[3]); throw new \ErrorException($error[1], $error[0], 1, $error[2], $error[3]);
} }
+4 -3
View File
@@ -21,14 +21,15 @@ class StdoutLogger extends Logger
* @param string $model * @param string $model
* @return bool * @return bool
*/ */
public function addError($message, string $model = 'app'): bool public function failure($message, string $model = 'app'): bool
{ {
if ($message instanceof \Exception) { if ($message instanceof \Exception) {
$this->errors[$model] = $message->getMessage(); $this->errors[$model] = $message->getMessage();
} else { } else {
$this->errors[$model] = $message; $this->errors[$model] = $message;
} }
return false; $this->error($model, [$message]);
return false;
} }
+1 -1
View File
@@ -167,7 +167,7 @@ SCRIPT;
try { try {
$response = $client->{$name}(...$arguments); $response = $client->{$name}(...$arguments);
} catch (\Throwable $throwable) { } catch (\Throwable $throwable) {
$response = addError($throwable, 'redis'); $response = trigger_print_error($throwable, 'redis');
} finally { } finally {
$this->pool()->push($this->host, $client); $this->pool()->push($this->host, $client);
} }