public function getLengthByScore($min, $max)
    {
        return $this->_getRediskaOn()->getSortedSetLengthByScore($this->getName(), $min, $max);
    }

public function getLengthByScore ( $ min , $ max ) { return $ this -> _getRediskaOn ( ) -> getSortedSetLengthByScore ( $ this -> getName ( ) , $ min , $ max ) ; }

Get count of members from sorted set by min and max score

@param integer $min Min score
@param integer $max Max score
@return integer


public function getByScore($min, $max, $withScores = false, $limit = null, $offset = null, $revert = false)
    {
        return $this->_getRediskaOn()->getFromSortedSetByScore($this->getName(), $min, $max, $withScores, $limit, $offset, $revert);
    }

public function getByScore ( $ min , $ max , $ withScores = false , $ limit = null , $ offset = null , $ revert = false ) { return $ this -> _getRediskaOn ( ) -> getFromSortedSetByScore ( $ this -> getName ( ) , $ min , $ max , $ withScores , $ limit , $ offset , $ revert ) ; }

Get Sorted set by score

@param number  $min        Min score
@param number  $max        Max score
@param boolean $withScores Get with scores
@param integer $limit      Limit
@param integer $offset     Offset
@param boolean $revert     Is revert result
@return array


public function removeByScore($min, $max)
    {
        return $this->_getRediskaOn()->DeleteFromSortedSetByScore($this->getName(), $min, $max);
    }

public function removeByScore ( $ min , $ max ) { return $ this -> _getRediskaOn ( ) -> DeleteFromSortedSetByScore ( $ this -> getName ( ) , $ min , $ max ) ; }

Remove members from sorted set by score

@param $min Min score
@param $max Max score
@return integer


public function incrementScore($value, $score)
    {
        return $this->_getRediskaOn()->incrementScoreInSortedSet($this->getName(), $value, $score);
    }

public function incrementScore ( $ value , $ score ) { return $ this -> _getRediskaOn ( ) -> incrementScoreInSortedSet ( $ this -> getName ( ) , $ value , $ score ) ; }

Increment score of element

@param $value
@return integer


public function getByRank($withScores = false, $start = 0, $end = -1, $revert = false, $responseIterator = false)
    {
        return $this->_getRediskaOn()->getSortedSet($this->getName(), $withScores, $start, $end, $revert, $responseIterator);
    }

public function getByRank ( $ withScores = false , $ start = 0 , $ end = - 1 , $ revert = false , $ responseIterator = false ) { return $ this -> _getRediskaOn ( ) -> getSortedSet ( $ this -> getName ( ) , $ withScores , $ start , $ end , $ revert , $ responseIterator ) ; }

Get Sorted set by Rank

@param boolean $withScores Get with scores
@param integer $start      Start index
@param integer $end        End index
@param boolean $revert     Revert elements (not used in sorting)
@param boolean $responseIterator[optional]  If true - command return iterator which read from socket buffer.
Important: new connection will be created

@return array


public function removeByRank($start, $end)
    {
        return $this->_getRediskaOn()->deleteFromSortedSetByRank($this->getName(), $start, $end);
    }

public function removeByRank ( $ start , $ end ) { return $ this -> _getRediskaOn ( ) -> deleteFromSortedSetByRank ( $ this -> getName ( ) , $ start , $ end ) ; }

Remove all elements in the sorted set at key with rank between start and end

@param numeric $start Start position
@param numeric $end   End position
@return integer


public function getRank($value, $revert = false)
    {
        return $this->_getRediskaOn()->getRankFromSortedSet($this->getName(), $value, $revert);
    }

public function getRank ( $ value , $ revert = false ) { return $ this -> _getRediskaOn ( ) -> getRankFromSortedSet ( $ this -> getName ( ) , $ value , $ revert ) ; }

Get rank of member

@param integer $value  Member value
@param boolean $revert Revert elements (not used in sorting)
@return integer


public function union($setOrSets, $storeKeyName, $aggregation = 'sum')
    {
        $sets = $this->_prepareSetsForComapre($setOrSets);

        return $this->_getRediskaOn()->unionSortedSets($sets, $storeKeyName, $aggregation);
    }

public function union ( $ setOrSets , $ storeKeyName , $ aggregation = 'sum' ) { $ sets = $ this -> _prepareSetsForComapre ( $ setOrSets ) ; return $ this -> _getRediskaOn ( ) -> unionSortedSets ( $ sets , $ storeKeyName , $ aggregation ) ; }

Store to key union between the sorted sets

@param string|Rediska_Key_SortedSet|array  $setOrSets    Sorted set key name or object, or array of its
@param string                              $storeKeyName Result sorted set key name
@param string                              $aggregation  Aggregation method: SUM (for default), MIN, MAX.
@return integer


public function intersect($setOrSets, $storeKeyName, $aggregation = 'sum')
    {
        $sets = $this->_prepareSetsForComapre($setOrSets);

        return $this->_getRediskaOn()->intersectSortedSets($sets, $storeKeyName, $aggregation);
    }

public function intersect ( $ setOrSets , $ storeKeyName , $ aggregation = 'sum' ) { $ sets = $ this -> _prepareSetsForComapre ( $ setOrSets ) ; return $ this -> _getRediskaOn ( ) -> intersectSortedSets ( $ sets , $ storeKeyName , $ aggregation ) ; }

Store to key intersection between sorted sets

@param string|Rediska_Key_SortedSet|array  $setOrSets    Sorted set key name or object, or array of its
@param string                              $storeKeyName Result sorted set key name
@param string                              $aggregation  Aggregation method: SUM (for default), MIN, MAX.
@return integer


public function toArray($withScores = false, $start = 0, $end = -1, $revert = false, $responseIterator = false)
    {
        return $this->getByRank($withScores, $start, $end, $revert, $responseIterator);
    }

public function toArray ( $ withScores = false , $ start = 0 , $ end = - 1 , $ revert = false , $ responseIterator = false ) { return $ this -> getByRank ( $ withScores , $ start , $ end , $ revert , $ responseIterator ) ; }

Get Sorted set values

@param integer $withScores  Return values with scores
@param integer $start       Start index
@param integer $end         End index
@param boolean $revert      Revert elements (not used in sorting)
@param boolean $responseIterator[optional]  If true - command return iterator which read from socket buffer.
Important: new connection will be created

@return array


public function fromArray(array $array)
    {
        $pipeline = $this->_getRediskaOn()->pipeline();

        foreach($array as $score => $value) {
            $pipeline->addToSortedSet($this->getName(), $value, $score);
        }

        if (!is_null($this->getExpire())) {
            $pipeline->expire($this->getName(), $this->getExpire(), $this->isExpireTimestamp());
        }

        $pipeline->execute();

        return true;
    }

public function fromArray ( array $ array ) { $ pipeline = $ this -> _getRediskaOn ( ) -> pipeline ( ) ; foreach ( $ array as $ score => $ value ) { $ pipeline -> addToSortedSet ( $ this -> getName ( ) , $ value , $ score ) ; } if ( ! is_null ( $ this -> getExpire ( ) ) ) { $ pipeline -> expire ( $ this -> getName ( ) , $ this -> getExpire ( ) , $ this -> isExpireTimestamp ( ) ) ; } $ pipeline -> execute ( ) ; return true ; }

Add array to Sorted set

@param array $array


public function setName($name)
    {
        $this->_options['name'] = $name;

        if ($this->_options['addToManager']) {
            Rediska_Manager::add($this);
        }

        return $this;
    }

public function setName ( $ name ) { $ this -> _options [ 'name' ] = $ name ; if ( $ this -> _options [ 'addToManager' ] ) { Rediska_Manager :: add ( $ this ) ; } return $ this ; }

Set Rediska client name

@param string $name
@return Rediska


public function getConnectionByKeyName($name)
    {
        if ($this->_specifiedConnection->getConnection()) {
            $connection = $this->_specifiedConnection->getConnection();
        } elseif (count($this->_connections) == 1) {
            $connections = array_values($this->_connections);
            $connection = $connections[0];
        } else {
            $alias = $this->_keyDistributor->getConnectionByKeyName($name);
            $connection = $this->_connections[$alias];
        }

        return $connection;
    }

public function getConnectionByKeyName ( $ name ) { if ( $ this -> _specifiedConnection -> getConnection ( ) ) { $ connection = $ this -> _specifiedConnection -> getConnection ( ) ; } elseif ( count ( $ this -> _connections ) == 1 ) { $ connections = array_values ( $ this -> _connections ) ; $ connection = $ connections [ 0 ] ; } else { $ alias = $ this -> _keyDistributor -> getConnectionByKeyName ( $ name ) ; $ connection = $ this -> _connections [ $ alias ] ; } return $ connection ; }

Get Rediska connection instance by key name

@throws Rediska_Connection_Exception
@param string $name Key name
@return Rediska_Connection


public function getConnections()
    {
        if ($this->_specifiedConnection->getConnection()) {
            return array($this->_specifiedConnection->getConnection());
        } else {
            return array_values($this->_connections);
        }
    }

public function getConnections ( ) { if ( $ this -> _specifiedConnection -> getConnection ( ) ) { return array ( $ this -> _specifiedConnection -> getConnection ( ) ) ; } else { return array_values ( $ this -> _connections ) ; } }

Get all Rediska connection instances

@throws Rediska_Connection_Exception
@return array


public function on($aliasOrConnection)
    {
        if ($aliasOrConnection instanceof Rediska_Connection) {
            $connection = $aliasOrConnection;
        } else {
            $alias = $aliasOrConnection;
            $connection = $this->getConnectionByAlias($alias);
        }

        $this->_specifiedConnection->setConnection($connection);

        return $this->_specifiedConnection;
    }

public function on ( $ aliasOrConnection ) { if ( $ aliasOrConnection instanceof Rediska_Connection ) { $ connection = $ aliasOrConnection ; } else { $ alias = $ aliasOrConnection ; $ connection = $ this -> getConnectionByAlias ( $ alias ) ; } $ this -> _specifiedConnection -> setConnection ( $ connection ) ; return $ this -> _specifiedConnection ; }

Chain method to work with keys on specified by alias server

@param $aliasOrConnection Alias or Rediska_Connection object
@return Rediska_Connection_Specified


public function subscribe($channelOrChannels, $timeout = null)
    {
        return new Rediska_PubSub_Channel($channelOrChannels, array(
            'rediska'       => $this,
            'timeout'       => $timeout,
            'serverAlias'   => $this->_specifiedConnection->getConnection()
        ));
    }

public function subscribe ( $ channelOrChannels , $ timeout = null ) { return new Rediska_PubSub_Channel ( $ channelOrChannels , array ( 'rediska' => $ this , 'timeout' => $ timeout , 'serverAlias' => $ this -> _specifiedConnection -> getConnection ( ) ) ) ; }

Subscribe to PubSub channel or channels

@param string|array      $channelOrChannels
@param integer[optional] $timeout
@return Rediska_PubSub_Channel


public function config($aliasOrConnection = null)
    {
        if ($aliasOrConnection instanceof Rediska_Connection) {
            $connection = $aliasOrConnection;
        } elseif ($aliasOrConnection !== null) {
            $connection = $this->getConnectionByAlias($aliasOrConnection);
        } elseif ($this->_specifiedConnection->getConnection()) {
            $connection = $this->_specifiedConnection->getConnection();
        } else {
            $connections = $this->getConnections();
            if (count($connections) == 1) {
                $connection = $connections[0];
            } else {
                throw new Rediska_Transaction_Exception('You must specify connection by $aliasOrConnection argument!');
            }
        }

        return new Rediska_Config($this, $connection);
    }

Get Redis server configuration

@param $aliasOrConnection Server alias or Rediska_Connection object
@return Rediska_Config


public function setKeyDistributor($name)
    {
        $this->_options['keyDistributor'] = $name;

        if (is_object($name)) {
            $this->_keyDistributor = $name;
        } else if (in_array($name, array('crc32', 'consistentHashing'))) {
            $name = ucfirst($name);
            $className = "Rediska_KeyDistributor_$name";
            $this->_keyDistributor = new $className;
        } else {
            if (!@class_exists($name)) {
                throw new Rediska_Exception("Key distributor '$name' not found. You need include it before or setup autoload.");
            }
            $this->_keyDistributor = new $name;
        }

        if (!$this->_keyDistributor instanceof Rediska_KeyDistributor_Interface) {
            throw new Rediska_Exception("'$name' must implement Rediska_KeyDistributor_Interface");
        }

        // Add available connections
        foreach($this->_connections as $connectionString => $connection) {
            $this->_keyDistributor->addConnection($connectionString);
        }

        return $this;
    }

