<?php
// +----------------------------------------------------------------------
// | Bwsaas
// +----------------------------------------------------------------------
// | Copyright (c) 2015~2020 http://www.buwangyun.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Gitee ( https://gitee.com/buwangyun/bwsaas )
// +----------------------------------------------------------------------
// | Author: buwangyun <hnlg666@163.com>
// +----------------------------------------------------------------------
// | Date: 2020-9-28 10:55:00
// +----------------------------------------------------------------------

namespace bw;



use traits\CacheTrait;

/** 接口唯一调用锁类
 * Class Common
 * @package app\bwmall\model
 */
class UrlLock
{

    use CacheTrait;

    private $lock_key = null;

    private $lock_suffix = "-lock-suffix" ;

    private $time_out = 120;

    private $is_lock = false;



    public function __construct($lock_key=null,$lock_suffix="",$time_out=null,$err_msg=null)
    {
        if($lock_key)$this->lock_key = $lock_key;
        if($lock_suffix)$this->lock_suffix = $lock_suffix;
        if($time_out)$this->time_out = $time_out;
        if($err_msg)$this->setCacheLockErrorMsg($err_msg);
    }


    public function lock($bool=false){
        try{
            $this->getLock($this->lock_key,$this->lock_suffix,$this->time_out);
        }catch (\Exception|\Throwable $e){
            $this->is_lock = false;
            if($bool){
                return false;
            }else{
                throw new UrlLockException($e->getMessage());
            }
        }
        $this->is_lock = true;
        return $this;
    }

    public function free($bool=false){
        try{
        $this->freeLock($this->lock_key,$this->lock_suffix);
        }catch (\Exception|\Throwable $e){
            if($bool){
                return false;
            }else{
                throw new UrlLockException($e->getMessage());
            }
        }
        $this->is_lock = false;
        return $this;
    }

    /** 析构时释放锁
     * @throws UrlLockException
     */
    public function __destruct()
    {
       if ($this->is_lock)$this->free();
    }
    public function hasLock(){
        return $this->is_lock;
    }


    public function setErrorInfo($msg){
        $this->setCacheLockErrorMsg($msg);
    }


}