helpers.php 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480
  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 = 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 = 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 ...$parameters
  213. * @return string
  214. */
  215. function route($name, ...$parameters)
  216. {
  217. $route = Route::getByName($name);
  218. if (!$route) {
  219. return '';
  220. }
  221. if (!$parameters) {
  222. return $route->url();
  223. }
  224. if (is_array(current($parameters))) {
  225. $parameters = current($parameters);
  226. }
  227. return $route->url($parameters);
  228. }
  229. /**
  230. * @param mixed $key
  231. * @param mixed $default
  232. * @return mixed
  233. */
  234. function session($key = null, $default = null)
  235. {
  236. $session = request()->session();
  237. if (null === $key) {
  238. return $session;
  239. }
  240. if (\is_array($key)) {
  241. $session->put($key);
  242. return null;
  243. }
  244. if (\strpos($key, '.')) {
  245. $key_array = \explode('.', $key);
  246. $value = $session->all();
  247. foreach ($key_array as $index) {
  248. if (!isset($value[$index])) {
  249. return $default;
  250. }
  251. $value = $value[$index];
  252. }
  253. return $value;
  254. }
  255. return $session->get($key, $default);
  256. }
  257. /**
  258. * @param null|string $id
  259. * @param array $parameters
  260. * @param string|null $domain
  261. * @param string|null $locale
  262. * @return string
  263. */
  264. function trans(string $id, array $parameters = [], string $domain = null, string $locale = null)
  265. {
  266. $res = Translation::trans($id, $parameters, $domain, $locale);
  267. return $res === '' ? $id : $res;
  268. }
  269. /**
  270. * @param null|string $locale
  271. * @return string
  272. */
  273. function locale(string $locale = null)
  274. {
  275. if (!$locale) {
  276. return Translation::getLocale();
  277. }
  278. Translation::setLocale($locale);
  279. }
  280. /**
  281. * 404 not found
  282. *
  283. * @return Response
  284. */
  285. function not_found()
  286. {
  287. return new Response(404, [], file_get_contents(public_path() . '/404.html'));
  288. }
  289. /**
  290. * Copy dir.
  291. * @param $source
  292. * @param $dest
  293. * @param bool $overwrite
  294. * @return void
  295. */
  296. function copy_dir($source, $dest, $overwrite = false)
  297. {
  298. if (is_dir($source)) {
  299. if (!is_dir($dest)) {
  300. mkdir($dest);
  301. }
  302. $files = scandir($source);
  303. foreach ($files as $file) {
  304. if ($file !== "." && $file !== "..") {
  305. copy_dir("$source/$file", "$dest/$file");
  306. }
  307. }
  308. } else if (file_exists($source) && ($overwrite || !file_exists($dest))) {
  309. copy($source, $dest);
  310. }
  311. }
  312. /**
  313. * Remove dir.
  314. * @param $dir
  315. * @return bool
  316. */
  317. function remove_dir($dir)
  318. {
  319. if (is_link($dir) || is_file($dir)) {
  320. return unlink($dir);
  321. }
  322. $files = array_diff(scandir($dir), array('.', '..'));
  323. foreach ($files as $file) {
  324. (is_dir("$dir/$file") && !is_link($dir)) ? remove_dir("$dir/$file") : unlink("$dir/$file");
  325. }
  326. return rmdir($dir);
  327. }
  328. /**
  329. * @param $worker
  330. * @param $class
  331. */
  332. function worker_bind($worker, $class)
  333. {
  334. $callback_map = [
  335. 'onConnect',
  336. 'onMessage',
  337. 'onClose',
  338. 'onError',
  339. 'onBufferFull',
  340. 'onBufferDrain',
  341. 'onWorkerStop',
  342. 'onWebSocketConnect'
  343. ];
  344. foreach ($callback_map as $name) {
  345. if (method_exists($class, $name)) {
  346. $worker->$name = [$class, $name];
  347. }
  348. }
  349. if (method_exists($class, 'onWorkerStart')) {
  350. call_user_func([$class, 'onWorkerStart'], $worker);
  351. }
  352. }
  353. /**
  354. * @param $process_name
  355. * @param $config
  356. * @return void
  357. */
  358. function worker_start($process_name, $config)
  359. {
  360. $worker = new Worker($config['listen'] ?? null, $config['context'] ?? []);
  361. $property_map = [
  362. 'count',
  363. 'user',
  364. 'group',
  365. 'reloadable',
  366. 'reusePort',
  367. 'transport',
  368. 'protocol',
  369. ];
  370. $worker->name = $process_name;
  371. foreach ($property_map as $property) {
  372. if (isset($config[$property])) {
  373. $worker->$property = $config[$property];
  374. }
  375. }
  376. $worker->onWorkerStart = function ($worker) use ($config) {
  377. require_once base_path() . '/support/bootstrap.php';
  378. foreach ($config['services'] ?? [] as $server) {
  379. if (!class_exists($server['handler'])) {
  380. echo "process error: class {$server['handler']} not exists\r\n";
  381. continue;
  382. }
  383. $listen = new Worker($server['listen'] ?? null, $server['context'] ?? []);
  384. if (isset($server['listen'])) {
  385. echo "listen: {$server['listen']}\n";
  386. }
  387. $instance = Container::make($server['handler'], $server['constructor'] ?? []);
  388. worker_bind($listen, $instance);
  389. $listen->listen();
  390. }
  391. if (isset($config['handler'])) {
  392. if (!class_exists($config['handler'])) {
  393. echo "process error: class {$config['handler']} not exists\r\n";
  394. return;
  395. }
  396. $instance = Container::make($config['handler'], $config['constructor'] ?? []);
  397. worker_bind($worker, $instance);
  398. }
  399. };
  400. }
  401. /**
  402. * Phar support.
  403. * Compatible with the 'realpath' function in the phar file.
  404. *
  405. * @param string $file_path
  406. * @return string
  407. */
  408. function get_realpath(string $file_path): string
  409. {
  410. if (strpos($file_path, 'phar://') === 0) {
  411. return $file_path;
  412. } else {
  413. return realpath($file_path);
  414. }
  415. }
  416. /**
  417. * @return bool
  418. */
  419. function is_phar()
  420. {
  421. return class_exists(\Phar::class, false) && Phar::running();
  422. }
  423. /**
  424. * @return int
  425. */
  426. function cpu_count()
  427. {
  428. // Windows does not support the number of processes setting.
  429. if (\DIRECTORY_SEPARATOR === '\\') {
  430. return 1;
  431. }
  432. $count = 4;
  433. if (is_callable('shell_exec')) {
  434. if (strtolower(PHP_OS) === 'darwin') {
  435. $count = (int)shell_exec('sysctl -n machdep.cpu.core_count');
  436. } else {
  437. $count = (int)shell_exec('nproc');
  438. }
  439. }
  440. return $count > 0 ? $count : 4;
  441. }