Set key distributor.
See options description for more information.

@throws Rediska_Exception
@param string $name Object or name of key distributor (crc32, consistentHashing or you personal class)
@return rediska

Set key distributor . See options description for more information .


public function getSerializer()
    {
        if ($this->_serializer === null) {
            $this->_serializer = new Rediska_Serializer($this->_options['serializerAdapter']);
        }

        return $this->_serializer;
    }

public function getSerializer ( ) { if ( $ this -> _serializer === null ) { $ this -> _serializer = new Rediska_Serializer ( $ this -> _options [ 'serializerAdapter' ] ) ; } return $ this -> _serializer ; }

Get Rediska serializer

@return Rediska_Serializer


public static function get(Rediska $rediska, $name, $arguments)
    {
        $lowerName = self::_getCommandLowerNameAndThrowIfNotPresent($name);

        return new self::$_commands[$lowerName]($rediska, $name, $arguments);
    }

Get command instance

@param Rediska $rediska   Rediska instance
@param string  $name      Command name
@param array   $arguments Command arguments
@return Rediska_Command_Abstract


protected static function _getCommandLowerNameAndThrowIfNotPresent($name)
    {
        $lowerName = strtolower($name);

        if (!isset(self::$_commands[$lowerName])) {
            throw new Rediska_Exception("Command '$name' not found");
        }

        return $lowerName;
    }

Get command lower name and throw exception if command not present

@param <type> $name
@return <type>


public function execute()
    {
        $results = array();

        if (!empty($this->_commands)) {
            $this->_rediska->getProfiler()->start($this);

            foreach($this->_commands as $command) {
                $command->write();
            }

            foreach($this->_commands as $command) {
                $results[] = $command->read();
            }

            $this->_rediska->getProfiler()->stop();
        }

        return $results;
    }

public function execute ( ) { $ results = array ( ) ; if ( ! empty ( $ this -> _commands ) ) { $ this -> _rediska -> getProfiler ( ) -> start ( $ this ) ; foreach ( $ this -> _commands as $ command ) { $ command -> write ( ) ; } foreach ( $ this -> _commands as $ command ) { $ results [ ] = $ command -> read ( ) ; } $ this -> _rediska -> getProfiler ( ) -> stop ( ) ; } return $ results ; }

Execute pipelined commands

@return array


protected function _addCommand($name, $args = array())
    {
        if ($this->_oneTimeConnection) {
            $connection = $this->_oneTimeConnection;
            $this->_oneTimeConnection = null;
        } else {
            $connection = $this->_defaultConnection;
        }

        if ($connection !== null) {
            $this->_specifiedConnection->setConnection($connection);
        } else {
            $this->_specifiedConnection->resetConnection();
        }

        $command = Rediska_Commands::get($this->_rediska, $name, $args);
        $command->initialize();

        if (!$command->isAtomic()) {
            throw new Rediska_Exception("Command '$name' doesn't work properly (not atomic) in pipeline on multiple servers");
        }

        $this->_commands[] = $command;

        $this->_specifiedConnection->resetConnection();

        return $this;
    }

Add command to pipeline

@param string $name Command name
@param array  $args Arguments
@return Rediska_Pipeline


public function write()
    {
        $result = $this->getConnection()->write($this->getCommand());
        $this->_isWritten = true;

        return $result;
    }

public function write ( ) { $ result = $ this -> getConnection ( ) -> write ( $ this -> getCommand ( ) ) ; $ this -> _isWritten = true ; return $ result ; }

Write command to connection

@return boolean


public function setResponseCallback($callback)
    {
        if ($callback !== null && !is_callable($callback)) {
            throw new Rediska_Connection_Exec_Exception('Bad callback');
        }

        $this->_responseCallback = $callback;

        return $this;
    }

public
function
setResponseCallback
(
$
callback
)
{
if
(
$
callback
!==
&&
!
is_callable
(
$
callback
)
)
{
throw
new
Rediska_Connection_Exec_Exception
(
'Bad callback'
)
;
}
$
this
->
_responseCallback
=
$
callback
;
return
$
this
;
}

Set response callback

@param mixin $callback
@return Rediska_Connection_Exec


public static function transformMultiBulkCommand(array $command)
    {
        $commandString = self::REPLY_MULTY_BULK . count($command) . Rediska::EOL;
        foreach($command as $argument) {
            $commandString .= self::REPLY_BULK . strlen($argument) . Rediska::EOL . $argument . Rediska::EOL;
        }
        return $commandString;
    }

public static function transformMultiBulkCommand ( array $ command ) { $ commandString = self :: REPLY_MULTY_BULK . count ( $ command ) . Rediska :: EOL ; foreach ( $ command as $ argument ) { $ commandString .= self :: REPLY_BULK . strlen ( $ argument ) . Rediska :: EOL . $ argument . Rediska :: EOL ; } return $ commandString ; }

Transfrom Multi Bulk command to string

@param array $command
@return string


public function append($value, $createIfNotExists = true)
    {
        $result = $this->_getRediskaOn()->appendToList($this->getName(), $value, $createIfNotExists);

        if (!is_null($this->getExpire()) && $result) {
            $this->expire($this->getExpire(), $this->isExpireTimestamp());
        }

        return $result;
    }

public function append ( $ value , $ createIfNotExists = true ) { $ result = $ this -> _getRediskaOn ( ) -> appendToList ( $ this -> getName ( ) , $ value , $ createIfNotExists ) ; if ( ! is_null ( $ this -> getExpire ( ) ) && $ result ) { $ this -> expire ( $ this -> getExpire ( ) , $ this -> isExpireTimestamp ( ) ) ; } return $ result ; }

Append value to the end of List

@param mixed             $value              Value
@param boolean[optional] $createIfNotExists  Create list if not exists
@return boolean


public function prepend($value, $createIfNotExists = true)
    {
        $result = $this->_getRediskaOn()->prependToList($this->getName(), $value, $createIfNotExists);

        if (!is_null($this->getExpire()) && $result) {
            $this->expire($this->getExpire(), $this->isExpireTimestamp());
        }

        return $result;
    }

public function prepend ( $ value , $ createIfNotExists = true ) { $ result = $ this -> _getRediskaOn ( ) -> prependToList ( $ this -> getName ( ) , $ value , $ createIfNotExists ) ; if ( ! is_null ( $ this -> getExpire ( ) ) && $ result ) { $ this -> expire ( $ this -> getExpire ( ) , $ this -> isExpireTimestamp ( ) ) ; } return $ result ; }

Append value to the head of List

@param mixed             $value              Value
@param boolean[optional] $createIfNotExists  Create list if not exists
@return boolean


public function truncate($start, $end)
    {
        $result = $this->_getRediskaOn()->truncateList($this->getName(), $start, $end);

        if (!is_null($this->getExpire()) && $result) {
            $this->expire($this->getExpire(), $this->isExpireTimestamp());
        }

        return $result;
    }

public function truncate ( $ start , $ end ) { $ result = $ this -> _getRediskaOn ( ) -> truncateList ( $ this -> getName ( ) , $ start , $ end ) ; if ( ! is_null ( $ this -> getExpire ( ) ) && $ result ) { $ this -> expire ( $ this -> getExpire ( ) , $ this -> isExpireTimestamp ( ) ) ; } return $ result ; }

Trim the list at key to the specified range of elements

@param integer $start Start index
@param integer $end End index
@return boolean


public function set($index, $value)
    {
        $result = $this->_getRediskaOn()->setToList($this->getName(), $index, $value);

        if (!is_null($this->getExpire()) && $result) {
            $this->expire($this->getExpire(), $this->isExpireTimestamp());
        }

        return $result;
    }

public function set ( $ index , $ value ) { $ result = $ this -> _getRediskaOn ( ) -> setToList ( $ this -> getName ( ) , $ index , $ value ) ; if ( ! is_null ( $ this -> getExpire ( ) ) && $ result ) { $ this -> expire ( $ this -> getExpire ( ) , $ this -> isExpireTimestamp ( ) ) ; } return $ result ; }

Set a new value as the element at index position of the List

@param integer $index Index
@param mixed $value Value
@return boolean


public function insertAfter($referenceValue, $value)
    {
        return $this->_getRediskaOn()->insertToListAfter($this->getName(), $referenceValue, $value);
    }

public function insertAfter ( $ referenceValue , $ value ) { return $ this -> _getRediskaOn ( ) -> insertToListAfter ( $ this -> getName ( ) , $ referenceValue , $ value ) ; }

Insert a new value as the element after the reference value

@param mixed   $referenceValue Reference value
@param mixed   $value          Value
@return integer|boolean


public function insertBefore($referenceValue, $value)
    {
        return $this->_getRediskaOn()->insertToListBefore($this->getName(), $referenceValue, $value);
    }

public function insertBefore ( $ referenceValue , $ value ) { return $ this -> _getRediskaOn ( ) -> insertToListBefore ( $ this -> getName ( ) , $ referenceValue , $ value ) ; }

Insert a new value as the element before the reference value

@param mixed   $referenceValue Reference value
@param mixed   $value          Value
@return integer|boolean


public function insert($position, $referenceValue, $value)
    {
        return $this->_getRediskaOn()->insertToList($this->getName(), $position, $referenceValue, $value);
    }

public function insert ( $ position , $ referenceValue , $ value ) { return $ this -> _getRediskaOn ( ) -> insertToList ( $ this -> getName ( ) , $ position , $ referenceValue , $ value ) ; }

Insert a new value as the element before or after the reference value

@param string  $position       BEFORE or AFTER
@param mixed   $referenceValue Reference value
@param mixed   $value          Value
@return integer|boolean


public function remove($value, $count = 0)
    {
        $result = $this->_getRediskaOn()->deleteFromList($this->getName(), $value, $count);

        if (!is_null($this->getExpire()) && $result) {
            $this->expire($this->getExpire(), $this->isExpireTimestamp());
        }

        return $result;
    }

public function remove ( $ value , $ count = 0 ) { $ result = $ this -> _getRediskaOn ( ) -> deleteFromList ( $ this -> getName ( ) , $ value , $ count ) ; if ( ! is_null ( $ this -> getExpire ( ) ) && $ result ) { $ this -> expire ( $ this -> getExpire ( ) , $ this -> isExpireTimestamp ( ) ) ; } return $ result ; }

Delete element from list by value

@throws Rediska_Exception
@param $value Element value
@param $count Limit of deleted items
@return integer


public function shift()
    {
        $result = $this->_getRediskaOn()->shiftFromList($this->getName());

        if (!is_null($this->getExpire()) && $result) {
            $this->expire($this->getExpire(), $this->isExpireTimestamp());
        }

        return $result;
    }

public function shift ( ) { $ result = $ this -> _getRediskaOn ( ) -> shiftFromList ( $ this -> getName ( ) ) ; if ( ! is_null ( $ this -> getExpire ( ) ) && $ result ) { $ this -> expire ( $ this -> getExpire ( ) , $ this -> isExpireTimestamp ( ) ) ; } return $ result ; }

Return and remove the first element of the List

@return mixed


public function shiftBlocking($timeout = 0)
    {
        $result = $this->_getRediskaOn()->shiftFromListBlocking($this->getName(), $timeout);

        if (!is_null($this->getExpire()) && $result) {
            $this->expire($this->getExpire(), $this->isExpireTimestamp());
        }

        return $result;
    }

public function shiftBlocking ( $ timeout = 0 ) { $ result = $ this -> _getRediskaOn ( ) -> shiftFromListBlocking ( $ this -> getName ( ) , $ timeout ) ; if ( ! is_null ( $ this -> getExpire ( ) ) && $ result ) { $ this -> expire ( $ this -> getExpire ( ) , $ this -> isExpireTimestamp ( ) ) ; } return $ result ; }

Return and remove the first element of the List and block if list empty or not exists

@param $timeout Blocking timeout
@return mixed


public function pop($pushTo = null)
    {
        if ($pushTo instanceof Rediska_Key_List) {
            $pushTo = $pushTo->getName();
        }

        $result = $this->_getRediskaOn()->popFromList($this->getName(), $pushTo);

        if (!is_null($this->getExpire()) && $result) {
            $this->expire($this->getExpire(), $this->isExpireTimestamp());
        }

        return $result;
    }

