<?php
namespace service;
use think\exception\HttpResponseException;
use think\facade\Response;
use think\facade\Session;
/**
* 系统工具服务
* Class ToolsService
* @package service
* @author Anyon <zoujingli@qq.com>
* @date 2016/10/25 14:49
*/
class ToolsService
{
public static function corsOptionsHandler()
{
if (PHP_SESSION_ACTIVE !== session_status()) {
Session::init(config('session.'));
}
$token = request()->header('token', '');
empty($token) && $token = request()->post('token', '');
empty($token) && $token = request()->get('token', '');
list($name, $value) = explode('=', decode($token) . '=');
if (!empty($value) && session_name() === $name) {
session_id($value);
}
if (request()->isOptions()) {
header('Access-Control-Allow-Origin:*');
header('Access-Control-Allow-Credentials:true');
header('Access-Control-Allow-Methods:GET,POST,OPTIONS');
header("Access-Control-Allow-Headers:Accept,Referer,Host,Keep-Alive,User-Agent,X-Requested-With,Cache-Control,Cookie,token");
header('Content-Type:text/plain charset=UTF-8');
header('Access-Control-Max-Age:1728000');
header('HTTP/1.0 204 No Content');
header('Content-Length:0');
header('status:204');
exit;
}
}
public static function corsRequestHander()
{
return [
'Access-Control-Allow-Origin' => request()->header('origin', '*'),
'Access-Control-Allow-Methods' => 'GET,POST,OPTIONS',
'Access-Control-Allow-Credentials' => "true",
];
}
public static function success($msg, $data = [], $code = 1)
{
$result = ['code' => $code, 'msg' => $msg, 'data' => $data, 'token' => encode(session_name() . '=' . session_id())];
throw new HttpResponseException(Response::create($result, 'json', 200, self::corsRequestHander()));
}
public static function error($msg, $data = [], $code = 0)
{
$result = ['code' => $code, 'msg' => $msg, 'data' => $data, 'token' => encode(session_name() . '=' . session_id())];
throw new HttpResponseException(Response::create($result, 'json', 200, self::corsRequestHander()));
}
public static function emojiEncode($content)
{
return json_decode(preg_replace_callback("/(\\\u[ed][0-9a-f]{3})/i", function ($str) {
return addslashes($str[0]);
}, json_encode($content)));
}
public static function emojiDecode($content)
{
return json_decode(preg_replace_callback('/\\\\\\\\/i', function () {
return '\\';
}, json_encode($content)));
}
public static function arr2tree($list, $id = 'id', $pid = 'pid', $son = 'sub')
{
list($tree, $map) = [[], []];
foreach ($list as $item) {
$map[$item[$id]] = $item;
}
foreach ($list as $item) {
if (isset($item[$pid]) && isset($map[$item[$pid]])) {
$map[$item[$pid]][$son][] = &$map[$item[$id]];
} else {
$tree[] = &$map[$item[$id]];
}
}
unset($map);
return $tree;
}
public static function arr2table(array $list, $id = 'id', $pid = 'pid', $path = 'path', $ppath = '')
{
$tree = [];
foreach (self::arr2tree($list, $id, $pid) as $attr) {
$attr[$path] = "{$ppath}-{$attr[$id]}";
$attr['sub'] = isset($attr['sub']) ? $attr['sub'] : [];
$attr['spt'] = substr_count($ppath, '-');
$attr['spl'] = str_repeat(" ├ ", $attr['spt']);
$sub = $attr['sub'];
unset($attr['sub']);
$tree[] = $attr;
if (!empty($sub)) {
$tree = array_merge($tree, self::arr2table($sub, $id, $pid, $path, $attr[$path]));
}
}
return $tree;
}
public static function getArrSubIds($list, $id = 0, $key = 'id', $pkey = 'pid')
{
$ids = [intval($id)];
foreach ($list as $vo) {
if (intval($vo[$pkey]) > 0 && intval($vo[$pkey]) === intval($id)) {
$ids = array_merge($ids, self::getArrSubIds($list, intval($vo[$key]), $key, $pkey));
}
}
return $ids;
}
public static function setCsvHeader($filename, array $headers)
{
header('Content-Type: application/octet-stream');
header("Content-Disposition: attachment; filename=" . iconv('utf-8', 'gb echo @iconv('utf-8', 'gb }
public static function setCsvBody(array $list, array $rules)
{
foreach ($list as $data) {
$rows = [];
foreach ($rules as $rule) {
$item = self::parseKeyDot($data, $rule);
$rows[] = $item === $data ? '' : $item;
}
echo @iconv('utf-8', 'gb flush();
}
}
private static function parseKeyDot(array $data, $rule)
{
list($temp, $attr) = [$data, explode('.', trim($rule, '.'))];
while ($key = array_shift($attr)) {
$temp = isset($temp[$key]) ? $temp[$key] : $temp;
}
return (is_string($temp) || is_numeric($temp)) ? str_replace('"', '""', "\t{$temp}") : '';
}
}