php常用方法类库分享

最常用方法:

Common:error('');   //此方法可直接在API接口返回,比如:return json(Common:error(''));

Common:success('', $data);

Common::checkCommonTrue($res); //判断方法是成功还是失败

Common::writeApiLog($data, $title, $fileName, $path); //写日志方法

<?php
/**
 * *
 *  * Created by PhpStorm.
 *  * ============================================================================
 *  * User: Ice
 *  * Email: 190520601@qq.com
 *  * Wechat: s190520601
 *  * Web Site: https://sbing.vip
 *  * ============================================================================
 *  * Date: 2019/8/30 下午4:44
 */

namespace ice;

use app\common\model\Config;
use fast\Random;
use think\facade\Db;
use think\facade\Log;

class Common
{

    /**
     * 生成订单号
     *
     * @param string $prefix
     *
     * @return string
     */
    public static function makeOrder(string $prefix): string
    {
        return strtoupper($prefix).date('YmdHis').Random::numeric(4);
    }


    /**
     * 用户名、邮箱、手机账号中间字符串以*隐藏
     *
     * @param $str
     *
     * @return string|string[]|null
     */
    public static function hideStar($str)
    {
        if (strpos($str, '@')) {
            $email_array = explode("@", $str);
            $prevfix = (strlen($email_array[0]) < 4) ? "" : substr($str, 0, 3); //邮箱前缀
            $count = 0;
            $str = preg_replace('/([\d\w+_-]{0,100})@/', '******@', $str, -1, $count);
            $rs = $prevfix.$str;
        } else {
            $pattern = '/(1[0-9]{1}[0-9])[0-9]{4}([0-9]{4})/i';
            if (preg_match($pattern, $str)) {
                $rs = preg_replace($pattern, '$1****$2', $str); // substr_replace($name,'****',3,4);
            } else {
                $rs = substr($str, 0, 3)."***".substr($str, -1);
            }
        }
        return $rs;
    }

    /**
     * 检测是否成功
     *
     * @param array $arr
     *
     * @return bool
     */
    public static function checkArr(array $arr): bool
    {
        $bool = true;
        foreach ($arr as $v) {
            if (! $v) {
                $bool = false;
                break;
            }
        }
        return $bool;
    }

    /**
     * 检测是否成功
     *
     * @param array $arr
     *
     * @return bool
     */
    public static function checkCommonTrue(array $arr): bool
    {
        if (isset($arr['code'])) {
            if ($arr['code'] == 1) {
                return true;
            } else {
                return false;
            }
        } else {
            return false;
        }
    }

    /**
     * error
     *
     * @param $msg
     * @param mixed $data
     *
     * @return array
     */
    public static function error($msg = '', $data = '')
    {
        return ['code' => 0, 'msg' => $msg, 'data' => $data, 'time' => time()];
    }

    public static function success($msg = '', $data = '')
    {
        return ['code' => 1, 'msg' => $msg, 'data' => $data, 'time' => time(),];
    }


    public static function getVisitCode()
    {
        $pool = '123456789';
        $pool2 = '123456789ABCDEFGHIJKLMNPQRSTUVWXYZ';
        $len = 4;
        $len2 = 2;
        //生成邀请码
        do {
            $c1 = substr(str_shuffle(str_repeat($pool, ceil($len / strlen($pool)))), 0, $len);
            $c2 = substr(str_shuffle(str_repeat($pool2, ceil($len2 / strlen($pool2)))), 0, $len2);
            $visit_code = str_shuffle($c1.$c2);
            $is_exist = Db::name('user')->where('invite_code', $visit_code)->count();
        } while (! empty($is_exist));

        return $visit_code;
    }

    /**
     * 异常写入日志并Email报警
     *
     * @param \Exception $exception
     */
    public static function exceptionWrite(\Exception $exception)
    {
        Log::write($exception->getMessage().$exception->getTraceAsString(), 'error');
    }

    /**
     * 写入日志
     *
     * @param $data
     * @param string $title
     * @param string $path
     * @param string $filename
     */
    public static function writeApiLog($data = '', $title = '', $filename = '', $path = '')
    {
        if ($path) {
            $tmpDir = root_path().DS.'logs'.DS.$path.DS;
        } else {
            $tmpDir = root_path().DS.'logs'.DS;
        }
        if (! file_exists($tmpDir)) {
            mkdir($tmpDir, 0777, true);
        }

        $ip = app()->request->ip();

        $data = is_array($data) ? json_encode($data, JSON_UNESCAPED_UNICODE, 512) : $data;
        $content = "TITLE:".$title."\rIP:".$ip."\rTIME:".date('Y-m-d H:i:s')."\rDATA:".$data."\r\r";
        file_put_contents(
            $tmpDir.$filename.date('Ymd').'.log',
            $content,
            FILE_APPEND
        );
    }