public function pop ( $ pushTo = null ) { if ( $ pushTo instanceof Rediska_Key_List ) { $ pushTo = $ pushTo -> getName ( ) ; } $ result = $ this -> _getRediskaOn ( ) -> popFromList ( $ this -> getName ( ) , $ pushTo ) ; if ( ! is_null ( $ this -> getExpire ( ) ) && $ result ) { $ this -> expire ( $ this -> getExpire ( ) , $ this -> isExpireTimestamp ( ) ) ; } return $ result ; }

Return and remove the last element of the List

@param string|Rediska_Key_List $pushTo After pop, push value to another list
@return mixed


public function popBlocking($timeout = 0, $pushToKey = null)
    {
        $result = $this->_getRediskaOn()->popFromListBlocking($this->getName(), $timeout, $pushToKey);

        if (!is_null($this->getExpire()) && $result) {
            $this->expire($this->getExpire(), $this->isExpireTimestamp());
        }

        return $result;
    }

public function popBlocking ( $ timeout = 0 , $ pushToKey = null ) { $ result = $ this -> _getRediskaOn ( ) -> popFromListBlocking ( $ this -> getName ( ) , $ timeout , $ pushToKey ) ; if ( ! is_null ( $ this -> getExpire ( ) ) && $ result ) { $ this -> expire ( $ this -> getExpire ( ) , $ this -> isExpireTimestamp ( ) ) ; } return $ result ; }

Return and remove the last element of the List and block if list empty or not exists.

@param integer $timeout[optional]   Blocking timeout. 0 for default - timeout is disabled.
@param string  $pushToKey[optional] If not null - push value to another list.
@return mixed

Return and remove the last element of the List and block if list empty or not exists .


public function fromArray(array $array)
    {
        $pipeline = $this->_getRediskaOn()->pipeline();
        foreach($array as $item) {
            $pipeline->appendToList($this->getName(), $item);
        }

        if (!is_null($this->getExpire())) {
            $pipeline->expire($this->getName(), $this->getExpire(), $this->isExpireTimestamp());
        }

        $pipeline->execute();

        return true;
    }

public function fromArray ( array $ array ) { $ pipeline = $ this -> _getRediskaOn ( ) -> pipeline ( ) ; foreach ( $ array as $ item ) { $ pipeline -> appendToList ( $ this -> getName ( ) , $ item ) ; } if ( ! is_null ( $ this -> getExpire ( ) ) ) { $ pipeline -> expire ( $ this -> getName ( ) , $ this -> getExpire ( ) , $ this -> isExpireTimestamp ( ) ) ; } $ pipeline -> execute ( ) ; return true ; }


public function load($id, $doNotTestCacheValidity = false)
    {
        $id = (array) $id;
        foreach ($id as $key){
            $key = $this->_options['storage']['prefix_key'] . $key;
            $this->_getTransactionByKey($key)
                ->getFromHash(
                    $key,
                    self::FIELD_DATA
                );
        }
        $oldSerializaerAdapter = $this->getRediska()->getSerializer()->getAdapter();
        $this->getRediska()->setSerializerAdapter('toString');
        $result = $this->_execTransactions();
        $this->getRediska()->getSerializer()->setAdapter($oldSerializaerAdapter);
        if(count($result) == 1){
            if(null === ($result = array_shift($result))){
                return false;
            } else {
                return $result;
            }
        } else {
            return $result;
        }
    }

public function load ( $ id , $ doNotTestCacheValidity = false ) { $ id = ( array ) $ id ; foreach ( $ id as $ key ) { $ key = $ this -> _options [ 'storage' ] [ 'prefix_key' ] . $ key ; $ this -> _getTransactionByKey ( $ key ) -> getFromHash ( $ key , self :: FIELD_DATA ) ; } $ oldSerializaerAdapter = $ this -> getRediska ( ) -> getSerializer ( ) -> getAdapter ( ) ; $ this -> getRediska ( ) -> setSerializerAdapter ( 'toString' ) ; $ result = $ this -> _execTransactions ( ) ; $ this -> getRediska ( ) -> getSerializer ( ) -> setAdapter ( $ oldSerializaerAdapter ) ; if ( count ( $ result ) == 1 ) { if ( null === ( $ result = array_shift ( $ result ) ) ) { return false ; } else { return $ result ; } } else { return $ result ; } }

Load value with given id from cache

@param  string  $id                     Cache id
@param  boolean $doNotTestCacheValidity If set to true, the cache validity won't be tested
@return string|false cached datas


public function save($data, $id, $tags = array(), $specificLifetime = false)
    {
        if(!is_array($tags)) $tags = array($tags);

        $lifetime = $this->getLifetime($specificLifetime);

        $oldTags = explode(
            ',', $this->getRediska()->getFromHash(
                $this->_options['storage']['prefix_key'].$id, self::FIELD_TAGS
            )
        );

        $this->_getTransactionByKey($this->_options['storage']['prefix_key'].$id)
            ->setToHash(
                $this->_options['storage']['prefix_key'].$id,  array(
                self::FIELD_DATA => $data,
                self::FIELD_TAGS => implode(',',$tags),
                self::FIELD_MTIME => time(),
                self::FIELD_INF => $lifetime ? 0 : 1)
            );
        $this->_getTransactionByKey($this->_options['storage']['prefix_key'].$id)
            ->expire($this->_options['storage']['prefix_key'].$id, $lifetime ? $lifetime : self::MAX_LIFETIME);
        if ($addTags = ($oldTags ? array_diff($tags, $oldTags) : $tags)) {
            foreach ($addTags as $add) {
                $this->_getTransactionByKey($this->_options['storage']['set_tags'])
                    ->addToSet($this->_options['storage']['set_tags'], $add);
            }
            foreach($addTags as $tag){
                $this->_getTransactionByKey($this->_options['storage']['prefix_tag_ids'] . $tag)
                    ->addToSet($this->_options['storage']['prefix_tag_ids'] . $tag, $id);
            }
        }
        if ($remTags = ($oldTags ? array_diff($oldTags, $tags) : false)){
            foreach($remTags as $tag){
                $this->_getTransactionByKey($this->_options['storage']['prefix_tag_ids'] . $tag)
                    ->deleteFromSet($this->_options['storage']['prefix_tag_ids'] . $tag, $id);
            }
        }
        $this->_getTransactionByKey($this->_options['storage']['set_ids'])
            ->addToSet($this->_options['storage']['set_ids'], $id);
        try {
            $this->_execTransactions();
            return true;
        } catch(Rediska_Transaction_Exception $e){
            $this->_log($e->getMessage(), Zend_Log::ERR);
            return false;
        }

    }

public function save ( $ data , $ id , $ tags = array ( ) , $ specificLifetime = false ) { if ( ! is_array ( $ tags ) ) $ tags = array ( $ tags ) ; $ lifetime = $ this -> getLifetime ( $ specificLifetime ) ; $ oldTags = explode ( ',' , $ this -> getRediska ( ) -> getFromHash ( $ this -> _options [ 'storage' ] [ 'prefix_key' ] . $ id , self :: FIELD_TAGS ) ) ; $ this -> _getTransactionByKey ( $ this -> _options [ 'storage' ] [ 'prefix_key' ] . $ id ) -> setToHash ( $ this -> _options [ 'storage' ] [ 'prefix_key' ] . $ id , array ( self :: FIELD_DATA => $ data , self :: FIELD_TAGS => implode ( ',' , $ tags ) , self :: FIELD_MTIME => time ( ) , self :: FIELD_INF => $ lifetime ? 0 : 1 ) ) ; $ this -> _getTransactionByKey ( $ this -> _options [ 'storage' ] [ 'prefix_key' ] . $ id ) -> expire ( $ this -> _options [ 'storage' ] [ 'prefix_key' ] . $ id , $ lifetime ? $ lifetime : self :: MAX_LIFETIME ) ; if ( $ addTags = ( $ oldTags ? array_diff ( $ tags , $ oldTags ) : $ tags ) ) { foreach ( $ addTags as $ add ) { $ this -> _getTransactionByKey ( $ this -> _options [ 'storage' ] [ 'set_tags' ] ) -> addToSet ( $ this -> _options [ 'storage' ] [ 'set_tags' ] , $ add ) ; } foreach ( $ addTags as $ tag ) { $ this -> _getTransactionByKey ( $ this -> _options [ 'storage' ] [ 'prefix_tag_ids' ] . $ tag ) -> addToSet ( $ this -> _options [ 'storage' ] [ 'prefix_tag_ids' ] . $ tag , $ id ) ; } } if ( $ remTags = ( $ oldTags ? array_diff ( $ oldTags , $ tags ) : false ) ) { foreach ( $ remTags as $ tag ) { $ this -> _getTransactionByKey ( $ this -> _options [ 'storage' ] [ 'prefix_tag_ids' ] . $ tag ) -> deleteFromSet ( $ this -> _options [ 'storage' ] [ 'prefix_tag_ids' ] . $ tag , $ id ) ; } } $ this -> _getTransactionByKey ( $ this -> _options [ 'storage' ] [ 'set_ids' ] ) -> addToSet ( $ this -> _options [ 'storage' ] [ 'set_ids' ] , $ id ) ; try { $ this -> _execTransactions ( ) ; return true ; } catch ( Rediska_Transaction_Exception $ e ) { $ this -> _log ( $ e -> getMessage ( ) , Zend_Log :: ERR ) ; return false ; } }

Save some string datas into a cache record

Note : $data is always "string" (serialization is done by the
core not by the backend)

@param  string  $data             Datas to cache
@param  string  $id               Cache id
@param  array   $tags             Array of strings, the cache record will be tagged by each string entry
@param  int     $specificLifetime If != false, set a specific lifetime for this cache record (null => infinite lifetime)
@return boolean True if no problem


public function remove($id)
    {
        $tags = explode(
            ',', $this->getRediska()->getFromHash(
                $this->_options['storage']['prefix_key'].$id, self::FIELD_TAGS
            )
        );

        $this->_getTransactionByKey($this->_options['storage']['prefix_key'].$id)
            ->delete($this->_options['storage']['prefix_key'].$id);
        $this->_getTransactionByKey($this->_options['storage']['set_ids'], $id)
            ->deleteFromSet( $this->_options['storage']['set_ids'], $id );
        foreach($tags as $tag) {
            $this->_getTransactionByKey($this->_options['storage']['prefix_tag_ids'] . $tag)
                ->deleteFromSet($this->_options['storage']['prefix_tag_ids'] . $tag, $id);
        }
        $result = $this->_execTransactions();
        if(count($result)){
            return array_shift($result);
        } else {
            return false;
        }
    }

public function remove ( $ id ) { $ tags = explode ( ',' , $ this -> getRediska ( ) -> getFromHash ( $ this -> _options [ 'storage' ] [ 'prefix_key' ] . $ id , self :: FIELD_TAGS ) ) ; $ this -> _getTransactionByKey ( $ this -> _options [ 'storage' ] [ 'prefix_key' ] . $ id ) -> delete ( $ this -> _options [ 'storage' ] [ 'prefix_key' ] . $ id ) ; $ this -> _getTransactionByKey ( $ this -> _options [ 'storage' ] [ 'set_ids' ] , $ id ) -> deleteFromSet ( $ this -> _options [ 'storage' ] [ 'set_ids' ] , $ id ) ; foreach ( $ tags as $ tag ) { $ this -> _getTransactionByKey ( $ this -> _options [ 'storage' ] [ 'prefix_tag_ids' ] . $ tag ) -> deleteFromSet ( $ this -> _options [ 'storage' ] [ 'prefix_tag_ids' ] . $ tag , $ id ) ; } $ result = $ this -> _execTransactions ( ) ; if ( count ( $ result ) ) { return array_shift ( $ result ) ; } else { return false ; } }

Remove a cache record

@param  string $id Cache id
@return boolean True if no problem


