helpers.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680
  1. <?php
  2. /**
  3. * This file is part of webman.
  4. *
  5. * Licensed under The MIT License
  6. * For full copyright and license information, please see the MIT-LICENSE.txt
  7. * Redistributions of files must retain the above copyright notice.
  8. *
  9. * @author walkor<walkor@workerman.net>
  10. * @copyright walkor<walkor@workerman.net>
  11. * @link http://www.workerman.net/
  12. * @license http://www.opensource.org/licenses/mit-license.php MIT License
  13. */
  14. use support\Container;
  15. use support\Request;
  16. use support\Response;
  17. use support\Translation;
  18. use support\view\Blade;
  19. use support\view\Raw;
  20. use support\view\ThinkPHP;
  21. use support\view\Twig;
  22. use Twig\Error\LoaderError;
  23. use Twig\Error\RuntimeError;
  24. use Twig\Error\SyntaxError;
  25. use Webman\App;
  26. use Webman\Config;
  27. use Webman\Route;
  28. use Workerman\Protocols\Http\Session;
  29. use Workerman\Worker;
  30. // Project base path
  31. define('BASE_PATH', dirname(__DIR__));
  32. /**
  33. * return the program execute directory
  34. * @param string $path
  35. * @return string
  36. */
  37. function run_path(string $path = ''): string
  38. {
  39. static $runPath = '';
  40. if (!$runPath) {
  41. $runPath = is_phar() ? dirname(Phar::running(false)) : BASE_PATH;
  42. }
  43. return path_combine($runPath, $path);
  44. }
  45. /**
  46. * if the param $path equal false,will return this program current execute directory
  47. * @param string|false $path
  48. * @return string
  49. */
  50. function base_path($path = ''): string
  51. {
  52. if (false === $path) {
  53. return run_path();
  54. }
  55. return path_combine(BASE_PATH, $path);
  56. }
  57. /**
  58. * App path
  59. * @param string $path
  60. * @return string
  61. */
  62. function app_path(string $path = ''): string
  63. {
  64. return path_combine(BASE_PATH . DIRECTORY_SEPARATOR . 'app', $path);
  65. }
  66. /**
  67. * Public path
  68. * @param string $path
  69. * @return string
  70. */
  71. function public_path(string $path = ''): string
  72. {
  73. static $publicPath = '';
  74. if (!$publicPath) {
  75. $publicPath = \config('app.public_path') ?: run_path('public');
  76. }
  77. return path_combine($publicPath, $path);
  78. }
  79. /**
  80. * Config path
  81. * @param string $path
  82. * @return string
  83. */
  84. function config_path(string $path = ''): string
  85. {
  86. return path_combine(BASE_PATH . DIRECTORY_SEPARATOR . 'config', $path);
  87. }
  88. /**
  89. * Runtime path
  90. * @param string $path
  91. * @return string
  92. */
  93. function runtime_path(string $path = ''): string
  94. {
  95. static $runtimePath = '';
  96. if (!$runtimePath) {
  97. $runtimePath = \config('app.runtime_path') ?: run_path('runtime');
  98. }
  99. return path_combine($runtimePath, $path);
  100. }
  101. /**
  102. * Generate paths based on given information
  103. * @param string $front
  104. * @param string $back
  105. * @return string
  106. */
  107. function path_combine(string $front, string $back): string
  108. {
  109. return $front . ($back ? (DIRECTORY_SEPARATOR . ltrim($back, DIRECTORY_SEPARATOR)) : $back);
  110. }
  111. /**
  112. * Response
  113. * @param int $status
  114. * @param array $headers
  115. * @param string $body
  116. * @return Response
  117. */
  118. function response(string $body = '', int $status = 200, array $headers = []): Response
  119. {
  120. return new Response($status, $headers, $body);
  121. }
  122. /**
  123. * Json response
  124. * @param $data
  125. * @param int $options
  126. * @return Response
  127. */
  128. function json($data, int $options = JSON_UNESCAPED_UNICODE): Response
  129. {
  130. return new Response(200, ['Content-Type' => 'application/json'], json_encode($data, $options));
  131. }
  132. function json_success($message, $data = '', $options = JSON_UNESCAPED_UNICODE)
  133. {
  134. // ini_set('json_encode_max_depth', 1024); // 设置最大深度
  135. // ini_set('json_encode_max_int_length', 4096); // 设置最大整数长度
  136. // ini_set('json_encode_max_other_length', 4096); // 设置其他类型值的最大长度
  137. \support\Log::info("开始打包返回数据");
  138. $return = [
  139. 'code' => 200,
  140. 'message' => $message,
  141. 'data' => $data,
  142. ];
  143. \support\Log::info("返回数据打包完成");
  144. return new Response(200, ['Content-Type' => 'application/json'], json_encode($return, $options,4096));
  145. }
  146. function json_fail($message, $options = JSON_UNESCAPED_UNICODE)
  147. {
  148. $return = [
  149. 'code' => 0,
  150. 'message' => $message,
  151. 'data' => ''
  152. ];
  153. return new Response(200, ['Content-Type' => 'application/json'], json_encode($return, $options));
  154. }
  155. function format_string($string)
  156. {
  157. return htmlspecialchars(strip_tags($string));
  158. }
  159. /**
  160. * Xml response
  161. * @param $xml
  162. * @return Response
  163. */
  164. function xml($xml): Response
  165. {
  166. if ($xml instanceof SimpleXMLElement) {
  167. $xml = $xml->asXML();
  168. }
  169. return new Response(200, ['Content-Type' => 'text/xml'], $xml);
  170. }
  171. /**
  172. * Jsonp response
  173. * @param $data
  174. * @param string $callbackName
  175. * @return Response
  176. */
  177. function jsonp($data, string $callbackName = 'callback'): Response
  178. {
  179. if (!is_scalar($data) && null !== $data) {
  180. $data = json_encode($data);
  181. }
  182. return new Response(200, [], "$callbackName($data)");
  183. }
  184. /**
  185. * Redirect response
  186. * @param string $location
  187. * @param int $status
  188. * @param array $headers
  189. * @return Response
  190. */
  191. function redirect(string $location, int $status = 302, array $headers = []): Response
  192. {
  193. $response = new Response($status, ['Location' => $location]);
  194. if (!empty($headers)) {
  195. $response->withHeaders($headers);
  196. }
  197. return $response;
  198. }
  199. /**
  200. * View response
  201. * @param string $template
  202. * @param array $vars
  203. * @param string|null $app
  204. * @param string|null $plugin
  205. * @return Response
  206. */
  207. function view(string $template, array $vars = [], string $app = null, string $plugin = null): Response
  208. {
  209. $request = \request();
  210. $plugin = $plugin === null ? ($request->plugin ?? '') : $plugin;
  211. $handler = \config($plugin ? "plugin.$plugin.view.handler" : 'view.handler');
  212. return new Response(200, [], $handler::render($template, $vars, $app, $plugin));
  213. }
  214. /**
  215. * Raw view response
  216. * @param string $template
  217. * @param array $vars
  218. * @param string|null $app
  219. * @return Response
  220. * @throws Throwable
  221. */
  222. function raw_view(string $template, array $vars = [], string $app = null): Response
  223. {
  224. return new Response(200, [], Raw::render($template, $vars, $app));
  225. }
  226. /**
  227. * Blade view response
  228. * @param string $template
  229. * @param array $vars
  230. * @param string|null $app
  231. * @return Response
  232. */
  233. function blade_view(string $template, array $vars = [], string $app = null): Response
  234. {
  235. return new Response(200, [], Blade::render($template, $vars, $app));
  236. }
  237. /**
  238. * Think view response
  239. * @param string $template
  240. * @param array $vars
  241. * @param string|null $app
  242. * @return Response
  243. */
  244. function think_view(string $template, array $vars = [], string $app = null): Response
  245. {
  246. return new Response(200, [], ThinkPHP::render($template, $vars, $app));
  247. }
  248. /**
  249. * Twig view response
  250. * @param string $template
  251. * @param array $vars
  252. * @param string|null $app
  253. * @return Response
  254. * @throws LoaderError
  255. * @throws RuntimeError
  256. * @throws SyntaxError
  257. */
  258. function twig_view(string $template, array $vars = [], string $app = null): Response
  259. {
  260. return new Response(200, [], Twig::render($template, $vars, $app));
  261. }
  262. /**
  263. * Get request
  264. * @return \Webman\Http\Request|Request|null
  265. */
  266. function request()
  267. {
  268. return App::request();
  269. }
  270. /**
  271. * Get config
  272. * @param string|null $key
  273. * @param $default
  274. * @return array|mixed|null
  275. */
  276. function config(string $key = null, $default = null)
  277. {
  278. return Config::get($key, $default);
  279. }
  280. /**
  281. * Create url
  282. * @param string $name
  283. * @param ...$parameters
  284. * @return string
  285. */
  286. function route(string $name, ...$parameters): string
  287. {
  288. $route = Route::getByName($name);
  289. if (!$route) {
  290. return '';
  291. }
  292. if (!$parameters) {
  293. return $route->url();
  294. }
  295. if (is_array(current($parameters))) {
  296. $parameters = current($parameters);
  297. }
  298. return $route->url($parameters);
  299. }
  300. /**
  301. * Session
  302. * @param mixed $key
  303. * @param mixed $default
  304. * @return mixed|bool|Session
  305. */
  306. function session($key = null, $default = null)
  307. {
  308. $session = \request()->session();
  309. if (null === $key) {
  310. return $session;
  311. }
  312. if (is_array($key)) {
  313. $session->put($key);
  314. return null;
  315. }
  316. if (strpos($key, '.')) {
  317. $keyArray = explode('.', $key);
  318. $value = $session->all();
  319. foreach ($keyArray as $index) {
  320. if (!isset($value[$index])) {
  321. return $default;
  322. }
  323. $value = $value[$index];
  324. }
  325. return $value;
  326. }
  327. return $session->get($key, $default);
  328. }
  329. /**
  330. * Translation
  331. * @param string $id
  332. * @param array $parameters
  333. * @param string|null $domain
  334. * @param string|null $locale
  335. * @return string
  336. */
  337. function trans(string $id, array $parameters = [], string $domain = null, string $locale = null): string
  338. {
  339. $res = Translation::trans($id, $parameters, $domain, $locale);
  340. return $res === '' ? $id : $res;
  341. }
  342. /**
  343. * Locale
  344. * @param string|null $locale
  345. * @return string
  346. */
  347. function locale(string $locale = null): string
  348. {
  349. if (!$locale) {
  350. return Translation::getLocale();
  351. }
  352. Translation::setLocale($locale);
  353. return $locale;
  354. }
  355. /**
  356. * 404 not found
  357. * @return Response
  358. */
  359. function not_found(): Response
  360. {
  361. return new Response(404, [], file_get_contents(public_path() . '/404.html'));
  362. }
  363. /**
  364. * Copy dir
  365. * @param string $source
  366. * @param string $dest
  367. * @param bool $overwrite
  368. * @return void
  369. */
  370. function copy_dir(string $source, string $dest, bool $overwrite = false)
  371. {
  372. if (is_dir($source)) {
  373. if (!is_dir($dest)) {
  374. mkdir($dest);
  375. }
  376. $files = scandir($source);
  377. foreach ($files as $file) {
  378. if ($file !== "." && $file !== "..") {
  379. copy_dir("$source/$file", "$dest/$file", $overwrite);
  380. }
  381. }
  382. } else if (file_exists($source) && ($overwrite || !file_exists($dest))) {
  383. copy($source, $dest);
  384. }
  385. }
  386. /**
  387. * Remove dir
  388. * @param string $dir
  389. * @return bool
  390. */
  391. function remove_dir(string $dir): bool
  392. {
  393. if (is_link($dir) || is_file($dir)) {
  394. return unlink($dir);
  395. }
  396. $files = array_diff(scandir($dir), array('.', '..'));
  397. foreach ($files as $file) {
  398. (is_dir("$dir/$file") && !is_link($dir)) ? remove_dir("$dir/$file") : unlink("$dir/$file");
  399. }
  400. return rmdir($dir);
  401. }
  402. /**
  403. * Bind worker
  404. * @param $worker
  405. * @param $class
  406. */
  407. function worker_bind($worker, $class)
  408. {
  409. $callbackMap = [
  410. 'onConnect',
  411. 'onMessage',
  412. 'onClose',
  413. 'onError',
  414. 'onBufferFull',
  415. 'onBufferDrain',
  416. 'onWorkerStop',
  417. 'onWebSocketConnect',
  418. 'onWorkerReload'
  419. ];
  420. foreach ($callbackMap as $name) {
  421. if (method_exists($class, $name)) {
  422. $worker->$name = [$class, $name];
  423. }
  424. }
  425. if (method_exists($class, 'onWorkerStart')) {
  426. call_user_func([$class, 'onWorkerStart'], $worker);
  427. }
  428. }
  429. /**
  430. * Start worker
  431. * @param $processName
  432. * @param $config
  433. * @return void
  434. */
  435. function worker_start($processName, $config)
  436. {
  437. $worker = new Worker($config['listen'] ?? null, $config['context'] ?? []);
  438. $propertyMap = [
  439. 'count',
  440. 'user',
  441. 'group',
  442. 'reloadable',
  443. 'reusePort',
  444. 'transport',
  445. 'protocol',
  446. ];
  447. $worker->name = $processName;
  448. foreach ($propertyMap as $property) {
  449. if (isset($config[$property])) {
  450. $worker->$property = $config[$property];
  451. }
  452. }
  453. $worker->onWorkerStart = function ($worker) use ($config) {
  454. require_once base_path('/support/bootstrap.php');
  455. if (isset($config['handler'])) {
  456. if (!class_exists($config['handler'])) {
  457. echo "process error: class {$config['handler']} not exists\r\n";
  458. return;
  459. }
  460. $instance = Container::make($config['handler'], $config['constructor'] ?? []);
  461. worker_bind($worker, $instance);
  462. }
  463. };
  464. }
  465. /**
  466. * Get realpath
  467. * @param string $filePath
  468. * @return string
  469. */
  470. function get_realpath(string $filePath): string
  471. {
  472. if (strpos($filePath, 'phar://') === 0) {
  473. return $filePath;
  474. } else {
  475. return realpath($filePath);
  476. }
  477. }
  478. /**
  479. * Is phar
  480. * @return bool
  481. */
  482. function is_phar(): bool
  483. {
  484. return class_exists(Phar::class, false) && Phar::running();
  485. }
  486. /**
  487. * Get cpu count
  488. * @return int
  489. */
  490. function cpu_count(): int
  491. {
  492. // Windows does not support the number of processes setting.
  493. if (DIRECTORY_SEPARATOR === '\\') {
  494. return 1;
  495. }
  496. $count = 4;
  497. if (is_callable('shell_exec')) {
  498. if (strtolower(PHP_OS) === 'darwin') {
  499. $count = (int)shell_exec('sysctl -n machdep.cpu.core_count');
  500. } else {
  501. $count = (int)shell_exec('nproc');
  502. }
  503. }
  504. return $count > 0 ? $count : 4;
  505. }
  506. /**
  507. * Get request parameters, if no parameter name is passed, an array of all values is returned, default values is supported
  508. * @param string|null $param param's name
  509. * @param mixed|null $default default value
  510. * @return mixed|null
  511. */
  512. function input(string $param = null, $default = null)
  513. {
  514. return is_null($param) ? request()->all() : request()->input($param, $default);
  515. }
  516. function random_string($length, $type = 'all')
  517. {
  518. $string = 'abcdefghijklmnopqrstuvwxyz';
  519. $stringUp = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
  520. $number = '0123456789';
  521. switch ($type) {
  522. case 'all':
  523. $result = $string . $number;
  524. break;
  525. case 'string':
  526. $result = $string;
  527. break;
  528. case 'up':
  529. $result = $stringUp . $number;
  530. break;
  531. case 'number':
  532. $result = $number;
  533. break;
  534. default:
  535. $result = '';
  536. break;
  537. }
  538. $return = '';
  539. $totalLength = strlen($result);
  540. for ($i = 0; $i < $length; $i++) {
  541. $return .= $result[mt_rand(0, $totalLength - 1)];
  542. }
  543. return $return;
  544. }
  545. /**
  546. * @Desc 验证是否是json数据
  547. * @Author Gorden
  548. * @Date 2024/2/22 15:37
  549. *
  550. * @param $string
  551. * @return bool
  552. */
  553. function is_json($string)
  554. {
  555. if (!is_string($string)) {
  556. return false;
  557. }
  558. json_decode($string);
  559. if (json_last_error() === JSON_ERROR_NONE) {
  560. return true;
  561. }
  562. return false;
  563. }
  564. /**
  565. * @Desc 周几-汉字
  566. * @Author Gorden
  567. * @Date 2024/3/5 17:29
  568. *
  569. * @param $week
  570. * @return string
  571. */
  572. function chinese_week($week)
  573. {
  574. $weekArray = ['日', '一', '二', '三', '四', '五', '六'];
  575. return '周' . $weekArray[$week];
  576. }
  577. /**
  578. * @Desc 颜色值转RGB
  579. * @Author Gorden
  580. * @Date 2024/5/15 17:22
  581. *
  582. * @param $hexColor
  583. * @return mixed
  584. */
  585. function hexToRgb($hexColor, $type = "string")
  586. {
  587. // 使用substr函数去掉前缀的'#'
  588. $hexColor = ltrim($hexColor, '#');
  589. // 使用hexdec函数将十六进制转换为十进制
  590. $red = hexdec(substr($hexColor, 0, 2));
  591. $green = hexdec(substr($hexColor, 2, 2));
  592. $blue = hexdec(substr($hexColor, 4, 2));
  593. if ($type == "string") {
  594. // rgb(46, 209, 153)
  595. return "rgb(" . $red . ", " . $green . ", " . $blue . ")";
  596. }
  597. return array('red' => $red, 'green' => $green, 'blue' => $blue);
  598. }
  599. function rgbToHex($rgb)
  600. {
  601. if (substr($rgb, 0, 3) == 'rgb') {
  602. $rgb = str_replace("rgb(", '', $rgb);
  603. $rgb = str_replace(")", "", $rgb);
  604. [$red, $green, $blue] = explode(',', $rgb);
  605. $hexRed = dechex($red);
  606. $hexGreen = dechex($green);
  607. $hexBlue = dechex($blue);
  608. // 如果颜色分量不足两位,前面补零
  609. $hexRed = strlen($hexRed) == 1 ? '0' . $hexRed : $hexRed;
  610. $hexGreen = strlen($hexGreen) == 1 ? '0' . $hexGreen : $hexGreen;
  611. $hexBlue = strlen($hexBlue) == 1 ? '0' . $hexBlue : $hexBlue;
  612. return "#" . $hexRed. $hexGreen. $hexBlue;
  613. }
  614. return "";
  615. }