helpers.php 9.7 KB

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