Files
kiri-core/function.php
T

750 lines
14 KiB
PHP
Raw Normal View History

2020-08-31 01:27:08 +08:00
<?php
2021-03-05 16:36:18 +08:00
defined('APP_PATH') or define('APP_PATH', realpath(__DIR__ . '/../../'));
2020-08-31 01:27:08 +08:00
2021-02-22 17:44:24 +08:00
use Annotation\Annotation;
2021-03-03 19:05:57 +08:00
use Annotation\Attribute;
2021-01-15 15:53:10 +08:00
use HttpServer\Http\HttpParams;
use HttpServer\Http\Request;
2020-08-31 01:27:08 +08:00
use HttpServer\Http\Response;
2020-10-29 18:17:25 +08:00
use HttpServer\Route\Router;
2020-09-11 15:01:22 +08:00
use Snowflake\Error\Logger;
use Snowflake\Exception\ComponentException;
2021-03-03 19:35:44 +08:00
use Snowflake\Exception\NotFindClassException;
2020-08-31 01:27:08 +08:00
use Snowflake\Snowflake;
2020-08-31 01:39:28 +08:00
use HttpServer\Http\Context;
2020-09-02 20:07:02 +08:00
use Snowflake\Core\ArrayAccess;
2020-08-31 01:27:08 +08:00
if (!function_exists('make')) {
2021-03-03 19:05:57 +08:00
/**
* @param $name
* @param $default
* @return mixed
* @throws
*/
function make($name, $default): mixed
{
if (Snowflake::has($name)) {
$class = Snowflake::app()->$name;
} else if (Snowflake::has($default)) {
$class = Snowflake::app()->$default;
} else {
$class = Snowflake::createObject($default);
Snowflake::setAlias($name, $default);
}
return $class;
}
2020-08-31 01:27:08 +08:00
2020-09-15 19:26:44 +08:00
}
2021-02-27 04:48:44 +08:00
if (!function_exists('workerName')) {
2021-03-03 19:05:57 +08:00
function workerName($worker_id)
{
return $worker_id >= Snowflake::app()->getSwoole()->setting['worker_num'] ? 'Task' : 'Worker';
}
2021-02-27 04:48:44 +08:00
}
2020-09-23 16:28:54 +08:00
2021-02-22 17:44:24 +08:00
if (!function_exists('annotation')) {
2021-03-03 19:05:57 +08:00
/**
* @return Annotation
* @throws ComponentException
*/
function annotation(): Annotation
{
return Snowflake::app()->getAttributes();
}
}
if (!function_exists('recursive_directory')) {
2021-03-03 19:35:44 +08:00
/**
* @param DirectoryIterator $file
* @throws ComponentException
* @throws ReflectionException
* @throws NotFindClassException
*/
function recursive_callback(DirectoryIterator $file)
{
$attributes = Snowflake::app()->getAttributes();
$annotations = $attributes->getFilename($file->getRealPath());
if (empty($annotations)) {
return;
}
2021-03-03 20:05:08 +08:00
/** @var Attribute $value */
2021-03-03 19:35:44 +08:00
foreach ($annotations['methods'] as $name => $attribute) {
2021-03-03 20:05:08 +08:00
foreach ($attribute as $value) {
if (!($value instanceof Attribute)) {
continue;
}
$value->execute([$annotations['handler'], $name]);
2021-03-03 19:35:44 +08:00
}
}
}
2021-03-03 19:05:57 +08:00
/**
* @param string $path
*/
2021-03-03 19:35:44 +08:00
function recursive_directory(string $path)
2021-03-03 19:05:57 +08:00
{
$directoryIterators = new \DirectoryIterator($path);
foreach ($directoryIterators as $directoryIterator) {
2021-03-03 19:31:24 +08:00
if ($directoryIterator->getFilename() === '.' || $directoryIterator->getFilename() === '..') {
continue;
}
2021-03-03 19:05:57 +08:00
if ($directoryIterator->isDir()) {
2021-03-03 19:35:44 +08:00
Recursive_directory($directoryIterator->getRealPath());
2021-03-03 19:05:57 +08:00
} else {
2021-03-03 19:35:44 +08:00
call_user_func('recursive_callback', $directoryIterator);
2021-03-03 19:05:57 +08:00
}
}
2021-03-03 19:28:55 +08:00
unset($directoryIterators);
2021-03-03 19:05:57 +08:00
}
2021-02-22 17:44:24 +08:00
}
2020-09-23 16:28:54 +08:00
if (!function_exists('isUrl')) {
2021-03-03 19:05:57 +08:00
/**
* @param $url
* @param bool $get_info
* @return false|array
*/
function isUrl($url, $get_info = true)
{
$queryMatch = '/((http[s]?):\/\/)?(([\w\-\_]+\.)+\w+(:\d+)?)(\/.*)?/';
if (!preg_match($queryMatch, $url, $outPut)) {
return false;
}
$port = str_replace(':', '', $outPut[5]);
2020-09-23 16:28:54 +08:00
2021-03-03 19:05:57 +08:00
[$isHttps, $domain, $port, $path] = [$outPut[2] == 'https', $outPut[3], $port, $outPut[6] ?? ''];
if ($isHttps && empty($port)) {
$port = 443;
}
2020-09-23 16:28:54 +08:00
2021-03-03 19:05:57 +08:00
unset($outPut);
2020-09-23 16:28:54 +08:00
2021-03-03 19:05:57 +08:00
return [$isHttps == 'https', $domain, $port, $path];
}
2020-09-23 16:28:54 +08:00
}
if (!function_exists('split_request_uri')) {
2021-03-03 19:05:57 +08:00
/**
* @param $url
* @return false|array
*/
function split_request_uri($url): bool|array
{
if (($parse = isUrl($url, null)) === false) {
return false;
}
2020-09-23 16:28:54 +08:00
2021-03-03 19:05:57 +08:00
[$isHttps, $domain, $port, $path] = $parse;
$uri = $isHttps ? 'https://' . $domain : 'http://' . $domain;
if (!empty($port)) {
$uri .= ':' . $port;
}
return [$uri, $path];
}
2020-09-23 16:28:54 +08:00
}
if (!function_exists('hadDomain')) {
2021-03-03 19:05:57 +08:00
/**
* @param $url
* @return false|array
*/
function hadDomain($url): bool|array
{
$param = split_request_uri($url);
return !is_array($param) ? false : $param[0];
}
2020-09-23 16:28:54 +08:00
}
if (!function_exists('isDomain')) {
2021-03-03 19:05:57 +08:00
/**
* @param $url
* @return false|array
*/
function isDomain($url): array|bool
{
return !isIp($url);
}
2020-09-23 16:28:54 +08:00
}
if (!function_exists('isIp')) {
2021-03-03 19:05:57 +08:00
/**
* @param $url
* @return false|array
*/
function isIp($url): bool|array
{
return preg_match('/(\d{1,3}\.){3}\.\d{1,3}(:\d{1,5})?/', $url);
}
2020-09-23 16:28:54 +08:00
}
2020-09-15 19:26:44 +08:00
if (!function_exists('loadByDir')) {
2021-03-03 19:05:57 +08:00
/**
* @param $namespace
* @param $dirname
*/
function classAutoload($namespace, $dirname)
{
foreach (glob(rtrim($dirname, '/') . '/*') as $value) {
$value = realpath($value);
if (is_dir($value)) {
classAutoload($namespace, $value);
} else {
$pos = strpos($value, '.php');
if ($pos === false || strlen($value) - 4 != $pos) {
continue;
}
2020-09-15 20:11:41 +08:00
2021-03-03 19:05:57 +08:00
$replace = ltrim(str_replace(__DIR__, '', $value), '/');
$replace = str_replace('.php', '', $replace);
2020-09-15 20:11:41 +08:00
2021-03-03 19:05:57 +08:00
$first = explode(DIRECTORY_SEPARATOR, $replace);
array_shift($first);
2020-09-15 20:11:41 +08:00
2021-03-03 19:05:57 +08:00
Snowflake::setAutoload($namespace . '\\' . implode('\\', $first), $value);
}
}
}
2020-09-15 19:26:44 +08:00
2020-08-31 01:27:08 +08:00
}
2020-09-16 20:23:23 +08:00
if (!function_exists('write')) {
2021-03-03 19:05:57 +08:00
/**
* @param string $messages
* @param string $category
* @throws ComponentException
*/
function write(string $messages, $category = 'app')
{
$logger = Snowflake::app()->getLogger();
$logger->write($messages, $category);
}
2020-09-16 20:23:23 +08:00
}
2020-10-30 11:04:04 +08:00
if (!function_exists('fire')) {
2021-03-03 19:05:57 +08:00
/**
* @param string $event
* @param array $params
* @throws ComponentException
* @throws Exception
*/
function fire(string $event, array $params = [])
{
$logger = Snowflake::app()->getEvent();
$logger->trigger($event, $params);
}
2020-10-30 11:04:04 +08:00
}
2020-09-16 20:23:23 +08:00
2021-02-23 17:19:46 +08:00
if (!function_exists('objectPool')) {
2021-03-03 19:05:57 +08:00
/**
* @param string $className
* @param callable $construct
* @return mixed
* @throws ComponentException
*/
function objectPool(mixed $className, callable $construct): mixed
{
return Snowflake::app()->getObject()->load($className, $construct);
}
2021-02-23 17:19:46 +08:00
}
2021-02-23 17:43:13 +08:00
if (!function_exists('objectRecover')) {
2021-03-03 19:05:57 +08:00
/**
* @param string $className
* @param $object
* @return mixed
* @throws ComponentException
*/
function objectRecover(mixed $className, $object): void
{
Snowflake::app()->getObject()->release($className, $object);
}
2021-02-23 17:43:13 +08:00
}
2021-02-23 17:19:46 +08:00
2020-09-15 20:17:14 +08:00
if (!function_exists('instance_load')) {
2021-03-03 19:05:57 +08:00
function instance_load()
{
$content = json_decode(file_get_contents(__DIR__ . '/composer.json'), true);
if (isset($content['autoload']) && isset($content['autoload']['psr-4'])) {
$psr4 = $content['autoload']['psr-4'];
foreach ($psr4 as $namespace => $dirname) {
classAutoload($namespace, __DIR__ . '/' . $dirname);
}
}
}
2020-09-15 20:17:14 +08:00
}
2020-08-31 12:38:32 +08:00
if (!function_exists('exif_imagetype')) {
2021-03-03 19:05:57 +08:00
/**
* @param $name
* @return string
*/
function exif_imagetype($name): string
{
return get_file_extension($name);
}
2020-08-31 12:38:32 +08:00
}
2020-09-11 15:01:22 +08:00
if (!function_exists('logger')) {
2021-03-03 19:05:57 +08:00
/**
* @return Logger
* @throws ComponentException
*/
function logger(): Logger
{
return Snowflake::app()->getLogger();
}
2020-09-11 15:01:22 +08:00
}
2020-08-31 12:38:32 +08:00
if (!function_exists('get_file_extension')) {
2021-03-03 19:05:57 +08:00
function get_file_extension($filename)
{
$mime_types = array(
'txt' => 'text/plain',
'htm' => 'text/html',
'html' => 'text/html',
'php' => 'text/html',
'css' => 'text/css',
'js' => 'application/javascript',
'json' => 'application/json',
'xml' => 'application/xml',
'swf' => 'application/x-shockwave-flash',
'flv' => 'video/x-flv',
// images
'png' => 'image/png',
'jpeg' => 'image/jpeg',
'gif' => 'image/gif',
'bmp' => 'image/bmp',
'ico' => 'image/vnd.microsoft.icon',
'tiff' => 'image/tiff',
'svg' => 'image/svg+xml',
// archives
'zip' => 'application/zip',
'rar' => 'application/x-rar-compressed',
'exe' => 'application/x-msdownload',
'msi' => 'application/x-msdownload',
'cab' => 'application/vnd.ms-cab-compressed',
// audio/video
'mp3' => 'audio/mpeg',
'qt' => 'video/quicktime',
'mov' => 'video/quicktime',
// adobe
'pdf' => 'application/pdf',
'psd' => 'image/vnd.adobe.photoshop',
'ai' => 'application/postscript',
'eps' => 'application/postscript',
'ps' => 'application/postscript',
// ms office
'doc' => 'application/msword',
'rtf' => 'application/rtf',
'xls' => 'application/vnd.ms-excel',
'ppt' => 'application/vnd.ms-powerpoint',
// open office
'odt' => 'application/vnd.oasis.opendocument.text',
'ods' => 'application/vnd.oasis.opendocument.spreadsheet',
);
$explode = explode('.', $filename);
$ext = strtolower(array_pop($explode));
if (array_key_exists($ext, $mime_types)) {
return $ext;
} elseif (function_exists('finfo_open')) {
$fInfo = finfo_open(FILEINFO_MIME);
$mimeType = finfo_file($fInfo, $filename);
finfo_close($fInfo);
$mimeType = current(explode('; ', $mimeType));
if (($search = array_search($mimeType, $mime_types)) == false) {
return $mimeType;
}
return $search;
} else {
return 'application/octet-stream';
}
}
2020-08-31 12:38:32 +08:00
}
if (!function_exists('request')) {
2021-03-03 19:05:57 +08:00
/**
* @return Request
*/
function request(): Request
{
if (!Context::hasContext('request')) {
return make('request', Request::class);
}
return Context::getContext('request');
}
2020-08-31 12:38:32 +08:00
}
if (!function_exists('Input')) {
2021-03-03 19:05:57 +08:00
/**
* @return HttpParams
*/
function Input(): HttpParams
{
return request()->params;
}
2020-08-31 12:38:32 +08:00
}
2020-08-31 01:27:08 +08:00
if (!function_exists('storage')) {
2021-03-03 19:05:57 +08:00
/**
* @param string $fileName
* @param string $path
* @return string
* @throws Exception
*/
function storage($fileName = '', $path = ''): string
{
$basePath = Snowflake::getStoragePath();
if (empty($path)) {
$fileName = rtrim($basePath, '/') . '/' . $fileName;
} else if (empty($fileName)) {
return rtrim(initDir($basePath, $path));
} else {
$fileName = rtrim(initDir($basePath, $path)) . '/' . $fileName;
}
if (!file_exists($fileName)) {
touch($fileName);
}
return $fileName;
}
/**
* @param $basePath
* @param $path
* @return false|string
* @throws Exception
*/
function initDir($basePath, $path): bool|string
{
$explode = array_filter(explode('/', $path));
$_path = '/' . trim($basePath, '/') . '/';
foreach ($explode as $value) {
$_path .= $value . '/';
if (!is_dir(rtrim($_path, '/'))) {
mkdir(rtrim($_path, '/'));
}
if (!is_dir($_path)) {
throw new Exception('System error, directory ' . $_path . ' is not writable');
}
}
return realpath($_path);
}
2020-08-31 01:27:08 +08:00
}
2021-02-22 17:44:24 +08:00
if (!function_exists('listen')) {
2021-03-03 19:05:57 +08:00
/**
* @param $name
* @param $callback
* @param $params
* @param $isAppend
* @throws ComponentException
* @throws Exception
*/
function listen($name, $callback, $params = [], $isAppend = true)
{
$event = Snowflake::app()->getEvent();
$event->on($name, $callback, $params, $isAppend);
}
2021-02-22 17:44:24 +08:00
}
2020-08-31 01:27:08 +08:00
if (!function_exists('alias')) {
2021-03-03 19:05:57 +08:00
/**
* @param $class
* @param $name
*/
function alias($class, $name)
{
Snowflake::setAlias($class, $name);
}
2020-08-31 01:27:08 +08:00
}
if (!function_exists('name')) {
2021-03-03 19:05:57 +08:00
/**
* @param string $name
2021-03-04 14:40:33 +08:00
* @throws Exception
2021-03-03 19:05:57 +08:00
*/
function name(string $name)
{
2021-03-04 14:40:33 +08:00
if (Snowflake::getPlatform()->isMac()) {
2021-03-03 19:05:57 +08:00
return;
}
swoole_set_process_name($name);
}
2020-08-31 01:27:08 +08:00
}
if (!function_exists('response')) {
2021-03-03 19:05:57 +08:00
/**
* @return Response|stdClass
* @throws
*/
function response(): Response|stdClass
{
if (!Context::hasContext('response')) {
return make('response', Response::class);
}
return Context::getContext('response');
}
2020-08-31 01:27:08 +08:00
}
2020-09-09 11:44:14 +08:00
if (!function_exists('send')) {
2021-03-03 19:05:57 +08:00
/**
* @param $context
* @param $statusCode
* @return bool|Response|stdClass|string
* @throws Exception
*/
function send($context, $statusCode = 404): Response|bool|string|stdClass
{
return \response()->send($context, $statusCode);
}
2020-09-09 11:44:14 +08:00
}
2020-08-31 01:27:08 +08:00
if (!function_exists('redirect')) {
2021-01-15 15:53:10 +08:00
2021-03-03 19:05:57 +08:00
/**
* @param $url
* @return int
*/
function redirect($url): int
{
return response()->redirect($url);
}
2020-08-31 01:27:08 +08:00
}
if (!function_exists('env')) {
2021-03-03 19:05:57 +08:00
/**
* @param $key
* @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;
}
2020-08-31 01:27:08 +08:00
}
2020-08-31 01:59:30 +08:00
if (!function_exists('sweep')) {
2021-03-03 19:05:57 +08:00
/**
* @param string $configPath
* @return array|false|string|null
*/
function sweep($configPath = APP_PATH . '/config'): bool|array|string|null
{
$array = [];
foreach (glob($configPath . '/*') as $config) {
$array = array_merge(require_once "$config", $array);
}
return $array;
}
2020-08-31 01:59:30 +08:00
}
2020-09-02 20:07:02 +08:00
if (!function_exists('merge')) {
2021-03-03 19:05:57 +08:00
/**
* @param $param
* @param $param1
* @return array
*/
function merge($param, $param1): array
{
return ArrayAccess::merge($param, $param1);
}
2020-09-02 20:07:02 +08:00
}
2020-09-03 18:51:13 +08:00
2020-10-29 18:17:25 +08:00
if (!function_exists('router')) {
2021-03-03 19:05:57 +08:00
/**
* @return Router
* @throws ComponentException
*/
function router(): Router
{
return Snowflake::app()->getRouter();
}
2020-10-29 18:17:25 +08:00
}
2020-09-03 18:51:13 +08:00
if (!function_exists('jTraceEx')) {
2021-03-03 19:05:57 +08:00
/**
* @param $e
* @param null $seen
* @return string
*/
function jTraceEx($e, $seen = null): string
{
$starter = $seen ? 'Caused by: ' : '';
$result = array();
if (!$seen) $seen = array();
$trace = $e->getTrace();
$prev = $e->getPrevious();
$result[] = sprintf('%s%s: %s', $starter, get_class($e), $e->getMessage());
$file = $e->getFile();
$line = $e->getLine();
while (true) {
$current = "$file:$line";
if (is_array($seen) && in_array($current, $seen)) {
$result[] = sprintf(' ... %d more', count($trace) + 1);
break;
}
$result[] = sprintf(' at %s%s%s(%s%s%s)',
count($trace) && array_key_exists('class', $trace[0]) ? str_replace('\\', '.', $trace[0]['class']) : '',
count($trace) && array_key_exists('class', $trace[0]) && array_key_exists('function', $trace[0]) ? '.' : '',
count($trace) && array_key_exists('function', $trace[0]) ? str_replace('\\', '.', $trace[0]['function']) : '(main)',
$line === null ? $file : basename($file),
$line === null ? '' : ':',
$line === null ? '' : $line);
if (is_array($seen))
$seen[] = "$file:$line";
if (!count($trace))
break;
$file = array_key_exists('file', $trace[0]) ? $trace[0]['file'] : 'Unknown Source';
$line = array_key_exists('file', $trace[0]) && array_key_exists('line', $trace[0]) && $trace[0]['line'] ? $trace[0]['line'] : null;
array_shift($trace);
}
$result = join("\n", $result);
if ($prev)
$result .= "\n" . jTraceEx($prev, $seen);
return $result;
}
2020-09-03 18:51:13 +08:00
}
2020-11-04 19:28:40 +08:00
if (!function_exists('swoole_substr_json_decode')) {
2021-03-03 19:05:57 +08:00
/**
* @param $packet
* @param int $length
* @return mixed
*/
function swoole_substr_json_decode($packet, $length = 0): mixed
{
return json_decode($packet, true);
}
2020-11-04 19:28:40 +08:00
}
if (!function_exists('swoole_substr_unserialize')) {
2021-03-03 19:05:57 +08:00
/**
* @param $packet
* @param int $length
* @return mixed
*/
function swoole_substr_unserialize($packet, $length = 0): mixed
{
return unserialize($packet);
}
2020-11-04 19:28:40 +08:00
}