public function clean($mode = Zend_Cache::CLEANING_MODE_ALL, $tags = array())
    {
        if( $tags && ! is_array($tags)) {
            $tags = array($tags);
        }
        $result = true;
        switch ($mode) {
            case Zend_Cache::CLEANING_MODE_ALL:
                $this->_removeIds($this->getIds());
                break;

            case Zend_Cache::CLEANING_MODE_OLD:
                break;

            case Zend_Cache::CLEANING_MODE_MATCHING_TAG:
                $this->_removeIdsByMatchingTags($tags);
                break;

            case Zend_Cache::CLEANING_MODE_NOT_MATCHING_TAG:
                $this->_removeIdsByNotMatchingTags($tags);
                break;

            case Zend_Cache::CLEANING_MODE_MATCHING_ANY_TAG:
                $this->_removeIdsByMatchingAnyTags($tags);
                break;

            default:
                Zend_Cache::throwException('Invalid mode for clean() method: '.$mode);
        }
        return $this->_collectGarbage();
    }

public
function
clean
(
$
mode
=
Zend_Cache
::
CLEANING_MODE_ALL
,
$
tags
=
array
(
)
)
{
if
(
$
tags
&&
!
is_array
(
$
tags
)
)
{
$
tags
=
array
(
$
tags
)
;
}
$
result
=
true
;
switch
(
$
mode
)
{
case
Zend_Cache
::
CLEANING_MODE_ALL
:
$
this
->
_removeIds
(
$
this
->
getIds
(
)
)
;
break
;
case
Zend_Cache
::
CLEANING_MODE_OLD
:
break
;
case
Zend_Cache
::
CLEANING_MODE_MATCHING_TAG
:
$
this
->
_removeIdsByMatchingTags
(
$
tags
)
;
break
;
case
Zend_Cache
::
CLEANING_MODE_NOT_MATCHING_TAG
:
$
this
->
_removeIdsByNotMatchingTags
(
$
tags
)
;
break
;
case
Zend_Cache
::
CLEANING_MODE_MATCHING_ANY_TAG
:
$
this
->
_removeIdsByMatchingAnyTags
(
$
tags
)
;
break
;
default
:
Zend_Cache
::
throwException
(
'Invalid mode for clean() method: '
.
$
mode
)
;
}
return
$
this
->
_collectGarbage
(
)
;
}

Clean some cache records

Available modes are :
'all' (default)  => remove all cache entries ($tags is not used)
'old'            => supported
'matchingTag'    => supported
'notMatchingTag' => supported
'matchingAnyTag' => supported

@param  string $mode Clean mode
@param  array  $tags Array of tags
@throws Zend_Cache_Exception
@return boolean True if no problem


public function setDirectives($directives)
    {
        parent::setDirectives($directives);
        $lifetime = $this->getLifetime(false);
        if ($lifetime > self::MAX_LIFETIME) {
            $this->_log(
                'redis backend has a limit of 30 days (' . self::MAX_LIFETIME
                . ' seconds) for the lifetime'
            );
        }
    }

Set the frontend directives

@param  array $directives Assoc of directives
@throws Zend_Cache_Exception
@return void


public function getIdsNotMatchingTags($tags = array())
    {
            $sets = $this->_preprocessTagIds($tags);
            array_unshift($sets, $this->_options['storage']['set_ids']);
            $data = $this->getRediska()->diffSets($sets);
            return $data;
    }

public function getIdsNotMatchingTags ( $ tags = array ( ) ) { $ sets = $ this -> _preprocessTagIds ( $ tags ) ; array_unshift ( $ sets , $ this -> _options [ 'storage' ] [ 'set_ids' ] ) ; $ data = $ this -> getRediska ( ) -> diffSets ( $ sets ) ; return $ data ; }

Return an array of stored cache ids which don't match given tags

In case of multiple tags, a logical OR is made between tags

@param array $tags array of tags
@return array array of not matching cache ids (string)

Return an array of stored cache ids which don t match given tags


public function getMetadatas($id)
    {
        $metaData = $this->getRediska()->getFromHash(
            $this->_options['storage']['prefix_key'].$id,
            array(self::FIELD_DATA, self::FIELD_TAGS, self::FIELD_MTIME, self::FIELD_INF)
        );
        if(!$metaData[self::FIELD_MTIME]) {
          return false;
        }
        $lifetime = $this->getRediska()
            ->getLifetime($this->_options['storage']['prefix_key'] . $id);
        $tags = explode(',', $metaData[self::FIELD_TAGS]);
        $expire = $metaData[self::FIELD_INF] === '1' ? false : time() + $lifetime;

        return array(
            'expire' => $expire,
            'tags'   => $tags,
            'mtime'  => $metaData[self::FIELD_MTIME],
        );
    }

public function getMetadatas ( $ id ) { $ metaData = $ this -> getRediska ( ) -> getFromHash ( $ this -> _options [ 'storage' ] [ 'prefix_key' ] . $ id , array ( self :: FIELD_DATA , self :: FIELD_TAGS , self :: FIELD_MTIME , self :: FIELD_INF ) ) ; if ( ! $ metaData [ self :: FIELD_MTIME ] ) { return false ; } $ lifetime = $ this -> getRediska ( ) -> getLifetime ( $ this -> _options [ 'storage' ] [ 'prefix_key' ] . $ id ) ; $ tags = explode ( ',' , $ metaData [ self :: FIELD_TAGS ] ) ; $ expire = $ metaData [ self :: FIELD_INF ] === '1' ? false : time ( ) + $ lifetime ; return array ( 'expire' => $ expire , 'tags' => $ tags , 'mtime' => $ metaData [ self :: FIELD_MTIME ] , ) ; }

Return an array of metadatas for the given cache id

The array must include these keys :
- expire : the expire timestamp
- tags : a string array of tags
- mtime : timestamp of last modification time

@param string $id cache id
@return array array of metadatas (false if the cache id is not found)


protected function _collectGarbage()
    {
        $exists = array();
        $tags = $this->getTags();
        foreach($tags as $tag){
            $prefix_tag_ids = $this->_options['storage']['prefix_tag_ids'] . $tag;
            $tagMembers = $this->getRediska()->getSet($prefix_tag_ids);
            $this->_getTransactionByKey($prefix_tag_ids)->watch($prefix_tag_ids);
            $expired = array();
            if(count($tagMembers)) {
                foreach($tagMembers as $id) {
                    if( ! isset($exists[$id])) {
                        $exists[$id] = $this->getRediska()
                            ->exists($this->_options['storage']['prefix_key'].$id);
                    }
                    if(!$exists[$id]) {
                        $expired[] = $id;
                    }
                }
                if(!count($expired)) continue;
            }
            if(!count($tagMembers) || count($expired) == count($tagMembers)) {
                $this->_getTransactionByKey($this->_options['storage']['set_tags'])
                    ->deleteFromSet($this->_options['storage']['set_tags'], $tag);
                $this->_getTransactionByKey($this->_options['storage']['prefix_tag_ids'] . $tag)
                    ->delete($this->_options['storage']['prefix_tag_ids'] . $tag);
            } else {
                $this->_getTransactionByKey($this->_options['storage']['prefix_tag_ids'] . $tag)
                    ->deleteFromSet( $this->_options['storage']['prefix_tag_ids'] . $tag, $expired);
            }
            $this->_getTransactionByKey($this->_options['storage']['set_ids'])
                ->deleteFromSet( $this->_options['storage']['set_ids'], $expired);
        }
        try{
            return (bool) $this->_execTransactions();
        } catch (Rediska_Transaction_AbortedException $e ){
            $this->_log($e->getMessage(), Zend_Log::ERR);
            return false;
        }
    }

protected function _collectGarbage ( ) { $ exists = array ( ) ; $ tags = $ this -> getTags ( ) ; foreach ( $ tags as $ tag ) { $ prefix_tag_ids = $ this -> _options [ 'storage' ] [ 'prefix_tag_ids' ] . $ tag ; $ tagMembers = $ this -> getRediska ( ) -> getSet ( $ prefix_tag_ids ) ; $ this -> _getTransactionByKey ( $ prefix_tag_ids ) -> watch ( $ prefix_tag_ids ) ; $ expired = array ( ) ; if ( count ( $ tagMembers ) ) { foreach ( $ tagMembers as $ id ) { if ( ! isset ( $ exists [ $ id ] ) ) { $ exists [ $ id ] = $ this -> getRediska ( ) -> exists ( $ this -> _options [ 'storage' ] [ 'prefix_key' ] . $ id ) ; } if ( ! $ exists [ $ id ] ) { $ expired [ ] = $ id ; } } if ( ! count ( $ expired ) ) continue ; } if ( ! count ( $ tagMembers ) || count ( $ expired ) == count ( $ tagMembers ) ) { $ this -> _getTransactionByKey ( $ this -> _options [ 'storage' ] [ 'set_tags' ] ) -> deleteFromSet ( $ this -> _options [ 'storage' ] [ 'set_tags' ] , $ tag ) ; $ this -> _getTransactionByKey ( $ this -> _options [ 'storage' ] [ 'prefix_tag_ids' ] . $ tag ) -> delete ( $ this -> _options [ 'storage' ] [ 'prefix_tag_ids' ] . $ tag ) ; } else { $ this -> _getTransactionByKey ( $ this -> _options [ 'storage' ] [ 'prefix_tag_ids' ] . $ tag ) -> deleteFromSet ( $ this -> _options [ 'storage' ] [ 'prefix_tag_ids' ] . $ tag , $ expired ) ; } $ this -> _getTransactionByKey ( $ this -> _options [ 'storage' ] [ 'set_ids' ] ) -> deleteFromSet ( $ this -> _options [ 'storage' ] [ 'set_ids' ] , $ expired ) ; } try { return ( bool ) $ this -> _execTransactions ( ) ; } catch ( Rediska_Transaction_AbortedException $ e ) { $ this -> _log ( $ e -> getMessage ( ) , Zend_Log :: ERR ) ; return false ; } }

Cleans up expired keys and list members
@return boolean


public function add($value)
    {
        $result = $this->_getRediskaOn()->addToSet($this->getName(), $value);

        if (!is_null($this->getExpire()) && $result) {
            $this->expire($this->getExpire(), $this->isExpireTimestamp());
        }

        return $result;
    }

public function add ( $ value ) { $ result = $ this -> _getRediskaOn ( ) -> addToSet ( $ this -> getName ( ) , $ value ) ; if ( ! is_null ( $ this -> getExpire ( ) ) && $ result ) { $ this -> expire ( $ this -> getExpire ( ) , $ this -> isExpireTimestamp ( ) ) ; } return $ result ; }

Add the specified member to the Set

@param mixed $value Value
@return boolean


public function remove($value)
    {
        $result = $this->_getRediskaOn()->deleteFromSet($this->getName(), $value);

        if (!is_null($this->getExpire()) && $result) {
            $this->expire($this->getExpire(), $this->isExpireTimestamp());
        }

        return $result;
    }

public function remove ( $ value ) { $ result = $ this -> _getRediskaOn ( ) -> deleteFromSet ( $ this -> getName ( ) , $ value ) ; if ( ! is_null ( $ this -> getExpire ( ) ) && $ result ) { $ this -> expire ( $ this -> getExpire ( ) , $ this -> isExpireTimestamp ( ) ) ; } return $ result ; }

Remove the specified member from the Set

@param mixed $value Value
@return boolean


public function move($set, $value)
    {
        if ($set instanceof Rediska_Key_Set) {
            $set = $set->getName();
        }

        return $this->_getRediskaOn()->moveToSet($this->getName(), $set, $value);
    }

public function move ( $ set , $ value ) { if ( $ set instanceof Rediska_Key_Set ) { $ set = $ set -> getName ( ) ; } return $ this -> _getRediskaOn ( ) -> moveToSet ( $ this -> getName ( ) , $ set , $ value ) ; }

Move the specified member from one Set to another atomically

@param string|Rediska_Key_Set $set   Set key name or object
@param mixed                  $value Value
@return boolean


public function intersect($setOrSets, $storeKeyName = null)
    {
        $sets = $this->_prepareSetsForCompare($setOrSets);

        return $this->_getRediskaOn()->intersectSets($sets, $storeKeyName);
    }

public function intersect ( $ setOrSets , $ storeKeyName = null ) { $ sets = $ this -> _prepareSetsForCompare ( $ setOrSets ) ; return $ this -> _getRediskaOn ( ) -> intersectSets ( $ sets , $ storeKeyName ) ; }

Return the intersection between the Sets

@param string|Rediska_Key_Set|array $setOrSets    Set key name or object, or array of its
@param string|null                  $storeKeyName Store intersection to set with key name
@return array|boolean


public function union($setOrSets, $storeKeyName = null)
    {
        $sets = $this->_prepareSetsForCompare($setOrSets);

        return $this->_getRediskaOn()->unionSets($sets, $storeKeyName);
    }

