Files
kiri-core/function.php
T

806 lines
16 KiB
PHP
Raw Normal View History

2022-01-09 03:50:38 +08:00
<?php
defined('APP_PATH') or define('APP_PATH', realpath(__DIR__ . '/../../'));
use JetBrains\PhpStorm\Pure;
2024-11-28 14:35:20 +08:00
use Kiri\Abstracts\Kernel;
2023-11-30 18:06:45 +08:00
use Kiri\Application;
2026-01-08 08:26:08 +00:00
use Kiri\Error\StdoutLogger;
2023-05-25 16:59:20 +08:00
use Kiri\Config\ConfigProvider;
2022-01-09 03:50:38 +08:00
use Kiri\Core\ArrayAccess;
2023-09-15 15:58:24 +08:00
use Kiri\Di\Context;
2022-01-09 03:50:38 +08:00
use Kiri\Events\EventDispatch;
use Kiri\Events\EventProvider;
2023-04-21 17:50:33 +08:00
use Kiri\Router\Request;
use Kiri\Router\Response;
2025-07-11 16:27:14 +08:00
use Kiri\Server\Task\TaskExecute;
2023-04-21 17:50:33 +08:00
use Psr\Http\Message\RequestInterface;
use Psr\Http\Message\ResponseInterface;
2022-01-09 03:50:38 +08:00
use Swoole\Process;
2023-11-10 14:01:37 +08:00
interface Arrayable
{
2025-12-31 00:19:31 +08:00
/**
* @return array
*/
public function toArray(): array;
2023-11-10 14:01:37 +08:00
}
2024-09-23 16:16:01 +08:00
if (!function_exists('json_validate')) {
2023-12-19 14:31:41 +08:00
2025-12-31 00:19:31 +08:00
/**
* @param string $data
* @return bool
*/
function json_validate(string $data): bool
{
return is_array(json_decode($data, true));
}
2023-12-19 14:31:41 +08:00
}
2026-01-08 08:26:08 +00:00
if (!function_exists('println')) {
/**
* @param string $data
* @return bool
*/
function println(string $data): void
{
$logger = \Kiri::getDi()->get(StdoutLogger::class);
$logger->println($data);
}
}
2023-11-30 18:06:45 +08:00
if (!function_exists('application')) {
2025-12-31 00:19:31 +08:00
/**
* @param Kernel $Kernel
* @return Application
*/
function application(Kernel $Kernel): Application
{
$application = Kiri::getDi()->get(Application::class);
$application->commands($Kernel);
return $application;
}
2023-11-30 18:06:45 +08:00
}
2025-07-11 16:27:14 +08:00
if (!function_exists('task')) {
2025-12-31 00:19:31 +08:00
/**
2026-06-30 22:39:56 +08:00
* @param string $handler
* @param mixed $data
* @param int $dstWorkerId
2025-12-31 00:19:31 +08:00
* @param callable|null $finishFinishCallback
* @return void
* @throws Exception
*/
function task(string $handler, mixed $data, int $dstWorkerId = -1, ?callable $finishFinishCallback = null): void
{
$execute = Kiri::getDi()->get(TaskExecute::class);
$execute->task($handler, $data, $dstWorkerId, $finishFinishCallback);
}
2025-07-11 16:27:14 +08:00
}
if (!function_exists('taskWait')) {
2025-12-31 00:19:31 +08:00
/**
* @param string $handler
2026-06-30 22:39:56 +08:00
* @param mixed $data
* @param float $timeout
* @param int $dstWorkerId
2025-12-31 00:19:31 +08:00
* @return mixed
* @throws Exception
*/
function taskWait(string $handler, mixed $data, float $timeout = 0.5, int $dstWorkerId = -1): mixed
{
$execute = Kiri::getDi()->get(TaskExecute::class);
return $execute->taskWait($handler, $data, $timeout, $dstWorkerId);
}
2025-07-11 16:27:14 +08:00
}
if (!function_exists('taskCo')) {
2025-12-31 00:19:31 +08:00
/**
* @param array $tasks
* @param float $timeout
* @return false|array
*/
function taskCo(array $tasks, float $timeout = 0.5): false|array
{
$execute = Kiri::getDi()->get(TaskExecute::class);
return $execute->taskCo($tasks, $timeout);
}
2025-07-11 16:27:14 +08:00
}
if (!function_exists('taskWaitMulti')) {
2025-12-31 00:19:31 +08:00
/**
* @param array $tasks
* @param float $timeout
* @return false|array
*/
function taskWaitMulti(array $tasks, float $timeout = 0.5): false|array
{
$execute = Kiri::getDi()->get(TaskExecute::class);
return $execute->taskWaitMulti($tasks, $timeout);
}
2025-07-11 16:27:14 +08:00
}
2022-01-09 03:50:38 +08:00
if (!function_exists('make')) {
2023-04-15 23:32:00 +08:00
2025-12-31 00:19:31 +08:00
/**
* @param $name
* @param $default
* @return mixed
* @throws
*/
function make($name, $default = NULL): mixed
{
if (!class_exists($name) && !interface_exists($name)) {
return Kiri::getDi()->get($default);
}
return Kiri::getDi()->get($name);
}
2023-04-15 23:32:00 +08:00
2022-09-23 18:59:35 +08:00
}
2023-04-15 23:32:00 +08:00
2022-09-23 18:59:35 +08:00
if (!function_exists('isJson')) {
2023-04-15 23:32:00 +08:00
2025-12-31 00:19:31 +08:00
function isJson(?string $string): bool
{
if (is_null($string))
return false;
2026-06-30 22:39:56 +08:00
return (str_starts_with($string, '{') && str_ends_with($string, '}')) || (str_ends_with($string, '[') && str_starts_with($string, ']'));
2025-12-31 00:19:31 +08:00
}
2023-04-15 23:32:00 +08:00
2022-06-22 16:29:42 +08:00
}
if (!function_exists('instance')) {
2023-04-15 23:32:00 +08:00
2025-12-31 00:19:31 +08:00
/**
2026-06-30 22:39:56 +08:00
* @param $class
2025-12-31 00:19:31 +08:00
* @param array $constrict
* @param array $config
* @return null|object
* @throws
*/
function instance($class, array $constrict = [], array $config = []): ?object
{
return Kiri::getDi()->make($class, $constrict, $config);
}
2023-04-15 23:32:00 +08:00
2022-01-09 03:50:38 +08:00
}
2022-06-16 17:38:23 +08:00
if (!function_exists('call')) {
2023-04-15 23:32:00 +08:00
2025-12-31 00:19:31 +08:00
/**
2026-06-30 22:39:56 +08:00
* @param $handler
2025-12-31 00:19:31 +08:00
* @param mixed ...$params
* @return mixed
* @throws
*/
function call($handler, ...$params): mixed
{
if (is_array($handler) && is_string($handler[0])) {
$handler[0] = di($handler[0]);
}
if (!is_callable($handler, true)) {
throw new Exception('Call function not exists.');
}
return call_user_func($handler, ...$params);
}
2023-04-15 23:32:00 +08:00
2022-06-16 17:38:23 +08:00
}
2026-07-15 10:41:18 +08:00
if (!function_exists('checkPortIsAlready')) {
/**
* @param $port
* @return bool|string
*/
function checkPortIsAlready($port): bool|string
{
$port = (int)$port;
if ($port <= 0) {
return FALSE;
}
if (!Kiri::getPlatform()->isLinux()) {
exec("lsof -i :" . $port . " | grep -i 'LISTEN' | awk '{print $2}'", $output);
if (empty($output)) {
return FALSE;
}
$output = explode(PHP_EOL, $output[0]);
return $output[0];
}
exec('netstat -lnp 2>/dev/null | grep :' . $port . ' | grep "LISTEN" | awk \'{print $7}\'', $output);
if (empty($output)) {
exec('ss -ltnp 2>/dev/null | grep :' . $port . ' | sed -n \"s/.*pid=\\([0-9]*\\).*/\\1/p\"', $output);
}
if (empty($output)) {
return FALSE;
}
$pid = trim((string)$output[0]);
if (str_contains($pid, '/')) {
$pid = explode('/', $pid)[0];
}
return $pid !== '' ? $pid : FALSE;
}
}
2022-01-09 03:50:38 +08:00
if (!function_exists('set_env')) {
2023-04-15 23:32:00 +08:00
2025-12-31 00:19:31 +08:00
/**
* @param $key
* @param $value
*/
function set_env($key, $value): void
{
putenv(sprintf('%s=%s', $key, $value));
}
2023-04-15 23:32:00 +08:00
2022-01-09 03:50:38 +08:00
}
if (!function_exists('enable_file_modification_listening')) {
2023-04-15 23:32:00 +08:00
2025-12-31 00:19:31 +08:00
function enable_file_modification_listening(): void
{
putenv('enable_file_modification_listening=on');
}
2023-04-15 23:32:00 +08:00
2022-01-09 03:50:38 +08:00
}
if (!function_exists('is_enable_file_modification_listening')) {
2023-04-15 23:32:00 +08:00
2025-12-31 00:19:31 +08:00
/**
* @return bool
*/
#[Pure]
function is_enable_file_modification_listening(): bool
{
return env('enable_file_modification_listening', 'off') == 'on';
}
2023-04-15 23:32:00 +08:00
2022-01-09 03:50:38 +08:00
}
if (!function_exists('disable_file_modification_listening')) {
2023-04-15 23:32:00 +08:00
2025-12-31 00:19:31 +08:00
function disable_file_modification_listening(): void
{
putenv('enable_file_modification_listening=off');
}
2023-04-15 23:32:00 +08:00
2022-01-09 03:50:38 +08:00
}
if (!function_exists('now')) {
2023-04-15 23:32:00 +08:00
2025-12-31 00:19:31 +08:00
/**
* @return string
*/
function now(): string
{
return date('Y-m-d H:i:s') . '.' . str_replace(time() . '.', '', (string)microtime(TRUE));
}
2022-01-09 03:50:38 +08:00
}
if (!function_exists('directory')) {
2023-04-15 23:32:00 +08:00
2025-12-31 00:19:31 +08:00
/**
* @param $name
* @return string
*/
function directory($name): string
{
return realpath(APP_PATH . $name);
}
2023-04-15 23:32:00 +08:00
2022-01-09 03:50:38 +08:00
}
2023-10-08 23:43:01 +08:00
if (!function_exists('msgpack_pack')) {
2025-12-31 00:19:31 +08:00
/**
* @param $content
* @return string
*/
function msgpack_pack($content): string
{
return serialize($content);
}
2023-10-08 23:43:01 +08:00
}
if (!function_exists('msgpack_unpack')) {
2025-12-31 00:19:31 +08:00
/**
* @param $content
* @return mixed
*/
function msgpack_unpack($content): mixed
{
return unserialize($content);
}
2023-10-08 23:43:01 +08:00
}
2022-01-09 03:50:38 +08:00
2023-04-21 17:50:33 +08:00
if (!function_exists('request')) {
2025-12-31 00:19:31 +08:00
/**
* @return Request
* @throws
*/
function request(): RequestInterface
{
$request = Kiri::getDi()->get(RequestInterface::class);
2023-10-11 13:14:37 +08:00
2025-12-31 00:19:31 +08:00
return Context::get(RequestInterface::class, $request);
}
2023-04-21 17:50:33 +08:00
}
2023-11-09 20:31:01 +08:00
if (!function_exists('inject')) {
2025-12-31 00:19:31 +08:00
/**
* @param object $object
* @return object
* @throws
*/
function inject(object $object): object
{
$container = Kiri::getDi();
$reflect = $container->getReflectionClass($object::class);
$container->resolveProperties($reflect, $object);
return $object;
}
2023-11-09 20:31:01 +08:00
}
2023-04-21 17:50:33 +08:00
if (!function_exists('response')) {
2025-12-31 00:19:31 +08:00
/**
* @return Response
* @throws
*/
function response(): ResponseInterface
{
$data = Kiri::getDi()->get(ResponseInterface::class);
2023-09-15 15:58:24 +08:00
2025-12-31 00:19:31 +08:00
return Context::get(ResponseInterface::class, $data);
}
2023-04-15 23:32:00 +08:00
2022-01-09 03:50:38 +08:00
}
if (!function_exists('redis')) {
2023-04-15 23:32:00 +08:00
2025-12-31 00:19:31 +08:00
/**
2026-07-15 10:45:15 +08:00
* @return \Kiri\NoSql\Redis|Redis
2025-12-31 00:19:31 +08:00
* @throws
*/
2026-07-15 10:45:15 +08:00
function redis(): \Kiri\NoSql\Redis|Redis
2025-12-31 00:19:31 +08:00
{
2026-07-15 10:45:15 +08:00
return Kiri::getDi()->get(\Kiri\NoSql\Redis::class);
2025-12-31 00:19:31 +08:00
}
2022-01-09 03:50:38 +08:00
}
if (!function_exists('fire')) {
2023-04-15 23:32:00 +08:00
2025-12-31 00:19:31 +08:00
/**
* @param object $event
* @throws
*/
function fire(object $event): void
{
di(EventDispatch::class)->dispatch($event);
}
2022-01-09 03:50:38 +08:00
}
if (!function_exists('trim_blank')) {
2023-04-15 23:32:00 +08:00
2025-12-31 00:19:31 +08:00
/**
* 空白字符替换
* @param string $content 内容
2026-06-30 22:39:56 +08:00
* @param int $len 截取长度
* @param string $encode 编码
* @param bool $htmlTags
2025-12-31 00:19:31 +08:00
* @return array|string|null
*/
function trim_blank(string $content, int $len = 0, string $encode = 'utf-8', bool $htmlTags = TRUE): array|string|null
{
$str = trim($content);
if ($htmlTags) {
$str = strip_tags($str);
}
$str = preg_replace('/[\n|\r|\t]+/', '', $str);
$str = preg_replace("/(\s|\&nbsp\;| |\xc2\xa0)/", '', $str);
if ($len > 0) {
return mb_substr($str, 0, $len, $encode);
} else {
return $str;
}
}
2022-01-09 03:50:38 +08:00
}
if (!function_exists('storage')) {
2023-04-15 23:32:00 +08:00
2025-12-31 00:19:31 +08:00
/**
* @param string|null $fileName
* @param string|null $path
* @return string
* @throws
*/
function storage(?string $fileName = '', ?string $path = ''): string
{
2026-01-02 04:51:16 +08:00
if (!str_ends_with($path, '/')) {
$path .= '/';
}
2025-12-31 00:19:31 +08:00
$basePath = rtrim(Kiri::getStoragePath(), '/');
if (!empty($path)) {
$path = ltrim($path, '/');
if (!is_dir($basePath . '/' . $path)) {
mkdir($basePath . '/' . $path, 0777, TRUE);
}
}
if (empty($fileName)) {
return $basePath . '/' . $path;
}
$fileName = $basePath . '/' . $path . $fileName;
if (!file_exists($fileName)) {
touch($fileName);
}
return $fileName;
}
2022-01-09 03:50:38 +08:00
}
2023-04-19 10:39:28 +08:00
if (!function_exists('on')) {
2023-04-15 23:32:00 +08:00
2025-12-31 00:19:31 +08:00
/**
2026-06-30 22:39:56 +08:00
* @param $name
* @param $callback
2025-12-31 00:19:31 +08:00
* @param int $index
* @throws
*/
function on($name, $callback, int $index = 0): void
{
$pro = di(EventProvider::class);
$pro->on($name, $callback, $index);
}
2023-04-15 23:32:00 +08:00
2022-01-09 03:50:38 +08:00
}
2023-08-11 09:47:33 +08:00
2023-08-11 00:12:33 +08:00
if (!function_exists('off')) {
2025-12-31 00:19:31 +08:00
/**
* @param $name
* @param $callback
* @throws
*/
function off($name, $callback): void
{
$pro = di(EventProvider::class);
$pro->off($name, $callback);
}
2023-08-11 00:12:33 +08:00
}
2022-01-09 03:50:38 +08:00
2023-07-31 23:09:00 +08:00
if (!function_exists('process_name_set')) {
2023-04-15 23:32:00 +08:00
2025-12-31 00:19:31 +08:00
/**
2026-06-30 22:39:56 +08:00
* @param int $pid
2025-12-31 00:19:31 +08:00
* @param string|null $prefix
* @throws
*/
function process_name_set(int $pid, ?string $prefix = NULL): void
{
if (Kiri::getPlatform()->isMac()) {
return;
}
2023-04-15 23:32:00 +08:00
2025-12-31 00:19:31 +08:00
$name = \config('site.id', 'system') . '[' . $pid . ']';
if (!empty($prefix)) {
$name .= '.' . $prefix;
}
swoole_set_process_name($name);
}
2023-04-15 23:32:00 +08:00
2022-01-09 03:50:38 +08:00
}
if (!function_exists('zero_full')) {
2023-07-31 23:09:00 +08:00
2025-12-31 00:19:31 +08:00
/**
* @param int $data
* @param int $length
* @return string
*/
function zero_full(int $data = 1, int $length = 10): string
{
return sprintf('%0' . $length . 'd', $data);
}
2022-01-09 03:50:38 +08:00
}
if (!function_exists('env')) {
2023-04-15 23:32:00 +08:00
2025-12-31 00:19:31 +08:00
/**
2026-06-30 22:39:56 +08:00
* @param $key
2025-12-31 00:19:31 +08:00
* @param null $default
* @return array|string|null
*/
function env($key, $default = NULL): null|array|string
{
$env = getenv($key);
if ($env === FALSE) {
return $default;
}
return $env;
}
2023-04-15 23:32:00 +08:00
}
if (!function_exists('config')) {
2025-12-31 00:19:31 +08:00
/**
2026-06-30 22:39:56 +08:00
* @param $key
2025-12-31 00:19:31 +08:00
* @param null $default
* @return mixed
*/
function config($key, mixed $default = NULL): mixed
{
return make(ConfigProvider::class)->get($key, $default);
}
2023-05-25 16:59:20 +08:00
}
if (!function_exists('created')) {
2025-12-31 00:19:31 +08:00
/**
2026-06-30 22:39:56 +08:00
* @param $key
2025-12-31 00:19:31 +08:00
* @param array $construct
* @param array $config
* @return null|object
* @throws
*/
function created($key, array $construct = [], array $config = []): ?object
{
return Kiri::getDi()->make($key, $construct, $config);
}
2023-04-15 23:32:00 +08:00
2022-01-09 03:50:38 +08:00
}
if (!function_exists('di')) {
2023-04-15 23:32:00 +08:00
2025-12-31 00:19:31 +08:00
/**
* @param string|object $className
* @return mixed
* @throws
*/
function di(string|object $className): mixed
{
if (is_object($className)) {
return $className;
}
return Kiri::getDi()->get($className);
}
2023-04-15 23:32:00 +08:00
2022-01-09 03:50:38 +08:00
}
if (!function_exists('sweep')) {
2025-12-31 00:19:31 +08:00
2025-12-18 15:03:43 +08:00
/**
* @param string $configPath
* @return array
*/
function sweep(string $configPath = APP_PATH . 'config'): array
{
$array = [];
2025-12-31 00:19:31 +08:00
2025-12-18 15:03:43 +08:00
// 检查目录是否存在
if (!is_dir($configPath)) {
throw new InvalidArgumentException("Config directory does not exist: {$configPath}");
}
2025-12-31 00:19:31 +08:00
2025-12-18 15:03:43 +08:00
// 获取所有PHP配置文件
$configFiles = glob($configPath . '/*.php');
foreach ($configFiles as $config) {
// 使用 pathinfo 更安全地获取文件名
$filename = pathinfo($config, PATHINFO_FILENAME);
2025-12-31 00:19:31 +08:00
$key = strtolower($filename);
2025-12-18 15:03:43 +08:00
// 验证文件是否可读
if (!is_readable($config)) {
throw new RuntimeException("Cannot read config file: {$config}");
}
2025-12-31 00:19:31 +08:00
2025-12-18 15:03:43 +08:00
// 使用 include 而不是 require_once,这样不会跳过已加载的文件
// 在配置加载场景中,通常希望每次都重新加载
2025-12-18 22:35:21 +08:00
$configData = require_once $config;
2025-12-31 00:19:31 +08:00
2025-12-18 15:03:43 +08:00
if (!is_array($configData)) {
continue;
}
2025-12-31 00:19:31 +08:00
2025-12-18 15:03:43 +08:00
$array[$key] = $configData;
}
2025-12-31 00:19:31 +08:00
2025-12-18 15:03:43 +08:00
return $array;
}
2025-12-31 00:19:31 +08:00
2022-01-09 03:50:38 +08:00
}
2023-08-11 09:47:33 +08:00
2022-01-09 03:50:38 +08:00
if (!function_exists('merge')) {
2023-04-15 23:32:00 +08:00
2025-12-31 00:19:31 +08:00
/**
* @param $param
* @param $param1
* @return array
*/
function merge($param, $param1): array
{
return ArrayAccess::merge($param, $param1);
}
2023-04-15 23:32:00 +08:00
2022-01-09 03:50:38 +08:00
}
2023-04-19 10:39:28 +08:00
if (!function_exists('event')) {
2025-12-31 00:19:31 +08:00
/**
* @param object $object
* @return void
* @throws
*/
function event(object $object): void
{
Kiri::getDi()->get(EventDispatch::class)->dispatch($object);
}
2023-04-19 10:39:28 +08:00
}
2022-01-11 16:16:05 +08:00
2022-06-22 16:29:42 +08:00
if (!function_exists('throwable')) {
2023-04-15 23:32:00 +08:00
2025-12-31 00:19:31 +08:00
/**
* 错误格式化
* @param Throwable|Error|string $throwable
* @return string
*/
function throwable(\Throwable|\Error|string $throwable): string
{
if (is_string($throwable)) {
return $throwable;
}
$message = $throwable::class . ' ' . $throwable->getMessage() . PHP_EOL;
$message .= ' File: ' . $throwable->getFile() . PHP_EOL;
$message .= ' Line: ' . $throwable->getLine() . PHP_EOL;
2023-07-26 17:26:47 +08:00
2025-12-31 00:19:31 +08:00
$file = $throwable->getFile();
$line = $throwable->getLine();
2023-07-26 17:26:47 +08:00
2025-12-31 00:19:31 +08:00
$trance = $throwable->getTrace();
$current = array_shift($trance);
2023-12-13 19:25:04 +08:00
2025-12-31 00:19:31 +08:00
if (!isset($current['file'])) {
$current['file'] = $file;
}
if (!isset($current['line'])) {
$current['line'] = $line;
}
$message .= ' Trance: ' . $current['file'] . ' -> ' . (isset($current['class']) ? $current['class'] . '::' : '') . ($current['function'] ?? 'Closure') . ' line ' . $current['line'] . PHP_EOL;
2023-12-13 19:22:39 +08:00
2025-12-31 00:19:31 +08:00
foreach ($trance as $value) {
if (!isset($value['file'])) {
$value['file'] = $file;
}
if (!isset($value['line'])) {
$value['line'] = $line;
}
$file = $value['file'];
$line = $value['line'];
2023-07-26 17:26:47 +08:00
2025-12-31 00:19:31 +08:00
$message .= ' ' . $value['file'] . ' -> ' . (isset($value['class']) ? $value['class'] . '::' : '') . ($value['function'] ?? 'Closure') . ' line ' . $line . PHP_EOL;
}
return $message;
}
2023-04-15 23:32:00 +08:00
2022-01-11 16:16:05 +08:00
}
2025-12-31 00:19:31 +08:00
if (!function_exists('json_log')) {
function json_log(Throwable $throwable, array $data = []): void
{
$param = [];
$param['time'] = date('Y-m-d H:i:s');
$param['request'] = [
'path' => \request()->getUri()->getPath(),
'headers' => \request()->getHeaders(),
'method' => \request()->getMethod(),
'params' => \request()->getBody()->getContents(),
];
$param['exception'] = [
'message' => $throwable->getMessage(),
'code' => $throwable->getCode(),
'file' => $throwable->getFile(),
'line' => $throwable->getLine(),
'trace' => $throwable->getTrace(),
];
$param['data'] = $data;
2026-06-30 22:39:56 +08:00
file_put_contents(storage('exception-' . date('Y-m-d') . '.log', 'exception'), json_encode($param, JSON_UNESCAPED_UNICODE) . PHP_EOL, FILE_APPEND);
2025-12-31 00:19:31 +08:00
}
}
2022-06-22 16:29:42 +08:00
if (!function_exists('map')) {
2023-04-15 23:32:00 +08:00
2025-12-31 00:19:31 +08:00
/**
2026-06-30 22:39:56 +08:00
* @param array $map
2025-12-31 00:19:31 +08:00
* @param Closure $closure
* @return void
*/
function map(array $map, Closure $closure): void
{
foreach ($map as $key => $value) {
$closure($key, $value);
}
}
2022-06-22 16:29:42 +08:00
}