hyperf-view/builder/Helper/functions.php

346 lines
8.7 KiB
PHP

<?php
/**
* MineAdmin is committed to providing solutions for quickly building web applications
* Please view the LICENSE file that was distributed with this source code,
* For the full copyright and license information.
* Thank you very much for using MineAdmin.
*
* @Author X.Mo<root@imoi.cn>
* @Link https://gitee.com/xmo/MineAdmin
*/
use App\System\Vo\QueueMessageVo;
use Hyperf\Contract\StdoutLoggerInterface;
use Hyperf\Logger\LoggerFactory;
use Hyperf\Utils\ApplicationContext;
use Hyperf\HttpMessage\Server\Response;
use Hyperf\HttpServer\Contract\ResponseInterface;
use Hyperf\HttpServer\Request;
use Builder\Helper\LoginUser;
use Builder\Helper\AppVerify;
use Builder\Helper\Id;
use Psr\EventDispatcher\EventDispatcherInterface;
use Psr\Log\LoggerInterface;
if (! function_exists('container')) {
/**
* 获取容器实例
* @return \Psr\Container\ContainerInterface
*/
function container(): \Psr\Container\ContainerInterface
{
return ApplicationContext::getContainer();
}
}
if (! function_exists('redis')) {
/**
* 获取Redis实例
* @return \Hyperf\Redis\Redis
* @throws \Psr\Container\ContainerExceptionInterface
* @throws \Psr\Container\NotFoundExceptionInterface
*/
function redis(): \Hyperf\Redis\Redis
{
return container()->get(\Hyperf\Redis\Redis::class);
}
}
if (! function_exists('console')) {
/**
* 获取控制台输出实例
* @return StdoutLoggerInterface
* @throws \Psr\Container\ContainerExceptionInterface
* @throws \Psr\Container\NotFoundExceptionInterface
*/
function console(): StdoutLoggerInterface
{
return container()->get(StdoutLoggerInterface::class);
}
}
if (! function_exists('logger')) {
/**
* 获取日志实例
* @param string $name
* @return LoggerInterface
* @throws \Psr\Container\ContainerExceptionInterface
* @throws \Psr\Container\NotFoundExceptionInterface
*/
function logger(string $name = 'Log'): LoggerInterface
{
return container()->get(LoggerFactory::class)->get($name);
}
}
if (! function_exists('user')) {
/**
* 获取当前登录用户实例
* @param string $scene
* @return LoginUser
*/
function user(string $scene = 'default'): LoginUser
{
return new LoginUser($scene);
}
}
if (! function_exists('format_size')) {
/**
* 格式化大小
* @param int $size
* @return string
*/
function format_size(int $size): string
{
$units = ['B', 'KB', 'MB', 'GB', 'TB', 'PB'];
$index = 0;
for ($i = 0; $size >= 1024 && $i < 5; $i++) {
$size /= 1024;
$index = $i;
}
return round($size, 2) . $units[$index];
}
}
if (! function_exists('t')) {
/**
* 多语言函数
* @param string $key
* @param array $replace
* @return string
* @throws \Psr\Container\ContainerExceptionInterface
* @throws \Psr\Container\NotFoundExceptionInterface
*/
function t(string $key, array $replace = []): string
{
$acceptLanguage = container()->get(\Builder\MineRequest::class)->getHeaderLine('accept-language');
$language = !empty($acceptLanguage) ? explode(',',$acceptLanguage)[0] : 'zh_CN';
return __($key, $replace, $language);
}
}
if (! function_exists('mine_collect')) {
/**
* 创建一个Mine的集合类
* @param null|mixed $value
* @return \Builder\MineCollection
*/
function mine_collect($value = null): \Builder\MineCollection
{
return new \Builder\MineCollection($value);
}
}
if (! function_exists('context_set')) {
/**
* 设置上下文数据
* @param string $key
* @param $data
* @return bool
*/
function context_set(string $key, $data): bool
{
return (bool)\Hyperf\Context\Context::set($key, $data);
}
}
if (! function_exists('context_get')) {
/**
* 获取上下文数据
* @param string $key
* @return mixed
*/
function context_get(string $key)
{
return \Hyperf\Context\Context::get($key);
}
}
if (! function_exists('app_verify')) {
/**
* 获取APP应用请求实例
* @param string $scene
* @return AppVerify
*/
function app_verify(string $scene = 'api'): AppVerify
{
return new AppVerify($scene);
}
}
if (! function_exists('snowflake_id')) {
/**
* 生成雪花ID
* @param int|null $workerId
* @return String
* @throws \Psr\Container\ContainerExceptionInterface
* @throws \Psr\Container\NotFoundExceptionInterface
*/
function snowflake_id(?int $workerId = null): String
{
return container()->get(Id::class)->getId($workerId);
}
}
if (! function_exists('event')) {
/**
* 事件调度快捷方法
* @param object $dispatch
* @return object
* @throws \Psr\Container\ContainerExceptionInterface
* @throws \Psr\Container\NotFoundExceptionInterface
*/
function event(object $dispatch): object
{
return container()->get(EventDispatcherInterface::class)->dispatch($dispatch);
}
}
if (! function_exists('push_queue_message')) {
/**
* 推送消息到队列
* @param QueueMessageVo $message
* @param array $receiveUsers
* @return bool
* @throws Throwable
* @throws \Psr\Container\ContainerExceptionInterface
* @throws \Psr\Container\NotFoundExceptionInterface
*/
function push_queue_message(QueueMessageVo $message, array $receiveUsers = []): bool
{
return container()
->get(\App\System\Service\SystemQueueLogService::class)
->pushMessage($message, $receiveUsers);
}
}
if (! function_exists('add_queue')) {
/**
* 添加任务到队列
* @param \App\System\Vo\AmqpQueueVo $amqpQueueVo
* @return bool
* @throws Throwable
* @throws \Psr\Container\ContainerExceptionInterface
* @throws \Psr\Container\NotFoundExceptionInterface
*/
function add_queue(\App\System\Vo\AmqpQueueVo $amqpQueueVo): bool
{
return container()
->get(\App\System\Service\SystemQueueLogService::class)
->addQueue($amqpQueueVo);
}
}
if (!function_exists('request')) {
/**
* Get admin path.
* @param null $key
* @param null $default
* @return string
*/
function request($key = null, $default = null)
{
if ($key !== null) {
return (new Request())->all()[$key] ?? $default;
}
return new Request();
}
}
if (!function_exists('response')) {
/**
* Get admin path.
*
* @param string $path
*
* @return string
*/
function response(): ResponseInterface
{
return new Response();//return $res->withBody(new SwooleStream(json_encode($re_data,256)));
}
}
if (!function_exists('admin_api_url')) {
/**
* Get admin url.
*
* @param string $path
* @param mixed $parameters
* @param bool $secure
*
* @return string
*/
function admin_api_url($path = '', $parameters = [], $secure = null)
{
return '/' . str_replace('/list', '', $path);
}
}
//输出控制台日志
if (!function_exists('p')) {
function p($val, $title = null, $starttime = '')
{
print_r('[ ' . date("Y-m-d H:i:s") . ']:');
if ($title != null) {
print_r("[" . $title . "]:");
}
print_r($val);
print_r("\r\n");
}
}
if (!function_exists('uuid')) {
function uuid($length)
{
if (function_exists('random_bytes')) {
$uuid = bin2hex(\random_bytes($length));
} else if (function_exists('openssl_random_pseudo_bytes')) {
$uuid = bin2hex(\openssl_random_pseudo_bytes($length));
} else {
$pool = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$uuid = substr(str_shuffle(str_repeat($pool, 5)), 0, $length);
}
return $uuid;
}
}
if (!function_exists('route')) {
function route($url, $param = [])
{
if (is_validURL($url)) {
return $url;
}
$prefix = config('admin.route.prefix');
$https = config('admin.https');
$uri = request()->getUri();
$param = http_build_query($param);
if ($https) {
$uri = $uri->withScheme('https');
}
$uri = $uri->withQuery($param);
if (substr($url, 0, 1) !== '/') {
$url = '/' . $prefix . '/' . $url;
}
return $uri->withPath($url)->__toString();
}
}
if (!function_exists('is_validURL')) {
function is_validURL($url)
{
$check = 0;
if (filter_var($url, FILTER_VALIDATE_URL) !== false) {
$check = 1;
}
return $check;
}
}