helpers.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677
  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. \support\Log::info("开始打包返回数据");
  135. $return = [
  136. 'code' => 200,
  137. 'message' => $message,
  138. 'data' => $data,
  139. ];
  140. \support\Log::info("返回数据打包完成");
  141. dump(new Response(200, ['Content-Type' => 'application/json'], json_encode($return, $options)));
  142. return new Response(200, ['Content-Type' => 'application/json'], json_encode($return, $options));
  143. }
  144. function json_fail($message, $options = JSON_UNESCAPED_UNICODE)
  145. {
  146. $return = [
  147. 'code' => 0,
  148. 'message' => $message,
  149. 'data' => ''
  150. ];
  151. return new Response(200, ['Content-Type' => 'application/json'], json_encode($return, $options));
  152. }
  153. function format_string($string)
  154. {
  155. return htmlspecialchars(strip_tags($string));
  156. }
  157. /**
  158. * Xml response
  159. * @param $xml
  160. * @return Response
  161. */
  162. function xml($xml): Response
  163. {
  164. if ($xml instanceof SimpleXMLElement) {
  165. $xml = $xml->asXML();
  166. }
  167. return new Response(200, ['Content-Type' => 'text/xml'], $xml);
  168. }
  169. /**
  170. * Jsonp response
  171. * @param $data
  172. * @param string $callbackName
  173. * @return Response
  174. */
  175. function jsonp($data, string $callbackName = 'callback'): Response
  176. {
  177. if (!is_scalar($data) && null !== $data) {
  178. $data = json_encode($data);
  179. }
  180. return new Response(200, [], "$callbackName($data)");
  181. }
  182. /**
  183. * Redirect response
  184. * @param string $location
  185. * @param int $status
  186. * @param array $headers
  187. * @return Response
  188. */
  189. function redirect(string $location, int $status = 302, array $headers = []): Response
  190. {
  191. $response = new Response($status, ['Location' => $location]);
  192. if (!empty($headers)) {
  193. $response->withHeaders($headers);
  194. }
  195. return $response;
  196. }
  197. /**
  198. * View response
  199. * @param string $template
  200. * @param array $vars
  201. * @param string|null $app
  202. * @param string|null $plugin
  203. * @return Response
  204. */
  205. function view(string $template, array $vars = [], string $app = null, string $plugin = null): Response
  206. {
  207. $request = \request();
  208. $plugin = $plugin === null ? ($request->plugin ?? '') : $plugin;
  209. $handler = \config($plugin ? "plugin.$plugin.view.handler" : 'view.handler');
  210. return new Response(200, [], $handler::render($template, $vars, $app, $plugin));
  211. }
  212. /**
  213. * Raw view response
  214. * @param string $template
  215. * @param array $vars
  216. * @param string|null $app
  217. * @return Response
  218. * @throws Throwable
  219. */
  220. function raw_view(string $template, array $vars = [], string $app = null): Response
  221. {
  222. return new Response(200, [], Raw::render($template, $vars, $app));
  223. }
  224. /**
  225. * Blade view response
  226. * @param string $template
  227. * @param array $vars
  228. * @param string|null $app
  229. * @return Response
  230. */
  231. function blade_view(string $template, array $vars = [], string $app = null): Response
  232. {
  233. return new Response(200, [], Blade::render($template, $vars, $app));
  234. }
  235. /**
  236. * Think view response
  237. * @param string $template
  238. * @param array $vars
  239. * @param string|null $app
  240. * @return Response
  241. */
  242. function think_view(string $template, array $vars = [], string $app = null): Response
  243. {
  244. return new Response(200, [], ThinkPHP::render($template, $vars, $app));
  245. }
  246. /**
  247. * Twig view response
  248. * @param string $template
  249. * @param array $vars
  250. * @param string|null $app
  251. * @return Response
  252. * @throws LoaderError
  253. * @throws RuntimeError
  254. * @throws SyntaxError
  255. */
  256. function twig_view(string $template, array $vars = [], string $app = null): Response
  257. {
  258. return new Response(200, [], Twig::render($template, $vars, $app));
  259. }
  260. /**
  261. * Get request
  262. * @return \Webman\Http\Request|Request|null
  263. */
  264. function request()
  265. {
  266. return App::request();
  267. }
  268. /**
  269. * Get config
  270. * @param string|null $key
  271. * @param $default
  272. * @return array|mixed|null
  273. */
  274. function config(string $key = null, $default = null)
  275. {
  276. return Config::get($key, $default);
  277. }
  278. /**
  279. * Create url
  280. * @param string $name
  281. * @param ...$parameters
  282. * @return string
  283. */
  284. function route(string $name, ...$parameters): string
  285. {
  286. $route = Route::getByName($name);
  287. if (!$route) {
  288. return '';
  289. }
  290. if (!$parameters) {
  291. return $route->url();
  292. }
  293. if (is_array(current($parameters))) {
  294. $parameters = current($parameters);
  295. }
  296. return $route->url($parameters);
  297. }
  298. /**
  299. * Session
  300. * @param mixed $key
  301. * @param mixed $default
  302. * @return mixed|bool|Session
  303. */
  304. function session($key = null, $default = null)
  305. {
  306. $session = \request()->session();
  307. if (null === $key) {
  308. return $session;
  309. }
  310. if (is_array($key)) {
  311. $session->put($key);
  312. return null;
  313. }
  314. if (strpos($key, '.')) {
  315. $keyArray = explode('.', $key);
  316. $value = $session->all();
  317. foreach ($keyArray as $index) {
  318. if (!isset($value[$index])) {
  319. return $default;
  320. }
  321. $value = $value[$index];
  322. }
  323. return $value;
  324. }
  325. return $session->get($key, $default);
  326. }
  327. /**
  328. * Translation
  329. * @param string $id
  330. * @param array $parameters
  331. * @param string|null $domain
  332. * @param string|null $locale
  333. * @return string
  334. */
  335. function trans(string $id, array $parameters = [], string $domain = null, string $locale = null): string
  336. {
  337. $res = Translation::trans($id, $parameters, $domain, $locale);
  338. return $res === '' ? $id : $res;
  339. }
  340. /**
  341. * Locale
  342. * @param string|null $locale
  343. * @return string
  344. */
  345. function locale(string $locale = null): string
  346. {
  347. if (!$locale) {
  348. return Translation::getLocale();
  349. }
  350. Translation::setLocale($locale);
  351. return $locale;
  352. }
  353. /**
  354. * 404 not found
  355. * @return Response
  356. */
  357. function not_found(): Response
  358. {
  359. return new Response(404, [], file_get_contents(public_path() . '/404.html'));
  360. }
  361. /**
  362. * Copy dir
  363. * @param string $source
  364. * @param string $dest
  365. * @param bool $overwrite
  366. * @return void
  367. */
  368. function copy_dir(string $source, string $dest, bool $overwrite = false)
  369. {
  370. if (is_dir($source)) {
  371. if (!is_dir($dest)) {
  372. mkdir($dest);
  373. }
  374. $files = scandir($source);
  375. foreach ($files as $file) {
  376. if ($file !== "." && $file !== "..") {
  377. copy_dir("$source/$file", "$dest/$file", $overwrite);
  378. }
  379. }
  380. } else if (file_exists($source) && ($overwrite || !file_exists($dest))) {
  381. copy($source, $dest);
  382. }
  383. }
  384. /**
  385. * Remove dir
  386. * @param string $dir
  387. * @return bool
  388. */
  389. function remove_dir(string $dir): bool
  390. {
  391. if (is_link($dir) || is_file($dir)) {
  392. return unlink($dir);
  393. }
  394. $files = array_diff(scandir($dir), array('.', '..'));
  395. foreach ($files as $file) {
  396. (is_dir("$dir/$file") && !is_link($dir)) ? remove_dir("$dir/$file") : unlink("$dir/$file");
  397. }
  398. return rmdir($dir);
  399. }
  400. /**
  401. * Bind worker
  402. * @param $worker
  403. * @param $class
  404. */
  405. function worker_bind($worker, $class)
  406. {
  407. $callbackMap = [
  408. 'onConnect',
  409. 'onMessage',
  410. 'onClose',
  411. 'onError',
  412. 'onBufferFull',
  413. 'onBufferDrain',
  414. 'onWorkerStop',
  415. 'onWebSocketConnect',
  416. 'onWorkerReload'
  417. ];
  418. foreach ($callbackMap as $name) {
  419. if (method_exists($class, $name)) {
  420. $worker->$name = [$class, $name];
  421. }
  422. }
  423. if (method_exists($class, 'onWorkerStart')) {
  424. call_user_func([$class, 'onWorkerStart'], $worker);
  425. }
  426. }
  427. /**
  428. * Start worker
  429. * @param $processName
  430. * @param $config
  431. * @return void
  432. */
  433. function worker_start($processName, $config)
  434. {
  435. $worker = new Worker($config['listen'] ?? null, $config['context'] ?? []);
  436. $propertyMap = [
  437. 'count',
  438. 'user',
  439. 'group',
  440. 'reloadable',
  441. 'reusePort',
  442. 'transport',
  443. 'protocol',
  444. ];
  445. $worker->name = $processName;
  446. foreach ($propertyMap as $property) {
  447. if (isset($config[$property])) {
  448. $worker->$property = $config[$property];
  449. }
  450. }
  451. $worker->onWorkerStart = function ($worker) use ($config) {
  452. require_once base_path('/support/bootstrap.php');
  453. if (isset($config['handler'])) {
  454. if (!class_exists($config['handler'])) {
  455. echo "process error: class {$config['handler']} not exists\r\n";
  456. return;
  457. }
  458. $instance = Container::make($config['handler'], $config['constructor'] ?? []);
  459. worker_bind($worker, $instance);
  460. }
  461. };
  462. }
  463. /**
  464. * Get realpath
  465. * @param string $filePath
  466. * @return string
  467. */
  468. function get_realpath(string $filePath): string
  469. {
  470. if (strpos($filePath, 'phar://') === 0) {
  471. return $filePath;
  472. } else {
  473. return realpath($filePath);
  474. }
  475. }
  476. /**
  477. * Is phar
  478. * @return bool
  479. */
  480. function is_phar(): bool
  481. {
  482. return class_exists(Phar::class, false) && Phar::running();
  483. }
  484. /**
  485. * Get cpu count
  486. * @return int
  487. */
  488. function cpu_count(): int
  489. {
  490. // Windows does not support the number of processes setting.
  491. if (DIRECTORY_SEPARATOR === '\\') {
  492. return 1;
  493. }
  494. $count = 4;
  495. if (is_callable('shell_exec')) {
  496. if (strtolower(PHP_OS) === 'darwin') {
  497. $count = (int)shell_exec('sysctl -n machdep.cpu.core_count');
  498. } else {
  499. $count = (int)shell_exec('nproc');
  500. }
  501. }
  502. return $count > 0 ? $count : 4;
  503. }
  504. /**
  505. * Get request parameters, if no parameter name is passed, an array of all values is returned, default values is supported
  506. * @param string|null $param param's name
  507. * @param mixed|null $default default value
  508. * @return mixed|null
  509. */
  510. function input(string $param = null, $default = null)
  511. {
  512. return is_null($param) ? request()->all() : request()->input($param, $default);
  513. }
  514. function random_string($length, $type = 'all')
  515. {
  516. $string = 'abcdefghijklmnopqrstuvwxyz';
  517. $stringUp = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
  518. $number = '0123456789';
  519. switch ($type) {
  520. case 'all':
  521. $result = $string . $number;
  522. break;
  523. case 'string':
  524. $result = $string;
  525. break;
  526. case 'up':
  527. $result = $stringUp . $number;
  528. break;
  529. case 'number':
  530. $result = $number;
  531. break;
  532. default:
  533. $result = '';
  534. break;
  535. }
  536. $return = '';
  537. $totalLength = strlen($result);
  538. for ($i = 0; $i < $length; $i++) {
  539. $return .= $result[mt_rand(0, $totalLength - 1)];
  540. }
  541. return $return;
  542. }
  543. /**
  544. * @Desc 验证是否是json数据
  545. * @Author Gorden
  546. * @Date 2024/2/22 15:37
  547. *
  548. * @param $string
  549. * @return bool
  550. */
  551. function is_json($string)
  552. {
  553. if (!is_string($string)) {
  554. return false;
  555. }
  556. json_decode($string);
  557. if (json_last_error() === JSON_ERROR_NONE) {
  558. return true;
  559. }
  560. return false;
  561. }
  562. /**
  563. * @Desc 周几-汉字
  564. * @Author Gorden
  565. * @Date 2024/3/5 17:29
  566. *
  567. * @param $week
  568. * @return string
  569. */
  570. function chinese_week($week)
  571. {
  572. $weekArray = ['日', '一', '二', '三', '四', '五', '六'];
  573. return '周' . $weekArray[$week];
  574. }
  575. /**
  576. * @Desc 颜色值转RGB
  577. * @Author Gorden
  578. * @Date 2024/5/15 17:22
  579. *
  580. * @param $hexColor
  581. * @return mixed
  582. */
  583. function hexToRgb($hexColor, $type = "string")
  584. {
  585. // 使用substr函数去掉前缀的'#'
  586. $hexColor = ltrim($hexColor, '#');
  587. // 使用hexdec函数将十六进制转换为十进制
  588. $red = hexdec(substr($hexColor, 0, 2));
  589. $green = hexdec(substr($hexColor, 2, 2));
  590. $blue = hexdec(substr($hexColor, 4, 2));
  591. if ($type == "string") {
  592. // rgb(46, 209, 153)
  593. return "rgb(" . $red . ", " . $green . ", " . $blue . ")";
  594. }
  595. return array('red' => $red, 'green' => $green, 'blue' => $blue);
  596. }
  597. function rgbToHex($rgb)
  598. {
  599. if (substr($rgb, 0, 3) == 'rgb') {
  600. $rgb = str_replace("rgb(", '', $rgb);
  601. $rgb = str_replace(")", "", $rgb);
  602. [$red, $green, $blue] = explode(',', $rgb);
  603. $hexRed = dechex($red);
  604. $hexGreen = dechex($green);
  605. $hexBlue = dechex($blue);
  606. // 如果颜色分量不足两位,前面补零
  607. $hexRed = strlen($hexRed) == 1 ? '0' . $hexRed : $hexRed;
  608. $hexGreen = strlen($hexGreen) == 1 ? '0' . $hexGreen : $hexGreen;
  609. $hexBlue = strlen($hexBlue) == 1 ? '0' . $hexBlue : $hexBlue;
  610. return "#" . $hexRed. $hexGreen. $hexBlue;
  611. }
  612. return "";
  613. }