modify plugin name

This commit is contained in:
2022-06-22 16:29:42 +08:00
parent f139f32c85
commit 38f00206eb
16 changed files with 597 additions and 815 deletions
+17 -78
View File
@@ -10,12 +10,15 @@ use Database\ModelInterface;
use JetBrains\PhpStorm\Pure; use JetBrains\PhpStorm\Pure;
use Kiri\Abstracts\Config; use Kiri\Abstracts\Config;
use Kiri\Annotation\Annotation; use Kiri\Annotation\Annotation;
use Kiri\Application; use Kiri\Main;
use Kiri\Core\Json; use Kiri\Core\Json;
use Kiri\Di\Container; use Kiri\Di\Container;
use Kiri\Di\LocalService;
use Kiri\Environmental; use Kiri\Environmental;
use Kiri\Di\ContainerInterface; use Kiri\Di\ContainerInterface;
use Kiri\Error\StdoutLoggerInterface;
use Kiri\Exception\ConfigException; use Kiri\Exception\ConfigException;
use Psr\Log\LoggerInterface;
use Swoole\Coroutine; use Swoole\Coroutine;
use Swoole\Process; use Swoole\Process;
use Swoole\WebSocket\Server; use Swoole\WebSocket\Server;
@@ -40,25 +43,10 @@ class Kiri
private static Container $container; private static Container $container;
/** @var ?Application */
private static ?Application $service = null;
/**
* @param $service
*
* 初始化服务
*/
public static function init($service)
{
static::$service = $service;
}
/** /**
* @param Container $container * @param Container $container
*/ */
public static function setContainer(Container $container) public static function setContainer(Container $container): void
{ {
$container->setBindings(ContainerInterface::class, $container); $container->setBindings(ContainerInterface::class, $container);
static::$container = $container; static::$container = $container;
@@ -74,54 +62,6 @@ class Kiri
} }
/**
* @param $alias
* @param array $array
* @throws Exception
*/
public static function set($alias, array $array = [])
{
static::app()->set($alias, $array);
}
/**
* @param string $name
* @return mixed
* @throws Exception
*/
public static function getApp(string $name): mixed
{
return static::app()->get($name);
}
/**
* @return Application|null
*/
public static function app(): ?Application
{
return static::$service;
}
/**
* @return Application|null
*/
public static function getFactory(): ?Application
{
return static::$service;
}
/**
* @return Application|null
*/
public static function getApplicationContext(): ?Application
{
return static::$service;
}
/** /**
* @return Container|null * @return Container|null
*/ */
@@ -130,16 +70,6 @@ class Kiri
return static::$container; return static::$container;
} }
/**
* @param $name
* @return bool
*/
public static function has($name): bool
{
return static::$service->has($name);
}
/** /**
* @return Annotation * @return Annotation
* @throws Exception * @throws Exception
@@ -215,11 +145,20 @@ class Kiri
/** /**
* @return Container * @return LocalService
*/ */
public static function di(): Container public static function service(): LocalService
{ {
return static::$container; return static::$container->get(LocalService::class);
}
/**
* @return LoggerInterface
*/
public static function getLogger(): LoggerInterface
{
return static::$container->get(LoggerInterface::class);
} }
+16
View File
@@ -0,0 +1,16 @@
<?php
if (class_exists('\ReturnTypeWillChange')) {
return;
}
#[\Attribute(\Attribute::TARGET_METHOD)]
final class ReturnTypeWillChange
{
public function __construct()
{
}
}
+1
View File
@@ -37,6 +37,7 @@
}, },
"files": [ "files": [
"Kiri.php", "Kiri.php",
"ReturnTypeWillChange.php",
"function.php" "function.php"
] ]
} }
+52 -84
View File
@@ -7,7 +7,7 @@ use JetBrains\PhpStorm\Pure;
use Kiri\Abstracts\Config; use Kiri\Abstracts\Config;
use Kiri\Annotation\Annotation; use Kiri\Annotation\Annotation;
use Kiri\Annotation\Route\Route; use Kiri\Annotation\Route\Route;
use Kiri\Application; use Kiri\Main;
use Kiri\Core\ArrayAccess; use Kiri\Core\ArrayAccess;
use Kiri\Di\TargetManager; use Kiri\Di\TargetManager;
use Kiri\Error\StdoutLoggerInterface; use Kiri\Error\StdoutLoggerInterface;
@@ -29,19 +29,27 @@ if (!function_exists('make')) {
*/ */
function make($name, $default = NULL): mixed function make($name, $default = NULL): mixed
{ {
if (is_string($name)) { if (!class_exists($name) && !interface_exists($name)) {
if (Kiri::has($name)) { return Kiri::getDi()->get($default);
return Kiri::app()->get($name);
}
if (empty($default)) {
throw new Exception("Unknown component ID: $name");
}
if (Kiri::has($default)) {
return Kiri::app()->get($default);
}
return null;
} }
return Kiri::createObject($default); return Kiri::getDi()->get($name);
}
}
if (!function_exists('instance')) {
/**
* @param $class
* @param array $constrict
* @param array $config
* @return mixed
*/
function instance($class, array $constrict = [], array $config = []): mixed
{
return Kiri::getDi()->create($class, $constrict, $config);
} }
@@ -232,22 +240,6 @@ if (!function_exists('scan_directory')) {
} }
if (!class_exists('ReturnTypeWillChange')) {
/**
* @since 8.1
*/
#[Attribute(Attribute::TARGET_METHOD)]
final class ReturnTypeWillChange
{
public function __construct()
{
}
}
}
if (!function_exists('injectRuntime')) { if (!function_exists('injectRuntime')) {
@@ -258,7 +250,7 @@ if (!function_exists('injectRuntime')) {
* @throws ReflectionException * @throws ReflectionException
* @throws Exception * @throws Exception
*/ */
function injectRuntime(string $path, array $exclude = []) function injectRuntime(string $path, array $exclude = []): void
{ {
$fileLists = Kiri::getAnnotation()->runtime($path, $exclude); $fileLists = Kiri::getAnnotation()->runtime($path, $exclude);
@@ -482,23 +474,13 @@ if (!function_exists('fire')) {
} }
} }
if (!function_exists('instance_load')) {
if (!function_exists('app')) {
/** /**
* @return Application|null * @return void
*/ */
#[Pure] function app(): ?Application function instance_load(): void
{
return Kiri::app();
}
}
if (!function_exists('instance_load')) {
function instance_load()
{ {
$content = json_decode(file_get_contents(__DIR__ . '/composer.json'), TRUE); $content = json_decode(file_get_contents(__DIR__ . '/composer.json'), TRUE);
if (isset($content['autoload']) && isset($content['autoload']['psr-4'])) { if (isset($content['autoload']) && isset($content['autoload']['psr-4'])) {
@@ -1028,36 +1010,6 @@ if (!function_exists('router')) {
} }
if (!function_exists('isService')) {
/**
* @param string $name
* @return bool
*/
function isService(string $name): bool
{
return Kiri::app()->has($name);
}
}
if (!function_exists('getService')) {
/**
* @param string $name
* @return mixed
* @throws Exception
*/
function getService(string $name): mixed
{
return Kiri::app()->get($name);
}
}
if (!function_exists('jTraceEx')) { if (!function_exists('jTraceEx')) {
/** /**
@@ -1139,9 +1091,9 @@ if (!function_exists('debug')) {
* @param string $method * @param string $method
* @throws Exception * @throws Exception
*/ */
function debug(mixed $message, string $method = 'app') function debug(mixed $message, string $method = 'app'): void
{ {
Kiri::app()->debug($message, $method); Kiri::getLogger()->debug($method, [$message]);
} }
} }
@@ -1153,9 +1105,9 @@ if (!function_exists('info')) {
* @param string $method * @param string $method
* @throws Exception * @throws Exception
*/ */
function info(mixed $message, string $method = 'app') function info(mixed $message, string $method = 'app'): void
{ {
Kiri::app()->info($message, $method); Kiri::getLogger()->info($method, [$message]);
} }
} }
@@ -1165,11 +1117,12 @@ if (!function_exists('error')) {
/** /**
* @param mixed $message * @param mixed $message
* @param string $method * @param string $method
* @throws Exception * @return bool
*/ */
function error(mixed $message, string $method = 'error') function error(mixed $message, string $method = 'error'): bool
{ {
Kiri::getDi()->get(LoggerInterface::class)->error($method, [$message]); Kiri::getLogger()->error($method, [$message]);
return false;
} }
} }
@@ -1182,19 +1135,19 @@ if (!function_exists('success')) {
*/ */
function success(mixed $message, string $method = 'app') function success(mixed $message, string $method = 'app')
{ {
Kiri::app()->success($message, $method); Kiri::getLogger()->critical($method, [$message]);
} }
} }
if (!function_exists('error_trigger_format')) { if (!function_exists('throwable')) {
/** /**
* @param Throwable|Error $throwable * @param Throwable|Error $throwable
* @return string * @return string
*/ */
function error_trigger_format(\Throwable|\Error $throwable): string function throwable(\Throwable|\Error $throwable): string
{ {
$message = "Throwable: " . $throwable->getMessage() . "\n" . ' ' . $throwable->getFile() . " at line " . $throwable->getLine() . "\n"; $message = "Throwable: " . $throwable->getMessage() . "\n" . ' ' . $throwable->getFile() . " at line " . $throwable->getLine() . "\n";
@@ -1205,8 +1158,23 @@ if (!function_exists('error_trigger_format')) {
} }
$message .= $value['file'] . " -> " . $value['line'] . "(" . (isset($value['class']) ? $value['class'] . '::' : '') . ($value['function'] ?? 'Closure') . ")\n"; $message .= $value['file'] . " -> " . $value['line'] . "(" . (isset($value['class']) ? $value['class'] . '::' : '') . ($value['function'] ?? 'Closure') . ")\n";
} }
return "\033[41;37m" . $message . "\033[0m"; return $message;
} }
} }
if (!function_exists('map')) {
/**
* @param array $map
* @param Closure $closure
* @return void
*/
function map(array $map, Closure $closure): void
{
foreach ($map as $key => $value) {
$closure($key, $value);
}
}
}
+1 -1
View File
@@ -17,7 +17,7 @@ abstract class AbstractAttribute implements IAnnotation
* @param mixed|string $method * @param mixed|string $method
* @return mixed * @return mixed
*/ */
#[\ReturnTypeWillChange] #[\Kiri\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.
+76 -74
View File
@@ -7,6 +7,7 @@ namespace Kiri\Annotation;
use Exception; use Exception;
use Kiri\Core\Str; use Kiri\Core\Str;
use Kiri; use Kiri;
use Kiri\Di\LocalService;
use ReflectionException; use ReflectionException;
use ReflectionProperty; use ReflectionProperty;
@@ -18,87 +19,88 @@ use ReflectionProperty;
{ {
/** /**
* Inject constructor. * Inject constructor.
* @param string $value * @param string $value
* @param array $construct * @param array $construct
*/ */
public function __construct(public string $value, public array $construct = []) public function __construct(public string $value, public array $construct = [])
{ {
} }
/** /**
* @param mixed $class * @param mixed $class
* @param mixed|null $method * @param mixed|null $method
* @return bool * @return bool
* @throws ReflectionException * @throws ReflectionException
* @throws Exception * @throws Exception
*/ */
public function execute(mixed $class, mixed $method = null): bool public function execute(mixed $class, mixed $method = null): bool
{ {
if (!($method = $this->getProperty($class, $method))) { if (!($method = $this->getProperty($class, $method))) {
return false; return false;
} }
/** @var ReflectionProperty $class */ /** @var ReflectionProperty $class */
$injectValue = static::parseInjectValue(); $injectValue = static::parseInjectValue();
if ($method->isPrivate() || $method->isProtected()) { if ($method->isPrivate() || $method->isProtected()) {
$this->setter($class, $method, $injectValue); $this->setter($class, $method, $injectValue);
} else { } else {
$class->{$method->getName()} = $injectValue; $class->{$method->getName()} = $injectValue;
} }
return true; return true;
} }
/** /**
* @param $class * @param $class
* @param $method * @param $method
* @param $injectValue * @param $injectValue
*/ */
private function setter($class, $method, $injectValue) private function setter($class, $method, $injectValue)
{ {
$method = 'set' . ucfirst(Str::convertUnderline($method->getName())); $method = 'set' . ucfirst(Str::convertUnderline($method->getName()));
if (!method_exists($class, $method)) { if (!method_exists($class, $method)) {
return; return;
} }
$class->$method($injectValue); $class->$method($injectValue);
} }
/** /**
* @param $class * @param $class
* @param $method * @param $method
* @return ReflectionProperty|bool * @return ReflectionProperty|bool
*/ * @throws ReflectionException
private function getProperty($class, $method): ReflectionProperty|bool */
{ private function getProperty($class, $method): ReflectionProperty|bool
if ($method instanceof ReflectionProperty && !$method->isStatic()) { {
return $method; if ($method instanceof ReflectionProperty && !$method->isStatic()) {
} return $method;
if (is_object($class)) $class = $class::class; }
$method = Kiri::getDi()->getClassReflectionProperty($class, $method); if (is_object($class)) $class = $class::class;
if (!$method || $method->isStatic()) { $method = Kiri::getDi()->getClassReflectionProperty($class, $method);
return false; if (!$method || $method->isStatic()) {
} return false;
return $method; }
} return $method;
}
/** /**
* @return mixed * @return mixed
* @throws Exception * @throws Exception
*/ */
private function parseInjectValue(): mixed private function parseInjectValue(): mixed
{ {
if (!Kiri::app()->has($this->value)) { $localService = Kiri::getDi()->get(LocalService::class);
if (!empty($this->construct)) { if ($localService->has($this->value)) {
return Kiri::getDi()->create($this->value, $this->construct); return $localService->get($this->value);
} }
return Kiri::getDi()->get($this->value); if (!empty($this->construct)) {
} else { return instance($this->value, $this->construct);
return Kiri::app()->get($this->value); }
} return di($this->value);
} }
} }
@@ -1,311 +1,277 @@
<?php <?php
/** /**
* Created by PhpStorm. * Created by PhpStorm.
* User: whwyy * User: whwyy
* Date: 2018/10/7 0007 * Date: 2018/10/7 0007
* Time: 2:13 * Time: 2:13
*/ */
declare(strict_types=1); declare(strict_types=1);
namespace Kiri\Abstracts; namespace Kiri\Abstracts;
use Exception; use Exception;
use Kiri; use Kiri;
use Kiri\Di\LocalService; use Kiri\Di\LocalService;
use Kiri\Error\{ErrorHandler, StdoutLogger, StdoutLoggerInterface}; use Kiri\Error\{ErrorHandler, StdoutLogger, StdoutLoggerInterface};
use Kiri\Exception\{InitException}; use Kiri\Exception\{InitException};
use Kiri\Di\ContainerInterface; use Kiri\Di\ContainerInterface;
use Kiri\Server\{Server}; use Kiri\Message\Constrict\Request;
use Psr\Container\ContainerExceptionInterface; use Kiri\Message\Constrict\RequestInterface;
use Psr\Container\NotFoundExceptionInterface; use Kiri\Message\Constrict\Response;
use Psr\Log\LoggerInterface; use Kiri\Message\Constrict\ResponseInterface;
use Kiri\Events\EventProvider; use Kiri\Message\Emitter;
use Kiri\Message\ResponseEmitter;
/** use Kiri\Server\{Server};
* Class BaseApplication use Psr\Log\LoggerInterface;
* @package Kiri\Base use Kiri\Events\EventProvider;
*/
abstract class BaseApplication extends Component /**
{ * Class BaseApplication
* @package Kiri\Base
*/
/** abstract class BaseMain extends Component
* @var string {
*/
public string $storage = APP_PATH . 'storage';
/**
public string $envPath = APP_PATH . '.env'; * @var string
*/
/** public string $storage = APP_PATH . 'storage';
* Init constructor.
* public string $envPath = APP_PATH . '.env';
*
* @throws /**
*/ * Init constructor.
public function __construct(public ContainerInterface $container, public EventProvider $eventProvider) *
{ *
Kiri::init($this); * @throws
$config = sweep(APP_PATH . '/config'); */
$this->mapping($config['mapping'] ?? []); public function __construct(public ContainerInterface $container, public EventProvider $provider)
$this->parseInt($config); {
$this->parseEvents($config); $config = sweep(APP_PATH . '/config');
$this->initErrorHandler(); $this->mapping($config['mapping'] ?? []);
$this->enableEnvConfig(); $this->parseInt($config);
parent::__construct(); $this->parseEvents($config);
} $this->initErrorHandler();
$this->enableEnvConfig();
parent::__construct();
/** }
* @param array $mapping
*/
public function mapping(array $mapping) /**
{ * @param array $mapping
$di = Kiri::getDi(); */
$di->mapping(StdoutLoggerInterface::class, StdoutLogger::class); public function mapping(array $mapping)
$di->mapping(LoggerInterface::class, Logger::class); {
foreach ($mapping as $interface => $class) { $di = Kiri::getDi();
$di->mapping($interface, $class); $di->mapping(StdoutLoggerInterface::class, StdoutLogger::class);
} $di->mapping(LoggerInterface::class, Logger::class);
} $di->mapping(Emitter::class, ResponseEmitter::class);
$di->mapping(ResponseInterface::class, Response::class);
$di->mapping(RequestInterface::class, Request::class);
/** foreach ($mapping as $interface => $class) {
* @return array $di->mapping($interface, $class);
*/ }
public function enableEnvConfig(): array }
{
if (!file_exists($this->envPath)) {
return []; /**
} * @return array
$lines = $this->readLinesFromFile($this->envPath); */
foreach ($lines as $line) { public function enableEnvConfig(): array
if (!$this->isComment($line) && $this->looksLikeSetter($line)) { {
[$key, $value] = explode('=', $line); if (!file_exists($this->envPath)) {
putenv(trim($key) . '=' . trim($value)); return [];
} }
} $lines = $this->readLinesFromFile($this->envPath);
return $lines; foreach ($lines as $line) {
} if (!$this->isComment($line) && $this->looksLikeSetter($line)) {
[$key, $value] = explode('=', $line);
putenv(trim($key) . '=' . trim($value));
/** }
* Read lines from the file, auto detecting line endings. }
* return $lines;
* @param string $filePath }
*
* @return array
*/ /**
protected function readLinesFromFile(string $filePath): array * Read lines from the file, auto detecting line endings.
{ *
// Read file into an array of lines with auto-detected line endings * @param string $filePath
// $autodetect = ini_get('auto_detect_line_endings'); *
// ini_set('auto_detect_line_endings', '1'); * @return array
// ini_set('auto_detect_line_endings', $autodetect); */
protected function readLinesFromFile(string $filePath): array
return file($filePath, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES); {
} // Read file into an array of lines with auto-detected line endings
// $autodetect = ini_get('auto_detect_line_endings');
/** // ini_set('auto_detect_line_endings', '1');
* Determine if the line in the file is a comment, e.g. begins with a #. // ini_set('auto_detect_line_endings', $autodetect);
*
* @param string $line return file($filePath, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
* }
* @return bool
*/ /**
protected function isComment(string $line): bool * Determine if the line in the file is a comment, e.g. begins with a #.
{ *
$line = ltrim($line); * @param string $line
*
return isset($line[0]) && $line[0] === '#'; * @return bool
} */
protected function isComment(string $line): bool
/** {
* Determine if the given line looks like it's setting a variable. $line = ltrim($line);
*
* @param string $line return isset($line[0]) && $line[0] === '#';
* }
* @return bool
*/ /**
protected function looksLikeSetter(string $line): bool * Determine if the given line looks like it's setting a variable.
{ *
return str_contains($line, '='); * @param string $line
} *
* @return bool
*/
/** protected function looksLikeSetter(string $line): bool
* @param $config {
* return str_contains($line, '=');
* @throws }
*/
public function parseInt($config)
{ /**
Config::sets($config); * @param $config
if ($storage = Config::get('storage', 'storage')) { *
if (!str_contains($storage, APP_PATH)) { * @throws
$storage = APP_PATH . $storage . '/'; */
} public function parseInt($config)
if (!is_dir($storage)) { {
mkdir($storage); Config::sets($config);
} if ($storage = Config::get('storage', 'storage')) {
if (!is_dir($storage) || !is_writeable($storage)) { if (!str_contains($storage, APP_PATH)) {
throw new InitException("Directory {$storage} does not have write permission"); $storage = APP_PATH . $storage . '/';
} }
} if (!is_dir($storage)) {
} mkdir($storage);
}
/** if (!is_dir($storage) || !is_writeable($storage)) {
* @param $config throw new InitException("Directory {$storage} does not have write permission");
* }
* @throws }
*/ }
public function parseEvents($config)
{ /**
if (!isset($config['events']) || !is_array($config['events'])) { * @param $config
return; *
} * @throws
foreach ($config['events'] as $key => $value) { */
if (is_string($value)) { public function parseEvents($config)
$value = Kiri::createObject($value); {
} if (!isset($config['events']) || !is_array($config['events'])) {
$this->addEvent($key, $value); return;
} }
} foreach ($config['events'] as $key => $value) {
if (is_string($value)) {
$value = Kiri::createObject($value);
/** }
* @param $key $this->addEvent($key, $value);
* @param $value }
* @return void }
* @throws InitException
* @throws ContainerExceptionInterface
* @throws NotFoundExceptionInterface /**
* @throws Exception * @param $key
*/ * @param $value
private function addEvent($key, $value): void * @return void
{ * @throws InitException
if ($value instanceof \Closure || is_object($value)) { * @throws Exception
$this->eventProvider->on($key, $value, 0); */
return; private function addEvent($key, $value): void
} {
if ($value instanceof \Closure || is_object($value)) {
$this->provider->on($key, $value, 0);
if (is_array($value)) { return;
if (is_object($value[0]) && !($value[0] instanceof \Closure)) { }
$this->eventProvider->on($key, $value, 0); if (!is_array($value)) {
return; return;
} }
if (is_object($value[0]) && !($value[0] instanceof \Closure)) {
if (is_string($value[0])) { $this->provider->on($key, $value, 0);
$value[0] = Kiri::createObject($value[0]); return;
$this->eventProvider->on($key, $value, 0); } else if (is_string($value[0])) {
return; $value[0] = Kiri::createObject($value[0]);
} $this->provider->on($key, $value, 0);
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.");
} }
$this->eventProvider->on($key, $item, 0); $this->provider->on($key, $item, 0);
} }
} }
}
/**
* @return mixed
/** */
* @param $name public function getLocalIps(): mixed
* @return mixed {
* @throws Exception return swoole_get_local_ip();
*/ }
public function clone($name): mixed
{
return clone $this->get($name); /**
} * @return mixed
*/
/** public function getFirstLocal(): mixed
* {
* @throws Exception return current($this->getLocalIps());
*/ }
public function initErrorHandler()
{
$error = Kiri::getDi()->get(ErrorHandler::class); /**
$error->register(); *
} * @return Server
* @throws
*/
/** public function getServer(): Server
* @param $name {
* @return mixed return Kiri::getDi()->get(Server::class);
* @throws }
*/
public function get($name): mixed
{ /**
return Kiri::getDi()->get(LocalService::class)->get($name); * @param string $name
} * @return mixed|null
* @throws Exception
*/
/** public function __get(string $name)
* @return mixed {
*/ $localService = Kiri::getDi()->get(LocalService::class);
public function getLocalIps(): mixed if ($localService->has($name)) {
{ return $localService->get($name);
return swoole_get_local_ip(); }
} return parent::__get($name); // TODO: Change the autogenerated stub
}
/**
* @return mixed /**
*/ * @param $id
public function getFirstLocal(): mixed * @param $definition
{ */
return current($this->getLocalIps()); public function set($id, $definition): void
} {
Kiri::getDi()->get(LocalService::class)->set($id, $definition);
}
/**
*
* @return Server /**
* @throws * @param $id
*/ * @return bool
public function getServer(): Server */
{ public function has($id): bool
return Kiri::getDi()->get(Server::class); {
} return Kiri::getDi()->get(LocalService::class)->has($id);
}
}
/**
* @param string $name
* @return mixed|null
* @throws Exception
*/
public function __get(string $name)
{
$localService = Kiri::getDi()->get(LocalService::class);
if ($localService->has($name)) {
return $localService->get($name);
}
return parent::__get($name); // TODO: Change the autogenerated stub
}
/**
* @param $id
* @param $definition
*/
public function set($id, $definition): void
{
Kiri::getDi()->get(LocalService::class)->set($id, $definition);
}
/**
* @param $id
* @return bool
*/
public function has($id): bool
{
return Kiri::getDi()->get(LocalService::class)->has($id);
}
}
+9 -10
View File
@@ -137,6 +137,7 @@ class Logger implements LoggerInterface
* @param string $message * @param string $message
* @param array $context * @param array $context
* @throws ConfigException * @throws ConfigException
* @throws Exception
*/ */
public function log($level, $message, array $context = []) public function log($level, $message, array $context = [])
{ {
@@ -146,8 +147,10 @@ class Logger implements LoggerInterface
return; return;
} }
$_string = '[' . now() . '] production.' . $level . ': ' . $this->_string($message, $context); $_string = '[' . now() . '] production.' . $level . ': ' . $message;
if (!empty($context)) {
$_string .= PHP_EOL . $this->_string($context);
}
file_put_contents('php://output', $_string); file_put_contents('php://output', $_string);
$filename = storage('log-' . date('Y-m-d') . '.log', 'log/'); $filename = storage('log-' . date('Y-m-d') . '.log', 'log/');
@@ -188,21 +191,17 @@ class Logger implements LoggerInterface
/** /**
* @param $message
* @param $context * @param $context
* @return string * @return string
*/ */
private function _string($message, $context): string private function _string($context): string
{ {
if ($context instanceof \Throwable) { if ($context instanceof \Throwable) {
$context = ['file' => $context->getFile(), 'line' => $context->getLine()]; $context = ['file' => $context->getFile(), 'line' => $context->getLine()];
} }
if (!empty($context)) { if (is_array($context) && $context[0] instanceof \Throwable) {
if (is_array($context) && $context[0] instanceof \Throwable) { $context = ['file' => $context[0]->getFile(), 'line' => $context[0]->getLine()];
$context = ['file' => $context[0]->getFile(), 'line' => $context[0]->getLine()];
}
return $message . ' ' . PHP_EOL . print_r($context, true) . PHP_EOL;
} }
return $message . PHP_EOL; return print_r($context, true) . PHP_EOL;
} }
} }
+2 -2
View File
@@ -4,11 +4,11 @@ declare(strict_types=1);
namespace Kiri\Abstracts; namespace Kiri\Abstracts;
use Kiri\Application; use Kiri\Di\LocalService;
interface Provider interface Provider
{ {
public function onImport(Application $application); public function onImport(LocalService $application);
} }
+13
View File
@@ -4,6 +4,9 @@ declare(strict_types=1);
namespace Kiri\Abstracts; namespace Kiri\Abstracts;
use Exception;
use Kiri\Di\ContainerInterface;
/** /**
* Class Providers * Class Providers
* @package Kiri\Abstracts * @package Kiri\Abstracts
@@ -12,4 +15,14 @@ abstract class Providers extends Component implements Provider
{ {
/**
* @param ContainerInterface $container
* @param array $config
* @throws Exception
*/
public function __construct(public ContainerInterface $container, array $config = [])
{
parent::__construct($config);
}
} }
-249
View File
@@ -1,249 +0,0 @@
<?php
/**
* Created by PhpStorm.
* User: whwyy
* Date: 2018/4/25 0025
* Time: 18:38
*/
declare(strict_types=1);
namespace Kiri;
use Closure;
use Database\DatabasesProviders;
use Exception;
use Kiri;
use Kiri\Abstracts\{BaseApplication, Config, Kernel};
use Kiri\Crontab\CrontabProviders;
use Kiri\Events\{OnAfterCommandExecute, OnBeforeCommandExecute};
use Kiri\Server\ServerProviders;
use Psr\Container\ContainerExceptionInterface;
use Psr\Container\NotFoundExceptionInterface;
use ReflectionException;
use stdClass;
use Swoole\Process;
use Swoole\Timer;
use Symfony\Component\Console\{Application as ConsoleApplication,
Command\Command,
Input\ArgvInput,
Output\ConsoleOutput,
Output\OutputInterface
};
/**
* Class Init
*
* @package Kiri
*
* @property-read Config $config
*/
class Application extends BaseApplication
{
/**
* @var string
*/
public string $id = 'uniqueId';
public string $state = '';
/** @var array<array<Process>> */
private array $_process = [];
/**
*/
public function init()
{
$this->import(ServerProviders::class);
}
/**
* @throws
*/
public function withDatabase()
{
$this->import(DatabasesProviders::class);
}
/**
* @throws
*/
public function withCrontab()
{
$this->import(CrontabProviders::class);
}
/**
* @param string $class
* @param Process $process
*/
public function addProcess(string $class, Process $process)
{
}
/**
* @return Process[]
*/
public function getProcess(): array
{
return $this->_process;
}
/**
* @param string $class
* @return Process|null
*/
public function getProcessName(string $class): ?Process
{
return $this->_process[$class] ?? null;
}
/**
* @param Closure|array $closure
* @return $this
* @throws Exception
*/
public function middleware(Closure|array $closure): static
{
return $this;
}
/**
* @param bool $useTree
* @return $this
* @throws Exception
*/
public function setUseTree(bool $useTree): static
{
return $this;
}
/**
* @param string $service
* @return $this
* @throws
*/
public function import(string $service): static
{
if (!class_exists($service)) {
return $this;
}
$class = Kiri::getDi()->get($service);
if (method_exists($class, 'onImport')) {
$class->onImport($this);
}
return $this;
}
/**
* @param Kernel $kernel
* @return $this
*/
public function commands(Kernel $kernel): static
{
foreach ($kernel->getCommands() as $command) {
$this->register($command);
}
return $this;
}
/**
* @param string $command
* @throws
*/
public function register(string $command)
{
di(ConsoleApplication::class)->add(di($command));
}
/**
* @param array $argv
* @return void
*/
public function execute(array $argv): void
{
ini_set('swoole.enable_preemptive_scheduler', 'On');
ini_set('swoole.enable_library', 'On');
[$input, $output] = $this->argument($argv);
try {
$console = di(ConsoleApplication::class);
$command = $input->getFirstArgument();
if (empty($command)) {
$command = 'sw:server';
}
$command = $console->find($command);
if ($command instanceof Command) {
$this->enableFileChange($command, $input, $output);
}
} catch (\Throwable $exception) {
$output->writeln(jTraceEx($exception));
} finally {
Timer::clearAll();
}
}
/**
* @param $argv
* @return array
*/
private function argument($argv): array
{
return [new ArgvInput($argv), new ConsoleOutput()];
}
/**
* @param Command $class
* @param $input
* @param $output
* @return void
* @throws ReflectionException
* @throws ContainerExceptionInterface
* @throws NotFoundExceptionInterface
* @throws Exception
*/
private function enableFileChange(Command $class, $input, $output): void
{
fire(new OnBeforeCommandExecute());
$this->container->setBindings(OutputInterface::class, $output);
if (!($class instanceof Kiri\Server\ServerCommand)) {
scan_directory(MODEL_PATH,'app\Model');
}
$class->run($input, $output);
fire(new OnAfterCommandExecute());
$output->writeln('ok' . PHP_EOL);
}
/**
* @param $className
* @param null $abstracts
* @return stdClass
* @throws Exception
*/
public function make($className, $abstracts = null): stdClass
{
return make($className, $abstracts);
}
}
+1 -1
View File
@@ -3,7 +3,7 @@
namespace Kiri\Core; namespace Kiri\Core;
use JetBrains\PhpStorm\Pure; use JetBrains\PhpStorm\Pure;
use ReturnTypeWillChange; use Kiri\ReturnTypeWillChange;
use Traversable; use Traversable;
class HashMap implements \ArrayAccess, \IteratorAggregate class HashMap implements \ArrayAccess, \IteratorAggregate
+2 -2
View File
@@ -131,7 +131,7 @@ class ErrorHandler extends Component implements ErrorInterface
* @return false|string * @return false|string
* @throws Exception * @throws Exception
*/ */
public function sendError($message, $file, $line, $code = 500): bool|string public function sendError($message, $file, $line, int $code = 500): bool|string
{ {
$path = ['file' => $file, 'line' => $line]; $path = ['file' => $file, 'line' => $line];
@@ -168,6 +168,6 @@ class ErrorHandler extends Component implements ErrorInterface
*/ */
public function writer($message, string $category = 'app') public function writer($message, string $category = 'app')
{ {
Kiri::app()->debug($message, $category); Kiri::getLogger()->debug($category, [$message]);
} }
} }
+1 -1
View File
@@ -23,6 +23,6 @@ interface ErrorInterface
* @param int $code * @param int $code
* @return mixed * @return mixed
*/ */
public function sendError($message, $file, $line, $code = 500): mixed; public function sendError($message, $file, $line, int $code = 500): mixed;
} }
+127
View File
@@ -0,0 +1,127 @@
<?php
/**
* Created by PhpStorm.
* User: whwyy
* Date: 2018/4/25 0025
* Time: 18:38
*/
declare(strict_types=1);
namespace Kiri;
use Exception;
use Kiri;
use Kiri\Abstracts\{BaseMain, Config, Kernel};
use Kiri\Events\{OnAfterCommandExecute, OnBeforeCommandExecute};
use Psr\Container\ContainerExceptionInterface;
use Psr\Container\NotFoundExceptionInterface;
use ReflectionException;
use Symfony\Component\Console\{Application as ConsoleApplication,
Input\ArgvInput,
Output\ConsoleOutput,
Output\OutputInterface
};
/**
* Class Init
*
* @package Kiri
*
* @property-read Config $config
*/
class Main extends BaseMain
{
/**
* @var string
*/
public string $id = 'uniqueId';
public string $state = '';
/**
* @param string $service
* @return $this
* @throws
*/
public function import(string $service): static
{
if (!class_exists($service)) {
return $this;
}
$class = Kiri::getDi()->get($service);
if (method_exists($class, 'onImport')) {
$class->onImport($this);
}
return $this;
}
/**
* @param Kernel $kernel
* @return $this
* @throws ContainerExceptionInterface
* @throws NotFoundExceptionInterface
*/
public function commands(Kernel $kernel): static
{
foreach ($kernel->getCommands() as $command) {
$this->command($command);
}
return $this;
}
/**
* @param string $command
* @return void
* @throws ContainerExceptionInterface
* @throws NotFoundExceptionInterface
*/
public function command(string $command): void
{
$console = $this->container->get(ConsoleApplication::class);
$console->add($this->container->get($command));
}
/**
* @param array $argv
* @return void
* @throws ContainerExceptionInterface
* @throws NotFoundExceptionInterface
* @throws ReflectionException
* @throws Exception
*/
public function execute(array $argv): void
{
[$input, $output] = $this->argument($argv);
$console = $this->container->get(ConsoleApplication::class);
$command = $console->find($input->getFirstArgument());
fire(new OnBeforeCommandExecute());
$command->run($input, $output);
fire(new OnAfterCommandExecute());
$output->writeln('ok' . PHP_EOL);
}
/**
* @param $argv
* @return array
*/
private function argument($argv): array
{
$input = new ArgvInput($argv);
$this->container->setBindings(ArgvInput::class, $input);
$output = new ConsoleOutput();
$this->container->setBindings(OutputInterface::class, $output);
return [$input, $output];
}
}
+2 -2
View File
@@ -37,7 +37,7 @@ class OnServerTask
} catch (\Throwable $exception) { } catch (\Throwable $exception) {
$data = jTraceEx($exception); $data = jTraceEx($exception);
$this->logger->error('task', [error_trigger_format($exception)]); $this->logger->error('task', [throwable($exception)]);
} finally { } finally {
$server->finish($data); $server->finish($data);
} }
@@ -56,7 +56,7 @@ class OnServerTask
} catch (\Throwable $exception) { } catch (\Throwable $exception) {
$data = jTraceEx($exception); $data = jTraceEx($exception);
$this->logger->error('task', [error_trigger_format($exception)]); $this->logger->error('task', [throwable($exception)]);
} finally { } finally {
$task->finish($data); $task->finish($data);
} }