helpers_now.php 15 KB

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