modify plugin name

This commit is contained in:
2022-02-23 16:32:08 +08:00
parent fa66eef192
commit 99c824c467
37 changed files with 317 additions and 937 deletions
+1 -10
View File
@@ -145,7 +145,7 @@ class Kiri
*/ */
public static function getAnnotation(): Annotation public static function getAnnotation(): Annotation
{ {
return static::app()->getAnnotation(); return static::getDi()->get(Annotation::class);
} }
@@ -311,15 +311,6 @@ class Kiri
} }
/**
* @return mixed
* @throws Exception
*/
public static function reload(): mixed
{
return Kiri::app()->getSwoole()->reload();
}
const PROCESS = 'process'; const PROCESS = 'process';
const TASK = 'task'; const TASK = 'task';
+11 -39
View File
@@ -9,8 +9,8 @@ use Kiri\Annotation\Annotation;
use Kiri\Annotation\Route\Route; use Kiri\Annotation\Route\Route;
use Kiri\Application; use Kiri\Application;
use Kiri\Core\ArrayAccess; use Kiri\Core\ArrayAccess;
use Kiri\Di\NoteManager; use Kiri\Di\TargetManager;
use Kiri\Error\Logger; use Kiri\Error\StdoutLoggerInterface;
use Kiri\Events\EventDispatch; use Kiri\Events\EventDispatch;
use Kiri\Events\EventProvider; use Kiri\Events\EventProvider;
use Kiri\Exception\ConfigException; use Kiri\Exception\ConfigException;
@@ -175,21 +175,6 @@ if (!function_exists('now')) {
} }
if (!function_exists('workerName')) {
/**
* @param $worker_id
* @return string
*/
function workerName($worker_id)
{
return $worker_id >= Kiri::app()->getSwoole()->setting['worker_num'] ? 'Task' : 'Worker';
}
}
if (!function_exists('Annotation')) { if (!function_exists('Annotation')) {
@@ -218,7 +203,7 @@ if (!function_exists('scan_directory')) {
*/ */
function scan_directory($dir, $namespace, array $exclude = []) function scan_directory($dir, $namespace, array $exclude = [])
{ {
$annotation = Kiri::app()->getAnnotation(); $annotation = Kiri::getDi()->get(Annotation::class);
$annotation->read($dir, $namespace, $exclude); $annotation->read($dir, $namespace, $exclude);
injectRuntime($dir, $exclude); injectRuntime($dir, $exclude);
@@ -259,18 +244,22 @@ if (!function_exists('injectRuntime')) {
$router = []; $router = [];
foreach ($fileLists as $class) { foreach ($fileLists as $class) {
foreach (NoteManager::getTargetAnnotation($class) as $value) { $targetAttributes = TargetManager::get($class)->getAttributes();
foreach ($targetAttributes as $value) {
$value = $value->newInstance();
if (!method_exists($value, 'execute')) { if (!method_exists($value, 'execute')) {
continue; continue;
} }
$value->execute($class); $value->execute($class);
} }
$methods = $di->getMethodAttribute($class);
$methods = TargetManager::get($class)->getMethodsAttribute();
foreach ($methods as $method => $attribute) { foreach ($methods as $method => $attribute) {
if (empty($attribute)) { if (empty($attribute)) {
continue; continue;
} }
foreach ($attribute as $item) { foreach ($attribute as $item) {
$item = $item->newInstance();
if ($item instanceof Route) { if ($item instanceof Route) {
$router[] = [$item, $class, $method]; $router[] = [$item, $class, $method];
} else { } else {
@@ -448,22 +437,6 @@ 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);
}
}
if (!function_exists('redis')) { if (!function_exists('redis')) {
@@ -536,12 +509,11 @@ if (!function_exists('logger')) {
/** /**
* @return Logger
* @throws Exception * @throws Exception
*/ */
function logger(): Logger function logger(): StdoutLoggerInterface
{ {
return Kiri::app()->getLogger(); return Kiri::getDi()->get(StdoutLoggerInterface::class);
} }
} }
@@ -1,27 +1,27 @@
<?php <?php
namespace Kiri\Annotation; namespace Kiri\Annotation;
/** /**
* Class Attribute * Class Attribute
* @package Annotation * @package Annotation
*/ */
abstract class Attribute implements IAnnotation abstract class AbstractAttribute implements IAnnotation
{ {
/** /**
* @param static $class * @param static $class
* @param mixed|string $method * @param mixed|string $method
* @return mixed * @return mixed
*/ */
#[\ReturnTypeWillChange] #[\ReturnTypeWillChange]
public function execute(mixed $class, mixed $method = ''): mixed public function execute(mixed $class, mixed $method = ''): mixed
{ {
// TODO: Implement execute() method. // TODO: Implement execute() method.
return true; return true;
} }
} }
+1 -1
View File
@@ -12,7 +12,7 @@ defined('ASPECT_ERROR') or define('ASPECT_ERROR', 'Aspect annotation must implem
* Class Aspect * Class Aspect
* @package Annotation * @package Annotation
*/ */
#[\Attribute(\Attribute::TARGET_METHOD)] class Aspect extends Attribute #[\Attribute(\Attribute::TARGET_METHOD)] class Aspect extends AbstractAttribute
{ {
+48 -25
View File
@@ -5,42 +5,65 @@ namespace Kiri\Annotation;
use Exception; use Exception;
use Kiri\Events\EventProvider;
use Kiri; use Kiri;
use Kiri\Events\EventProvider;
/** /**
* Class Event * Class Event
* @package Annotation * @package Annotation
*/ */
#[\Attribute(\Attribute::TARGET_METHOD)] class Event extends Attribute #[\Attribute(\Attribute::TARGET_METHOD)] class Event extends AbstractAttribute
{ {
/** /**
* Event constructor. * Event constructor.
* @param string $name * @param string $name
* @param array $params * @param array $params
*/ */
public function __construct(public string $name, public array $params = []) public function __construct(public string $name, public array $params = [])
{ {
} }
/** public function __serialize()
* @param mixed $class {
* @param mixed|null $method // TODO: Implement __serialize() method.
* @return bool }
* @throws Exception
*/
public function execute(mixed $class, mixed $method = null): bool public function __unserialize(array $data)
{ {
$pro = Kiri::getDi()->get(EventProvider::class); // TODO: Implement __unserialize() method.
if (is_string($class)) { }
$class = Kiri::getDi()->get($class);
}
$pro->on($this->name, [$class, $method]); public function serialize(): array
return true; {
} // TODO: Implement __serialize() method.
}
public function unserialize(array|string $data): void
{
}
/**
* @param mixed $class
* @param mixed|null $method
* @return bool
* @throws Exception
*/
public function execute(mixed $class, mixed $method = null): bool
{
$pro = Kiri::getDi()->get(EventProvider::class);
if (is_string($class)) {
$class = Kiri::getDi()->get($class);
}
$pro->on($this->name, [$class, $method]);
return true;
}
} }
+1 -1
View File
@@ -14,7 +14,7 @@ use ReflectionProperty;
* Class Inject * Class Inject
* @package Annotation * @package Annotation
*/ */
#[\Attribute(\Attribute::TARGET_PROPERTY)] class Inject extends Attribute #[\Attribute(\Attribute::TARGET_PROPERTY)] class Inject extends AbstractAttribute
{ {
+2 -2
View File
@@ -124,7 +124,7 @@ class Loader extends Component
} }
$this->appendFileToDirectory($path->getRealPath(), $replace->getName()); $this->appendFileToDirectory($path->getRealPath(), $replace->getName());
} catch (Throwable $throwable) { } catch (Throwable $throwable) {
$this->error(jTraceEx($throwable), 'throwable'); $this->logger->error(jTraceEx($throwable));
} }
} }
@@ -167,7 +167,7 @@ class Loader extends Component
} }
return $paths; return $paths;
} catch (Throwable $exception) { } catch (Throwable $exception) {
$this->addError($exception, 'throwable'); $this->logger->addError($exception, 'throwable');
return []; return [];
} }
} }
+1 -1
View File
@@ -4,7 +4,7 @@ namespace Kiri\Annotation;
use Kiri; use Kiri;
#[\Attribute(\Attribute::TARGET_CLASS)] class Mapping extends Attribute #[\Attribute(\Attribute::TARGET_CLASS)] class Mapping extends AbstractAttribute
{ {
+2 -2
View File
@@ -4,13 +4,13 @@
namespace Kiri\Annotation\Route; namespace Kiri\Annotation\Route;
use Kiri\Annotation\Attribute; use Kiri\Annotation\AbstractAttribute;
/** /**
* Class Document * Class Document
* @package Annotation\Route * @package Annotation\Route
*/ */
#[\Attribute(\Attribute::TARGET_METHOD)] class Document extends Attribute #[\Attribute(\Attribute::TARGET_METHOD)] class Document extends AbstractAttribute
{ {
const INTEGER = 'int'; const INTEGER = 'int';
+16
View File
@@ -0,0 +1,16 @@
<?php
namespace Kiri\Annotation\Route;
enum Method
{
case REQUEST_POST;
case REQUEST_GET;
case REQUEST_HEAD;
case REQUEST_OPTIONS;
case REQUEST_DELETE;
case REQUEST_PUT;
}
+2 -2
View File
@@ -4,7 +4,7 @@
namespace Kiri\Annotation\Route; namespace Kiri\Annotation\Route;
use Kiri\Annotation\Attribute; use Kiri\Annotation\AbstractAttribute;
use Kiri\Message\Handler\Abstracts\MiddlewareManager; use Kiri\Message\Handler\Abstracts\MiddlewareManager;
use Psr\Http\Server\MiddlewareInterface; use Psr\Http\Server\MiddlewareInterface;
@@ -12,7 +12,7 @@ use Psr\Http\Server\MiddlewareInterface;
* Class Middleware * Class Middleware
* @package Annotation\Route * @package Annotation\Route
*/ */
#[\Attribute(\Attribute::TARGET_METHOD | \Attribute::IS_REPEATABLE)] class Middleware extends Attribute #[\Attribute(\Attribute::TARGET_METHOD | \Attribute::IS_REPEATABLE)] class Middleware extends AbstractAttribute
{ {
+21
View File
@@ -0,0 +1,21 @@
<?php
namespace Kiri\Annotation\Route;
use Kiri\Annotation\AbstractAttribute;
#[\Attribute(\Attribute::TARGET_METHOD)] class RequestMapping extends AbstractAttribute
{
/**
* @param Method $method
* @param string $path
* @param string|null $version
*/
public function __construct(Method $method, string $path, string $version = null)
{
}
}
+2 -2
View File
@@ -4,11 +4,11 @@
namespace Kiri\Annotation\Route; namespace Kiri\Annotation\Route;
use Kiri\Annotation\Attribute; use Kiri\Annotation\AbstractAttribute;
use Kiri\Message\Handler\Router; use Kiri\Message\Handler\Router;
use Kiri; use Kiri;
#[\Attribute(\Attribute::TARGET_METHOD | \Attribute::IS_REPEATABLE)] class Route extends Attribute #[\Attribute(\Attribute::TARGET_METHOD | \Attribute::IS_REPEATABLE)] class Route extends AbstractAttribute
{ {
/** /**
+2 -2
View File
@@ -4,13 +4,13 @@
namespace Kiri\Annotation\Route; namespace Kiri\Annotation\Route;
use Kiri\Annotation\Attribute; use Kiri\Annotation\AbstractAttribute;
/** /**
* Class Socket * Class Socket
* @package Annotation * @package Annotation
*/ */
#[\Attribute(\Attribute::TARGET_METHOD)] class Socket extends Attribute #[\Attribute(\Attribute::TARGET_METHOD)] class Socket extends AbstractAttribute
{ {
const CLOSE = 'CLOSE'; const CLOSE = 'CLOSE';
+24
View File
@@ -0,0 +1,24 @@
<?php
namespace Kiri\Annotation\Route;
use Kiri\Annotation\Aspect;
use Kiri\Error\LoggerAspect;
class TestController
{
/**
* @return void
*/
#[RequestMapping(method: Method::REQUEST_GET, path: '/', version: 'v1')]
#[Aspect(aspect: LoggerAspect::class)]
#[Middleware(middleware: LoggerAspect::class)]
public function index()
{
}
}
+1 -1
View File
@@ -8,7 +8,7 @@ namespace Kiri\Annotation;
* Class Target * Class Target
* @package Annotation * @package Annotation
*/ */
#[\Attribute(\Attribute::TARGET_CLASS)] class Target extends Attribute #[\Attribute(\Attribute::TARGET_CLASS)] class Target extends AbstractAttribute
{ {
+23 -126
View File
@@ -14,15 +14,17 @@ use Database\Connection;
use Exception; use Exception;
use Kafka\KafkaProvider; use Kafka\KafkaProvider;
use Kiri; use Kiri;
use Kiri\Annotation\Annotation as SAnnotation;
use Kiri\Cache\Redis; use Kiri\Cache\Redis;
use Kiri\Di\LocalService; use Kiri\Di\LocalService;
use Kiri\Error\{ErrorHandler, Logger}; use Kiri\Error\{ErrorHandler};
use Kiri\Error\StdoutLogger;
use Kiri\Error\StdoutLoggerInterface;
use Kiri\Exception\{InitException, NotFindClassException}; use Kiri\Exception\{InitException, NotFindClassException};
use Kiri\Message\Handler\Router; use Kiri\Message\Handler\Router;
use Kiri\Server\{Server, ServerManager}; use Psr\Container\ContainerExceptionInterface;
use Kiri\Task\AsyncTaskExecute; use Psr\Container\NotFoundExceptionInterface;
use Kiri\Task\OnTaskInterface; use Kiri\Server\{Server};
use Psr\Log\LoggerInterface;
use ReflectionException; use ReflectionException;
use Swoole\Table; use Swoole\Table;
@@ -53,6 +55,8 @@ abstract class BaseApplication extends Component
{ {
Kiri::init($this); Kiri::init($this);
$this->mapping($config['mapping'] ?? []);
$config = sweep(APP_PATH . '/config'); $config = sweep(APP_PATH . '/config');
$this->moreComponents(); $this->moreComponents();
@@ -60,7 +64,6 @@ abstract class BaseApplication extends Component
$this->parseEvents($config); $this->parseEvents($config);
$this->initErrorHandler(); $this->initErrorHandler();
$this->enableEnvConfig(); $this->enableEnvConfig();
$this->mapping($config['mapping'] ?? []);
parent::__construct(); parent::__construct();
} }
@@ -72,6 +75,8 @@ abstract class BaseApplication extends Component
public function mapping(array $mapping) public function mapping(array $mapping)
{ {
$di = Kiri::getDi(); $di = Kiri::getDi();
$di->mapping(StdoutLoggerInterface::class, StdoutLogger::class);
$di->mapping(LoggerInterface::class, Logger::class);
foreach ($mapping as $interface => $class) { foreach ($mapping as $interface => $class) {
$di->mapping($interface, $class); $di->mapping($interface, $class);
} }
@@ -109,10 +114,9 @@ abstract class BaseApplication extends Component
// Read file into an array of lines with auto-detected line endings // Read file into an array of lines with auto-detected line endings
// $autodetect = ini_get('auto_detect_line_endings'); // $autodetect = ini_get('auto_detect_line_endings');
// ini_set('auto_detect_line_endings', '1'); // ini_set('auto_detect_line_endings', '1');
$lines = file($filePath, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES); // ini_set('auto_detect_line_endings', $autodetect);
// ini_set('auto_detect_line_endings', $autodetect);
return $lines; return file($filePath, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
} }
/** /**
@@ -199,39 +203,34 @@ abstract class BaseApplication extends Component
} }
/**
* @param OnTaskInterface $execute
* @throws ReflectionException|Exception
*/
public function task(OnTaskInterface $execute): void
{
di(AsyncTaskExecute::class)->execute($execute);
}
/** /**
* @param $key * @param $key
* @param $value * @param $value
* @return void
* @throws InitException * @throws InitException
* @throws ContainerExceptionInterface
* @throws NotFoundExceptionInterface
* @throws Exception * @throws Exception
*/ */
private function addEvent($key, $value): void private function addEvent($key, $value): void
{ {
$provider = $this->getEventProvider();
if ($value instanceof \Closure || is_object($value)) { if ($value instanceof \Closure || is_object($value)) {
$this->getEventProvider()->on($key, $value, 0); $provider->on($key, $value, 0);
return; return;
} }
if (is_array($value)) { if (is_array($value)) {
if (is_object($value[0]) && !($value[0] instanceof \Closure)) { if (is_object($value[0]) && !($value[0] instanceof \Closure)) {
$this->getEventProvider()->on($key, $value, 0); $provider->on($key, $value, 0);
return; return;
} }
if (is_string($value[0])) { if (is_string($value[0])) {
$value[0] = Kiri::createObject($value[0]); $value[0] = Kiri::createObject($value[0]);
$this->getEventProvider()->on($key, $value, 0); $provider->on($key, $value, 0);
return; return;
} }
@@ -240,7 +239,7 @@ abstract class BaseApplication extends Component
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.");
} }
$this->getEventProvider()->on($key, $item, 0); $provider->on($key, $item, 0);
} }
} }
@@ -263,7 +262,8 @@ abstract class BaseApplication extends Component
*/ */
public function initErrorHandler() public function initErrorHandler()
{ {
$this->get('error')->register(); $error = $this->container->get(ErrorHandler::class);
$error->register();
} }
@@ -305,65 +305,6 @@ abstract class BaseApplication extends Component
} }
/**
* @return \Redis|Redis
* @throws
*/
public function getRedis(): Redis|\Redis
{
return Kiri::getDi()->get(Redis::class);
}
/**
* @param $ip
* @return bool
*/
public function isLocal($ip): bool
{
return $this->getFirstLocal() == $ip;
}
/**
* @return ErrorHandler
* @throws
*/
public function getError(): ErrorHandler
{
return $this->get('error');
}
/**
* @param $name
* @return Table
* @throws
*/
public function getTable($name): Table
{
return $this->get($name);
}
/**
* @return Config
* @throws
*/
public function getConfig(): Config
{
return $this->get('config');
}
/**
* @return Router
* @throws
*/
public function getRouter(): Router
{
return Kiri::getDi()->get(Router::class);
}
/** /**
* @return Server * @return Server
@@ -375,34 +316,6 @@ abstract class BaseApplication extends Component
} }
/**
* @return \Swoole\Http\Server|\Swoole\Server|\Swoole\WebSocket\Server|null
* @throws
*/
public function getSwoole(): \Swoole\Http\Server|\Swoole\Server|\Swoole\WebSocket\Server|null
{
return di(ServerManager::class)->getServer();
}
/**
* @return SAnnotation
* @throws
*/
public function getAnnotation(): SAnnotation
{
return $this->get('Annotation');
}
/**
* @param $array
*/
private function setComponents($array): void
{
di(LocalService::class)->setComponents($array);
}
/** /**
* @param $id * @param $id
@@ -422,20 +335,4 @@ abstract class BaseApplication extends Component
{ {
return di(LocalService::class)->has($id); return di(LocalService::class)->has($id);
} }
/**
* @throws Exception
*/
protected function moreComponents(): void
{
$this->setComponents([
'error' => ['class' => ErrorHandler::class],
'config' => ['class' => Config::class],
'logger' => ['class' => Logger::class],
'Annotation' => ['class' => SAnnotation::class],
'databases' => ['class' => Connection::class],
'kafka-container' => ['class' => KafkaProvider::class],
]);
}
} }
+48 -136
View File
@@ -12,10 +12,11 @@ namespace Kiri\Abstracts;
use Exception; use Exception;
use JetBrains\PhpStorm\Pure; use JetBrains\PhpStorm\Pure;
use Kiri;
use Kiri\Di\Container; use Kiri\Di\Container;
use Kiri\Error\StdoutLogger;
use Kiri\Events\EventDispatch; use Kiri\Events\EventDispatch;
use Kiri\Events\EventProvider; use Kiri\Events\EventProvider;
use Kiri;
use Psr\Container\ContainerExceptionInterface; use Psr\Container\ContainerExceptionInterface;
use Psr\Container\ContainerInterface; use Psr\Container\ContainerInterface;
use Psr\Container\NotFoundExceptionInterface; use Psr\Container\NotFoundExceptionInterface;
@@ -23,11 +24,17 @@ use Psr\Container\NotFoundExceptionInterface;
/** /**
* Class Component * Class Component
* @package Kiri\Base * @package Kiri\Base
* @property EventDispatch $eventDispatch
* @property EventProvider $eventProvider
* @property Container $container
*/ */
class Component implements Configure class Component implements Configure
{ {
protected ?StdoutLogger $logger = null;
/** /**
* BaseAbstract constructor. * BaseAbstract constructor.
* *
@@ -36,11 +43,30 @@ class Component implements Configure
*/ */
public function __construct(array $config = []) public function __construct(array $config = [])
{ {
if (is_null($this->logger)) {
$this->logger = Kiri::getDi()->get(StdoutLogger::class);
}
if (!empty($config) && is_array($config)) { if (!empty($config) && is_array($config)) {
Kiri::configure($this, $config); Kiri::configure($this, $config);
} }
} }
/**
* @throws Exception
*/
public function init()
{
}
/**
* @return string
*/
#[Pure] public static function className(): string
{
return static::class;
}
/** /**
* @return Container|ContainerInterface * @return Container|ContainerInterface
@@ -72,156 +98,42 @@ class Component implements Configure
return $this->getContainer()->get(EventDispatch::class); return $this->getContainer()->get(EventDispatch::class);
} }
/** /**
* @param string $name
* @return mixed
* @throws Exception * @throws Exception
*/ */
public function init() public function __get(string $name)
{ {
} $method = 'get' . ucfirst($name);
if (method_exists($this, $method)) {
return $this->{$method}();
/** } else if (method_exists($this, $name)) {
* @return string return $this->{$name};
*/
#[Pure] public static function className(): string
{
return static::class;
}
/**
* @param $message
* @param string $model
* @return bool
* @throws Exception
*/
public function addError($message, string $model = 'app'): bool
{
if ($message instanceof \Throwable) {
$this->error($message = jTraceEx($message));
} else { } else {
if (!is_string($message)) { throw new Exception('Unable getting property ' . get_called_class() . '::' . $name);
$message = json_encode($message, JSON_UNESCAPED_UNICODE);
}
$this->error($message);
} }
Kiri::app()->getLogger()->fail($message, $model);
return FALSE;
} }
/** /**
* @return Logger * @param string $name
* @param $value
* @return void
* @throws Exception * @throws Exception
*/ */
protected function logger(): Logger public function __set(string $name, $value): void
{ {
return Kiri::getDi()->get(Logger::class); $method = 'set' . ucfirst($name);
} if (method_exists($this, $method)) {
$this->{$method}($value);
} else if (method_exists($this, $name)) {
/** $this->{$name} = $value;
* @param mixed $message
* @param string $method
* @param string $file
* @throws Exception
*/
public function debug(mixed $message, string $method = '', string $file = '')
{
if (!is_string($message)) {
$message = print_r($message, true);
}
$context = [];
if (!empty($method)) $context['method'] = $method;
if (!empty($file)) $context['file'] = $file;
$this->logger()->debug($message, $context);
}
/**
* @param mixed $message
* @param string $method
* @param string $file
* @throws Exception
*/
public function info(mixed $message, string $method = '', string $file = '')
{
if (!is_string($message)) {
$message = print_r($message, true);
}
$context = [];
if (!empty($method)) $context['method'] = $method;
if (!empty($file)) $context['file'] = $file;
$this->logger()->info($message, $context);
}
/**
* @param mixed $message
* @param string $method
* @param string $file
* @throws Exception
*/
public function success(mixed $message, string $method = '', string $file = '')
{
if (!is_string($message)) {
$message = print_r($message, true);
}
$context = [];
if (!empty($method)) $context['method'] = $method;
if (!empty($file)) $context['file'] = $file;
$this->logger()->notice($message, $context);
}
/**
* @param mixed $message
* @param string $method
* @param string $file
* @throws Exception
*/
public function warning(mixed $message, string $method = '', string $file = '')
{
if (!is_string($message)) {
$message = print_r($message, true);
}
$context = [];
if (!empty($method)) $context['method'] = $method;
if (!empty($file)) $context['file'] = $file;
$this->logger()->critical($message, $context);
}
/**
* @param mixed $message
* @param null $method
* @param null $file
* @throws Exception
*/
public function error(mixed $message, $method = null, $file = null)
{
if ($message instanceof \Throwable) {
$message = $message->getMessage() . " on line " . $message->getLine() . " at file " . $message->getFile();
}
$context = [];
if (is_string($method)) {
$message = (empty($method) ? '' : $method . ': ') . $message;
} else { } else {
if (is_null($method)) { throw new Exception('Unable setting property ' . get_called_class() . '::' . $name);
$method = [];
}
$context = $method;
} }
if (!empty($method)) $context['method'] = $method;
if (!empty($file)) $context['file'] = $file;
$this->logger()->error($message, $context);
} }
} }
-1
View File
@@ -36,7 +36,6 @@ class Logger implements LoggerInterface
/** /**
* @return void * @return void
* @throws ReflectionException
*/ */
public function init() public function init()
{ {
@@ -9,7 +9,6 @@ use Database\Connection;
use Database\DatabasesProviders; use Database\DatabasesProviders;
use Kiri\Message\Handler\Router; use Kiri\Message\Handler\Router;
use Kiri\Server\Server; use Kiri\Server\Server;
use Kiri\Error\Logger;
use Kiri\Jwt\JWTAuth; use Kiri\Jwt\JWTAuth;
/** /**
@@ -18,7 +17,6 @@ use Kiri\Jwt\JWTAuth;
* @property Router $router * @property Router $router
* @property Server $server * @property Server $server
* @property DatabasesProviders $db * @property DatabasesProviders $db
* @property Logger $logger
* @property JWTAuth $jwt * @property JWTAuth $jwt
* @property SAnnotation $annotation * @property SAnnotation $annotation
* @property Connection $databases * @property Connection $databases
-3
View File
@@ -11,7 +11,6 @@ namespace Kiri;
use Closure; use Closure;
use Database\CreateConnectionPool;
use Database\DatabasesProviders; use Database\DatabasesProviders;
use Exception; use Exception;
use Kiri; use Kiri;
@@ -62,8 +61,6 @@ class Application extends BaseApplication
public function init() public function init()
{ {
$this->import(ServerProviders::class); $this->import(ServerProviders::class);
$this->register(Runtime::class);
} }
-44
View File
@@ -1,44 +0,0 @@
<?php
namespace Kiri;
use Exception;
use Kiri\Abstracts\Component;
use Kiri\Server\ServerManager;
use Kiri\Task\AsyncTaskExecute;
use Kiri;
/**
* Class Async
* @package Kiri
*/
class Async extends Component
{
private static array $_absences = [];
/**
* @param string $name
* @param string $handler
*/
public function addAsync(string $name, string $handler)
{
static::$_absences[$name] = $handler;
}
/**
* @param string $name
* @param array $params
* @throws Exception
*/
public function dispatch(string $name, array $params = [])
{
$context = di(AsyncTaskExecute::class);
$context->execute(static::$_absences[$name], $params);
}
}
+1 -1
View File
@@ -80,7 +80,7 @@ class Redis extends Component
$data = $this->proxy($name, $arguments); $data = $this->proxy($name, $arguments);
} }
if (microtime(true) - $time >= 0.02) { if (microtime(true) - $time >= 0.02) {
$this->warning('Redis:' . Json::encode([$name, $arguments]) . (microtime(true) - $time)); $this->logger->warning('Redis:' . Json::encode([$name, $arguments]) . (microtime(true) - $time));
} }
return $data; return $data;
} }
+1 -2
View File
@@ -93,11 +93,10 @@ class ErrorHandler extends Component implements ErrorInterface
$data = Json::to(500, $error[1], $path); $data = Json::to(500, $error[1], $path);
Kiri::app()->error($data, 'error'); $this->logger->error('On error handler', [$data]);
di(EventDispatch::class)->dispatch(new OnAfterRequest()); di(EventDispatch::class)->dispatch(new OnAfterRequest());
throw new \ErrorException($error[1], $error[0], 1, $error[2], $error[3]); throw new \ErrorException($error[1], $error[0], 1, $error[2], $error[3]);
} }
-117
View File
@@ -1,117 +0,0 @@
<?php
/**
* Created by PhpStorm.
* User: admin
* Date: 2019-03-22
* Time: 14:36
*/
declare(strict_types=1);
namespace Kiri\Error;
use Exception;
use Kiri\Abstracts\Component;
use Kiri\Core\Json;
use Kiri;
use Kiri\Annotation\Inject;
use Psr\Log\LoggerInterface;
use Throwable;
/**
* Class Logger
* @package Kiri\Error
* @mixin \Kiri\Abstracts\Logger
*/
class Logger extends Component
{
private array $logs = [];
/**
* inject logger
*
* @var LoggerInterface
*/
#[Inject(LoggerInterface::class)]
public LoggerInterface $logger;
private array $sources = [];
/**
* @param string $application
* @return string
*/
public function getLastError(string $application = 'app'): string
{
return $this->logs[$application] ?? 'Unknown error.';
}
/**
* @param $message
* @param $method
* @return void
*/
public function fail($message, $method)
{
$this->logs[$method] = $message;
}
/**
* @param string $messages
* @param string $method
* @throws Exception
*/
public function write(string $messages, string $method = 'app')
{
if (empty($messages)) {
return;
}
$to_day = date('Y-m-d');
$fileName = storage('server-' . $to_day . '.log', $dirName = 'log/' . ($method ?? 'app'));
file_put_contents($fileName, '[' . date('Y-m-d H:i:s') . ']:' . PHP_EOL . $messages . PHP_EOL);
}
/**
* @param Throwable $exception
* @return mixed
* @throws Exception
*/
public function exception(Throwable $exception): mixed
{
$code = $exception->getCode() == 0 ? 500 : $exception->getCode();
$logger = Kiri::app()->getLogger();
$logger->write(jTraceEx($exception), 'exception');
return Json::to($code, $exception->getMessage(), [
'file' => $exception->getFile(),
'line' => $exception->getLine()
]);
}
/**
* @param string $name
* @param array $arguments
* @return mixed
*/
public function __call(string $name, array $arguments): mixed
{
if (!method_exists($this, $name)) {
return $this->logger->{$name}(...$arguments);
} else {
return $this->{$name}(...$arguments);
}
}
}
+42
View File
@@ -0,0 +1,42 @@
<?php
namespace Kiri\Error;
use Kiri\Abstracts\Logger;
use Kiri\Exception\ConfigException;
class StdoutLogger extends Logger implements StdoutLoggerInterface
{
private array $errors = [];
/**
* @param $message
* @param string $model
* @return bool
* @throws ConfigException
*/
public function addError($message, string $model = 'app'): bool
{
$this->error($model, [$message]);
if ($message instanceof \Exception) {
$this->errors[$model] = $message->getMessage();
} else {
$this->errors[$model] = $message;
}
return false;
}
/**
* @param string $model
* @return mixed
*/
public function getLastError(string $model = 'app'): mixed
{
return $this->errors[$model] ?? 'Unknown error.';
}
}
@@ -0,0 +1,26 @@
<?php
namespace Kiri\Error;
use Psr\Log\LoggerInterface;
interface StdoutLoggerInterface extends LoggerInterface
{
/**
* @param $message
* @param string $model
* @return bool
*/
public function addError($message, string $model = 'app'): bool;
/**
* @param string $model
* @return mixed
*/
public function getLastError(string $model = 'app'): mixed;
}
-238
View File
@@ -1,238 +0,0 @@
<?php
declare(strict_types=1);
namespace Kiri;
use Exception;
use Kiri\Abstracts\Component;
use Kiri;
/**
* Class Event
* @package Kiri
*/
class Event extends Component
{
public bool $isVide = true;
private static array $_events = [];
const PIPE_MESSAGE = 'SERVER:PIPE:MESSAGE';
const TASK_FINISH = 'SERVER:TASK::FINISH';
const EVENT_AFTER_REQUEST = 'SERVER:REQUEST:AFTER:START';
const EVENT_BEFORE_REQUEST = 'SERVER:REQUEST:BEFORE:START';
const RECEIVE_CONNECTION = 'SERVER:RECEIVE:CONNECTION';
const SYSTEM_RESOURCE_RELEASES = 'SYSTEM::RESOURCE::RELEASES';
const SYSTEM_RESOURCE_CLEAN = 'SYSTEM::RESOURCE::CLEAN';
const PROCESS_WORKER_STOP = 'SERVER:PROCESS:WORKER:STOP';
const SERVER_AFTER_RELOAD = 'SERVER:AFTER:RELOAD';
const SERVER_BEFORE_RELOAD = 'SERVER:BEFORE:RELOAD';
const SERVER_CONNECT = 'SERVER:CONNECT';
const SERVER_PACKAGE = 'SERVER:PACKAGE';
const SERVER_RECEIVE = 'SERVER:RECEIVE';
const SERVER_EVENT_START = 'SERVER:EVENT:START';
const SERVER_MANAGER_START = 'SERVER:EVENT:MANAGER:START';
const SERVER_MANAGER_STOP = 'SERVER:EVENT:MANAGER:START';
const SERVER_WORKER_STOP = 'SERVER:EVENT:WORKER:STOP';
const SERVER_WORKER_START = 'SERVER:EVENT:WORKER:START';
const SERVER_AFTER_WORKER_START = 'SERVER:EVENT:AFTER:WORKER:START';
const SERVER_BEFORE_START = 'SERVER:EVENT:BEFORE:START';
const BEFORE_COMMAND_EXECUTE = 'COMMAND:EVENT:BEFORE:EXECUTE';
const AFTER_COMMAND_EXECUTE = 'COMMAND:EVENT:AFTER:EXECUTE';
const SERVER_TASK_START = 'SERVER:EVENT:TASK:START';
const SERVER_WORKER_EXIT = 'SERVER:EVENT:WORKER:EXIT';
const SERVER_WORKER_ERROR = 'SERVER:EVENT:WORKER:ERROR';
const SERVER_SHUTDOWN = 'SERVER:EVENT:SHUTDOWN';
const SERVER_HANDSHAKE = 'on handshake';
const SERVER_MESSAGE = 'on message';
const SERVER_CLIENT_CLOSE = 'SERVER:CLIENT:CLOSE';
const SERVER_ON_START = 'Start';
const SERVER_ON_SHUTDOWN = 'Shutdown';
const SERVER_ON_WORKER_START = 'WorkerStart';
const SERVER_ON_WORKER_STOP = 'WorkerStop';
const SERVER_ON_WORKER_EXIT = 'WorkerExit';
const SERVER_ON_CONNECT = 'Connect';
const SERVER_ON_RECEIVE = 'Receive';
const SERVER_ON_PACKET = 'Packet';
const SERVER_ON_REQUEST = 'request';
const SERVER_ON_CLOSE = 'Close';
const SERVER_ON_TASK = 'Task';
const SERVER_ON_FINISH = 'Finish';
const SERVER_ON_PIPE_MESSAGE = 'OnPipeMessageInterface';
const SERVER_ON_WORKER_ERROR = 'WorkerError';
const SERVER_ON_MANAGER_START = 'ManagerStart';
const SERVER_ON_MANAGER_STOP = 'ManagerStop';
const SERVER_ON_BEFORE_RELOAD = 'BeforeReload';
const SERVER_ON_AFTER_RELOAD = 'AfterReload';
/**
* @param $name
* @param $callback
* @param bool $isAppend
* @throws Exception
*/
public static function on($name, $callback, bool $isAppend = false)
{
if (!isset(static::$_events[$name])) {
static::$_events[$name] = [];
}
if (is_array($callback) && is_string($callback[0])) {
if (!class_exists($callback[0])) {
throw new Exception('Undefined callback class.');
}
$callback[0] = di($callback[0]);
}
if (static::exists($name, $callback)) {
return;
}
if (!empty(static::$_events[$name]) && $isAppend === true) {
array_unshift(static::$_events[$name], [$callback]);
} else {
static::$_events[$name][] = [$callback];
}
}
/**
* @param $name
* @param $callback
*/
public static function of($name, $callback): void
{
if (!isset(static::$_events[$name])) {
return;
}
foreach (static::$_events[$name] as $index => $event) {
[$handler] = $event;
if ($handler !== $callback) {
continue;
}
unset(static::$_events[$name][$index]);
}
}
/**
* @param $name
*/
public static function offName($name): void
{
unset(static::$_events[$name]);
}
/**
* @param $name
* @param null $callback
* @return bool
*/
public static function exists($name, $callback): bool
{
if ($callback instanceof \Closure || !isset(static::$_events[$name])) {
return false;
}
foreach (static::$_events[$name] as $event) {
[$handler] = $event;
if ($handler === $callback) {
return true;
}
}
return false;
}
/**
* @param $name
* @param $handler
* @return mixed
*/
public static function get($name, $handler): mixed
{
if (!static::exists($name, $handler)) {
return null;
}
if (empty($handler)) {
return static::$_events[$name];
}
foreach (static::$_events[$name] as $event) {
[$callback] = $event;
if ($callback === $handler) {
return [$event];
}
}
return null;
}
public static function clean()
{
static::$_events = [];
}
/**
* @param $name
* @param array $params
* @return bool
* @throws Exception
*/
public function dispatch($name, array $params = []): bool
{
return static::trigger($name, $params);
}
/**
* @param $name
* @param null $parameter
* @param false $is_remove
* @return bool
* @throws Exception
*/
public static function trigger($name, $parameter = null, bool $is_remove = false): bool
{
foreach ((static::$_events[$name] ?? []) as $key => $event) {
static::execute($event, $parameter);
if ($event instanceof \Closure) {
unset(static::$_events[$name][$key]);
}
}
if ($is_remove) {
unset(static::$_events[$name]);
}
return true;
}
/**
* @param $event
* @param $parameter
* @return void
* @throws Exception
*/
private static function execute($event, $parameter): void
{
try {
call_user_func($event[0], ...$parameter);
} catch (\Throwable $throwable) {
logger()->addError($throwable, 'throwable');
return;
}
}
}
+3 -3
View File
@@ -7,11 +7,11 @@ use Kiri;
use Kiri\Abstracts\Config; use Kiri\Abstracts\Config;
use Kiri\Annotation\Inject; use Kiri\Annotation\Inject;
use Kiri\Core\Json; use Kiri\Core\Json;
use Kiri\Error\Logger;
use Kiri\Exception\ConfigException; use Kiri\Exception\ConfigException;
use Swoole\Coroutine; use Swoole\Coroutine;
use Swoole\Process; use Swoole\Process;
use Swoole\Timer; use Swoole\Timer;
use Kiri\Error\StdoutLogger;
use Symfony\Component\Console\Command\Command; use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface; use Symfony\Component\Console\Output\OutputInterface;
@@ -39,8 +39,8 @@ class HotReload extends Command
public Inotify|Scaner $driver; public Inotify|Scaner $driver;
#[Inject(Logger::class)] #[Inject(StdoutLogger::class)]
public Logger $logger; public StdoutLogger $logger;
protected mixed $source = NULL; protected mixed $source = NULL;
+4 -3
View File
@@ -3,7 +3,7 @@
namespace Kiri\FileListen; namespace Kiri\FileListen;
use Exception; use Exception;
use Kiri\Error\Logger; use Kiri\Error\StdoutLogger;
use Swoole\Event; use Swoole\Event;
use Swoole\Timer; use Swoole\Timer;
@@ -103,7 +103,7 @@ class Inotify
*/ */
public function reload($path) public function reload($path)
{ {
\Kiri::getDi()->get(Logger::class)->warning('file change'); \Kiri::getDi()->get(StdoutLogger::class)->warning('file change');
$this->process->trigger_reload($path); $this->process->trigger_reload($path);
$this->process->int = -1; $this->process->int = -1;
@@ -137,7 +137,8 @@ class Inotify
{ {
//目录不存在 //目录不存在
if (!is_dir($dir)) { if (!is_dir($dir)) {
return logger()->addError("[$dir] is not a directory."); logger()->addError("[$dir] is not a directory.");
return false;
} }
//避免重复监听 //避免重复监听
if (isset($this->watchFiles[$dir])) { if (isset($this->watchFiles[$dir])) {
+2 -2
View File
@@ -3,7 +3,7 @@
namespace Kiri\FileListen; namespace Kiri\FileListen;
use Exception; use Exception;
use Kiri\Error\Logger; use Kiri\Error\StdoutLogger;
class Scaner class Scaner
{ {
@@ -113,7 +113,7 @@ class Scaner
{ {
$this->isReloading = TRUE; $this->isReloading = TRUE;
\Kiri::getDi()->get(Logger::class)->warning('file change'); \Kiri::getDi()->get(StdoutLogger::class)->warning('file change');
$this->process->trigger_reload($path); $this->process->trigger_reload($path);
-13
View File
@@ -1,13 +0,0 @@
<?php
namespace Kiri;
interface IProxy
{
public function execute();
}
+1 -1
View File
@@ -229,7 +229,7 @@ class Connection extends Component
$result = true; $result = true;
} }
} catch (Error|Throwable $exception) { } catch (Error|Throwable $exception) {
$result = $this->addError($exception, 'mysql'); $result = $this->logger->addError($exception, 'mysql');
} finally { } finally {
return $result; return $result;
} }
-27
View File
@@ -1,27 +0,0 @@
<?php
namespace Kiri;
class Proxy
{
/**
* Proxy constructor.
* @param IProxy $IProxy
*/
public function __construct(public IProxy $IProxy)
{
}
/**
* @return mixed
*/
public function execute(): mixed
{
return $this->IProxy->execute();
}
}
-100
View File
@@ -1,100 +0,0 @@
<?php
namespace Kiri;
use Exception;
use Kiri\Abstracts\Config;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Kiri;
/**
* Class Runtime
* @package Kiri
*/
class Runtime extends Command
{
public string $command = 'runtime:builder';
public string $description = 'create app file cache';
const CACHE_NAME = '.runtime.cache';
const CONFIG_NAME = '.config.cache';
protected function configure()
{
$this->setName('runtime:builder');
}
/**
* @param InputInterface $input
* @param OutputInterface $output
* @return int
* @throws Exception
*/
public function execute(InputInterface $input, OutputInterface $output): int
{
// TODO: Implement onHandler() method.
$annotation = Kiri::app()->getAnnotation();
$runtime = storage(static::CACHE_NAME);
$config = storage(static::CONFIG_NAME);
Kiri::writeFile($config, $this->configEach());
Kiri::writeFile($runtime, serialize($annotation->getLoader()));
return 1;
}
/**
* @return string
* @throws Exception
*/
public function configEach(): string
{
$array = [];
foreach (Config::getData() as $key => $datum) {
if ($datum instanceof \Closure) {
continue;
}
if (is_array($datum)) {
$array[$key] = $this->arrayEach($datum);
} else {
$array[$key] = $datum;
}
}
return serialize($array);
}
/**
* @param array $value
* @return array
*/
private function arrayEach(array $value): array
{
$array = [];
foreach ($value as $key => $item) {
if ($item instanceof \Closure) {
continue;
}
if (is_array($item)) {
$array[$key] = $this->arrayEach($item);
} else {
$array[$key] = $item;
}
}
return $array;
}
}
+2 -1
View File
@@ -60,7 +60,8 @@ namespace {$namespace};
$import = $this->getImports($path['path'] . '/' . $managerName . 'Controller.php', $class); $import = $this->getImports($path['path'] . '/' . $managerName . 'Controller.php', $class);
} catch (\Throwable $Exception) { } catch (\Throwable $Exception) {
exit(logger()->addError($Exception, 'throwable')); logger()->addError($Exception, 'throwable');
exit();
} }
} else { } else {
$import = "use Kiri; $import = "use Kiri;
+2 -2
View File
@@ -3,10 +3,10 @@
namespace Kiri\Task\Annotation; namespace Kiri\Task\Annotation;
use Kiri\Annotation\Attribute; use Kiri\Annotation\AbstractAttribute;
use Kiri\Task\TaskManager; use Kiri\Task\TaskManager;
#[\Attribute(\Attribute::TARGET_CLASS)] class AsynchronousTask extends Attribute #[\Attribute(\Attribute::TARGET_CLASS)] class AsynchronousTask extends AbstractAttribute
{ {