    /**
     * 反转义
     *
     * @param string $data
     *
     * @return string
     */
    public static function dataHtmlEntityDecode($data = '')
    {
        if (! $data) {
            return $data;
        }
        if (is_array($data)) {
            foreach ($data as $k => &$v) {
                $v = html_entity_decode($v);
            }
        } else {
            $data = html_entity_decode($data);
        }
        return $data;
    }


    /**
     * 数组转XML
     * @param $arr
     *
     * @return string
     */
    public static function arrayToXml($arr)
    {
        $xml = "<xml>";
        foreach ($arr as $key=>$val)
        {
            if (is_numeric($val)){
                $xml.="<".$key.">".$val."</".$key.">";
            }else{
                $xml.="<".$key."><![CDATA[".$val."]]></".$key.">";
            }
        }
        $xml.="</xml>";
        return $xml;
    }

    //

    /**
     * 将XML转为array
     * @param $xml
     *
     * @return mixed
     */
    public static function xmlToArray($xml)
    {
        //禁止引用外部xml实体
        libxml_disable_entity_loader(true);
        $values = json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
        return $values;
    }


    /**
     * 检测是否是 金额 >0 整数或小数二位的正则
     * @param  int  $number
     *
     * @return bool
     */
    public static function checkMoneyPoint($number=0)
    {
        if ($number<=0){
            return false;
        }
        if (preg_match('/^[0-9]+(.[0-9]{1,8})?$/', $number)) {
            return true;
        }else{
            return false;
        }
    }


    /**
     * 获取分享链接
     *
     * @param  string  $code
     * @param  string  $url
     *
     * @return string
     */
    public static function getShareLink($code='',$url='')
    {
        $share_link = config('site.share_url')?:'';
        $share_link = str_replace('{$code}', $code, $share_link);
        $share_link = str_replace('{$url}', $url, $share_link);
        return Common::getNowDomain().$share_link;
    }

    /**
     * 获取终端IP
     *
     * @return mixed|string
     */
    public static function getTerminalIp()
    {
        $cdn_ip = request()->server('HTTP_ALI_CDN_REAL_IP');
        if (!$cdn_ip){
            $ip = request()->ip();
        }else{
            $ip = $cdn_ip;
        }
        return $ip;
    }

    /**
     * 获取当前https 域名
     * @return string
     */
    public static function getNowDomain()
    {
        return "http://".$_SERVER["SERVER_NAME"];
    }


    /**
     * 获取数据库中配置值
     *
     * @param string $name
     * @return string
     */
    public static function getConfigVal($name='')
    {
        if (!$name){
            return '';
        }
        $value = Config::where('name',$name)->value('value')?:'';
        return $value;
    }
}

方法使用示例:

/**
     * 用户金额变动
     *
     * @param         $money
     * @param         $user_id
     * @param         $memo
     * @param  array  $options
     *
     * @return array
     */
    public static function money($money, $user_id, $memo, $options = [])
    {
        if ($money == 0) {
            return Common::error(__('金额错误'));
        }
        //事务嵌套
        Db::startTrans();
        try {
            $user = self::lockUser($user_id);
        } catch (\Exception $exception) {
            Db::rollback();
            Common::exceptionWrite($exception);
            Common::writeApiLog($exception, '用户金额变动出错:user_id='.$user_id, 'money_error', 'usermoney');
            return Common::error(__('用户信息出错'));
        }
        if ($user) {
            $before = $user->money;
            $after  = $user->money + $money;
            if ($after < 0) {
                Db::rollback();
                //return false;
                return Common::error(__('账户余额不足'));
            }
            $user_data['money'] = ['inc', $money];
            //更新会员信息
            $rs[] = $user->save($user_data);
            //写入日志
            $data = [
                'user_id' => $user_id,
                'money'   => $money,
                'before'  => $before,
                'after'   => $after,
                'memo'    => $memo,
            ];
            $data = array_merge($data, $options);
            $rs[] = UserMoneyLog::create($data);
            if (Common::checkArr($rs)) {
                Db::commit();
                return Common::success('ok');
            }
        }
        Db::rollback();
        return Common::error('用户不存在');
    }
Db::startTrans();

        //添加到提现订单
        $order_no = Common::makeOrder('TB');
        $order= UserTixian::create([
            'user_id'=>$user->id,
            'order_no'=>$order_no,
            'money'=>$money,
            'fee'=>$money_fee,
            'real_money'=>$real_money,
            'status'=>0,
        ]);
        if (!$order){
            $rs[] = false;
            Db::rollback();
            return Common::error('创建提现订单失败');
        }else{
            $rs[] =true;
        }


        $memo_fee = $money_fee > 0 ? ',手续费:'.$money_fee : '';
        $memo = '提现:'.$money.$memo_fee;

        $res = User::money(-$money, $user->id, $memo, 2, ['from_order_id'=>$order->id]);
        $rs[] = Common::checkCommonTrue($res);
        if (!Common::checkArr($rs)){
            Db::rollback();
            return Common::error('提现申请失败');
        }
        Db::commit();
        return Common::success('提现申请成功,请耐心等待审核');

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值