helpers.php 12 KB

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