helpers.php 11 KB

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