helpers.php 15 KB

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