<?php
namespace Lock;
/**
 * User: liuyuzhen
 * Date: 2018/8/20
 * Time: 15:30
 * Description:
 */
class LockSystem{

    const LOCK_TYPE_DB = 'DbLock';
    const LOCK_TYPE_FILE = 'FileLock';
    const LOCK_TYPE_REDIS = 'RedisLock';

    private $_lock = null;
    private static $_supportLocks = array('FileLock', 'DbLock', 'RedisLock');

    public function __construct($type, $options = array()){
        if(false == empty($type))
        {
            $this->createLock($type, $options);
        }
    }

    public function createLock($type, $options=array()){
        if (false == in_array($type, self::$_supportLocks))
        {
            throw new Exception("not support lock of ${type}");
        }
        $this->_lock = new $type($options);
    }

    public function getLock($key, $timeout = \Lock\ILock::EXPIRE){
        if (false == $this->_lock instanceof \Lock\ILock)
        {
            throw new Exception('false == $this->_lock instanceof ILock');
        }
        $this->_lock->getLock($key, $timeout);
    }

    public function releaseLock($key){
        if (false == $this->_lock instanceof \Lock\ILock)
        {
            throw new Exception('false == $this->_lock instanceof ILock');
        }
        $this->_lock->releaseLock($key);
    }

    /**
     * 类实例
     *
     */
    private static $_instance = null;

    /**
     * 获取类实例
     */
    public static function getInstance($type,$options= array()) {
        if (!(self::$_instance instanceof self)) {
            self::$_instance = new self($type,$options);
        }
        return self::$_instance;
    }
}