helpers.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539
  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. * @param string|null $plugin
  70. * @return string
  71. */
  72. function public_path(string $path = '', string $plugin = null): string
  73. {
  74. static $publicPaths = [];
  75. $plugin = $plugin ?? '';
  76. if (isset($publicPaths[$plugin])) {
  77. $publicPath = $publicPaths[$plugin];
  78. } else {
  79. $prefix = $plugin ? "plugin.$plugin." : '';
  80. $pathPrefix = $plugin ? 'plugin' . DIRECTORY_SEPARATOR . $plugin . DIRECTORY_SEPARATOR : '';
  81. $publicPath = \config("{$prefix}app.public_path", run_path("{$pathPrefix}public"));
  82. if (count($publicPaths) > 32) {
  83. $publicPaths = [];
  84. }
  85. $publicPaths[$plugin] = $publicPath;
  86. }
  87. return path_combine($publicPath, $path);
  88. }
  89. /**
  90. * Config path
  91. * @param string $path
  92. * @return string
  93. */
  94. function config_path(string $path = ''): string
  95. {
  96. return path_combine(BASE_PATH . DIRECTORY_SEPARATOR . 'config', $path);
  97. }
  98. /**
  99. * Runtime path
  100. * @param string $path
  101. * @return string
  102. */
  103. function runtime_path(string $path = ''): string
  104. {
  105. static $runtimePath = '';
  106. if (!$runtimePath) {
  107. $runtimePath = \config('app.runtime_path') ?: run_path('runtime');
  108. }
  109. return path_combine($runtimePath, $path);
  110. }
  111. /**
  112. * Generate paths based on given information
  113. * @param string $front
  114. * @param string $back
  115. * @return string
  116. */
  117. function path_combine(string $front, string $back): string
  118. {
  119. return $front . ($back ? (DIRECTORY_SEPARATOR . ltrim($back, DIRECTORY_SEPARATOR)) : $back);
  120. }
  121. /**
  122. * Response
  123. * @param int $status
  124. * @param array $headers
  125. * @param string $body
  126. * @return Response
  127. */
  128. function response(string $body = '', int $status = 200, array $headers = []): Response
  129. {
  130. return new Response($status, $headers, $body);
  131. }
  132. /**
  133. * Json response
  134. * @param $data
  135. * @param int $options
  136. * @return Response
  137. */
  138. function json($data, int $options = JSON_UNESCAPED_UNICODE): Response
  139. {
  140. return new Response(200, ['Content-Type' => 'application/json'], json_encode($data, $options));
  141. }
  142. /**
  143. * Xml response
  144. * @param $xml
  145. * @return Response
  146. */
  147. function xml($xml): Response
  148. {
  149. if ($xml instanceof SimpleXMLElement) {
  150. $xml = $xml->asXML();
  151. }
  152. return new Response(200, ['Content-Type' => 'text/xml'], $xml);
  153. }
  154. /**
  155. * Jsonp response
  156. * @param $data
  157. * @param string $callbackName
  158. * @return Response
  159. */
  160. function jsonp($data, string $callbackName = 'callback'): Response
  161. {
  162. if (!is_scalar($data) && null !== $data) {
  163. $data = json_encode($data);
  164. }
  165. return new Response(200, [], "$callbackName($data)");
  166. }
  167. /**
  168. * Redirect response
  169. * @param string $location
  170. * @param int $status
  171. * @param array $headers
  172. * @return Response
  173. */
  174. function redirect(string $location, int $status = 302, array $headers = []): Response
  175. {
  176. $response = new Response($status, ['Location' => $location]);
  177. if (!empty($headers)) {
  178. $response->withHeaders($headers);
  179. }
  180. return $response;
  181. }
  182. /**
  183. * View response
  184. * @param string $template
  185. * @param array $vars
  186. * @param string|null $app
  187. * @param string|null $plugin
  188. * @return Response
  189. */
  190. function view(string $template, array $vars = [], string $app = null, string $plugin = null): Response
  191. {
  192. $request = \request();
  193. $plugin = $plugin === null ? ($request->plugin ?? '') : $plugin;
  194. $handler = \config($plugin ? "plugin.$plugin.view.handler" : 'view.handler');
  195. return new Response(200, [], $handler::render($template, $vars, $app, $plugin));
  196. }
  197. /**
  198. * Raw view response
  199. * @param string $template
  200. * @param array $vars
  201. * @param string|null $app
  202. * @return Response
  203. * @throws Throwable
  204. */
  205. function raw_view(string $template, array $vars = [], string $app = null): Response
  206. {
  207. return new Response(200, [], Raw::render($template, $vars, $app));
  208. }
  209. /**
  210. * Blade view response
  211. * @param string $template
  212. * @param array $vars
  213. * @param string|null $app
  214. * @return Response
  215. */
  216. function blade_view(string $template, array $vars = [], string $app = null): Response
  217. {
  218. return new Response(200, [], Blade::render($template, $vars, $app));
  219. }
  220. /**
  221. * Think view response
  222. * @param string $template
  223. * @param array $vars
  224. * @param string|null $app
  225. * @return Response
  226. */
  227. function think_view(string $template, array $vars = [], string $app = null): Response
  228. {
  229. return new Response(200, [], ThinkPHP::render($template, $vars, $app));
  230. }
  231. /**
  232. * Twig view response
  233. * @param string $template
  234. * @param array $vars
  235. * @param string|null $app
  236. * @return Response
  237. */
  238. function twig_view(string $template, array $vars = [], string $app = null): Response
  239. {
  240. return new Response(200, [], Twig::render($template, $vars, $app));
  241. }
  242. /**
  243. * Get request
  244. * @return \Webman\Http\Request|Request|null
  245. */
  246. function request()
  247. {
  248. return App::request();
  249. }
  250. /**
  251. * Get config
  252. * @param string|null $key
  253. * @param $default
  254. * @return array|mixed|null
  255. */
  256. function config(string $key = null, $default = null)
  257. {
  258. return Config::get($key, $default);
  259. }
  260. /**
  261. * Create url
  262. * @param string $name
  263. * @param ...$parameters
  264. * @return string
  265. */
  266. function route(string $name, ...$parameters): string
  267. {
  268. $route = Route::getByName($name);
  269. if (!$route) {
  270. return '';
  271. }
  272. if (!$parameters) {
  273. return $route->url();
  274. }
  275. if (is_array(current($parameters))) {
  276. $parameters = current($parameters);
  277. }
  278. return $route->url($parameters);
  279. }
  280. /**
  281. * Session
  282. * @param mixed $key
  283. * @param mixed $default
  284. * @return mixed|bool|Session
  285. */
  286. function session($key = null, $default = null)
  287. {
  288. $session = \request()->session();
  289. if (null === $key) {
  290. return $session;
  291. }
  292. if (is_array($key)) {
  293. $session->put($key);
  294. return null;
  295. }
  296. if (strpos($key, '.')) {
  297. $keyArray = explode('.', $key);
  298. $value = $session->all();
  299. foreach ($keyArray as $index) {
  300. if (!isset($value[$index])) {
  301. return $default;
  302. }
  303. $value = $value[$index];
  304. }
  305. return $value;
  306. }
  307. return $session->get($key, $default);
  308. }
  309. /**
  310. * Translation
  311. * @param string $id
  312. * @param array $parameters
  313. * @param string|null $domain
  314. * @param string|null $locale
  315. * @return string
  316. */
  317. function trans(string $id, array $parameters = [], string $domain = null, string $locale = null): string
  318. {
  319. $res = Translation::trans($id, $parameters, $domain, $locale);
  320. return $res === '' ? $id : $res;
  321. }
  322. /**
  323. * Locale
  324. * @param string|null $locale
  325. * @return string
  326. */
  327. function locale(string $locale = null): string
  328. {
  329. if (!$locale) {
  330. return Translation::getLocale();
  331. }
  332. Translation::setLocale($locale);
  333. return $locale;
  334. }
  335. /**
  336. * 404 not found
  337. * @return Response
  338. */
  339. function not_found(): Response
  340. {
  341. return new Response(404, [], file_get_contents(public_path() . '/404.html'));
  342. }
  343. /**
  344. * Copy dir
  345. * @param string $source
  346. * @param string $dest
  347. * @param bool $overwrite
  348. * @return void
  349. */
  350. function copy_dir(string $source, string $dest, bool $overwrite = false)
  351. {
  352. if (is_dir($source)) {
  353. if (!is_dir($dest)) {
  354. mkdir($dest);
  355. }
  356. $files = scandir($source);
  357. foreach ($files as $file) {
  358. if ($file !== "." && $file !== "..") {
  359. copy_dir("$source/$file", "$dest/$file", $overwrite);
  360. }
  361. }
  362. } else if (file_exists($source) && ($overwrite || !file_exists($dest))) {
  363. copy($source, $dest);
  364. }
  365. }
  366. /**
  367. * Remove dir
  368. * @param string $dir
  369. * @return bool
  370. */
  371. function remove_dir(string $dir): bool
  372. {
  373. if (is_link($dir) || is_file($dir)) {
  374. return unlink($dir);
  375. }
  376. $files = array_diff(scandir($dir), array('.', '..'));
  377. foreach ($files as $file) {
  378. (is_dir("$dir/$file") && !is_link($dir)) ? remove_dir("$dir/$file") : unlink("$dir/$file");
  379. }
  380. return rmdir($dir);
  381. }
  382. /**
  383. * Bind worker
  384. * @param $worker
  385. * @param $class
  386. */
  387. function worker_bind($worker, $class)
  388. {
  389. $callbackMap = [
  390. 'onConnect',
  391. 'onMessage',
  392. 'onClose',
  393. 'onError',
  394. 'onBufferFull',
  395. 'onBufferDrain',
  396. 'onWorkerStop',
  397. 'onWebSocketConnect',
  398. 'onWorkerReload'
  399. ];
  400. foreach ($callbackMap as $name) {
  401. if (method_exists($class, $name)) {
  402. $worker->$name = [$class, $name];
  403. }
  404. }
  405. if (method_exists($class, 'onWorkerStart')) {
  406. call_user_func([$class, 'onWorkerStart'], $worker);
  407. }
  408. }
  409. /**
  410. * Start worker
  411. * @param $processName
  412. * @param $config
  413. * @return void
  414. */
  415. function worker_start($processName, $config)
  416. {
  417. $worker = new Worker($config['listen'] ?? null, $config['context'] ?? []);
  418. $propertyMap = [
  419. 'count',
  420. 'user',
  421. 'group',
  422. 'reloadable',
  423. 'reusePort',
  424. 'transport',
  425. 'protocol',
  426. ];
  427. $worker->name = $processName;
  428. foreach ($propertyMap as $property) {
  429. if (isset($config[$property])) {
  430. $worker->$property = $config[$property];
  431. }
  432. }
  433. $worker->onWorkerStart = function ($worker) use ($config) {
  434. require_once base_path('/support/bootstrap.php');
  435. if (isset($config['handler'])) {
  436. if (!class_exists($config['handler'])) {
  437. echo "process error: class {$config['handler']} not exists\r\n";
  438. return;
  439. }
  440. $instance = Container::make($config['handler'], $config['constructor'] ?? []);
  441. worker_bind($worker, $instance);
  442. }
  443. };
  444. }
  445. /**
  446. * Get realpath
  447. * @param string $filePath
  448. * @return string
  449. */
  450. function get_realpath(string $filePath): string
  451. {
  452. if (strpos($filePath, 'phar://') === 0) {
  453. return $filePath;
  454. } else {
  455. return realpath($filePath);
  456. }
  457. }
  458. /**
  459. * Is phar
  460. * @return bool
  461. */
  462. function is_phar(): bool
  463. {
  464. return class_exists(Phar::class, false) && Phar::running();
  465. }
  466. /**
  467. * Get cpu count
  468. * @return int
  469. */
  470. function cpu_count(): int
  471. {
  472. // Windows does not support the number of processes setting.
  473. if (DIRECTORY_SEPARATOR === '\\') {
  474. return 1;
  475. }
  476. $count = 4;
  477. if (is_callable('shell_exec')) {
  478. if (strtolower(PHP_OS) === 'darwin') {
  479. $count = (int)shell_exec('sysctl -n machdep.cpu.core_count');
  480. } else {
  481. try {
  482. $count = (int)shell_exec('nproc');
  483. } catch (\Throwable $ex) {
  484. // Do nothing
  485. }
  486. }
  487. }
  488. return $count > 0 ? $count : 4;
  489. }
  490. /**
  491. * Get request parameters, if no parameter name is passed, an array of all values is returned, default values is supported
  492. * @param string|null $param param's name
  493. * @param mixed|null $default default value
  494. * @return mixed|null
  495. */
  496. function input(string $param = null, $default = null)
  497. {
  498. return is_null($param) ? request()->all() : request()->input($param, $default);
  499. }