public function union ( $ setOrSets , $ storeKeyName = null ) { $ sets = $ this -> _prepareSetsForCompare ( $ setOrSets ) ; return $ this -> _getRediskaOn ( ) -> unionSets ( $ sets , $ storeKeyName ) ; }

Return the union between the Sets

@param string|Rediska_Key_Set|array $setOrSets    Set key name or object, or array of its
@param string|null                  $storeKeyName Store union to set with key name
@return array|boolean


public function diff($setOrSets, $storeKeyName = null)
    {
        $sets = $this->_prepareSetsForCompare($setOrSets);

        return $this->_getRediskaOn()->diffSets($sets, $storeKeyName);
    }

public function diff ( $ setOrSets , $ storeKeyName = null ) { $ sets = $ this -> _prepareSetsForCompare ( $ setOrSets ) ; return $ this -> _getRediskaOn ( ) -> diffSets ( $ sets , $ storeKeyName ) ; }

Return the difference between the Sets

@param string|array $setOrSets    Set key name or object, or array of its
@param string|null  $storeKeyName Store union to set with key name
@return array|boolean


public function getRediska()
    {
        if (!is_object($this->_rediska)) {
            $this->_rediska = self::getRediskaInstance($this->_rediska, $this->_optionsException, $this->_rediskaOptionName);
        }

        return $this->_rediska;
    }

public function getRediska ( ) { if ( ! is_object ( $ this -> _rediska ) ) { $ this -> _rediska = self :: getRediskaInstance ( $ this -> _rediska , $ this -> _optionsException , $ this -> _rediskaOptionName ) ; } return $ this -> _rediska ; }


public function setValue($value)
    {
        if ($this->getExpire() !== null && !$this->isExpireTimestamp()) {
            $reply = $this->setAndExpire($value, $this->getExpire());
        } else {
            $reply = $this->_getRediskaOn()->set($this->getName(), $value);

            if ($reply && !is_null($this->getExpire())) {
                $this->expire($this->getExpire(), $this->isExpireTimestamp());
            }
        }

        return $reply;
    }

public function setValue ( $ value ) { if ( $ this -> getExpire ( ) !== null && ! $ this -> isExpireTimestamp ( ) ) { $ reply = $ this -> setAndExpire ( $ value , $ this -> getExpire ( ) ) ; } else { $ reply = $ this -> _getRediskaOn ( ) -> set ( $ this -> getName ( ) , $ value ) ; if ( $ reply && ! is_null ( $ this -> getExpire ( ) ) ) { $ this -> expire ( $ this -> getExpire ( ) , $ this -> isExpireTimestamp ( ) ) ; } } return $ reply ; }

Set key value

@param $value
@return boolean


public function setAndExpire($value, $seconds)
    {
        return $this->_getRediskaOn()->setAndExpire($this->getName(), $value, $seconds);
    }

public function setAndExpire ( $ value , $ seconds ) { return $ this -> _getRediskaOn ( ) -> setAndExpire ( $ this -> getName ( ) , $ value , $ seconds ) ; }

Set and expire

@param mixed   $value
@param integer $seconds
@return boolean


public function setBit($offset, $bit)
    {
        return $this->_getRediskaOn()->setBit($this->getName(), $offset, $bit);
    }

public function setBit ( $ offset , $ bit ) { return $ this -> _getRediskaOn ( ) -> setBit ( $ this -> getName ( ) , $ offset , $ bit ) ; }

Returns the bit value at offset in the string value stored at key

@param integer $offset Offset
@param integer $bit    Bit (0 or 1)
@return integer


public function getOrSetValue($object = null, $expire = null, $expireIsTimestamp = false)
    {
        return new Rediska_Key_GetOrSetValue($this, $object, $expire, $expireIsTimestamp);
    }

public function getOrSetValue ( $ object = null , $ expire = null , $ expireIsTimestamp = false ) { return new Rediska_Key_GetOrSetValue ( $ this , $ object , $ expire , $ expireIsTimestamp ) ; }

Get value, if value not present set it from chain method

@param mixin[optional]   $object            Object of chain method
@param integer[optional] $expire            Expire
@param boolean[optional] $expireIsTimestamp If true $expire argument in seconds, or $expire is timestamp
@return Rediska_Key_GetOrSetValue

Get value if value not present set it from chain method


public function followersAction()
    {
        $userId = $this->_getParam('userId');

        $user = new User($userId);
        $this->view->user = $user->getValue();

        $followers = new Followers($userId);

        $this->view->users = User::getMultiple($followers->toArray());
        $this->_setUsersIFollow();
    }

public function followersAction ( ) { $ userId = $ this -> _getParam ( 'userId' ) ; $ user = new User ( $ userId ) ; $ this -> view -> user = $ user -> getValue ( ) ; $ followers = new Followers ( $ userId ) ; $ this -> view -> users = User :: getMultiple ( $ followers -> toArray ( ) ) ; $ this -> _setUsersIFollow ( ) ; }


public function followingAction()
    {
        $userId = $this->_getParam('userId');

        $following = new Following($userId);

        $this->view->users = User::getMultiple($following->toArray());
        $this->_setUsersIFollow();
    }

public function followingAction ( ) { $ userId = $ this -> _getParam ( 'userId' ) ; $ following = new Following ( $ userId ) ; $ this -> view -> users = User :: getMultiple ( $ following -> toArray ( ) ) ; $ this -> _setUsersIFollow ( ) ; }


public function followAction()
    {
        $auth = Zend_Auth::getInstance();
        if (!$auth->hasIdentity()) {
            throw new Zend_Auth_Exception("You're not authorized to see this page");
        }

        $userId = $this->_getParam('userId');
        $follower = $auth->getStorage()->read();

        if ($userId != $follower['id']) {
            $followers = new Followers($userId);
            $followers[] = $follower['id'];

            $following = new Following($follower['id']);
            $following[] = $userId;
        }
        $this->_redirect('/user/followers/userId/' . $userId);
    }


public function moveToDb($dbIndex)
    {
        $result = $this->_getRediskaOn()->moveToDb($this->getName(), $dbIndex);

        if (!is_null($this->getExpire()) && $result) {
            $this->expire($this->getExpire(), $this->isExpireTimestamp());
        }

        return $result;
    }

public function moveToDb ( $ dbIndex ) { $ result = $ this -> _getRediskaOn ( ) -> moveToDb ( $ this -> getName ( ) , $ dbIndex ) ; if ( ! is_null ( $ this -> getExpire ( ) ) && $ result ) { $ this -> expire ( $ this -> getExpire ( ) , $ this -> isExpireTimestamp ( ) ) ; } return $ result ; }

Move key to other Db

@see Rediska#moveToDb
@param integer $dbIndex
@return boolean


public function setExpire($secondsOrTimestamp, $isTimestamp = false)
    {
        if ($secondsOrTimestamp !== null) {
            trigger_error('Expire option is deprecated, because expire behaviour was changed in Redis 2.2. Use expire method instead.', E_USER_WARNING);
        }

        $this->_options['expire'] = $secondsOrTimestamp;
        $this->_options['expireIsTimestamp'] = $isTimestamp;

        return $this;
    }

Set expire time

@param $secondsOrTimestamp Time in seconds or timestamp
@param $isTimestamp        Time is timestamp? Default is false.
@return Rediska_Key_Abstract


protected function _getRediskaOn()
    {
        $rediska = $this->getRediska();

        if (!is_null($this->getServerAlias())) {
            $rediska = $rediska->on($this->getServerAlias());
        }

        return $rediska;
    }

protected function _getRediskaOn ( ) { $ rediska = $ this -> getRediska ( ) ; if ( ! is_null ( $ this -> getServerAlias ( ) ) ) { $ rediska = $ rediska -> on ( $ this -> getServerAlias ( ) ) ; } return $ rediska ; }

Get rediska and set specified connection

@return Rediska


public function setMode($mode)
    {
        if (is_resource($this->_stream) && $this->_mode != $mode) {
            $meta = stream_get_meta_data($this->_stream);
            $this->setStream($meta['uri']);
        }

        $this->_mode = $mode;

        return $this;
    }

public function setMode ( $ mode ) { if ( is_resource ( $ this -> _stream ) && $ this -> _mode != $ mode ) { $ meta = stream_get_meta_data ( $ this -> _stream ) ; $ this -> setStream ( $ meta [ 'uri' ] ) ; } $ this -> _mode = $ mode ; return $ this ; }

Set access mode

@param string $mode
@return Rediska_Profiler_Stream


public static function add($rediska)
    {
        if ($rediska instanceof Rediska) {
            if (!self::has($rediska->getName())) {
                foreach(self::$_instances as $name => $instance) {
                    if ($instance === $rediska && $name != $rediska->getName()) {
                        unset(self::$_instances[$name]);
                        break;
                    }
                }
            }
            $name = $rediska->getName();
        } else if (is_array($rediska)) {
            if (isset($rediska['name'])) {
                $name = $rediska['name'];
            } else {
                $name = Rediska::DEFAULT_NAME;
            }
        } else {
            throw new Rediska_Exception('Rediska must be a instance or options');
        }

        if (self::has($name)) {
            $result = false;
        } else {
            $result = true;
        }

        self::$_instances[$name] = $rediska;

        return $result;
    }

public
static
function
add
(
$
rediska
)
{
if
(
$
rediska
instanceof
Rediska
)
{
if
(
!
self
::
has
(
$
rediska
->
getName
(
)
)
)
{
foreach
(
self
::
$
_instances
as
$
name
=>
$
instance
)
{
if
(
$
instance
===
$
rediska
&&
$
name
!=
$
rediska
->
getName
(
)
)
{
unset
(
self
::
$
_instances
[
$
name
]
)
;
break
;
}
}
}
$
name
=
$
rediska
->
getName
(
)
;
}
else
if
(
is_array
(
$
rediska
)
)
{
if
(
isset
(
$
rediska
[
'name'
]
)
)
{
$
name
=
$
rediska
[
'name'
]
;
}
else
{
$
name
=
Rediska
::
DEFAULT_NAME
;
}
}
else
{
throw
new
Rediska_Exception
(
'Rediska must be a instance or options'
)
;
}
if
(
self
::
has
(
$
name
)
)
{
$
result
=
false
;
}
else
{
$
result
=
true
;
}
self
::
$
_instances
[
$
name
]
=
$
rediska
;
return
$
result
;
}

Add Rediska
Return true if new instance and false if instance overwrited

@param Rediska $rediska Rediska instance or options
@return boolean


public static function getAll()
    {
        foreach(self::$_instances as $name => $instanceOrOptions) {
            self::_instanceFromOptions($name);
        }

        return self::$_instances;
    }

public static function getAll ( ) { foreach ( self :: $ _instances as $ name => $ instanceOrOptions ) { self :: _instanceFromOptions ( $ name ) ; } return self :: $ _instances ; }

Get all Rediska instances

@return array


protected static function _instanceFromOptions($name)
    {
        if (!is_object(self::$_instances[$name])) {
            $options = self::$_instances[$name];
            self::$_instances[$name] = new Rediska($options);
        }
    }

protected static function _instanceFromOptions ( $ name ) { if ( ! is_object ( self :: $ _instances [ $ name ] ) ) { $ options = self :: $ _instances [ $ name ] ; self :: $ _instances [ $ name ] = new Rediska ( $ options ) ; } }

Instance from options if not yet

@static
@param  $name
@return void


public function increment($subject) {
		$bucket = $this->_getBucketName();
		$transaction = $this->_getTransaction();
		$this->_setMultiIncrementTransactionPart($transaction, $subject, $bucket);
		$transaction->execute();
	}

public function increment ( $ subject ) { $ bucket = $ this -> _getBucketName ( ) ; $ transaction = $ this -> _getTransaction ( ) ; $ this -> _setMultiIncrementTransactionPart ( $ transaction , $ subject , $ bucket ) ; $ transaction -> execute ( ) ; }

Increment the count for the specified subject.

@param string $subject A unique identifier, for example a session id or an IP
@return void

Increment the count for the specified subject .


public function reset($subject) {
		$keyName = $this->_getKeyName($subject);
		return (bool) $this->_rediska->delete($keyName);
	}

public function reset ( $ subject ) { $ keyName = $ this -> _getKeyName ( $ subject ) ; return ( bool ) $ this -> _rediska -> delete ( $ keyName ) ; }

Resets the counter for the specified subject.

