helpers.php 15 KB

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