helpers.php 15 KB

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