MultiExecState.php 2.74 KB
<?php namespace common\components\redis\transaction;

/**
 * Class MultiExecState
 * 管理事务的状态
 * 一个事务可以同时存在多个状态
 * 比如同时存在INITIALIZED,INSIDEBLOCK,DISCARDED,WATCH等四个状态
 * 注意:该类原型来自 \Predis\Transaction\MultiExecState
 * @package common\components\redis\transaction
 */
class MultiExecState
{
    const INITIALIZED = 1;    // 0b00001
    const INSIDEBLOCK = 2;    // 0b00010
    const DISCARDED = 4;    // 0b00100
    const CAS = 8;    // 0b01000
    const WATCH = 16;   // 0b10000

    public $flags;

    public function __construct()
    {
        $this->flags = 0;
    }

    /**
     * Sets the internal state flags.
     *
     * @param int $flags Set of flags
     */
    public function set($flags)
    {
        $this->flags = $flags;
    }

    /**
     * Gets the internal state flags.
     *
     * @return int
     */
    public function get()
    {
        return $this->flags;
    }

    /**
     * 设置一个状态
     * @param int $flags Set of flags
     */
    public function flag($flags)
    {
        $this->flags |= $flags;
    }

    /**
     * 移除一个存在的状态
     * @param int $flags Set of flags
     */
    public function unflag($flags)
    {
        $this->flags &= ~$flags;
    }

    /**
     * 当前状态,或者多个状态是否存在
     * @param int $flags Flag
     * @return bool
     */
    public function check($flags)
    {
        return ($this->flags & $flags) === $flags;
    }

    /**
     * 重置事务的状态
     */
    public function reset()
    {
        $this->flags = 0;
    }

    /**
     * 状态是否被重置了
     * @return bool
     */
    public function isReset()
    {
        return $this->flags === 0;
    }

    /**
     * 返回INITIALIZED状态标识
     * @return bool
     */
    public function isInitialized()
    {
        return $this->check(self::INITIALIZED);
    }

    /**
     * 返回INSIDEBLOCK状态标识
     * @return bool
     */
    public function isExecuting()
    {
        return $this->check(self::INSIDEBLOCK);
    }

    /**
     * 返回CAS状态标识
     * @return bool
     */
    public function isCAS()
    {
        return $this->check(self::CAS);
    }

    /**
     * 返回INITIALIZED状态标识,是否执行WATCH命令
     * @return bool
     */
    public function isWatchAllowed()
    {
        return $this->check(self::INITIALIZED) && !$this->check(self::CAS);
    }

    /**
     * 返回WATCH状态标识
     * @return bool
     */
    public function isWatching()
    {
        return $this->check(self::WATCH);
    }

    /**
     * 返回DISCARDED状态标识
     * @return bool
     */
    public function isDiscarded()
    {
        return $this->check(self::DISCARDED);
    }
}