use App\Library\Ding\Ding;
use Symfony\Component\HttpFoundation\Response;
use \Illuminate\Contracts\Pagination\LengthAwarePaginator;
use Predis\Response\Status;
use Illuminate\Support\Facades\Redis;
if (! function_exists('stored')) {
function stored($data, $message = '创建成功') {
return respond($data, $message);
}
}
if (! function_exists('updated')) {
function updated($data, $message = '更新成功') {
return respond($data, $message);
}
}
if (! function_exists('deleted')) {
function deleted($message = '删除成功') {
return message($message);
}
}
if (! function_exists('accepted')) {
function accepted($message = '请求已接受,等待处理') {
return message($message, Response::HTTP_ACCEPTED);
}
}
if (! function_exists('notFound')) {
function notFound($message = '您访问的资源不存在') {
return message($message, Response::HTTP_NOT_FOUND,$header=[],$status_code=Response::HTTP_NOT_FOUND);
}
}
if (! function_exists('internalError')) {
function internalError($message = '未知错误导致请求失败', $code = Response::HTTP_INTERNAL_SERVER_ERROR) {
return message($message, $code);
}
}
if (! function_exists('failed')) {
function failed($message, $code = Response::HTTP_BAD_REQUEST,$status_code = Response::HTTP_OK) {
return message($message, $code,$header=[],$status_code);
}
}
if (! function_exists('success')) {
function success($data,$header=[],$message='请求成功') {
return respond($data, $message,$code= Response::HTTP_OK,$header);
}
}
if (! function_exists('resp')) {
function resp($data,$header=[],$message='请求成功') {
return respData($data, $message,$code= Response::HTTP_OK,$header);
}
}
if (! function_exists('message')) {
function message($message, $code = Response::HTTP_OK,$header=[],$status_code=Response::HTTP_OK) {
return respond([], $message, $code,$header,$status_code);
}
}
if (! function_exists('respond')) {
function respond($data = [], $message = '请求成功', $code = Response::HTTP_OK, array $header = [],$status_code=200) {
if($data instanceof LengthAwarePaginator){
return response()->json([
'code' => $code,
'msg' => $message,
'time' => time(),
'data' => [
'list'=>$data->items(),
'total'=>$data->total(),
],
], $status_code, $header)->setEncodingOptions(JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
}
return response()->json([
'code' => $code,
'msg' => $message,
'time' => time(),
'data' => $data ? $data: null,
], $status_code, $header)->setEncodingOptions(JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
}
}
if(! function_exists('respData')){
function respData($data = [], $message = '请求成功', $code = Response::HTTP_OK, array $header = [],$status_code=200) {
return response()->json([
'code' => $code,
'msg' => $message,
'time' => time(),
'data' => [
'list' => $data['data'],
'total' => $data['total'],
],
], $status_code, $header)->setEncodingOptions(JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
}
}
if(! function_exists('respCallbackData')){
function respCallbackData($message = '请求成功', $code = '01', array $header = [],$status_code=200) {
return response()->json([
'respCode' => $code,
'respMessage' => $message,
], $status_code, $header)->setEncodingOptions(JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
}
}
if(! function_exists('respCommonCallbackData')){
function respCommonCallbackData($result = 'success', array $header = [],$status_code=200) {
return response()->json([
'result' => $result,
], $status_code, $header)->setEncodingOptions(JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
}
}
/**
* 小黑鱼返回体
* @param array $data
* @param string $message
* @param int $code
* @param bool $success
* @param array $header
* @param int $status_code
* @return \Illuminate\Http\JsonResponse
* @author luwei
* @date 2019-02-13 15:11
*/
if(! function_exists('fishResp')){
function fishResp($data = [], $message = '请求成功', $code = Response::HTTP_OK, $success = true, array $header = [], $status_code=200) {
$time= bcmul(bcsub(microtime(true), LARAVEL_START,3),1000);
return response()->json([
'success' => $success,
'code' => $code,
'msg' => $message,
'cost_time' => intval($time),
'data' => $data,
], $status_code, $header)->setEncodingOptions(JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
}
}
/**
* 催收被调接口返回图
*/
if(! function_exists('collectionResp')){
function collectionResp($data = [], $message = '请求成功', $code = Response::HTTP_OK, $success = true, array $header = [], $status_code=200) {
\App\Models\CollectionApiRequest::createApiRequestData($data);
$sign= '';
if(!isset($data['obj'])){
$data['obj'] = null;
}
$resultData= $data;
return response()->json([
'sign' => $sign,
'resultData' => $resultData,
], $status_code, $header)->setEncodingOptions(JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
}
}
if (! function_exists('getOssUrl')) {
function getOssUrl($path = '', $timeout = 60*60*2) {
//判断文件是否存在
return Storage::disk('oss')->exists($path) ? (Storage::disk('oss')->signUrl($path, $timeout)) : '';
}
}
/**
* 手机验证码验证
*/
if (! function_exists('verifyPhoneCode')) {
function verifyPhoneCode($phone,$code) {
$verify_code= Cache::get($phone.'_code');
return $verify_code== $code;
}
}
/**
* 返回两个时间相差天数
* 2019-11-9 2019-11-7
*/
if (! function_exists('count_days')) {
function count_days($now_time,$normal_time){
$now_time = strtotime($now_time);
$normal_time = strtotime($normal_time);
$a_dt= getdate($now_time);
$b_dt= getdate($normal_time);
$a_new= mktime(12, 0, 0, $a_dt['mon'], $a_dt['mday'], $a_dt['year']);
$b_new= mktime(12, 0, 0, $b_dt['mon'], $b_dt['mday'], $b_dt['year']);
return round(($a_new-$b_new)/86400);
}
}
if(! function_exists('getDayWithCh')){
function getDayWithCh($day)
{
$info= '';
switch(\Carbon\Carbon::parse($day)->dayOfWeek){
case 1:
$info= '星期一';
break;
case 2:
$info= '星期二';
break;
case 3:
$info= '星球三';
break;
case 4:
$info= '星期四';
break;
case 5:
$info= '星期五';
break;
case 6:
$info= '星球六';
break;
case 0 :
$info= '星期天';
break;
}
return $info;
}
}
/**
* 融360基础返回体
*/
if(!function_exists('r360Response')){
function r360Response($message="",$data = [],$code=200,$http_code=Response::HTTP_OK){
$resData= [
"code"=>$code,
"msg"=>"$message",
];
if(!empty($data)){
foreach ($data as $key=> $value){
$resData[$key] = $value;
}
}
return response()->json($resData, $http_code)->setEncodingOptions(JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
}
}
/**
* 融360成功返回体
*/
if(!function_exists('r360success')){
function r360Success($message="",$data = []){
return r360Response($message,$data);
}
}
/**
* 融360失败返回体
*/
if(!function_exists('r360fail')){
function r360fail($message="",$data = [],$code=400){
return r360Response($message,$data,$code);
}
}
/**
* 13位时间戳
* @param $data
* @param $sign
* @return int
* @author shenzengguang
* @date 2019-03-15 17:37
*/
if (!function_exists('microtime_float')){
function microtime_float(){
list($usec, $sec) = explode(" ", microtime());
return ((float)$usec+ (float)$sec);
}
}
if (!function_exists('_sql')) {
/**
* 将此方法放在sql语句查询之前,可直接打印sql语句
* @param int $sqlNo 1:打印单条sql,其他打印所有sql
* @param string $method
* @return bool
*/
function _sql($sqlNo = 2, $method = 'log')
{
if (config('app.env') !== 'local' || config('app.debug') !== true) {
return false;
}
\DB::listen(function($queryExcuted) use ($sqlNo, $method) {
$sql= $queryExcuted->sql;
$bindings= $queryExcuted->bindings;
foreach ($bindingsas $replace){
$value= is_numeric($replace) ? $replace: "'".$replace."'";
$sql= preg_replace('/\?/', $value, $sql, 1);
}
if (! is_numeric($sqlNo)) {
$method= $sqlNo=== 'dd' ? 'dd' : 'dump';
}
if ($method=== 'log') {
\Log::info($sql);
if ($sqlNo=== 1) {
die;
}
} else {
$method($sql);
}
});
}
}
if (!function_exists('setOssUrlCache')) {
/**
* Description:获取oss文件并缓存
* Author: wjl
* DateTime: 2019-04-20 15:03
* @param $img_path
* @param float|int $ttl
* @param float|int $oss_ttl
* @return mixed|string
* @throws \Psr\SimpleCache\InvalidArgumentException
*/
function setOssUrlCache($img_path, $ttl = 60 * 24 * 30, $oss_ttl = 60 * 60 * 24 * 30)
{
if (empty($img_path)) return '';
$key= md5($img_path);
$img_url= \Cache::get($key);
//添加oss域名
if (!$img_url) {
$img_url= getOssUrl($img_path, $oss_ttl);
\Cache::set($key, $img_url, $ttl);
}
return $img_url;
}
}
/**
* 请求悲观锁
* @param $key
* @param int $expired
* @param null $value
* @return bool
* @author luwei
* @date 2019-04-22 14:42
*/
if (!function_exists('getPessimisticLock')){
function getPessimisticLock($key, $expired = 60, $value = null)
{
if (!is_string($value)) {
$value = time();
}
$flag= Redis::set($key, $value, 'EX', $expired, 'NX');
if ($flag&& $flaginstanceof Status && $flag->getPayload() === 'OK') {
\Log::debug('获取悲观锁成功,key:' . $key);
return true;
} elseif (is_null($flag)) {
\Log::debug('获取悲观锁失败,key:' . $key);
} else {
\Log::debug('获取悲观锁失败,失败原因未知,key:' . $key);
}
}
}
/**
* 释放悲观锁
* @param $key
* @param null $value
* @return bool
* @author luwei
* @date 2019-04-22 14:45
*/
if (!function_exists('delPessimisticLock')) {
function delPessimisticLock($key, $value = null) {
$flag= false;
$actualValue= Redis::get($key);
if (!is_null($actualValue) && !is_null($value) && $actualValue!= $value) {
\Log::debug('解铃还须系铃人,key:' . $key);
}
if (is_null($actualValue)) {
//锁已经不存在了
\Log::debug('未找到悲观锁......key:' . $key);
} else {
Redis::watch($key);
if ($actualValue!= Redis::get($key)) {
//lock updated
Redis::unwatch();
\Log::debug('释放悲观锁失败,锁被其他客户端抢占了,key:' . $key);
} else {
Redis::multi();
Redis::del($key);
$delRet= Redis::exec();
if ($delRet&& is_array($delRet) && isset($delRet[0]) && $delRet[0] === 1) {
\Log::debug('释放悲观锁成功,key:' . $key);
$flag=true;
} elseif (is_null($delRet)) {
//事务执行失败
Redis::unwatch();
\Log::debug('释放悲观锁失败,key:' . $key);
} else {
Redis::unwatch();
\Log::debug('释放悲观锁失败,key:' . $key);
}
}
}
return $flag;
}
}
if (!function_exists('getFilterInputParams')) {
/**
* Description: 将表单数据中null转为''
* Author: WangSx
* DateTime: 2019-05-14 09:40
* @param $arr
* @return array
*/
function getFilterInputParams($arr)
{
$data= [];
if (!empty($arr)) {
$data= array_map(function ($item) {
return $item ?: '';
},$arr);
}
return $data;
}
}
/**
* @param array $data
* @param array $headers
* @param array $specHeaders
* @param $fileName
* @param bool $isFirst
* @author luwei
* @date 2019-05-20 18:08
*/
function csv_export(array $data, array $headers, $specHeaders = [], $fileName,$isFirst = false) {
//终端导出无需header头
// header('Content-Type: application/vnd.ms-excel');
// header('Content-Disposition: attachment;filename="'.$fileName.'.csv"');
// header('Cache-Control: max-age=0');
$fp= fopen(storage_path($fileName), 'a');
// $fp = fopen(storage_path('files/'.$fileName), 'a');
foreach ($headers as $key=> $value) {
$headers[$key] = iconv('utf-8', 'gbk', $value);
}
if($isFirst){
fputcsv($fp, $headers);
}
//计数器
$num= 0;
$limit= 500000;
//逐行取出数据,不浪费内存
$count= count($data);
for ($i= 0; $i< $count; $i++) {
$num++;
if ($limit== $num) {
ob_flush();
flush();
$num= 0;
}
$row= $data[$i];
$ret= [];
foreach ($headers as $key=> $value) {
if($specHeaders && in_array($key,$specHeaders)){
$ret[$key] = iconv('utf-8', 'gbk//IGNORE', $row[$key])."\t";
}else{
$ret[$key] = iconv('utf-8', 'gbk//IGNORE', $row[$key]);
}
}
fputcsv($fp, $ret);
}
}
function urlSafeBase64encode($string) {
$data= base64_encode($string);
$data= str_replace(array('+','/','='),array('-','_',''),$data);
return $data;
}
function urlSafeBase64decode($string) {
$data= str_replace(array('-','_'),array('+','/'),$string);
$mod4= strlen($data) % 4;
if ($mod4) {
$data.= substr('====', $mod4);
}
return base64_decode($data);
}
/**
* 拍拍贷日志
* @param string $message
* @return \Illuminate\Http\JsonResponse
* @author luwei
* @date 2019-06-25 17:22
*/
if (! function_exists('PPDLogger')) {
function PPDLogger($message = null, array $context = [])
{
if (is_null($message)) {
return app('log');
}
return app('log')->channel('ppdLog')->debug($message, $context);
}
}
/**
* 挖财基础返回体
*/
if (!function_exists('wacaiResponse')) {
function wacaiResponse($message = "", $data = [], $code = "0000", $http_code = Response::HTTP_OK)
{
$resData= [
"code" => $code,
"message" => "$message",
"data"=> !empty($data) ? $data : null,
];
return response()->json($resData, $http_code)->setEncodingOptions(JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
}
}
/**
* 挖财成功返回体
*/
if(!function_exists('wacaiSuccess')){
function wacaiSuccess($message="",$data = [],$code="0000"){
return wacaiResponse($message,$data,$code);
}
}
/**
* 挖财失败返回体
*/
if(!function_exists('wacaiFail')){
function wacaiFail($message="",$data = [],$code="1000"){
return wacaiResponse($message,$data,$code);
}
}
/**
* 获取毫秒时间戳
*/
if(!function_exists('getMillisecond')){
function getMillisecond(){
list($s1, $s2) = explode(' ', microtime());
return (float)sprintf('%.0f', (floatval($s1) + floatval($s2)) * 1000);
}
}
/**
* PHP判断一个string 是否是json string
*/
if(!function_exists('isJsonString')) {
function isJsonString($str)
{
try {
$jObject= json_decode($str);
} catch (\Exception $e) {
return FALSE;
}
return (is_object($jObject)) ? TRUE : FALSE;
}
}
/**
* 检测某个表中是否存在某个索引
* @param $table
* @param $index
* @return bool
* @author zhaohao
* @date 2019-08-26 17:42
*/
if(!function_exists('hasIndex')) {
function hasIndex($table, $name)
{
$conn= \Illuminate\Support\Facades\Schema::getConnection();
$dbSchemaManager= $conn->getDoctrineSchemaManager();
$doctrineTable= $dbSchemaManager->listTableDetails($table);
return $doctrineTable->hasIndex($name);
}
}