helper.php 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663
  1. <?php
  2. // +----------------------------------------------------------------------
  3. // | ThinkPHP [ WE CAN DO IT JUST THINK ]
  4. // +----------------------------------------------------------------------
  5. // | Copyright (c) 2006~2019 http://thinkphp.cn All rights reserved.
  6. // +----------------------------------------------------------------------
  7. // | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
  8. // +----------------------------------------------------------------------
  9. // | Author: liu21st <liu21st@gmail.com>
  10. // +----------------------------------------------------------------------
  11. declare (strict_types = 1);
  12. //------------------------
  13. // ThinkPHP 助手函数
  14. //-------------------------
  15. use think\App;
  16. use think\Container;
  17. use think\exception\HttpException;
  18. use think\exception\HttpResponseException;
  19. use think\facade\Cache;
  20. use think\facade\Config;
  21. use think\facade\Cookie;
  22. use think\facade\Env;
  23. use think\facade\Event;
  24. use think\facade\Lang;
  25. use think\facade\Log;
  26. use think\facade\Request;
  27. use think\facade\Route;
  28. use think\facade\Session;
  29. use think\Response;
  30. use think\response\File;
  31. use think\response\Json;
  32. use think\response\Jsonp;
  33. use think\response\Redirect;
  34. use think\response\View;
  35. use think\response\Xml;
  36. use think\route\Url as UrlBuild;
  37. use think\Validate;
  38. if (!function_exists('abort')) {
  39. /**
  40. * 抛出HTTP异常
  41. * @param integer|Response $code 状态码 或者 Response对象实例
  42. * @param string $message 错误信息
  43. * @param array $header 参数
  44. */
  45. function abort($code, string $message = '', array $header = [])
  46. {
  47. if ($code instanceof Response) {
  48. throw new HttpResponseException($code);
  49. } else {
  50. throw new HttpException($code, $message, null, $header);
  51. }
  52. }
  53. }
  54. if (!function_exists('app')) {
  55. /**
  56. * 快速获取容器中的实例 支持依赖注入
  57. * @param string $name 类名或标识 默认获取当前应用实例
  58. * @param array $args 参数
  59. * @param bool $newInstance 是否每次创建新的实例
  60. * @return object|App
  61. */
  62. function app(string $name = '', array $args = [], bool $newInstance = false)
  63. {
  64. return Container::getInstance()->make($name ?: App::class, $args, $newInstance);
  65. }
  66. }
  67. if (!function_exists('bind')) {
  68. /**
  69. * 绑定一个类到容器
  70. * @param string|array $abstract 类标识、接口(支持批量绑定)
  71. * @param mixed $concrete 要绑定的类、闭包或者实例
  72. * @return Container
  73. */
  74. function bind($abstract, $concrete = null)
  75. {
  76. return Container::getInstance()->bind($abstract, $concrete);
  77. }
  78. }
  79. if (!function_exists('cache')) {
  80. /**
  81. * 缓存管理
  82. * @param string $name 缓存名称
  83. * @param mixed $value 缓存值
  84. * @param mixed $options 缓存参数
  85. * @param string $tag 缓存标签
  86. * @return mixed
  87. */
  88. function cache(string $name = null, $value = '', $options = null, $tag = null)
  89. {
  90. if (is_null($name)) {
  91. return app('cache');
  92. }
  93. if ('' === $value) {
  94. // 获取缓存
  95. return 0 === strpos($name, '?') ? Cache::has(substr($name, 1)) : Cache::get($name);
  96. } elseif (is_null($value)) {
  97. // 删除缓存
  98. return Cache::delete($name);
  99. }
  100. // 缓存数据
  101. if (is_array($options)) {
  102. $expire = $options['expire'] ?? null; //修复查询缓存无法设置过期时间
  103. } else {
  104. $expire = $options;
  105. }
  106. if (is_null($tag)) {
  107. return Cache::set($name, $value, $expire);
  108. } else {
  109. return Cache::tag($tag)->set($name, $value, $expire);
  110. }
  111. }
  112. }
  113. if (!function_exists('config')) {
  114. /**
  115. * 获取和设置配置参数
  116. * @param string|array $name 参数名
  117. * @param mixed $value 参数值
  118. * @return mixed
  119. */
  120. function config($name = '', $value = null)
  121. {
  122. if (is_array($name)) {
  123. return Config::set($name, $value);
  124. }
  125. return 0 === strpos($name, '?') ? Config::has(substr($name, 1)) : Config::get($name, $value);
  126. }
  127. }
  128. if (!function_exists('cookie')) {
  129. /**
  130. * Cookie管理
  131. * @param string $name cookie名称
  132. * @param mixed $value cookie值
  133. * @param mixed $option 参数
  134. * @return mixed
  135. */
  136. function cookie(string $name, $value = '', $option = null)
  137. {
  138. if (is_null($value)) {
  139. // 删除
  140. Cookie::delete($name);
  141. } elseif ('' === $value) {
  142. // 获取
  143. return 0 === strpos($name, '?') ? Cookie::has(substr($name, 1)) : Cookie::get($name);
  144. } else {
  145. // 设置
  146. return Cookie::set($name, $value, $option);
  147. }
  148. }
  149. }
  150. if (!function_exists('download')) {
  151. /**
  152. * 获取\think\response\Download对象实例
  153. * @param string $filename 要下载的文件
  154. * @param string $name 显示文件名
  155. * @param bool $content 是否为内容
  156. * @param int $expire 有效期(秒)
  157. * @return \think\response\File
  158. */
  159. function download(string $filename, string $name = '', bool $content = false, int $expire = 180): File
  160. {
  161. return Response::create($filename, 'file')->name($name)->isContent($content)->expire($expire);
  162. }
  163. }
  164. if (!function_exists('dump')) {
  165. /**
  166. * 浏览器友好的变量输出
  167. * @param mixed $vars 要输出的变量
  168. * @return void
  169. */
  170. function dump(...$vars)
  171. {
  172. ob_start();
  173. var_dump(...$vars);
  174. $output = ob_get_clean();
  175. $output = preg_replace('/\]\=\>\n(\s+)/m', '] => ', $output);
  176. if (PHP_SAPI == 'cli') {
  177. $output = PHP_EOL . $output . PHP_EOL;
  178. } else {
  179. if (!extension_loaded('xdebug')) {
  180. $output = htmlspecialchars($output, ENT_SUBSTITUTE);
  181. }
  182. $output = '<pre>' . $output . '</pre>';
  183. }
  184. echo $output;
  185. }
  186. }
  187. if (!function_exists('env')) {
  188. /**
  189. * 获取环境变量值
  190. * @access public
  191. * @param string $name 环境变量名(支持二级 .号分割)
  192. * @param string $default 默认值
  193. * @return mixed
  194. */
  195. function env(string $name = null, $default = null)
  196. {
  197. return Env::get($name, $default);
  198. }
  199. }
  200. if (!function_exists('event')) {
  201. /**
  202. * 触发事件
  203. * @param mixed $event 事件名(或者类名)
  204. * @param mixed $args 参数
  205. * @return mixed
  206. */
  207. function event($event, $args = null)
  208. {
  209. return Event::trigger($event, $args);
  210. }
  211. }
  212. if (!function_exists('halt')) {
  213. /**
  214. * 调试变量并且中断输出
  215. * @param mixed $vars 调试变量或者信息
  216. */
  217. function halt(...$vars)
  218. {
  219. dump(...$vars);
  220. throw new HttpResponseException(Response::create());
  221. }
  222. }
  223. if (!function_exists('input')) {
  224. /**
  225. * 获取输入数据 支持默认值和过滤
  226. * @param string $key 获取的变量名
  227. * @param mixed $default 默认值
  228. * @param string $filter 过滤方法
  229. * @return mixed
  230. */
  231. function input(string $key = '', $default = null, $filter = '')
  232. {
  233. if (0 === strpos($key, '?')) {
  234. $key = substr($key, 1);
  235. $has = true;
  236. }
  237. if ($pos = strpos($key, '.')) {
  238. // 指定参数来源
  239. $method = substr($key, 0, $pos);
  240. if (in_array($method, ['get', 'post', 'put', 'patch', 'delete', 'route', 'param', 'request', 'session', 'cookie', 'server', 'env', 'path', 'file'])) {
  241. $key = substr($key, $pos + 1);
  242. if ('server' == $method && is_null($default)) {
  243. $default = '';
  244. }
  245. } else {
  246. $method = 'param';
  247. }
  248. } else {
  249. // 默认为自动判断
  250. $method = 'param';
  251. }
  252. return isset($has) ?
  253. request()->has($key, $method) :
  254. request()->$method($key, $default, $filter);
  255. }
  256. }
  257. if (!function_exists('invoke')) {
  258. /**
  259. * 调用反射实例化对象或者执行方法 支持依赖注入
  260. * @param mixed $call 类名或者callable
  261. * @param array $args 参数
  262. * @return mixed
  263. */
  264. function invoke($call, array $args = [])
  265. {
  266. if (is_callable($call)) {
  267. return Container::getInstance()->invoke($call, $args);
  268. }
  269. return Container::getInstance()->invokeClass($call, $args);
  270. }
  271. }
  272. if (!function_exists('json')) {
  273. /**
  274. * 获取\think\response\Json对象实例
  275. * @param mixed $data 返回的数据
  276. * @param int $code 状态码
  277. * @param array $header 头部
  278. * @param array $options 参数
  279. * @return \think\response\Json
  280. */
  281. function json($data = [], $code = 200, $header = [], $options = []): Json
  282. {
  283. return Response::create($data, 'json', $code)->header($header)->options($options);
  284. }
  285. }
  286. if (!function_exists('jsonp')) {
  287. /**
  288. * 获取\think\response\Jsonp对象实例
  289. * @param mixed $data 返回的数据
  290. * @param int $code 状态码
  291. * @param array $header 头部
  292. * @param array $options 参数
  293. * @return \think\response\Jsonp
  294. */
  295. function jsonp($data = [], $code = 200, $header = [], $options = []): Jsonp
  296. {
  297. return Response::create($data, 'jsonp', $code)->header($header)->options($options);
  298. }
  299. }
  300. if (!function_exists('lang')) {
  301. /**
  302. * 获取语言变量值
  303. * @param string $name 语言变量名
  304. * @param array $vars 动态变量值
  305. * @param string $lang 语言
  306. * @return mixed
  307. */
  308. function lang(string $name, array $vars = [], string $lang = '')
  309. {
  310. return Lang::get($name, $vars, $lang);
  311. }
  312. }
  313. if (!function_exists('parse_name')) {
  314. /**
  315. * 字符串命名风格转换
  316. * type 0 将Java风格转换为C的风格 1 将C风格转换为Java的风格
  317. * @param string $name 字符串
  318. * @param int $type 转换类型
  319. * @param bool $ucfirst 首字母是否大写(驼峰规则)
  320. * @return string
  321. */
  322. function parse_name(string $name, int $type = 0, bool $ucfirst = true): string
  323. {
  324. if ($type) {
  325. $name = preg_replace_callback('/_([a-zA-Z])/', function ($match) {
  326. return strtoupper($match[1]);
  327. }, $name);
  328. return $ucfirst ? ucfirst($name) : lcfirst($name);
  329. }
  330. return strtolower(trim(preg_replace("/[A-Z]/", "_\\0", $name), "_"));
  331. }
  332. }
  333. if (!function_exists('redirect')) {
  334. /**
  335. * 获取\think\response\Redirect对象实例
  336. * @param string $url 重定向地址
  337. * @param int $code 状态码
  338. * @return \think\response\Redirect
  339. */
  340. function redirect(string $url, int $code = 302): Redirect
  341. {
  342. return Response::create($url, 'redirect', $code);
  343. }
  344. }
  345. if (!function_exists('request')) {
  346. /**
  347. * 获取当前Request对象实例
  348. * @return Request
  349. */
  350. function request(): \think\Request
  351. {
  352. return app('request');
  353. }
  354. }
  355. if (!function_exists('response')) {
  356. /**
  357. * 创建普通 Response 对象实例
  358. * @param mixed $data 输出数据
  359. * @param int|string $code 状态码
  360. * @param array $header 头信息
  361. * @param string $type
  362. * @return Response
  363. */
  364. function response($data = '', $code = 200, $header = [], $type = 'html'): Response
  365. {
  366. return Response::create($data, $type, $code)->header($header);
  367. }
  368. }
  369. if (!function_exists('session')) {
  370. /**
  371. * Session管理
  372. * @param string $name session名称
  373. * @param mixed $value session值
  374. * @return mixed
  375. */
  376. function session($name = '', $value = '')
  377. {
  378. if (is_null($name)) {
  379. // 清除
  380. Session::clear();
  381. } elseif ('' === $name) {
  382. return Session::all();
  383. } elseif (is_null($value)) {
  384. // 删除
  385. Session::delete($name);
  386. } elseif ('' === $value) {
  387. // 判断或获取
  388. return 0 === strpos($name, '?') ? Session::has(substr($name, 1)) : Session::get($name);
  389. } else {
  390. // 设置
  391. Session::set($name, $value);
  392. }
  393. }
  394. }
  395. if (!function_exists('token')) {
  396. /**
  397. * 获取Token令牌
  398. * @param string $name 令牌名称
  399. * @param mixed $type 令牌生成方法
  400. * @return string
  401. */
  402. function token(string $name = '__token__', string $type = 'md5'): string
  403. {
  404. return Request::buildToken($name, $type);
  405. }
  406. }
  407. if (!function_exists('token_field')) {
  408. /**
  409. * 生成令牌隐藏表单
  410. * @param string $name 令牌名称
  411. * @param mixed $type 令牌生成方法
  412. * @return string
  413. */
  414. function token_field(string $name = '__token__', string $type = 'md5'): string
  415. {
  416. $token = Request::buildToken($name, $type);
  417. return '<input type="hidden" name="' . $name . '" value="' . $token . '" />';
  418. }
  419. }
  420. if (!function_exists('token_meta')) {
  421. /**
  422. * 生成令牌meta
  423. * @param string $name 令牌名称
  424. * @param mixed $type 令牌生成方法
  425. * @return string
  426. */
  427. function token_meta(string $name = '__token__', string $type = 'md5'): string
  428. {
  429. $token = Request::buildToken($name, $type);
  430. return '<meta name="csrf-token" content="' . $token . '">';
  431. }
  432. }
  433. if (!function_exists('trace')) {
  434. /**
  435. * 记录日志信息
  436. * @param mixed $log log信息 支持字符串和数组
  437. * @param string $level 日志级别
  438. * @return array|void
  439. */
  440. function trace($log = '[think]', string $level = 'log')
  441. {
  442. if ('[think]' === $log) {
  443. return Log::getLog();
  444. }
  445. Log::record($log, $level);
  446. }
  447. }
  448. if (!function_exists('url')) {
  449. /**
  450. * Url生成
  451. * @param string $url 路由地址
  452. * @param array $vars 变量
  453. * @param bool|string $suffix 生成的URL后缀
  454. * @param bool|string $domain 域名
  455. * @return UrlBuild
  456. */
  457. function url(string $url = '', array $vars = [], $suffix = true, $domain = false): UrlBuild
  458. {
  459. return Route::buildUrl($url, $vars)->suffix($suffix)->domain($domain);
  460. }
  461. }
  462. if (!function_exists('validate')) {
  463. /**
  464. * 生成验证对象
  465. * @param string|array $validate 验证器类名或者验证规则数组
  466. * @param array $message 错误提示信息
  467. * @param bool $batch 是否批量验证
  468. * @param bool $failException 是否抛出异常
  469. * @return Validate
  470. */
  471. function validate($validate = '', array $message = [], bool $batch = false, bool $failException = true): Validate
  472. {
  473. if (is_array($validate) || '' === $validate) {
  474. $v = new Validate();
  475. if (is_array($validate)) {
  476. $v->rule($validate);
  477. }
  478. } else {
  479. if (strpos($validate, '.')) {
  480. // 支持场景
  481. list($validate, $scene) = explode('.', $validate);
  482. }
  483. $class = false !== strpos($validate, '\\') ? $validate : app()->parseClass('validate', $validate);
  484. $v = new $class();
  485. if (!empty($scene)) {
  486. $v->scene($scene);
  487. }
  488. }
  489. return $v->message($message)->batch($batch)->failException($failException);
  490. }
  491. }
  492. if (!function_exists('view')) {
  493. /**
  494. * 渲染模板输出
  495. * @param string $template 模板文件
  496. * @param array $vars 模板变量
  497. * @param int $code 状态码
  498. * @param callable $filter 内容过滤
  499. * @return \think\response\View
  500. */
  501. function view(string $template = '', $vars = [], $code = 200, $filter = null): View
  502. {
  503. return Response::create($template, 'view', $code)->assign($vars)->filter($filter);
  504. }
  505. }
  506. if (!function_exists('display')) {
  507. /**
  508. * 渲染模板输出
  509. * @param string $content 渲染内容
  510. * @param array $vars 模板变量
  511. * @param int $code 状态码
  512. * @param callable $filter 内容过滤
  513. * @return \think\response\View
  514. */
  515. function display(string $content, $vars = [], $code = 200, $filter = null): View
  516. {
  517. return Response::create($content, 'view', $code)->isContent(true)->assign($vars)->filter($filter);
  518. }
  519. }
  520. if (!function_exists('xml')) {
  521. /**
  522. * 获取\think\response\Xml对象实例
  523. * @param mixed $data 返回的数据
  524. * @param int $code 状态码
  525. * @param array $header 头部
  526. * @param array $options 参数
  527. * @return \think\response\Xml
  528. */
  529. function xml($data = [], $code = 200, $header = [], $options = []): Xml
  530. {
  531. return Response::create($data, 'xml', $code)->header($header)->options($options);
  532. }
  533. }
  534. if (!function_exists('app_path')) {
  535. /**
  536. * 获取当前应用目录
  537. *
  538. * @param string $path
  539. * @return string
  540. */
  541. function app_path($path = '')
  542. {
  543. return app()->getAppPath() . ($path ? $path . DIRECTORY_SEPARATOR : $path);
  544. }
  545. }
  546. if (!function_exists('base_path')) {
  547. /**
  548. * 获取应用基础目录
  549. *
  550. * @param string $path
  551. * @return string
  552. */
  553. function base_path($path = '')
  554. {
  555. return app()->getBasePath() . ($path ? $path . DIRECTORY_SEPARATOR : $path);
  556. }
  557. }
  558. if (!function_exists('config_path')) {
  559. /**
  560. * 获取应用配置目录
  561. *
  562. * @param string $path
  563. * @return string
  564. */
  565. function config_path($path = '')
  566. {
  567. return app()->getConfigPath() . ($path ? $path . DIRECTORY_SEPARATOR : $path);
  568. }
  569. }
  570. if (!function_exists('public_path')) {
  571. /**
  572. * 获取web根目录
  573. *
  574. * @param string $path
  575. * @return string
  576. */
  577. function public_path($path = '')
  578. {
  579. return app()->getRootPath() . ($path ? ltrim($path, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR : $path);
  580. }
  581. }
  582. if (!function_exists('runtime_path')) {
  583. /**
  584. * 获取应用运行时目录
  585. *
  586. * @param string $path
  587. * @return string
  588. */
  589. function runtime_path($path = '')
  590. {
  591. return app()->getRuntimePath() . ($path ? $path . DIRECTORY_SEPARATOR : $path);
  592. }
  593. }
  594. if (!function_exists('root_path')) {
  595. /**
  596. * 获取项目根目录
  597. *
  598. * @param string $path
  599. * @return string
  600. */
  601. function root_path($path = '')
  602. {
  603. return app()->getRootPath() . ($path ? $path . DIRECTORY_SEPARATOR : $path);
  604. }
  605. }