<?php
/**
 * @package merchant
 *
 * @author xaboy
 * @day 2020-04-24
 *
 * 
 */

namespace app\common\repositories\system;


use app\common\dao\system\CacheDao;
use app\common\repositories\BaseRepository;
use think\db\exception\DbException;
use think\facade\Db;

/**
 * Class CacheRepository
 * @package app\common\repositories\system
 * @author xaboy
 * @day 2020-04-24
 * @mixin CacheDao
 */
class CacheRepository extends BaseRepository
{
    /**
     * CacheRepository constructor.
     * @param CacheDao $dao
     */
    public function __construct(CacheDao $dao)
    {
        $this->dao = $dao;
    }

    /**
     * @param string $key
     * @param $result
     * @param int $expire_time
     * @throws DbException
     * @author xaboy
     * @day 2020-04-24
     */
    public function save(string $key, $result, int $expire_time = 0)
    {
        if(!empty($result)){
            $result=json_encode($result);
        }
        if (!$this->dao->fieldExists('key', $key)) {
            Db::name('cache')->insert(['result'=>$result,'expire_time'=>$expire_time,'create_time'=>date('Y-m-d H:i:s',time())]);
        } else {
            Db::name('cache')->where('key',$key)->update(['result'=>$result,'expire_time'=>$expire_time,'create_time'=>date('Y-m-d H:i:s',time())]);
        }
    }
}