helpers.php 15 KB

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