HighSpeaker/support/helpers.php

529 lines
12 KiB
PHP
Raw Permalink Normal View History

2022-12-17 20:38:00 +08:00
<?php
/**
* This file is part of webman.
*
* Licensed under The MIT License
* For full copyright and license information, please see the MIT-LICENSE.txt
* Redistributions of files must retain the above copyright notice.
*
* @author walkor<walkor@workerman.net>
* @copyright walkor<walkor@workerman.net>
* @link http://www.workerman.net/
* @license http://www.opensource.org/licenses/mit-license.php MIT License
*/
use support\Container;
use support\Request;
use support\Response;
use support\Translation;
use support\view\Blade;
2024-01-31 22:15:08 +08:00
use support\view\Raw;
2022-12-17 20:38:00 +08:00
use support\view\ThinkPHP;
use support\view\Twig;
2024-01-31 22:15:08 +08:00
use Twig\Error\LoaderError;
use Twig\Error\RuntimeError;
use Twig\Error\SyntaxError;
2022-12-17 20:38:00 +08:00
use Webman\App;
use Webman\Config;
use Webman\Route;
2024-01-31 22:15:08 +08:00
use Workerman\Protocols\Http\Session;
use Workerman\Worker;
2022-12-17 20:38:00 +08:00
// Project base path
define('BASE_PATH', dirname(__DIR__));
/**
* return the program execute directory
* @param string $path
* @return string
*/
function run_path(string $path = ''): string
{
2024-01-31 22:15:08 +08:00
static $runPath = '';
if (!$runPath) {
$runPath = is_phar() ? dirname(Phar::running(false)) : BASE_PATH;
2022-12-17 20:38:00 +08:00
}
2024-01-31 22:15:08 +08:00
return path_combine($runPath, $path);
2022-12-17 20:38:00 +08:00
}
/**
* if the param $path equal false,will return this program current execute directory
* @param string|false $path
* @return string
*/
function base_path($path = ''): string
{
if (false === $path) {
2024-01-31 22:15:08 +08:00
return run_path();
2022-12-17 20:38:00 +08:00
}
2024-01-31 22:15:08 +08:00
return path_combine(BASE_PATH, $path);
2022-12-17 20:38:00 +08:00
}
/**
* App path
* @param string $path
* @return string
*/
function app_path(string $path = ''): string
{
2024-01-31 22:15:08 +08:00
return path_combine(BASE_PATH . DIRECTORY_SEPARATOR . 'app', $path);
2022-12-17 20:38:00 +08:00
}
/**
* Public path
* @param string $path
* @return string
*/
function public_path(string $path = ''): string
{
2024-01-31 22:15:08 +08:00
static $publicPath = '';
if (!$publicPath) {
$publicPath = \config('app.public_path') ?: run_path('public');
2022-12-17 20:38:00 +08:00
}
2024-01-31 22:15:08 +08:00
return path_combine($publicPath, $path);
2022-12-17 20:38:00 +08:00
}
/**
* Config path
* @param string $path
* @return string
*/
function config_path(string $path = ''): string
{
2024-01-31 22:15:08 +08:00
return path_combine(BASE_PATH . DIRECTORY_SEPARATOR . 'config', $path);
2022-12-17 20:38:00 +08:00
}
/**
* Runtime path
* @param string $path
* @return string
*/
function runtime_path(string $path = ''): string
{
2024-01-31 22:15:08 +08:00
static $runtimePath = '';
if (!$runtimePath) {
$runtimePath = \config('app.runtime_path') ?: run_path('runtime');
2022-12-17 20:38:00 +08:00
}
2024-01-31 22:15:08 +08:00
return path_combine($runtimePath, $path);
2022-12-17 20:38:00 +08:00
}
/**
* Generate paths based on given information
* @param string $front
* @param string $back
* @return string
*/
function path_combine(string $front, string $back): string
{
return $front . ($back ? (DIRECTORY_SEPARATOR . ltrim($back, DIRECTORY_SEPARATOR)) : $back);
}
/**
* Response
* @param int $status
* @param array $headers
* @param string $body
* @return Response
*/
function response(string $body = '', int $status = 200, array $headers = []): Response
{
return new Response($status, $headers, $body);
}
/**
* Json response
* @param $data
* @param int $options
* @return Response
*/
function json($data, int $options = JSON_UNESCAPED_UNICODE): Response
{
2024-01-31 22:15:08 +08:00
return new Response(200, ['Content-Type' => 'application/json'], json_encode($data, $options));
2022-12-17 20:38:00 +08:00
}
/**
* Xml response
* @param $xml
* @return Response
*/
function xml($xml): Response
{
if ($xml instanceof SimpleXMLElement) {
$xml = $xml->asXML();
}
return new Response(200, ['Content-Type' => 'text/xml'], $xml);
}
/**
* Jsonp response
* @param $data
2024-01-31 22:15:08 +08:00
* @param string $callbackName
2022-12-17 20:38:00 +08:00
* @return Response
*/
2024-01-31 22:15:08 +08:00
function jsonp($data, string $callbackName = 'callback'): Response
2022-12-17 20:38:00 +08:00
{
2024-01-31 22:15:08 +08:00
if (!is_scalar($data) && null !== $data) {
$data = json_encode($data);
2022-12-17 20:38:00 +08:00
}
2024-01-31 22:15:08 +08:00
return new Response(200, [], "$callbackName($data)");
2022-12-17 20:38:00 +08:00
}
/**
* Redirect response
* @param string $location
* @param int $status
* @param array $headers
* @return Response
*/
function redirect(string $location, int $status = 302, array $headers = []): Response
{
$response = new Response($status, ['Location' => $location]);
if (!empty($headers)) {
$response->withHeaders($headers);
}
return $response;
}
/**
* View response
* @param string $template
* @param array $vars
* @param string|null $app
2024-01-31 22:15:08 +08:00
* @param string|null $plugin
2022-12-17 20:38:00 +08:00
* @return Response
*/
2024-01-31 22:15:08 +08:00
function view(string $template, array $vars = [], string $app = null, string $plugin = null): Response
2022-12-17 20:38:00 +08:00
{
$request = \request();
2024-01-31 22:15:08 +08:00
$plugin = $plugin === null ? ($request->plugin ?? '') : $plugin;
2022-12-17 20:38:00 +08:00
$handler = \config($plugin ? "plugin.$plugin.view.handler" : 'view.handler');
2024-01-31 22:15:08 +08:00
return new Response(200, [], $handler::render($template, $vars, $app, $plugin));
2022-12-17 20:38:00 +08:00
}
/**
* Raw view response
* @param string $template
* @param array $vars
* @param string|null $app
* @return Response
* @throws Throwable
*/
function raw_view(string $template, array $vars = [], string $app = null): Response
{
return new Response(200, [], Raw::render($template, $vars, $app));
}
/**
* Blade view response
* @param string $template
* @param array $vars
* @param string|null $app
* @return Response
*/
function blade_view(string $template, array $vars = [], string $app = null): Response
{
return new Response(200, [], Blade::render($template, $vars, $app));
}
/**
* Think view response
* @param string $template
* @param array $vars
* @param string|null $app
* @return Response
*/
function think_view(string $template, array $vars = [], string $app = null): Response
{
return new Response(200, [], ThinkPHP::render($template, $vars, $app));
}
/**
* Twig view response
* @param string $template
* @param array $vars
* @param string|null $app
* @return Response
2024-01-31 22:15:08 +08:00
* @throws LoaderError
* @throws RuntimeError
* @throws SyntaxError
2022-12-17 20:38:00 +08:00
*/
function twig_view(string $template, array $vars = [], string $app = null): Response
{
return new Response(200, [], Twig::render($template, $vars, $app));
}
/**
* Get request
* @return \Webman\Http\Request|Request|null
*/
function request()
{
return App::request();
}
/**
* Get config
* @param string|null $key
* @param $default
* @return array|mixed|null
*/
function config(string $key = null, $default = null)
{
return Config::get($key, $default);
}
/**
* Create url
* @param string $name
* @param ...$parameters
* @return string
*/
function route(string $name, ...$parameters): string
{
$route = Route::getByName($name);
if (!$route) {
return '';
}
if (!$parameters) {
return $route->url();
}
2024-01-31 22:15:08 +08:00
if (is_array(current($parameters))) {
$parameters = current($parameters);
2022-12-17 20:38:00 +08:00
}
return $route->url($parameters);
}
/**
* Session
* @param mixed $key
* @param mixed $default
2024-01-31 22:15:08 +08:00
* @return mixed|bool|Session
2022-12-17 20:38:00 +08:00
*/
function session($key = null, $default = null)
{
$session = \request()->session();
if (null === $key) {
return $session;
}
2024-01-31 22:15:08 +08:00
if (is_array($key)) {
2022-12-17 20:38:00 +08:00
$session->put($key);
return null;
}
2024-01-31 22:15:08 +08:00
if (strpos($key, '.')) {
$keyArray = explode('.', $key);
2022-12-17 20:38:00 +08:00
$value = $session->all();
2024-01-31 22:15:08 +08:00
foreach ($keyArray as $index) {
2022-12-17 20:38:00 +08:00
if (!isset($value[$index])) {
return $default;
}
$value = $value[$index];
}
return $value;
}
return $session->get($key, $default);
}
/**
* Translation
* @param string $id
* @param array $parameters
* @param string|null $domain
* @param string|null $locale
* @return string
*/
function trans(string $id, array $parameters = [], string $domain = null, string $locale = null): string
{
$res = Translation::trans($id, $parameters, $domain, $locale);
return $res === '' ? $id : $res;
}
/**
* Locale
* @param string|null $locale
2024-01-31 22:15:08 +08:00
* @return string
2022-12-17 20:38:00 +08:00
*/
function locale(string $locale = null): string
{
if (!$locale) {
return Translation::getLocale();
}
Translation::setLocale($locale);
2024-01-31 22:15:08 +08:00
return $locale;
2022-12-17 20:38:00 +08:00
}
/**
* 404 not found
* @return Response
*/
function not_found(): Response
{
2024-01-31 22:15:08 +08:00
return new Response(404, [], file_get_contents(public_path() . '/404.html'));
2022-12-17 20:38:00 +08:00
}
/**
* Copy dir
* @param string $source
* @param string $dest
* @param bool $overwrite
* @return void
*/
function copy_dir(string $source, string $dest, bool $overwrite = false)
{
2024-01-31 22:15:08 +08:00
if (is_dir($source)) {
2022-12-17 20:38:00 +08:00
if (!is_dir($dest)) {
2024-01-31 22:15:08 +08:00
mkdir($dest);
2022-12-17 20:38:00 +08:00
}
2024-01-31 22:15:08 +08:00
$files = scandir($source);
2022-12-17 20:38:00 +08:00
foreach ($files as $file) {
if ($file !== "." && $file !== "..") {
2024-01-31 22:15:08 +08:00
copy_dir("$source/$file", "$dest/$file", $overwrite);
2022-12-17 20:38:00 +08:00
}
}
2024-01-31 22:15:08 +08:00
} else if (file_exists($source) && ($overwrite || !file_exists($dest))) {
copy($source, $dest);
2022-12-17 20:38:00 +08:00
}
}
/**
* Remove dir
* @param string $dir
* @return bool
*/
function remove_dir(string $dir): bool
{
2024-01-31 22:15:08 +08:00
if (is_link($dir) || is_file($dir)) {
return unlink($dir);
2022-12-17 20:38:00 +08:00
}
2024-01-31 22:15:08 +08:00
$files = array_diff(scandir($dir), array('.', '..'));
2022-12-17 20:38:00 +08:00
foreach ($files as $file) {
2024-01-31 22:15:08 +08:00
(is_dir("$dir/$file") && !is_link($dir)) ? remove_dir("$dir/$file") : unlink("$dir/$file");
2022-12-17 20:38:00 +08:00
}
2024-01-31 22:15:08 +08:00
return rmdir($dir);
2022-12-17 20:38:00 +08:00
}
/**
* Bind worker
* @param $worker
* @param $class
*/
function worker_bind($worker, $class)
{
2024-01-31 22:15:08 +08:00
$callbackMap = [
2022-12-17 20:38:00 +08:00
'onConnect',
'onMessage',
'onClose',
'onError',
'onBufferFull',
'onBufferDrain',
'onWorkerStop',
2024-01-31 22:15:08 +08:00
'onWebSocketConnect',
'onWorkerReload'
2022-12-17 20:38:00 +08:00
];
2024-01-31 22:15:08 +08:00
foreach ($callbackMap as $name) {
if (method_exists($class, $name)) {
2022-12-17 20:38:00 +08:00
$worker->$name = [$class, $name];
}
}
2024-01-31 22:15:08 +08:00
if (method_exists($class, 'onWorkerStart')) {
call_user_func([$class, 'onWorkerStart'], $worker);
2022-12-17 20:38:00 +08:00
}
}
/**
* Start worker
2024-01-31 22:15:08 +08:00
* @param $processName
2022-12-17 20:38:00 +08:00
* @param $config
* @return void
*/
2024-01-31 22:15:08 +08:00
function worker_start($processName, $config)
2022-12-17 20:38:00 +08:00
{
$worker = new Worker($config['listen'] ?? null, $config['context'] ?? []);
2024-01-31 22:15:08 +08:00
$propertyMap = [
2022-12-17 20:38:00 +08:00
'count',
'user',
'group',
'reloadable',
'reusePort',
'transport',
'protocol',
];
2024-01-31 22:15:08 +08:00
$worker->name = $processName;
foreach ($propertyMap as $property) {
2022-12-17 20:38:00 +08:00
if (isset($config[$property])) {
$worker->$property = $config[$property];
}
}
$worker->onWorkerStart = function ($worker) use ($config) {
2024-01-31 22:15:08 +08:00
require_once base_path('/support/bootstrap.php');
2022-12-17 20:38:00 +08:00
if (isset($config['handler'])) {
2024-01-31 22:15:08 +08:00
if (!class_exists($config['handler'])) {
2022-12-17 20:38:00 +08:00
echo "process error: class {$config['handler']} not exists\r\n";
return;
}
$instance = Container::make($config['handler'], $config['constructor'] ?? []);
2024-01-31 22:15:08 +08:00
worker_bind($worker, $instance);
2022-12-17 20:38:00 +08:00
}
};
}
/**
* Get realpath
2024-01-31 22:15:08 +08:00
* @param string $filePath
2022-12-17 20:38:00 +08:00
* @return string
*/
2024-01-31 22:15:08 +08:00
function get_realpath(string $filePath): string
2022-12-17 20:38:00 +08:00
{
2024-01-31 22:15:08 +08:00
if (strpos($filePath, 'phar://') === 0) {
return $filePath;
2022-12-17 20:38:00 +08:00
} else {
2024-01-31 22:15:08 +08:00
return realpath($filePath);
2022-12-17 20:38:00 +08:00
}
}
/**
* Is phar
* @return bool
*/
function is_phar(): bool
{
2024-01-31 22:15:08 +08:00
return class_exists(Phar::class, false) && Phar::running();
2022-12-17 20:38:00 +08:00
}
/**
* Get cpu count
* @return int
*/
function cpu_count(): int
{
// Windows does not support the number of processes setting.
2024-01-31 22:15:08 +08:00
if (DIRECTORY_SEPARATOR === '\\') {
2022-12-17 20:38:00 +08:00
return 1;
}
$count = 4;
2024-01-31 22:15:08 +08:00
if (is_callable('shell_exec')) {
if (strtolower(PHP_OS) === 'darwin') {
$count = (int)shell_exec('sysctl -n machdep.cpu.core_count');
2022-12-17 20:38:00 +08:00
} else {
2024-01-31 22:15:08 +08:00
$count = (int)shell_exec('nproc');
2022-12-17 20:38:00 +08:00
}
}
return $count > 0 ? $count : 4;
}
2024-01-31 22:15:08 +08:00
/**
* Get request parameters, if no parameter name is passed, an array of all values is returned, default values is supported
* @param string|null $param param's name
* @param mixed|null $default default value
* @return mixed|null
*/
function input(string $param = null, $default = null)
{
return is_null($param) ? request()->all() : request()->input($param, $default);
}