Helper.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503
  1. <?php
  2. namespace easyTask;
  3. use easyTask\Exception\ErrorException;
  4. use \Exception as Exception;
  5. use \Throwable as Throwable;
  6. /**
  7. * Class Helper
  8. * @package easyTask
  9. */
  10. class Helper
  11. {
  12. /**
  13. * 睡眠函数
  14. * @param int $time 时间
  15. * @param int $type 类型:1秒 2毫秒
  16. */
  17. public static function sleep($time, $type = 1)
  18. {
  19. if ($type == 2) $time *= 1000;
  20. $type == 1 ? sleep($time) : usleep($time);
  21. }
  22. /**
  23. * 设置进程标题
  24. * @param string $title
  25. */
  26. public static function cli_set_process_title($title)
  27. {
  28. set_error_handler(function () {
  29. });
  30. if (function_exists('cli_set_process_title')) {
  31. cli_set_process_title($title);
  32. }
  33. restore_error_handler();
  34. }
  35. /**
  36. * 设置掩码
  37. */
  38. public static function setMask()
  39. {
  40. umask(0);
  41. }
  42. /**
  43. * 设置代码页
  44. * @param int $code
  45. */
  46. public static function setCodePage($code = 65001)
  47. {
  48. $ds = DIRECTORY_SEPARATOR;
  49. $codePageBinary = "C:{$ds}Windows{$ds}System32{$ds}chcp.com";
  50. if (file_exists($codePageBinary) && static::canUseExcCommand()) {
  51. @shell_exec("{$codePageBinary} {$code}");
  52. }
  53. }
  54. /**
  55. * 获取命令行输入
  56. * @param int $type
  57. * @return string|array
  58. */
  59. public static function getCliInput($type = 1)
  60. {
  61. //输入参数
  62. $argv = $_SERVER['argv'];
  63. //组装PHP路径
  64. array_unshift($argv, Env::get('phpPath'));
  65. //自动校正
  66. foreach ($argv as $key => $value) {
  67. if (file_exists($value)) {
  68. $argv[$key] = realpath($value);
  69. }
  70. }
  71. //返回
  72. if ($type == 1) {
  73. return join(' ', $argv);
  74. }
  75. return $argv;
  76. }
  77. /**
  78. * 设置PHP二进制文件
  79. * @param string $path
  80. */
  81. public static function setPhpPath($path = '')
  82. {
  83. if (!$path) $path = self::getBinary();;
  84. Env::set('phpPath', $path);
  85. }
  86. /**
  87. * 获取进程二进制文件
  88. * @return string
  89. */
  90. public static function getBinary()
  91. {
  92. return PHP_BINARY;
  93. }
  94. /**
  95. * 是否Win平台
  96. * @return bool
  97. */
  98. public static function isWin()
  99. {
  100. return (DIRECTORY_SEPARATOR == '\\') ? true : false;
  101. }
  102. /**
  103. * 开启异步信号
  104. * @return bool
  105. */
  106. public static function openAsyncSignal()
  107. {
  108. return pcntl_async_signals(true);
  109. }
  110. /**
  111. * 是否支持异步信号
  112. * @return bool
  113. */
  114. public static function canUseAsyncSignal()
  115. {
  116. return (function_exists('pcntl_async_signals'));
  117. }
  118. /**
  119. * 是否支持event事件
  120. * @return bool
  121. */
  122. public static function canUseEvent()
  123. {
  124. return (extension_loaded('event'));
  125. }
  126. /**
  127. * 是否可执行命令
  128. * @return bool
  129. */
  130. public static function canUseExcCommand()
  131. {
  132. return function_exists('shell_exec');
  133. }
  134. /**
  135. * 获取运行时目录
  136. * @return string
  137. */
  138. public static function getRunTimePath()
  139. {
  140. $path = Env::get('runTimePath') ? Env::get('runTimePath') : sys_get_temp_dir();
  141. if (!is_dir($path)) {
  142. static::showSysError('please set runTimePath');
  143. }
  144. $path = $path . DIRECTORY_SEPARATOR . Env::get('prefix') . DIRECTORY_SEPARATOR;
  145. $path = str_replace(DIRECTORY_SEPARATOR . DIRECTORY_SEPARATOR, DIRECTORY_SEPARATOR, $path);
  146. return $path;
  147. }
  148. /**
  149. * 获取Win进程目录
  150. * @return string
  151. */
  152. public static function getWinPath()
  153. {
  154. return Helper::getRunTimePath() . 'Win' . DIRECTORY_SEPARATOR;
  155. }
  156. /**
  157. * 获取日志目录
  158. * @return string
  159. */
  160. public static function getLogPath()
  161. {
  162. return Helper::getRunTimePath() . 'Log' . DIRECTORY_SEPARATOR;
  163. }
  164. /**
  165. * 获取进程命令通信目录
  166. * @return string
  167. */
  168. public static function getCsgPath()
  169. {
  170. return Helper::getRunTimePath() . 'Csg' . DIRECTORY_SEPARATOR;
  171. }
  172. /**
  173. * 获取进程队列目录
  174. * @return string
  175. */
  176. public static function getQuePath()
  177. {
  178. return Helper::getRunTimePath() . 'Que' . DIRECTORY_SEPARATOR;
  179. }
  180. /**
  181. * 获取进程锁目录
  182. * @return string
  183. */
  184. public static function getLokPath()
  185. {
  186. return Helper::getRunTimePath() . 'Lok' . DIRECTORY_SEPARATOR;
  187. }
  188. /**
  189. * 获取标准输入输出目录
  190. * @return string
  191. */
  192. public static function getStdPath()
  193. {
  194. return Helper::getRunTimePath() . 'Std' . DIRECTORY_SEPARATOR;
  195. }
  196. /**
  197. * 初始化所有目录
  198. */
  199. public static function initAllPath()
  200. {
  201. $paths = [
  202. static::getRunTimePath(),
  203. static::getWinPath(),
  204. static::getLogPath(),
  205. static::getLokPath(),
  206. static::getQuePath(),
  207. static::getCsgPath(),
  208. static::getStdPath(),
  209. ];
  210. foreach ($paths as $path) {
  211. if (!is_dir($path)) {
  212. mkdir($path, 0777, true);
  213. }
  214. }
  215. }
  216. /**
  217. * 保存标准输入|输出
  218. * @param string $char 输入|输出
  219. */
  220. public static function saveStdChar($char)
  221. {
  222. $path = static::getStdPath();
  223. $file = $path . date('Y_m_d') . '.std';
  224. $char = static::convert_char($char);
  225. file_put_contents($file, $char, FILE_APPEND);
  226. }
  227. /**
  228. * 保存日志
  229. * @param string $message
  230. */
  231. public static function writeLog($message)
  232. {
  233. //日志文件
  234. $path = Helper::getLogPath();
  235. $file = $path . date('Y_m_d') . '.log';
  236. //加锁保存
  237. $message = static::convert_char($message);
  238. file_put_contents($file, $message, FILE_APPEND | LOCK_EX);
  239. }
  240. /**
  241. * 保存类型日志
  242. * @param string $message
  243. * @param string $type
  244. * @param bool $isExit
  245. */
  246. public static function writeTypeLog($message, $type = 'info', $isExit = false)
  247. {
  248. //格式化信息
  249. $text = Helper::formatMessage($message, $type);
  250. //记录日志
  251. static::writeLog($text);
  252. if ($isExit) exit();
  253. }
  254. /**
  255. * 编码转换
  256. * @param string $char
  257. * @param string $coding
  258. * @return string
  259. */
  260. public static function convert_char($char, $coding = 'UTF-8')
  261. {
  262. $encode_arr = ['UTF-8', 'ASCII', 'GBK', 'GB2312', 'BIG5', 'JIS', 'eucjp-win', 'sjis-win', 'EUC-JP'];
  263. $encoded = mb_detect_encoding($char, $encode_arr);
  264. if ($encoded) {
  265. $char = mb_convert_encoding($char, $coding, $encoded);
  266. }
  267. return $char;
  268. }
  269. /**
  270. * 格式化异常信息
  271. * @param ErrorException|Exception|Throwable $exception
  272. * @param string $type
  273. * @return string
  274. */
  275. public static function formatException($exception, $type = 'exception')
  276. {
  277. //参数
  278. $pid = getmypid();
  279. $date = date('Y/m/d H:i:s', time());
  280. //组装
  281. return $date . " [$type] : errStr:" . $exception->getMessage() . ',errFile:' . $exception->getFile() . ',errLine:' . $exception->getLine() . " (pid:$pid)" . PHP_EOL;
  282. }
  283. /**
  284. * 格式化异常信息
  285. * @param string $message
  286. * @param string $type
  287. * @return string
  288. */
  289. public static function formatMessage($message, $type = 'error')
  290. {
  291. //参数
  292. $pid = getmypid();
  293. $date = date('Y/m/d H:i:s', time());
  294. //组装
  295. return $date . " [$type] : " . $message . " (pid:$pid)" . PHP_EOL;
  296. }
  297. /**
  298. * 检查任务时间是否合法
  299. * @param mixed $time
  300. */
  301. public static function checkTaskTime($time)
  302. {
  303. if (is_int($time)) {
  304. if ($time < 0) static::showSysError('time must be greater than or equal to 0');
  305. } elseif (is_float($time)) {
  306. if (!static::canUseEvent()) static::showSysError('please install php_event.(dll/so) extend for using milliseconds');
  307. } else {
  308. static::showSysError('time parameter is an unsupported type');
  309. }
  310. }
  311. /**
  312. * 输出字符串
  313. * @param string $char
  314. * @param bool $exit
  315. */
  316. public static function output($char, $exit = false)
  317. {
  318. echo $char;
  319. if ($exit) exit();
  320. }
  321. /**
  322. * 输出信息
  323. * @param string $message
  324. * @param bool $isExit
  325. * @param string $type
  326. * @throws
  327. */
  328. public static function showInfo($message, $isExit = false, $type = 'info')
  329. {
  330. //格式化信息
  331. $text = static::formatMessage($message, $type);
  332. //记录日志
  333. static::writeLog($text);
  334. //输出信息
  335. static::output($text, $isExit);
  336. }
  337. /**
  338. * 输出错误
  339. * @param string $errStr
  340. * @param bool $isExit
  341. * @param string $type
  342. * @param bool $log
  343. * @throws
  344. */
  345. public static function showError($errStr, $isExit = true, $type = 'error', $log = true)
  346. {
  347. //格式化信息
  348. $text = static::formatMessage($errStr, $type);
  349. //记录日志
  350. if ($log) static::writeLog($text);
  351. //输出信息
  352. static::output($text, $isExit);
  353. }
  354. /**
  355. * 输出系统错误
  356. * @param string $errStr
  357. * @param bool $isExit
  358. * @param string $type
  359. * @throws
  360. */
  361. public static function showSysError($errStr, $isExit = true, $type = 'warring')
  362. {
  363. //格式化信息
  364. $text = static::formatMessage($errStr, $type);
  365. //输出信息
  366. static::output($text, $isExit);
  367. }
  368. /**
  369. * 输出异常
  370. * @param mixed $exception
  371. * @param string $type
  372. * @param bool $isExit
  373. * @throws
  374. */
  375. public static function showException($exception, $type = 'exception', $isExit = true)
  376. {
  377. //格式化信息
  378. $text = static::formatException($exception, $type);
  379. //记录日志
  380. Helper::writeLog($text);
  381. //输出信息
  382. static::output($text, $isExit);
  383. }
  384. /**
  385. * 控制台输出表格
  386. * @param array $data
  387. * @param boolean $exit
  388. */
  389. public static function showTable($data, $exit = true)
  390. {
  391. //提取表头
  392. $header = array_keys($data['0']);
  393. //组装数据
  394. foreach ($data as $key => $row) {
  395. $data[$key] = array_values($row);
  396. }
  397. //输出表格
  398. $table = new Table();
  399. $table->setHeader($header);
  400. $table->setStyle('box');
  401. $table->setRows($data);
  402. $render = static::convert_char($table->render());
  403. if ($exit) {
  404. exit($render);
  405. }
  406. echo($render);
  407. }
  408. /**
  409. * 通过Curl方式提交数据
  410. *
  411. * @param string $url 目标URL
  412. * @param null $data 提交的数据
  413. * @param bool $return_array 是否转成数组
  414. * @param null $header 请求头信息 如:array("Content-Type: application/json")
  415. *
  416. * @return array|mixed
  417. */
  418. public static function curl($url, $data = null, $return_array = false, $header = null)
  419. {
  420. //初始化curl
  421. $curl = curl_init();
  422. //设置超时
  423. curl_setopt($curl, CURLOPT_TIMEOUT, 30);
  424. curl_setopt($curl, CURLOPT_URL, $url);
  425. curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
  426. curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
  427. if (is_array($header)) {
  428. curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
  429. }
  430. if ($data) {
  431. curl_setopt($curl, CURLOPT_POST, true);
  432. curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
  433. }
  434. curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
  435. //运行curl,获取结果
  436. $result = @curl_exec($curl);
  437. //关闭句柄
  438. curl_close($curl);
  439. //转成数组
  440. if ($return_array) {
  441. return json_decode($result, true);
  442. }
  443. //返回结果
  444. return $result;
  445. }
  446. }