@param string $subject A unique identifier, for example a session id or an IP
@return bool

Resets the counter for the specified subject .


protected function _getBucketName($time = null) {
		$time = $time ? : time();
		return (int) floor(($time % $this->_bucketSpan) / $this->_bucketInterval);
	}

protected function _getBucketName ( $ time = null ) { $ time = $ time ? : time ( ) ; return ( int ) floor ( ( $ time % $ this -> _bucketSpan ) / $ this -> _bucketInterval ) ; }

Get the bucket associated with the current time.

@param int $time (optional) - default is the current time (seconds since epoch)
@return int bucket

Get the bucket associated with the current time .


protected function _setMultiIncrementTransactionPart(Rediska_Transaction $transaction, $subject, $bucket) {
		$keyName = $this->_getKeyName($subject);

		$transaction->incrementinhash($keyName, $bucket, 1)
				->deletefromhash($keyName, ($bucket + 1) % $this->_bucketCount)
				->deletefromhash($keyName, ($bucket + 2) % $this->_bucketCount)
				->expire($keyName, $this->_subjectExpire);
	}

protected function _setMultiIncrementTransactionPart ( Rediska_Transaction $ transaction , $ subject , $ bucket ) { $ keyName = $ this -> _getKeyName ( $ subject ) ; $ transaction -> incrementinhash ( $ keyName , $ bucket , 1 ) -> deletefromhash ( $ keyName , ( $ bucket + 1 ) % $ this -> _bucketCount ) -> deletefromhash ( $ keyName , ( $ bucket + 2 ) % $ this -> _bucketCount ) -> expire ( $ keyName , $ this -> _subjectExpire ) ; }

Adds the commands needed for the increment function

@param Rediska_Transaction $transaction
@param string $subject A unique identifier, for example a session id or an IP
@param int $bucket
@return void


protected function _setMulitExecGetCountPart(Rediska_Transaction $transaction, $subject, $bucket, $count) {
		$keyName = $this->_getKeyName($subject);
		// Get the counts from the previous `$count` buckets
		$transaction->getfromhash($keyName, $bucket);
		for ($i = $count; $i > 0; $i--) {
			$transaction->getfromhash($keyName, (--$bucket + $this->_bucketCount) % $this->_bucketCount);
		}
		return $transaction;
	}

Adds the commands needed for the count function

@param Rediska_Transaction $transaction
@param string $subject A unique identifier, for example a session id or an IP
@param int $bucket
@param int $count
@return void


protected function _createSocketConnection()
    {
        $socket = socket_create(AF_INET, SOCK_STREAM, getprotobyname('tcp'));

        socket_set_option($socket, SOL_SOCKET, TCP_NODELAY, 1);

        @socket_set_nonblock($socket);
        $result = @socket_connect($socket, $this->getHost(), $this->getPort());

        if ($result === false) {
            $errorCode = socket_last_error($socket);
            if ($errorCode !== SOCKET_EINPROGRESS) {
                return null;
            }
        }else{
            //@socket_set_block($socket);

            return $socket;
        }

        /* Do whatever we want while the connect is taking place. */
        $result = @socket_select($r = array($socket), $w = array($socket), $e = array($socket), $this->getTimeout());

        if ($result === 0 || $result === false) {
            return null;
        }

        if (!(($r && count($r)) || ($w && count($w))) || @socket_get_option($socket, SOL_SOCKET, SO_ERROR) != 0) {
            return null;
        }

        //@socket_set_block($socket);

        return $socket;
    }

Create socket connection

@return null|resource


protected function _getReadBuffer()
    {
        if ($this->_readBuffer === null) {
            $this->_readBuffer = new Rediska_Connection_Socket_ReadBuffer($this);
        }

        return $this->_readBuffer;
    }

protected function _getReadBuffer ( ) { if ( $ this -> _readBuffer === null ) { $ this -> _readBuffer = new Rediska_Connection_Socket_ReadBuffer ( $ this ) ; } return $ this -> _readBuffer ; }

Get read buffer

@return Rediska_Connection_Socket_ReadBuffer


public function read($length)
    {
        if (!$this->isConnected()) {
            throw new Rediska_Connection_Exception("Can't read without connection to Redis server. Do connect or write first.");
        }

        if ($length > 0) {
            $data = $this->_readAndThrowException($length);
        } else {
            $data = null;
        }

        if ($length !== -1) {
            $this->_readAndThrowException(2);
        }

        return $data;
    }

Read length bytes from connection stram

@throws Rediska_Connection_Exception
@param integer $length
@return boolean


public function readLine()
    {
        if (!$this->isConnected()) {
            throw new Rediska_Connection_Exception("Can't read without connection to Redis server. Do connect or write first.");
        }

        $reply = @fgets($this->_socket);

        if ($reply === false || $reply === '') {
            $metaData = stream_get_meta_data($this->_socket);
            if ($metaData['timed_out']) {
                throw new Rediska_Connection_TimeoutException("Connection read timed out.");
            }

            if ($this->_options['blockingMode'] && !$metaData['eof']) {
                $this->disconnect();
                throw new Rediska_Connection_Exception("Can't read from socket.");
            }

            $reply = null;
        } else {
            $reply = trim($reply);
        }

        return $reply;
    }

Read line from connection stream

@throws Rediska_Connection_Exception
@throws Rediska_Connection_TimeoutException
@return string


public function setReadTimeout($timeout)
    {
        $this->_options['readTimeout'] = $timeout;

        if ($this->isConnected()) {
            $seconds = floor($this->_options['readTimeout']);
            $microseconds = ($this->_options['readTimeout'] - $seconds) * 1000000;

            stream_set_timeout($this->_socket, $seconds, $microseconds);
        }

        return $this;
    }

public function setReadTimeout ( $ timeout ) { $ this -> _options [ 'readTimeout' ] = $ timeout ; if ( $ this -> isConnected ( ) ) { $ seconds = floor ( $ this -> _options [ 'readTimeout' ] ) ; $ microseconds = ( $ this -> _options [ 'readTimeout' ] - $ seconds ) * 1000000 ; stream_set_timeout ( $ this -> _socket , $ seconds , $ microseconds ) ; } return $ this ; }

Set read timeout

@param $timeout
@return Rediska_Connection


public function getStreamContext()
    {
        if ($this->_options['streamContext'] !== null) {
            if (is_resource($this->_options['streamContext'])) {
                return $this->_options['streamContext'];
            }
            if (is_array($this->_options['streamContext'])) {
                return stream_context_create($this->_options['streamContext']);
            }
        }
        return null;
    }

public function getStreamContext ( ) { if ( $ this -> _options [ 'streamContext' ] !== null ) { if ( is_resource ( $ this -> _options [ 'streamContext' ] ) ) { return $ this -> _options [ 'streamContext' ] ; } if ( is_array ( $ this -> _options [ 'streamContext' ] ) ) { return stream_context_create ( $ this -> _options [ 'streamContext' ] ) ; } } return null ; }

If a stream context is provided, use it creating the socket.

It's supported to provide either an array with options, or an already created
resource.

@return mixed null or resource
@see    self::connect()

If a stream context is provided use it creating the socket .


protected function _readAndThrowException($length)
    {
        $data = @stream_get_contents($this->_socket, $length);

        $info = stream_get_meta_data($this->_socket);
        if ($info['timed_out']) {
            throw new Rediska_Connection_TimeoutException("Connection read timed out.");
        }

        if ($data === false) {
            $this->disconnect();
            throw new Rediska_Connection_Exception("Can't read from socket.");
        }

        return $data;
    }

protected
function
_readAndThrowException
(
$
length
)
{
$
data
=
@
stream_get_contents
(
$
this
->
_socket
,
$
length
)
;
$
info
=
stream_get_meta_data
(
$
this
->
_socket
)
;
if
(
$
info
[
'timed_out'
]
)
{
throw
new
Rediska_Connection_TimeoutException
(
"Connection read timed out."
)
;
}
if
(
$
data
===
false
)
{
$
this
->
disconnect
(
)
;
throw
new
Rediska_Connection_Exception
(
"Can't read from socket."
)
;
}
return
$
data
;
}

Read and throw exception if somthing wrong

@param $length Lenght of bytes to read
@return string


public function validate(NonceContextInterface $context = null)
    {
        $context or $context = new RequestGlobalsContext();

        $value = $context->offsetExists($this->action) ? $context[$this->action] : '';
        if (!$value || !is_string($value)) {
            return false;
        }

        $lifeFilter = $this->lifeFilter();

        add_filter('nonce_life', $lifeFilter);
        $valid = wp_verify_nonce($value, $this->hashedAction());
        remove_filter('nonce_life', $lifeFilter);

        return (bool)$valid;
    }

public function validate ( NonceContextInterface $ context = null ) { $ context or $ context = new RequestGlobalsContext ( ) ; $ value = $ context -> offsetExists ( $ this -> action ) ? $ context [ $ this -> action ] : '' ; if ( ! $ value || ! is_string ( $ value ) ) { return false ; } $ lifeFilter = $ this -> lifeFilter ( ) ; add_filter ( 'nonce_life' , $ lifeFilter ) ; $ valid = wp_verify_nonce ( $ value , $ this -> hashedAction ( ) ) ; remove_filter ( 'nonce_life' , $ lifeFilter ) ; return ( bool ) $ valid ; }

Validates the nonce against given context.

When not provided, context defaults to `RequestGlobalsContext`, so that value is searched
in super globals.

We need to filter the nonce life and remove the filter afterwards, because WP does not
allow to filter nonce by action (yet? @link https://core.trac.wordpress.org/ticket/35188)

@param NonceContextInterface $context
@return bool

Validates the nonce against given context .


public function declareAndBindQueue($exchange, $queueName, $routingKey = '')
    {
        $this->declareSimpleQueue($queueName);
        $this->bindQueue($exchange, $queueName, $routingKey);
    }

public function declareAndBindQueue ( $ exchange , $ queueName , $ routingKey = '' ) { $ this -> declareSimpleQueue ( $ queueName ) ; $ this -> bindQueue ( $ exchange , $ queueName , $ routingKey ) ; }

Create a persisting queue and bind it to an exchange

@param  string $exchange
@param  string $queueName
@param  string $routingKey

@return void

@throws \AMQPConnectionException
@throws \AMQPChannelException
@throws \AMQPQueueException


public function ack(Message $message)
    {
        $queue = $this->getQueue($message->getQueue());
        $queue->ack($message->getDeliveryTag());
    }

public function ack ( Message $ message ) { $ queue = $ this -> getQueue ( $ message -> getQueue ( ) ) ; $ queue -> ack ( $ message -> getDeliveryTag ( ) ) ; }

Acknowledge the reception of the message.

@param Message $message

@return void

@throws \AMQPConnectionException
@throws \AMQPChannelException
@throws \AMQPQueueException

Acknowledge the reception of the message .


public function nack(Message $message, $requeue = true)
    {
        $queue = $this->getQueue($message->getQueue());
        $queue->nack($message->getDeliveryTag(), $requeue ? AMQP_REQUEUE : AMQP_NOPARAM);
    }

public function nack ( Message $ message , $ requeue = true ) { $ queue = $ this -> getQueue ( $ message -> getQueue ( ) ) ; $ queue -> nack ( $ message -> getDeliveryTag ( ) , $ requeue ? AMQP_REQUEUE : AMQP_NOPARAM ) ; }

Acknowledge an error during the consumption of the message

@param Message $message
@param bool    $requeue

@return void

@throws \AMQPConnectionException
@throws \AMQPChannelException
@throws \AMQPQueueException


private static function getMessageProperties(Message $message)
    {
        $properties = [
            self::DELIVERY_MODE       => 2,
            self::CONTENT_TYPE        => 'text/plain',
            self::APPLICATION_HEADERS => $message->getHeaders()
        ];

        if ($message->getCorrelationId() !== null) {
            $properties[self::CORRELATION_ID] = $message->getCorrelationId();
        }

        if ($message->getReplyTo() !== null) {
            $properties[self::REPLY_TO] = $message->getReplyTo();
        }

        return $properties;
    }

private static function getMessageProperties ( Message $ message ) { $ properties = [ self :: DELIVERY_MODE => 2 , self :: CONTENT_TYPE => 'text/plain' , self :: APPLICATION_HEADERS => $ message -> getHeaders ( ) ] ; if ( $ message -> getCorrelationId ( ) !== null ) { $ properties [ self :: CORRELATION_ID ] = $ message -> getCorrelationId ( ) ; } if ( $ message -> getReplyTo ( ) !== null ) { $ properties [ self :: REPLY_TO ] = $ message -> getReplyTo ( ) ; } return $ properties ; }

Returns the message parameters

@param Message $message

@return array


public function start()
    {
        $this->eventEmitter->emit(new DaemonStarted());

        $this->logger->info('Starting daemon...');

        $options = $this->handler->options(new ConsumeOptions());

        $this->driver->consume(
            $this->queueName,
            function (Message $message) {
                $this->eventEmitter->emit(new MessageReceived());
                $this->monitor->monitor($this, $message);

                $result = $this->handler->handle($message);

                $this->eventEmitter->emit(new MessageConsumed());
                pcntl_signal_dispatch();

                return $result;
            },
            $options->getTimeout(),
            $options->isAutoAck()
        );

        $this->stop();
    }

public
function
start
(
)
{
$
this
->
eventEmitter
->
emit
(
new
DaemonStarted
(
)
)
;
$
this
->
logger
->
info
(
'Starting daemon...'
)
;
$
options
=
$
this
->
handler
->
options
(
new
ConsumeOptions
(
)
)
;
$
this
->
driver
->
consume
(
$
this
->
queueName
,
function
(
Message
$
message
)
{
$
this
->
eventEmitter
->
emit
(
new
MessageReceived
(
)
)
;
$
this
->
monitor
->
monitor
(
$
this
,
$
message
)
;
$
result
=
$
this
->
handler
->
handle
(
$
message
)
;
$
this
->
eventEmitter
->
emit
(
new
MessageConsumed
(
)
)
;
pcntl_signal_dispatch
(
)
;
return
$
result
;
}
,
$
options
->
getTimeout
(
)
,
$
options
->
isAutoAck
(
)
)
;
$
this
->
stop
(
)
;
}


public function stop()
    {
        $this->logger->info('Closing daemon...');

        $this->driver->close();

        $this->eventEmitter->emit(new DaemonStopped());
    }

public
function
stop
(
)
{
$
this
->
logger
->
info
(
'Closing daemon...'
)
;
$
this
->
driver
->
close
(
)
;
$
this
->
eventEmitter
->
emit
(
new
DaemonStopped
(
)
)
;
}


public static function build(\Exception $e, $timeout)
    {
        return new self(
            sprintf('The connection timed out after %d sec while awaiting incoming data', $timeout),
            $e->getCode(),
            $e
        );
    }

Build the exception from another timeout exception.

@param \Exception $e
@param int        $timeout

@return TimeoutException

Build the exception from another timeout exception .


public function build(QueueConsumer $consumer)
    {
        Assertion::notNull($this->sync, 'You must specify if the handler must be sync or async');

        // Sync
        $handler = $this->sync ?
            new SyncConsumerHandler($consumer, $this->driver) :
            new AsyncConsumerHandler($consumer);
        $handler->setLogger($this->logger);

        // Ack
        $handler = $this->autoAck ?
            $handler :
            new AckHandler($handler, $this->driver, $this->requeueOnFailure);

        // Stop / Continue
        $handler = $this->stopOnFailure ?
            new StopOnExceptionHandler($handler) :
            new ContinueOnExceptionHandler($handler);
        $handler->setLogger($this->logger);

        return $handler;
    }

Build the Handler.

@param QueueConsumer $consumer

@return QueueHandler

@throws AssertionFailedException


private function handleSyncMessage(Message $message, $returnValue)
    {
        self::checkMessageIsSync($message);

        $this->logger->debug(
            'Send return value back!',
            [
                'returnValue' => $returnValue,
                'correlationId' => $message->getCorrelationId(),
                'replyTo' => $message->getReplyTo()
            ]
        );

        $this->driver->publish(
            '',
            new Message(
                $returnValue,
                $message->getReplyTo(),
                $message->getHeaders(),
                $message->getCorrelationId()
            )
        );
    }

private
function
handleSyncMessage
(
Message
$
message
,
$
returnValue
)
{
self
::
checkMessageIsSync
(
$
message
)
;
$
this
->
logger
->
debug
(
'Send return value back!'
,
[
'returnValue'
=>
$
returnValue
,
'correlationId'
=>
$
message
->
getCorrelationId
(
)
,
'replyTo'
=>
$
message
->
getReplyTo
(
)
]
)
;
$
this
->
driver
->
publish
(
''
,
new
Message
(
$
returnValue
,
$
message
->
getReplyTo
(
)
,
$
message
->
getHeaders
(
)
,
$
message
->
getCorrelationId
(
)
)
)
;
}

Handle the return value.

@param Message $message
@param string  $returnValue

@throws ConsumerException
@throws AssertionFailedException
@throws \InvalidArgumentException


public static function getDriver($connection)
    {
        if (is_array($connection) &&
            isset($connection['host'], $connection['port'], $connection['user'], $connection['pwd'])
        ) {
            $connection = self::getConnectionFromArray($connection);
        }

        if ($connection instanceof AbstractConnection) {
            return new PhpAmqpLibDriver($connection);
        }

        if ($connection instanceof \AMQPConnection) {
            return new PeclAmqpDriver($connection);
        }

        throw new \InvalidArgumentException('You provided an unsupported connection');
    }

Return the driver for your system

It accepts a PECL connection, a PhpAmqpLib connection or an array following
the following schema :
[
'host' => '<hostValue>',
'port' => '<portValue>',
'user' => '<userValue>',
'pwd'  => '<pwdValue>'
]

If you provide an array, the PECL extension has precedence over the PhpAmqpLib.

@param $connection

@return Driver

@throws \AMQPConnectionException
@throws \InvalidArgumentException


public function nack(Message $message, $requeue = true)
    {
        $this->getChannel()->basic_reject($message->getDeliveryTag(), $requeue);
    }

public function nack ( Message $ message , $ requeue = true ) { $ this -> getChannel ( ) -> basic_reject ( $ message -> getDeliveryTag ( ) , $ requeue ) ; }

Aknowledge an error during the consumption of the message

@param Message $message
@param bool   $requeue

@return void


public function close()
    {
        $this->stop = true;

        $this->getChannel()->close();
        $this->connection->close();
    }

public function close ( ) { $ this -> stop = true ; $ this -> getChannel ( ) -> close ( ) ; $ this -> connection -> close ( ) ; }


public function consume($message, array $headers = [])
    {
        return $this->serializer->serialize(
            $this->consumer->consume(
                $this->serializer->deserialize($message),
                $headers
            )
        );
    }

public function consume ( $ message , array $ headers = [ ] ) { return $ this -> serializer -> serialize ( $ this -> consumer -> consume ( $ this -> serializer -> deserialize ( $ message ) , $ headers ) ) ; }

Consumes a message.

@param mixed    $message
@param string[] $headers

@return string


protected function replaceModel(&$stub)
    {
        $model = explode('\\', $this->getModel());
        $model = array_pop($model);
        $stub  = str_replace('ModelName', $model, $stub);

        return $stub;
    }

protected function replaceModel ( & $ stub ) { $ model = explode ( '\\' , $ this -> getModel ( ) ) ; $ model = array_pop ( $ model ) ; $ stub = str_replace ( 'ModelName' , $ model , $ stub ) ; return $ stub ; }

Replace model name.

@param string $stub
@return string


protected function qualifyClass($name)
    {
        $rootNamespace = $this->laravel->getNamespace();

        if (Str::startsWith($name, $rootNamespace)) {
            return $name;
        }

        if (Str::contains($name, '/')) {
            $name = str_replace('/', '\\', $name);
        }

        if (! Str::contains(Str::lower($name), 'datatable')) {
            $name .= $this->type;
        }

        return $this->getDefaultNamespace(trim($rootNamespace, '\\')) . '\\' . $name;
    }

protected function qualifyClass ( $ name ) { $ rootNamespace = $ this -> laravel -> getNamespace ( ) ; if ( Str :: startsWith ( $ name , $ rootNamespace ) ) { return $ name ; } if ( Str :: contains ( $ name , '/' ) ) { $ name = str_replace ( '/' , '\\' , $ name ) ; } if ( ! Str :: contains ( Str :: lower ( $ name ) , 'datatable' ) ) { $ name .= $ this -> type ; } return $ this -> getDefaultNamespace ( trim ( $ rootNamespace , '\\' ) ) . '\\' . $ name ; }

Parse the name and format according to the root namespace.

@param  string $name
@return string

Parse the name and format according to the root namespace .


public function process(Request $request)
    {
        $action = $request->get('action');

        if (! in_array($action, $this->actions)) {
            throw new DataTablesEditorException('Requested action not supported!');
        }

        return $this->{$action}($request);
    }

public
function
process
(
Request
$
request
)
{
$
action
=
$
request
->
get
(
'action'
)
;
if
(
!
in_array
(
$
action
,
$
this
->
actions
)
)
{
throw
new
DataTablesEditorException
(
'Requested action not supported!'
)
;
}
return
$
this
->
{
$
action
}
(
$
request
)
;
}

Process dataTables editor action request.

@param Request $request
@return JsonResponse|mixed
@throws DataTablesEditorException

Process dataTables editor action request .


public function create(Request $request)
    {
        $instance   = $this->resolveModel();
        $connection = $instance->getConnection();
        $affected   = [];
        $errors     = [];

        $connection->beginTransaction();
        foreach ($request->get('data') as $data) {
            $validator = $this->getValidationFactory()->make($data, $this->createRules(), $this->createMessages(), $this->attributes());
            if ($validator->fails()) {
                foreach ($this->formatErrors($validator) as $error) {
                    $errors[] = $error;
                }

                continue;
            }

            if (method_exists($this, 'creating')) {
                $data = $this->creating($instance, $data);
            }

            if (method_exists($this, 'saving')) {
                $data = $this->saving($instance, $data);
            }

            $model = $instance->newQuery()->create($data);
            $model->setAttribute('DT_RowId', $model->getKey());

            if (method_exists($this, 'created')) {
                $this->created($model, $data);
            }

            if (method_exists($this, 'saved')) {
                $this->saved($model, $data);
            }

            $affected[] = $model;
        }

        if (! $errors) {
            $connection->commit();
        } else {
            $connection->rollBack();
        }

        return $this->toJson($affected, $errors);
    }

public function create ( Request $ request ) { $ instance = $ this -> resolveModel ( ) ; $ connection = $ instance -> getConnection ( ) ; $ affected = [ ] ; $ errors = [ ] ; $ connection -> beginTransaction ( ) ; foreach ( $ request -> get ( 'data' ) as $ data ) { $ validator = $ this -> getValidationFactory ( ) -> make ( $ data , $ this -> createRules ( ) , $ this -> createMessages ( ) , $ this -> attributes ( ) ) ; if ( $ validator -> fails ( ) ) { foreach ( $ this -> formatErrors ( $ validator ) as $ error ) { $ errors [ ] = $ error ; } continue ; } if ( method_exists ( $ this , 'creating' ) ) { $ data = $ this -> creating ( $ instance , $ data ) ; } if ( method_exists ( $ this , 'saving' ) ) { $ data = $ this -> saving ( $ instance , $ data ) ; } $ model = $ instance -> newQuery ( ) -> create ( $ data ) ; $ model -> setAttribute ( 'DT_RowId' , $ model -> getKey ( ) ) ; if ( method_exists ( $ this , 'created' ) ) { $ this -> created ( $ model , $ data ) ; } if ( method_exists ( $ this , 'saved' ) ) { $ this -> saved ( $ model , $ data ) ; } $ affected [ ] = $ model ; } if ( ! $ errors ) { $ connection -> commit ( ) ; } else { $ connection -> rollBack ( ) ; } return $ this -> toJson ( $ affected , $ errors ) ; }

Process create action request.

@param Request $request
@return JsonResponse


protected function toJson(array $data, array $errors = [])
    {
        $response = ['data' => $data];
        if ($errors) {
            $response['fieldErrors'] = $errors;
        }

        return new JsonResponse($response, 200);
    }

protected function toJson ( array $ data , array $ errors = [ ] ) { $ response = [ 'data' => $ data ] ; if ( $ errors ) { $ response [ 'fieldErrors' ] = $ errors ; } return new JsonResponse ( $ response , 200 ) ; }

Display success data in dataTables editor format.

@param array $data
@param array $errors
@return JsonResponse

Display success data in dataTables editor format .


public function edit(Request $request)
    {
        $instance   = $this->resolveModel();
        $connection = $instance->getConnection();
        $affected   = [];
        $errors     = [];

        $connection->beginTransaction();
        foreach ($request->get('data') as $key => $data) {
            $model     = $instance->newQuery()->find($key);
            $validator = $this->getValidationFactory()->make($data, $this->editRules($model), $this->editMessages(), $this->attributes());
            if ($validator->fails()) {
                foreach ($this->formatErrors($validator) as $error) {
                    $errors[] = $error;
                }

                continue;
            }

            if (method_exists($this, 'updating')) {
                $data = $this->updating($model, $data);
            }

            if (method_exists($this, 'saving')) {
                $data = $this->saving($model, $data);
            }

            $model->update($data);

            if (method_exists($this, 'updated')) {
                $this->updated($model, $data);
            }

            if (method_exists($this, 'saved')) {
                $this->saved($model, $data);
            }

            $model->setAttribute('DT_RowId', $model->getKey());
            $affected[] = $model;
        }

        if (! $errors) {
            $connection->commit();
        } else {
            $connection->rollBack();
        }

        return $this->toJson($affected, $errors);
    }

public function edit ( Request $ request ) { $ instance = $ this -> resolveModel ( ) ; $ connection = $ instance -> getConnection ( ) ; $ affected = [ ] ; $ errors = [ ] ; $ connection -> beginTransaction ( ) ; foreach ( $ request -> get ( 'data' ) as $ key => $ data ) { $ model = $ instance -> newQuery ( ) -> find ( $ key ) ; $ validator = $ this -> getValidationFactory ( ) -> make ( $ data , $ this -> editRules ( $ model ) , $ this -> editMessages ( ) , $ this -> attributes ( ) ) ; if ( $ validator -> fails ( ) ) { foreach ( $ this -> formatErrors ( $ validator ) as $ error ) { $ errors [ ] = $ error ; } continue ; } if ( method_exists ( $ this , 'updating' ) ) { $ data = $ this -> updating ( $ model , $ data ) ; } if ( method_exists ( $ this , 'saving' ) ) { $ data = $ this -> saving ( $ model , $ data ) ; } $ model -> update ( $ data ) ; if ( method_exists ( $ this , 'updated' ) ) { $ this -> updated ( $ model , $ data ) ; } if ( method_exists ( $ this , 'saved' ) ) { $ this -> saved ( $ model , $ data ) ; } $ model -> setAttribute ( 'DT_RowId' , $ model -> getKey ( ) ) ; $ affected [ ] = $ model ; } if ( ! $ errors ) { $ connection -> commit ( ) ; } else { $ connection -> rollBack ( ) ; } return $ this -> toJson ( $ affected , $ errors ) ; }

Process edit action request.

@param Request $request
@return JsonResponse


public function remove(Request $request)
    {
        $instance   = $this->resolveModel();
        $connection = $instance->getConnection();
        $affected   = [];
        $errors     = [];

        $connection->beginTransaction();
        foreach ($request->get('data') as $key => $data) {
            $model     = $instance->newQuery()->find($key);
            $validator = $this->getValidationFactory()
                              ->make($data, $this->removeRules($model), $this->removeMessages(), $this->attributes());
            if ($validator->fails()) {
                foreach ($this->formatErrors($validator) as $error) {
                    $errors[] = $error['status'];
                }

                continue;
            }

            try {
                if (method_exists($this, 'deleting')) {
                    $this->deleting($model, $data);
                }

                $model->delete();

                if (method_exists($this, 'deleted')) {
                    $this->deleted($model, $data);
                }
            } catch (QueryException $exception) {
                $error    = config('app.debug') ? $exception->errorInfo[2] : $this->removeExceptionMessage($exception, $model);
                $errors[] = $error;
            }

            $affected[] = $model;
        }

        if (! $errors) {
            $connection->commit();
        } else {
            $connection->rollBack();
        }

        $response = ['data' => $affected];
        if ($errors) {
            $response['error'] = implode("\n", $errors);
        }

        return new JsonResponse($response, 200);
    }

public function remove ( Request $ request ) { $ instance = $ this -> resolveModel ( ) ; $ connection = $ instance -> getConnection ( ) ; $ affected = [ ] ; $ errors = [ ] ; $ connection -> beginTransaction ( ) ; foreach ( $ request -> get ( 'data' ) as $ key => $ data ) { $ model = $ instance -> newQuery ( ) -> find ( $ key ) ; $ validator = $ this -> getValidationFactory ( ) -> make ( $ data , $ this -> removeRules ( $ model ) , $ this -> removeMessages ( ) , $ this -> attributes ( ) ) ; if ( $ validator -> fails ( ) ) { foreach ( $ this -> formatErrors ( $ validator ) as $ error ) { $ errors [ ] = $ error [ 'status' ] ; } continue ; } try { if ( method_exists ( $ this , 'deleting' ) ) { $ this -> deleting ( $ model , $ data ) ; } $ model -> delete ( ) ; if ( method_exists ( $ this , 'deleted' ) ) { $ this -> deleted ( $ model , $ data ) ; } } catch ( QueryException $ exception ) { $ error = config ( 'app.debug' ) ? $ exception -> errorInfo [ 2 ] : $ this -> removeExceptionMessage ( $ exception , $ model ) ; $ errors [ ] = $ error ; } $ affected [ ] = $ model ; } if ( ! $ errors ) { $ connection -> commit ( ) ; } else { $ connection -> rollBack ( ) ; } $ response = [ 'data' => $ affected ] ; if ( $ errors ) { $ response [ 'error' ] = implode ( "\n" , $ errors ) ; } return new JsonResponse ( $ response , 200 ) ; }

Process remove action request.

@param Request $request
@return JsonResponse


protected function voteOnAttribute($attribute, $subject, TokenInterface $token)
    {
        /** @var $subject Query */
        return $this->isLoggedInUser($token) || !$this->inList($subject->getName());
    }

protected
function
voteOnAttribute
(
$
attribute
,
$
subject
,
TokenInterface
$
token
)
{
/** @var $subject Query */
return
$
this
->
isLoggedInUser
(
$
token
)
||
!
$
this
->
inList
(
$
subject
->
getName
(
)
)
;
}

Perform a single access check operation on a given attribute, subject and token.

@param string         $attribute
@param mixed          $subject
@param TokenInterface $token

@return bool

Perform a single access check operation on a given attribute subject and token .


public function render(DocumentInterface $document, $parameters = [])
    {
        $html = $this->twig->render($this->template, [
            'doc' => $document,
            'params' => $parameters,
        ]);

        return $html;
    }

public function render ( DocumentInterface $ document , $ parameters = [ ] ) { $ html = $ this -> twig -> render ( $ this -> template , [ 'doc' => $ document , 'params' => $ parameters , ] ) ; return $ html ; }

Build html report.

@param DocumentInterface $document
@param array             $parameters

@return mixed

@throws \Twig_Error_Loader
@throws \Twig_Error_Runtime
@throws \Twig_Error_Syntax


public function getString() {
        $zeroByteIndex = strpos($this->byteArray, "\0", $this->position);
        if($zeroByteIndex === false) {
            return '';
        } else {
            $dataString = $this->get($zeroByteIndex - $this->position);
            $this->position ++;

            return $dataString;
        }
    }

public function getString ( ) { $ zeroByteIndex = strpos ( $ this -> byteArray , "\0" , $ this -> position ) ; if ( $ zeroByteIndex === false ) { return '' ; } else { $ dataString = $ this -> get ( $ zeroByteIndex - $ this -> position ) ; $ this -> position ++ ; return $ dataString ; } }

Reads a zero-byte terminated string from the current position of the
byte buffer

This reads the buffer up until the first occurance of a zero-byte or the
end of the buffer. The zero-byte is not included in the returned string.

@return string The zero-byte terminated string read from the byte stream

Reads a zero - byte terminated string from the current position of the byte buffer


public static function getGlobalPercentages($appId) {
        $params = ['gameid' => $appId];
        $data = WebApi::getJSONObject('ISteamUserStats', 'GetGlobalAchievementPercentagesForApp', 2, $params);

        $percentages = [];
        foreach($data->achievementpercentages->achievements as $achievementData) {
            $percentages[$achievementData->name] = (float) $achievementData->percent;
        }

        return $percentages;
    }

public static function getGlobalPercentages ( $ appId ) { $ params = [ 'gameid' => $ appId ] ; $ data = WebApi :: getJSONObject ( 'ISteamUserStats' , 'GetGlobalAchievementPercentagesForApp' , 2 , $ params ) ; $ percentages = [ ] ; foreach ( $ data -> achievementpercentages -> achievements as $ achievementData ) { $ percentages [ $ achievementData -> name ] = ( float ) $ achievementData -> percent ; } return $ percentages ; }

Loads the global unlock percentages of all achievements for the given
game

@param int $appId The unique Steam Application ID of the game (e.g.
<var>440</var> for Team Fortress 2). See
http://developer.valvesoftware.com/wiki/Steam_Application_IDs for
all application IDs
@return array The symbolic achievement names with the corresponding
global unlock percentages
@throws \SteamCondenser\Exceptions\WebApiException if a request to
Steam's Web API fails


public function close() {
        if(!empty($this->socket) && $this->socket->isOpen()) {
            $this->socket->close();
        }
    }

public function close ( ) { if ( ! empty ( $ this -> socket ) && $ this -> socket -> isOpen ( ) ) { $ this -> socket -> close ( ) ; } }

Closes the underlying socket

@see UDPSocket::close()


public function receivePacket($bufferLength = 0) {
        if(!$this->socket->select(self::$timeout)) {
            throw new TimeoutException();
        }

        if($bufferLength == 0) {
            $this->buffer->clear();
        } else {
            $this->buffer = ByteBuffer::allocate($bufferLength);
        }

        try {
            $data = $this->socket->recv($this->buffer->remaining());
            $this->buffer->put($data);
        } catch (ConnectionResetException $e) {
            $this->socket->close();
            throw $e;
        }

        $bytesRead = $this->buffer->position();
        $this->buffer->rewind();
        $this->buffer->limit($bytesRead);

        return $bytesRead;
    }

public function receivePacket ( $ bufferLength = 0 ) { if ( ! $ this -> socket -> select ( self :: $ timeout ) ) { throw new TimeoutException ( ) ; } if ( $ bufferLength == 0 ) { $ this -> buffer -> clear ( ) ; } else { $ this -> buffer = ByteBuffer :: allocate ( $ bufferLength ) ; } try { $ data = $ this -> socket -> recv ( $ this -> buffer -> remaining ( ) ) ; $ this -> buffer -> put ( $ data ) ; } catch ( ConnectionResetException $ e ) { $ this -> socket -> close ( ) ; throw $ e ; } $ bytesRead = $ this -> buffer -> position ( ) ; $ this -> buffer -> rewind ( ) ; $ this -> buffer -> limit ( $ bytesRead ) ; return $ bytesRead ; }

Reads the given amount of data from the socket and wraps it into the
buffer

@param int $bufferLength The data length to read from the socket
@throws SocketException if an error occurs while reading data
@throws TimeoutException if no packet is received on time
@return int The number of bytes that have been read from the socket
@see ByteBuffer


public function send(SteamPacket $dataPacket) {
        $this->logger->debug("Sending packet of type \"" . get_class($dataPacket) . "\"...");

        $this->socket->send($dataPacket->__toString());
    }

public
function
send
(
SteamPacket
$
dataPacket
)
{
$
this
->
logger
->
debug
(
"Sending packet of type \""
.
get_class
(
$
dataPacket
)
.
"\"..."
)
;
$
this
->
socket
->
send
(
$
dataPacket
->
__toString
(
)
)
;
}

Sends the given packet to the server

This converts the packet into a byte stream first before writing it to
the socket.

@param SteamPacket $dataPacket The packet to send to the server
@see SteamPacket::__toString()


public function getReply() {
        $this->receivePacket(1500);

        if($this->buffer->getLong() != -1) {
            throw new PacketFormatException("Master query response has wrong packet header.");
        }

        $packet = SteamPacketFactory::getPacketFromData($this->buffer->get());

        $this->logger->debug("Received reply of type \"" . get_class($packet) . "\"");

        return $packet;
    }

Reads a single packet from the socket

@return SteamPacket The packet replied from the server
@throws PacketFormatException if the packet has the wrong format