repo stringlengths 7 63 | file_url stringlengths 81 284 | file_path stringlengths 5 200 | content stringlengths 0 32.8k | language stringclasses 1
value | license stringclasses 7
values | commit_sha stringlengths 40 40 | retrieved_at stringdate 2026-01-04 15:02:33 2026-01-05 05:24:06 | truncated bool 2
classes |
|---|---|---|---|---|---|---|---|---|
mariano/disque-php | https://github.com/mariano/disque-php/blob/56cf00d97e739fec861717484657dbef2888df60/src/Connection/AuthenticationException.php | src/Connection/AuthenticationException.php | <?php
namespace Disque\Connection;
class AuthenticationException extends ConnectionException
{
} | php | MIT | 56cf00d97e739fec861717484657dbef2888df60 | 2026-01-05T05:12:23.969054Z | false |
mariano/disque-php | https://github.com/mariano/disque-php/blob/56cf00d97e739fec861717484657dbef2888df60/src/Connection/Node/NodePrioritizerInterface.php | src/Connection/Node/NodePrioritizerInterface.php | <?php
namespace Disque\Connection\Node;
use Traversable;
/**
* Sort Disque nodes by priority in order to connect to the most useful one
*
* The Connection\Manager accepts an implementation of this interface and asks
* it to sort nodes by priority. It then tries to connect to the best available
* node. The library provides a default implementation.
*
* In order to make a decision, Nodes have a resettable jobCount,
* a totalJobCount and can be extended to accept more markers, eg. latency etc.
*/
interface NodePrioritizerInterface
{
/**
* Sort the nodes by priority
*
* @param Node[] $nodes A list of known Disque nodes indexed
* by a node ID
* @param string $currentNodeId Node ID of the currently connected node
*
* @return Traversable|Node[] A list of nodes sorted by priority
*/
public function sort(array $nodes, $currentNodeId);
}
| php | MIT | 56cf00d97e739fec861717484657dbef2888df60 | 2026-01-05T05:12:23.969054Z | false |
mariano/disque-php | https://github.com/mariano/disque-php/blob/56cf00d97e739fec861717484657dbef2888df60/src/Connection/Node/ConservativeJobCountPrioritizer.php | src/Connection/Node/ConservativeJobCountPrioritizer.php | <?php
namespace Disque\Connection\Node;
use InvalidArgumentException;
/**
* A prioritizer switching nodes if they have more jobs by a given margin
*
* This class prioritizes nodes by job count and its Disque priority. Because
* there is a cost to switch, it doesn't switch from the current node unless
* the new candidate has a safe margin over the current node.
*
* This margin can be set manually and defaults to 5%, ie. the new candidate
* must have 5% more jobs than the current node.
*
* This parameter makes the prioritizer behave conservatively - it prefers
* the status quo and won't switch immediately if the difference is small.
*
* You can make the prioritizer eager by setting the margin to 0, or more
* conservative by setting it higher. Setting the margin to negative values
* is not allowed.
*/
class ConservativeJobCountPrioritizer implements NodePrioritizerInterface
{
/**
* @var float A margin to switch from the current node
*
* 0.05 means the new node must have 5% more jobs than the current node
* in order to recommend switching over.
*/
private $marginToSwitch = 0.05;
/**
* Get the margin to switch
*
* @return float
*/
public function getMarginToSwitch()
{
return $this->marginToSwitch;
}
/**
* Set the margin to switch
*
* @param float $marginToSwitch A positive float or 0
*
* @throws InvalidArgumentException
*/
public function setMarginToSwitch($marginToSwitch)
{
if ($marginToSwitch < 0) {
throw new InvalidArgumentException('Margin to switch must not be negative');
}
$this->marginToSwitch = $marginToSwitch;
}
/**
* @inheritdoc
*/
public function sort(array $nodes, $currentNodeId)
{
// Optimize for a "cluster" consisting of just 1 node - skip everything
if (count($nodes) === 1) {
return $nodes;
}
uasort($nodes, function(Node $nodeA, Node $nodeB) use ($currentNodeId) {
$priorityA = $this->calculateNodePriority($nodeA, $currentNodeId);
$priorityB = $this->calculateNodePriority($nodeB, $currentNodeId);
if ($priorityA === $priorityB) {
return 0;
}
// Nodes with a higher priority should go first
return ($priorityA < $priorityB) ? 1 : -1;
});
return $nodes;
}
/**
* Calculate the node priority from its job count, stick to the current node
*
* As the priority is based on the number of jobs, higher is better.
*
* @param Node $node
* @param string $currentNodeId
*
* @return float Node priority
*/
private function calculateNodePriority(Node $node, $currentNodeId)
{
$priority = $node->getJobCount();
if ($node->getId() === $currentNodeId) {
$margin = 1 + $this->marginToSwitch;
$priority = $priority * $margin;
}
// Apply a weight determined by the node priority as assigned by Disque.
// Priority 1 means the node is healthy.
// Priority 10 to 100 means the node is probably failing, or has failed
$disquePriority = $node->getPriority();
// Disque node priority should never be lower than 1, but let's be sure
if ($disquePriority < Node::PRIORITY_OK) {
$disquePriorityWeight = 1;
} elseif (Node::PRIORITY_OK <= $disquePriority && $disquePriority < Node::PRIORITY_POSSIBLE_FAILURE) {
// Node is OK, but Disque may have assigned a lower priority to it
// We use the base-10 logarithm in the formula, so priorities
// 1 to 10 transform into a weight of 1 to 0.5. When Disque starts
// using more priority steps, priority 9 will discount about a half
// of the job count.
$disquePriorityWeight = 1 / (1 + log10($disquePriority));
} else {
// Node is failing, or it has failed
$disquePriorityWeight = 0;
}
$priority = $priority * $disquePriorityWeight;
return (float) $priority;
}
} | php | MIT | 56cf00d97e739fec861717484657dbef2888df60 | 2026-01-05T05:12:23.969054Z | false |
mariano/disque-php | https://github.com/mariano/disque-php/blob/56cf00d97e739fec861717484657dbef2888df60/src/Connection/Node/Node.php | src/Connection/Node/Node.php | <?php
namespace Disque\Connection\Node;
use Disque\Command\Auth;
use Disque\Command\CommandInterface;
use Disque\Command\Hello;
use Disque\Command\Response\HelloResponse;
use Disque\Connection\ConnectionException;
use Disque\Connection\ConnectionInterface;
use Disque\Connection\Credentials;
use Disque\Connection\AuthenticationException;
use Disque\Connection\Response\ResponseException;
/**
* Describe one Disque node, its properties and the connection to it
*/
class Node
{
/**
* The response Disque returns if password authentication succeeded
*/
const AUTH_SUCCESS_MESSAGE = 'OK';
/**
* The beginning of a response Disque returns if authentication required
*/
const AUTH_REQUIRED_MESSAGE = 'NOAUTH';
/**
* Node prefix boundaries
*/
const PREFIX_START = 0;
const PREFIX_LENGTH = 8;
/**
* Disque-assigned node priorities
* @see $priority
*/
const PRIORITY_OK = 1;
const PRIORITY_POSSIBLE_FAILURE = 10;
const PRIORITY_FAILURE = 100;
/**
* A fallback node priority if the HELLO response doesn't contain a priority
* This should not happen, but let's be sure.
*/
const PRIORITY_FALLBACK = 2;
/**
* @var Credentials Credentials of this node - host, port, password
*/
private $credentials;
/**
* @var ConnectionInterface The connection to this node
*/
private $connection;
/**
* @var string Node ID
*/
private $id;
/**
* @var string Node prefix, or the first 8 bytes of the ID
*/
private $prefix;
/**
* @var int Node priority set by Disque, 1-100, lower is better
*
* This priority is set by Disque, lower number is better. As of 09/2015
* there are three possible values:
*
* 1 - Node is working correctly
* 10 - Possible failure (PFAIL) - Node may be failing
* 100 - Failure (FAIL) - The majority of nodes agree that the node is failing
*
* For priority values,
* @see https://github.com/antirez/disque/blob/master/src/cluster.c, helloCommand()
*
* For the difference between PFAIL and FAIL states,
* @see http://redis.io/topics/cluster-spec#failure-detection
* @see also https://github.com/antirez/disque/blob/master/src/cluster.c
* Look for CLUSTER_NODE_PFAIL and CLUSTER_NODE_FAIL
*
*/
private $priority = 1;
/**
* @var array The result of the HELLO command
*
* @see Disque\Command\Response\HelloResponse
*/
private $hello;
/**
* @var int The number of jobs from this node since the last counter reset
* This counter can be reset, eg. upon a node switch
*/
private $jobCount = 0;
/**
* @var int The number of jobs from this node during its lifetime
*/
private $totalJobCount = 0;
public function __construct(Credentials $credentials, ConnectionInterface $connection)
{
$this->credentials = $credentials;
$this->connection = $connection;
}
/**
* Get the node credentials
*
* @return Credentials
*/
public function getCredentials()
{
return $this->credentials;
}
/**
* Get the node connection
*
* @return ConnectionInterface
*/
public function getConnection()
{
return $this->connection;
}
/**
* Get the node ID
*
* @return string
*/
public function getId()
{
return $this->id;
}
/**
* Get the node prefix - the first 8 bytes from the ID
*
* @return string
*/
public function getPrefix()
{
return $this->prefix;
}
/**
* Get the node priority as set by the cluster. 1-100, lower is better.
*
* @return int
*/
public function getPriority()
{
return $this->priority;
}
/**
* @param int $priority Disque priority as revealed by a HELLO
*/
public function setPriority($priority)
{
$this->priority = (int) $priority;
}
/**
* Get the node's last HELLO response
*
* @return array
*/
public function getHello()
{
return $this->hello;
}
/**
* Get the node job count since the last reset (usually a node switch)
*
* @return int
*/
public function getJobCount()
{
return $this->jobCount;
}
/**
* Increase the node job counts by the given number
*
* @param int $jobsAdded
*/
public function addJobCount($jobsAdded)
{
$this->jobCount += $jobsAdded;
$this->totalJobCount += $jobsAdded;
}
/**
* Reset the node job count
*/
public function resetJobCount()
{
$this->jobCount = 0;
}
/**
* Get the total job count since the node instantiation
*
* @return int
*/
public function getTotalJobCount()
{
return $this->totalJobCount;
}
/**
* Connect to the node and return the HELLO response
*
* This method is idempotent and can be called multiple times
*
* @return array The HELLO response
* @throws ConnectionException
* @throws AuthenticationException
*/
public function connect()
{
if ($this->connection->isConnected() && !empty($this->hello)) {
return $this->hello;
}
$this->connectToTheNode();
$this->authenticateWithPassword();
try {
$this->sayHello();
} catch (ResponseException $e) {
/**
* If the node requires a password but we didn't supply any,
* Disque returns a message "NOAUTH Authentication required"
*
* HELLO is the first place we would get this error.
*
* @see https://github.com/antirez/disque/blob/master/src/server.c
* Look for "noautherr"
*/
$message = $e->getMessage();
if (stripos($message, self::AUTH_REQUIRED_MESSAGE) === 0) {
throw new AuthenticationException($message, 0, $e);
}
}
return $this->hello;
}
/**
* Check if this object holds a working connection to Disque node
*
* @return bool
*/
public function isConnected()
{
return $this->connection->isConnected();
}
/**
* Execute a command on this Disque node
*
* @param CommandInterface $command
* @return mixed Response
*
* @throws ConnectionException
*/
public function execute(CommandInterface $command)
{
return $this->connection->execute($command);
}
/**
* Say a new HELLO to the node and parse the response
*
* @return array The HELLO response
*
* @throws ConnectionException
*/
public function sayHello()
{
$helloCommand = new Hello();
$helloResponse = $this->connection->execute($helloCommand);
$this->hello = (array) $helloCommand->parse($helloResponse);
$this->id = $this->hello[HelloResponse::NODE_ID];
$this->createPrefix($this->id);
$this->priority = $this->readPriorityFromHello($this->hello, $this->id);
return $this->hello;
}
/**
* Connect to the node
*
* @throws ConnectionException
*/
private function connectToTheNode()
{
$this->connection->connect(
$this->credentials->getConnectionTimeout(),
$this->credentials->getResponseTimeout()
);
}
/**
* Authenticate with the node with a password, if set
*
* @throws AuthenticationException
*/
private function authenticateWithPassword()
{
if ($this->credentials->havePassword()) {
$authCommand = new Auth();
$authCommand->setArguments([$this->credentials->getPassword()]);
$authResponse = $this->connection->execute($authCommand);
$response = $authCommand->parse($authResponse);
if ($response !== self::AUTH_SUCCESS_MESSAGE) {
throw new AuthenticationException();
}
}
}
/**
* Create a node prefix from the node ID
*
* @param string $id
*/
private function createPrefix($id)
{
$this->prefix = substr($id, self::PREFIX_START, self::PREFIX_LENGTH);
}
/**
* Read out the node's own priority from a HELLO response
*
* @param array $hello The HELLO response
* @param string $id Node ID
*
* @return int Node priority
*/
private function readPriorityFromHello($hello, $id)
{
foreach ($hello[HelloResponse::NODES] as $node) {
if ($node[HelloResponse::NODE_ID] === $id) {
return $node[HelloResponse::NODE_PRIORITY];
}
}
// Node not found in the HELLO? This should not happen.
// Return a fallback value
return self::PRIORITY_FALLBACK;
}
}
| php | MIT | 56cf00d97e739fec861717484657dbef2888df60 | 2026-01-05T05:12:23.969054Z | false |
mariano/disque-php | https://github.com/mariano/disque-php/blob/56cf00d97e739fec861717484657dbef2888df60/src/Connection/Node/RandomPrioritizer.php | src/Connection/Node/RandomPrioritizer.php | <?php
namespace Disque\Connection\Node;
/**
* This prioritizer advises the Manager to switch nodes randomly
*
* It can be used to test the availability of nodes in a cluster.
*/
class RandomPrioritizer implements NodePrioritizerInterface
{
/**
* @inheritdoc
*/
public function sort(array $nodes, $currentNodeId)
{
if (count($nodes) === 1) {
return $nodes;
}
$nodeIds = array_keys($nodes);
shuffle($nodeIds);
$shuffledNodes = [];
foreach ($nodeIds as $nodeId) {
$shuffledNodes[$nodeId] = $nodes[$nodeId];
}
return $shuffledNodes;
}
}
| php | MIT | 56cf00d97e739fec861717484657dbef2888df60 | 2026-01-05T05:12:23.969054Z | false |
mariano/disque-php | https://github.com/mariano/disque-php/blob/56cf00d97e739fec861717484657dbef2888df60/src/Connection/Node/NullPrioritizer.php | src/Connection/Node/NullPrioritizer.php | <?php
namespace Disque\Connection\Node;
/**
* This prioritizer always advises to stay on the current node
*/
class NullPrioritizer implements NodePrioritizerInterface
{
/**
* @inheritdoc
*/
public function sort(array $nodes, $currentNodeId)
{
if (current($nodes) === $nodes[$currentNodeId]) {
return $nodes;
}
// Move the current node to the first place
$currentNode = $nodes[$currentNodeId];
unset($nodes[$currentNodeId]);
array_unshift($nodes, $currentNode);
return $nodes;
}
}
| php | MIT | 56cf00d97e739fec861717484657dbef2888df60 | 2026-01-05T05:12:23.969054Z | false |
mariano/disque-php | https://github.com/mariano/disque-php/blob/56cf00d97e739fec861717484657dbef2888df60/src/Connection/Response/BaseResponse.php | src/Connection/Response/BaseResponse.php | <?php
namespace Disque\Connection\Response;
use Closure;
abstract class BaseResponse
{
/**
* Data
*
* @var string
*/
protected $data;
/**
* Reader
*
* @var Closure
*/
protected $reader;
/**
* Receiver
*
* @var Closure
*/
protected $receiver;
/**
* Create instance
*
* @param string $data
*/
public function __construct($data)
{
$this->data = substr($data, 0, -2); // Get rid of last CRLF
}
/**
* Set reader
*
* @param Closure $reader Reader function
* @return void
*/
public function setReader(Closure $reader)
{
$this->reader = $reader;
}
/**
* Set receiver
*
* @param Closure $receiver Receiver function
* @return void
*/
public function setReceiver(Closure $receiver)
{
$this->receiver = $receiver;
}
/**
* Parse response
*
* @return mixed Response
*/
abstract public function parse();
} | php | MIT | 56cf00d97e739fec861717484657dbef2888df60 | 2026-01-05T05:12:23.969054Z | false |
mariano/disque-php | https://github.com/mariano/disque-php/blob/56cf00d97e739fec861717484657dbef2888df60/src/Connection/Response/ErrorResponse.php | src/Connection/Response/ErrorResponse.php | <?php
namespace Disque\Connection\Response;
class ErrorResponse extends BaseResponse
{
/**
* Parse response
*
* @return ResponseException Response
*/
public function parse()
{
$error = (string) $this->data;
$exceptionClass = $this->getExceptionClass($error);
return new $exceptionClass($error);
}
/**
* Creates ResponseException based off error
*
* @param string $error Error
* @return string Class Name
*/
private function getExceptionClass($error)
{
$errors = [
'PAUSED' => QueuePausedResponseException::class
];
$exceptionClass = ResponseException::class;
list($errorCode) = explode(" ", $error);
if (!empty($errorCode) && isset($errors[$errorCode])) {
$exceptionClass = $errors[$errorCode];
}
return $exceptionClass;
}
} | php | MIT | 56cf00d97e739fec861717484657dbef2888df60 | 2026-01-05T05:12:23.969054Z | false |
mariano/disque-php | https://github.com/mariano/disque-php/blob/56cf00d97e739fec861717484657dbef2888df60/src/Connection/Response/QueuePausedResponseException.php | src/Connection/Response/QueuePausedResponseException.php | <?php
namespace Disque\Connection\Response;
class QueuePausedResponseException extends ResponseException
{
} | php | MIT | 56cf00d97e739fec861717484657dbef2888df60 | 2026-01-05T05:12:23.969054Z | false |
mariano/disque-php | https://github.com/mariano/disque-php/blob/56cf00d97e739fec861717484657dbef2888df60/src/Connection/Response/ResponseException.php | src/Connection/Response/ResponseException.php | <?php
namespace Disque\Connection\Response;
use Disque\Connection\ConnectionException;
class ResponseException extends ConnectionException
{
} | php | MIT | 56cf00d97e739fec861717484657dbef2888df60 | 2026-01-05T05:12:23.969054Z | false |
mariano/disque-php | https://github.com/mariano/disque-php/blob/56cf00d97e739fec861717484657dbef2888df60/src/Connection/Response/StringResponse.php | src/Connection/Response/StringResponse.php | <?php
namespace Disque\Connection\Response;
class StringResponse extends BaseResponse
{
/**
* Parse response
*
* @return string Response
*/
public function parse()
{
return (string) $this->data;
}
} | php | MIT | 56cf00d97e739fec861717484657dbef2888df60 | 2026-01-05T05:12:23.969054Z | false |
mariano/disque-php | https://github.com/mariano/disque-php/blob/56cf00d97e739fec861717484657dbef2888df60/src/Connection/Response/IntResponse.php | src/Connection/Response/IntResponse.php | <?php
namespace Disque\Connection\Response;
class IntResponse extends BaseResponse
{
/**
* Parse response
*
* @return string Response
*/
public function parse()
{
return (int) $this->data;
}
} | php | MIT | 56cf00d97e739fec861717484657dbef2888df60 | 2026-01-05T05:12:23.969054Z | false |
mariano/disque-php | https://github.com/mariano/disque-php/blob/56cf00d97e739fec861717484657dbef2888df60/src/Connection/Response/TextResponse.php | src/Connection/Response/TextResponse.php | <?php
namespace Disque\Connection\Response;
use Disque\Connection\ConnectionException;
class TextResponse extends BaseResponse
{
const READ_BUFFER_LENGTH = 8192;
/**
* Parse response
*
* @return string Response
* @throws ConnectionException
*/
public function parse()
{
$bytes = (int) $this->data;
if ($bytes < 0) {
return null;
}
$bytes += 2; // CRLF
$string = '';
do {
$buffer = $this->read($bytes);
$string .= $buffer;
$bytes -= strlen($buffer);
} while ($bytes > 0);
return substr($string, 0, -2); // Remove last CRLF
}
/**
* Read text
*
* @param int $bytes Bytes to read
* @return string Text
* @throws ConnectionException
*/
private function read($bytes)
{
$buffer = call_user_func($this->reader, min($bytes, self::READ_BUFFER_LENGTH));
if ($buffer === false || $buffer === '') {
throw new ConnectionException('Error while reading buffered string from client');
}
return $buffer;
}
} | php | MIT | 56cf00d97e739fec861717484657dbef2888df60 | 2026-01-05T05:12:23.969054Z | false |
mariano/disque-php | https://github.com/mariano/disque-php/blob/56cf00d97e739fec861717484657dbef2888df60/src/Connection/Response/ArrayResponse.php | src/Connection/Response/ArrayResponse.php | <?php
namespace Disque\Connection\Response;
use Disque\Connection\ConnectionException;
class ArrayResponse extends BaseResponse
{
/**
* Parse response
*
* @return string Response
* @throws ConnectionException
*/
public function parse()
{
$count = (int) $this->data;
if ($count < 0) {
return null;
}
$elements = [];
for ($i=0; $i < $count; $i++) {
$elements[$i] = call_user_func($this->receiver);
}
return $elements;
}
}
| php | MIT | 56cf00d97e739fec861717484657dbef2888df60 | 2026-01-05T05:12:23.969054Z | false |
mariano/disque-php | https://github.com/mariano/disque-php/blob/56cf00d97e739fec861717484657dbef2888df60/src/Connection/Factory/SocketFactory.php | src/Connection/Factory/SocketFactory.php | <?php
namespace Disque\Connection\Factory;
use Disque\Connection\Socket;
/**
* Create the default Disque connection
*/
class SocketFactory implements ConnectionFactoryInterface
{
/**
* @inheritdoc
*/
public function create($host, $port)
{
return new Socket($host, $port);
}
}
| php | MIT | 56cf00d97e739fec861717484657dbef2888df60 | 2026-01-05T05:12:23.969054Z | false |
mariano/disque-php | https://github.com/mariano/disque-php/blob/56cf00d97e739fec861717484657dbef2888df60/src/Connection/Factory/PredisFactory.php | src/Connection/Factory/PredisFactory.php | <?php
namespace Disque\Connection\Factory;
use Disque\Connection\Predis;
/**
* Create the default Disque connection
*/
class PredisFactory implements ConnectionFactoryInterface
{
/**
* @inheritdoc
*/
public function create($host, $port)
{
return new Predis($host, $port);
}
}
| php | MIT | 56cf00d97e739fec861717484657dbef2888df60 | 2026-01-05T05:12:23.969054Z | false |
mariano/disque-php | https://github.com/mariano/disque-php/blob/56cf00d97e739fec861717484657dbef2888df60/src/Connection/Factory/ConnectionFactoryInterface.php | src/Connection/Factory/ConnectionFactoryInterface.php | <?php
namespace Disque\Connection\Factory;
interface ConnectionFactoryInterface
{
/**
* Create a new Connection object
*
* @param string $host
* @param int $port
*
* @return ConnectionInterface
*/
public function create($host, $port);
}
| php | MIT | 56cf00d97e739fec861717484657dbef2888df60 | 2026-01-05T05:12:23.969054Z | false |
mariano/disque-php | https://github.com/mariano/disque-php/blob/56cf00d97e739fec861717484657dbef2888df60/src/Queue/JobInterface.php | src/Queue/JobInterface.php | <?php
namespace Disque\Queue;
interface JobInterface
{
/**
* Get the job ID
*
* @return string
*/
public function getId();
/**
* Set the job ID
*
* @param string $id
*/
public function setId($id);
/**
* Get the job body
*
* @return mixed Job body
*/
public function getBody();
/**
* Set the job body
*
* @return mixed $body
*/
public function setBody($body);
/**
* Get the name of the queue the job belongs to
*
* @return string
*/
public function getQueue();
/**
* Set the name of the queue the job belongs to
*
* @param string $queue
*/
public function setQueue($queue);
/**
* Get the number of NACKs
*
* The `nacks` counter is incremented every time a worker uses the `NACK`
* command to tell the queue the job was not processed correctly and should
* be put back on the queue.
*
* @return int
*/
public function getNacks();
/**
* Set the number of NACKs
*
* @param int $nacks
*/
public function setNacks($nacks);
/**
* Get the number of additional deliveries
*
* The `additional-deliveries` counter is incremented for every other
* condition (different than `NACK` call) that requires a job to be put
* back on the queue again. This includes jobs that get lost and are
* enqueued again or jobs that are delivered multiple times because they
* time out.
*
* @return int
*/
public function getAdditionalDeliveries();
/**
* Set the number of additional deliveries
*
* @param int $additionalDeliveries
*/
public function setAdditionalDeliveries($additionalDeliveries);
}
| php | MIT | 56cf00d97e739fec861717484657dbef2888df60 | 2026-01-05T05:12:23.969054Z | false |
mariano/disque-php | https://github.com/mariano/disque-php/blob/56cf00d97e739fec861717484657dbef2888df60/src/Queue/Job.php | src/Queue/Job.php | <?php
namespace Disque\Queue;
class Job extends BaseJob implements JobInterface
{
}
| php | MIT | 56cf00d97e739fec861717484657dbef2888df60 | 2026-01-05T05:12:23.969054Z | false |
mariano/disque-php | https://github.com/mariano/disque-php/blob/56cf00d97e739fec861717484657dbef2888df60/src/Queue/QueueException.php | src/Queue/QueueException.php | <?php
namespace Disque\Queue;
use Disque\DisqueException;
class QueueException extends DisqueException
{
} | php | MIT | 56cf00d97e739fec861717484657dbef2888df60 | 2026-01-05T05:12:23.969054Z | false |
mariano/disque-php | https://github.com/mariano/disque-php/blob/56cf00d97e739fec861717484657dbef2888df60/src/Queue/BaseJob.php | src/Queue/BaseJob.php | <?php
namespace Disque\Queue;
abstract class BaseJob implements JobInterface
{
/**
* Job ID
*
* @var string
*/
protected $id;
/**
* Job body
*
* This is the job data. Whether just an integer, an array, that depends
* on the use case.
*
* @var mixed
*/
protected $body;
/**
* The name of the queue the job belongs to
*
* This is optional and can be null eg. when adding a new job.
* It can however be used to identify what queue the job came from,
* eg. in case of a consumer reading from multiple queues.
*
* @var string
*/
protected $queue;
/**
* The number of NACKs this job has received
*
* NACK is a command which tells Disque that the job wasn't processed
* successfully and it should return to the queue immediately.
*
* @var int
*/
protected $nacks = 0;
/**
* The number of times this job has been re-delivered for reasons other
* than a NACK
*
* @var int
*/
protected $additionalDeliveries = 0;
/**
* An optional shortcut for instantiating the job with one call
*
* To make it more flexible, all arguments in the constructor are optional
* and the job can be populated by calling the setters.
*
* @param mixed $body Body The job body
* @param string $id The job ID
* @param string $queue Name of the queue the job belongs to
* @param int $nacks The number of NACKs
* @param int $additionalDeliveries The number of additional deliveries
*/
public function __construct(
$body = null,
$id = null,
$queue = '',
$nacks = 0,
$additionalDeliveries = 0
) {
$this->body = $body;
$this->id = $id;
$this->queue = $queue;
$this->nacks = $nacks;
$this->additionalDeliveries = $additionalDeliveries;
}
/**
* @inheritdoc
*/
public function getBody()
{
return $this->body;
}
/**
* @inheritdoc
*/
public function setBody($body)
{
$this->body = $body;
}
/**
* @inheritdoc
*/
public function getId()
{
return $this->id;
}
/**
* @inheritdoc
*/
public function setId($id)
{
$this->id = $id;
}
/**
* @inheritdoc
*/
public function getQueue()
{
return $this->queue;
}
/**
* @inheritdoc
*/
public function setQueue($queue)
{
$this->queue = $queue;
}
/**
* @inheritdoc
*/
public function getNacks()
{
return $this->nacks;
}
/**
* @inheritdoc
*/
public function setNacks($nacks)
{
$this->nacks = $nacks;
}
/**
* @inheritdoc
*/
public function getAdditionalDeliveries()
{
return $this->additionalDeliveries;
}
/**
* @inheritdoc
*/
public function setAdditionalDeliveries($additionalDeliveries)
{
$this->additionalDeliveries = $additionalDeliveries;
}
}
| php | MIT | 56cf00d97e739fec861717484657dbef2888df60 | 2026-01-05T05:12:23.969054Z | false |
mariano/disque-php | https://github.com/mariano/disque-php/blob/56cf00d97e739fec861717484657dbef2888df60/src/Queue/Queue.php | src/Queue/Queue.php | <?php
namespace Disque\Queue;
use DateTime;
use DateTimeZone;
use Disque\Client;
use Disque\Queue\Marshal\JobMarshaler;
use Disque\Queue\Marshal\MarshalerInterface;
use InvalidArgumentException;
use Disque\Command\Response\JobsResponse AS Response;
use Disque\Command\Response\JobsWithCountersResponse AS Counters;
class Queue
{
const DEFAULT_JOB_TIMEZONE = 'UTC';
/**
* Client
*
* @var Client
*/
protected $client;
/**
* Name
*
* @var string
*/
protected $name;
/**
* Job marshaler
*
* @var MarshalerInterface
*/
private $marshaler;
/**
* Default time zone
*
* @var DateTimeZone
*/
private $timeZone;
/**
* Create a queue
*
* @param Client $client Client
* @param string $name Queue name
*/
public function __construct(Client $client, $name)
{
$this->client = $client;
$this->name = $name;
$this->setMarshaler(new JobMarshaler());
}
/**
* Get the queue name
*
* @return string
*/
public function getName()
{
return $this->name;
}
/**
* Set Job marshaler
*
* @param MarshalerInterface Marshaler
* @return void
*/
public function setMarshaler(MarshalerInterface $marshaler)
{
$this->marshaler = $marshaler;
}
/**
* Pushes a job into the queue, setting it to be up for processing only at
* the specific date & time.
*
* @param JobInterface $job Job
* @param DateTime $when Date & time on when job should be ready for processing
* @param array $options ADDJOB options sent to the client
* @return JobInterface Job pushed
* @throws InvalidArgumentException
*/
public function schedule(JobInterface $job, DateTime $when, array $options = [])
{
if (!isset($this->timeZone)) {
$this->timeZone = new DateTimeZone(self::DEFAULT_JOB_TIMEZONE);
}
$date = clone($when);
$date->setTimeZone($this->timeZone);
$now = new DateTime('now', $this->timeZone);
if ($date < $now) {
throw new InvalidArgumentException('Specified schedule time has passed');
}
$options['delay'] = ($date->getTimestamp() - $now->getTimestamp());
return $this->push($job, $options);
}
/**
* Pushes a job into the queue
*
* @param JobInterface $job Job
* @param array $options ADDJOB options sent to the client
* @return JobInterface Job pushed
*/
public function push(JobInterface $job, array $options = [])
{
$this->checkConnected();
$id = $this->client->addJob($this->name, $this->marshaler->marshal($job), $options);
$job->setId($id);
return $job;
}
/**
* Pulls a single job from the queue (if none available, and if $timeout
* specified, then wait only this much time for a job, otherwise return
* `null`)
*
* @param int $timeout If specified, wait these many seconds
* @return Job|null A job, or null if no job was found before timeout
*/
public function pull($timeout = 0)
{
$this->checkConnected();
$jobs = $this->client->getJob($this->name, [
'timeout' => $timeout,
'count' => 1,
'withcounters' => true
]);
if (empty($jobs)) {
return null;
}
$jobData = $jobs[0];
$job = $this->marshaler->unmarshal($jobData[Response::KEY_BODY]);
$job->setId($jobData[Response::KEY_ID]);
$job->setNacks($jobData[Counters::KEY_NACKS]);
$job->setAdditionalDeliveries(
$jobData[Counters::KEY_ADDITIONAL_DELIVERIES]
);
return $job;
}
/**
* Marks that a Job is still being processed
*
* @param JobInterface $job Job
* @return int Number of seconds that the job visibility was postponed
*/
public function processing(JobInterface $job)
{
$this->checkConnected();
return $this->client->working($job->getId());
}
/**
* Acknowledges a Job as properly handled
*
* @param JobInterface $job Job
* @return void
*/
public function processed(JobInterface $job)
{
$this->checkConnected();
$this->client->ackJob($job->getId());
}
/**
* Marks the job as failed and returns it to the queue
*
* This increases the NACK counter of the job
*
* @param JobInterface $job
* @return void
*/
public function failed(JobInterface $job)
{
$this->checkConnected();
$this->client->nack($job->getId());
}
/**
* Check that we are connected to a node, and if not connect
*
* @return void
* @throws Disque\Connection\ConnectionException
*/
private function checkConnected()
{
if (!$this->client->isConnected()) {
$this->client->connect();
}
}
}
| php | MIT | 56cf00d97e739fec861717484657dbef2888df60 | 2026-01-05T05:12:23.969054Z | false |
mariano/disque-php | https://github.com/mariano/disque-php/blob/56cf00d97e739fec861717484657dbef2888df60/src/Queue/Marshal/MarshalerInterface.php | src/Queue/Marshal/MarshalerInterface.php | <?php
namespace Disque\Queue\Marshal;
use Disque\Queue\JobInterface;
interface MarshalerInterface
{
/**
* Creates a JobInterface instance based on data obtained from queue
*
* @param string $source Source data
* @return JobInterface
* @throws MarshalException
*/
public function unmarshal($source);
/**
* Marshals the body of the job ready to be put into the queue
*
* @param JobInterface $job Job to put in the queue
* @return string Source data to be put in the queue
* @throws MarshalException
*/
public function marshal(JobInterface $job);
}
| php | MIT | 56cf00d97e739fec861717484657dbef2888df60 | 2026-01-05T05:12:23.969054Z | false |
mariano/disque-php | https://github.com/mariano/disque-php/blob/56cf00d97e739fec861717484657dbef2888df60/src/Queue/Marshal/JobMarshaler.php | src/Queue/Marshal/JobMarshaler.php | <?php
namespace Disque\Queue\Marshal;
use Disque\Queue\Job;
use Disque\Queue\JobInterface;
/**
* Serialize and deserialize the job body
*
* Serialize the job body when adding the job to the queue,
* deserialize it and instantiate a new Job object when reading the job
* from the queue.
*
* This marshaler uses JSON serialization for the whole Job body.
*/
class JobMarshaler implements MarshalerInterface
{
/**
* @inheritdoc
*/
public function unmarshal($source)
{
$body = json_decode($source, true);
if (is_null($body)) {
throw new MarshalException("Could not deserialize {$source}");
}
return new Job($body);
}
/**
* @inheritdoc
*/
public function marshal(JobInterface $job)
{
return json_encode($job->getBody());
}
}
| php | MIT | 56cf00d97e739fec861717484657dbef2888df60 | 2026-01-05T05:12:23.969054Z | false |
mariano/disque-php | https://github.com/mariano/disque-php/blob/56cf00d97e739fec861717484657dbef2888df60/src/Queue/Marshal/MarshalException.php | src/Queue/Marshal/MarshalException.php | <?php
namespace Disque\Queue\Marshal;
use Disque\Queue\QueueException;
class MarshalException extends QueueException
{
} | php | MIT | 56cf00d97e739fec861717484657dbef2888df60 | 2026-01-05T05:12:23.969054Z | false |
mariano/disque-php | https://github.com/mariano/disque-php/blob/56cf00d97e739fec861717484657dbef2888df60/src/Command/JScan.php | src/Command/JScan.php | <?php
namespace Disque\Command;
use Disque\Command\Argument\ArrayChecker;
use Disque\Command\Argument\OptionChecker;
use Disque\Command\Argument\InvalidCommandArgumentException;
use Disque\Command\Argument\InvalidOptionException;
use Disque\Command\Response\JscanResponse;
class JScan extends BaseCommand implements CommandInterface
{
use ArrayChecker;
use OptionChecker;
/**
* Tells which class handles the response
*
* @var int
*/
protected $responseHandler = JscanResponse::class;
/**
* Available command options
*
* @var array
*/
protected $options = [
'busyloop' => false,
'count' => null,
'queue' => null,
'state' => null,
'reply' => null
];
/**
* Available command arguments, and their mapping to options
*
* @var array
*/
protected $availableArguments = [
'busyloop' => 'BUSYLOOP',
'count' => 'COUNT',
'queue' => 'QUEUE',
'state' => 'STATE',
'reply' => 'REPLY'
];
/**
* Get command
*
* @return string Command
*/
public function getCommand()
{
return 'JSCAN';
}
/**
* Set arguments for the command
*
* @param array $arguments Arguments
* @throws InvalidOptionException
*/
public function setArguments(array $arguments)
{
$options = [];
if (!empty($arguments)) {
if (
!$this->checkFixedArray($arguments, count($arguments) > 1 ? 2 : 1) ||
!is_numeric($arguments[0]) ||
(isset($arguments[1]) && !is_array($arguments[1]))
) {
throw new InvalidCommandArgumentException($this, $arguments);
}
if (isset($arguments[1])) {
$options = $arguments[1];
$this->checkOptionsInt($options, ['count']);
$this->checkOptionsString($options, ['queue', 'reply']);
$this->checkOptionsArray($options, ['state']);
}
}
$this->arguments = array_merge([
!empty($arguments) ? (int) $arguments[0] : 0
], $this->toArguments($options));
}
} | php | MIT | 56cf00d97e739fec861717484657dbef2888df60 | 2026-01-05T05:12:23.969054Z | false |
mariano/disque-php | https://github.com/mariano/disque-php/blob/56cf00d97e739fec861717484657dbef2888df60/src/Command/QLen.php | src/Command/QLen.php | <?php
namespace Disque\Command;
use Disque\Command\Response\IntResponse;
class QLen extends BaseCommand implements CommandInterface
{
/**
* Tells the argument types for this command
*
* @var int
*/
protected $argumentsType = self::ARGUMENTS_TYPE_STRING;
/**
* Tells which class handles the response
*
* @var int
*/
protected $responseHandler = IntResponse::class;
/**
* Get command
*
* @return string Command
*/
public function getCommand()
{
return 'QLEN';
}
} | php | MIT | 56cf00d97e739fec861717484657dbef2888df60 | 2026-01-05T05:12:23.969054Z | false |
mariano/disque-php | https://github.com/mariano/disque-php/blob/56cf00d97e739fec861717484657dbef2888df60/src/Command/Dequeue.php | src/Command/Dequeue.php | <?php
namespace Disque\Command;
use Disque\Command\Response\IntResponse;
class Dequeue extends BaseCommand implements CommandInterface
{
/**
* Tells the argument types for this command
*
* @var int
*/
protected $argumentsType = self::ARGUMENTS_TYPE_STRINGS;
/**
* Tells which class handles the response
*
* @var int
*/
protected $responseHandler = IntResponse::class;
/**
* Get command
*
* @return string Command
*/
public function getCommand()
{
return 'DEQUEUE';
}
} | php | MIT | 56cf00d97e739fec861717484657dbef2888df60 | 2026-01-05T05:12:23.969054Z | false |
mariano/disque-php | https://github.com/mariano/disque-php/blob/56cf00d97e739fec861717484657dbef2888df60/src/Command/DelJob.php | src/Command/DelJob.php | <?php
namespace Disque\Command;
use Disque\Command\Response\IntResponse;
class DelJob extends BaseCommand implements CommandInterface
{
/**
* Tells the argument types for this command
*
* @var int
*/
protected $argumentsType = self::ARGUMENTS_TYPE_STRINGS;
/**
* Tells which class handles the response
*
* @var int
*/
protected $responseHandler = IntResponse::class;
/**
* Get command
*
* @return string Command
*/
public function getCommand()
{
return 'DELJOB';
}
} | php | MIT | 56cf00d97e739fec861717484657dbef2888df60 | 2026-01-05T05:12:23.969054Z | false |
mariano/disque-php | https://github.com/mariano/disque-php/blob/56cf00d97e739fec861717484657dbef2888df60/src/Command/Enqueue.php | src/Command/Enqueue.php | <?php
namespace Disque\Command;
use Disque\Command\Response\IntResponse;
class Enqueue extends BaseCommand implements CommandInterface
{
/**
* Tells the argument types for this command
*
* @var int
*/
protected $argumentsType = self::ARGUMENTS_TYPE_STRINGS;
/**
* Tells which class handles the response
*
* @var int
*/
protected $responseHandler = IntResponse::class;
/**
* Get command
*
* @return string Command
*/
public function getCommand()
{
return 'ENQUEUE';
}
} | php | MIT | 56cf00d97e739fec861717484657dbef2888df60 | 2026-01-05T05:12:23.969054Z | false |
mariano/disque-php | https://github.com/mariano/disque-php/blob/56cf00d97e739fec861717484657dbef2888df60/src/Command/CommandInterface.php | src/Command/CommandInterface.php | <?php
namespace Disque\Command;
interface CommandInterface
{
/**
* Get the command name
*
* The command name determines how the command will be called on Client.
* If this method returns "foo", the command must be invoked by calling
* the Client::foo() method (the method name is case insensitive)
*
* @return string Command
*/
public function getCommand();
/**
* Tells if this command blocks while waiting for a response, to avoid
* being affected by connection timeouts.
*
* @return bool If true, this command blocks
*/
public function isBlocking();
/**
* Get processed arguments for command
*
* @return array Arguments
*/
public function getArguments();
/**
* Set arguments for the command
*
* @param array $arguments Arguments
* @return void
* @throws Disque\Command\Argument\InvalidCommandArgumentException
*/
public function setArguments(array $arguments);
/**
* Parse response
*
* @param mixed $body Response body
* @return mixed Parsed response
* @throws Disque\Command\Response\InvalidResponseException
*/
public function parse($body);
}
| php | MIT | 56cf00d97e739fec861717484657dbef2888df60 | 2026-01-05T05:12:23.969054Z | false |
mariano/disque-php | https://github.com/mariano/disque-php/blob/56cf00d97e739fec861717484657dbef2888df60/src/Command/Auth.php | src/Command/Auth.php | <?php
namespace Disque\Command;
use Disque\Command\Response\AuthResponse;
class Auth extends BaseCommand implements CommandInterface
{
/**
* Tells the argument types for this command
*
* @var int
*/
protected $argumentsType = self::ARGUMENTS_TYPE_STRING;
/**
* Get command
*
* @return string Command
*/
public function getCommand()
{
return 'AUTH';
}
} | php | MIT | 56cf00d97e739fec861717484657dbef2888df60 | 2026-01-05T05:12:23.969054Z | false |
mariano/disque-php | https://github.com/mariano/disque-php/blob/56cf00d97e739fec861717484657dbef2888df60/src/Command/AckJob.php | src/Command/AckJob.php | <?php
namespace Disque\Command;
use Disque\Command\Response\IntResponse;
class AckJob extends BaseCommand implements CommandInterface
{
/**
* Tells the argument types for this command
*
* @var int
*/
protected $argumentsType = self::ARGUMENTS_TYPE_STRINGS;
/**
* Tells which class handles the response
*
* @var int
*/
protected $responseHandler = IntResponse::class;
/**
* Get command
*
* @return string Command
*/
public function getCommand()
{
return 'ACKJOB';
}
} | php | MIT | 56cf00d97e739fec861717484657dbef2888df60 | 2026-01-05T05:12:23.969054Z | false |
mariano/disque-php | https://github.com/mariano/disque-php/blob/56cf00d97e739fec861717484657dbef2888df60/src/Command/InvalidCommandException.php | src/Command/InvalidCommandException.php | <?php
namespace Disque\Command;
use Disque\DisqueException;
class InvalidCommandException extends DisqueException
{
public function __construct($command)
{
parent::__construct("Invalid command {$command}");
}
} | php | MIT | 56cf00d97e739fec861717484657dbef2888df60 | 2026-01-05T05:12:23.969054Z | false |
mariano/disque-php | https://github.com/mariano/disque-php/blob/56cf00d97e739fec861717484657dbef2888df60/src/Command/AddJob.php | src/Command/AddJob.php | <?php
namespace Disque\Command;
use Disque\Command\Argument\ArrayChecker;
use Disque\Command\Argument\OptionChecker;
use Disque\Command\Argument\InvalidCommandArgumentException;
class AddJob extends BaseCommand implements CommandInterface
{
use ArrayChecker;
use OptionChecker;
/**
* Available command options
*
* @var array
*/
protected $options = [
'timeout' => 0,
'replicate' => null,
'delay' => null,
'retry' => null,
'ttl' => null,
'maxlen' => null,
'async' => false
];
/**
* Available command arguments, and their mapping to options
*
* @var array
*/
protected $availableArguments = [
'replicate' => 'REPLICATE',
'delay' => 'DELAY',
'retry' => 'RETRY',
'ttl' => 'TTL',
'maxlen' => 'MAXLEN',
'async' => 'ASYNC'
];
/**
* Get command
*
* @return string Command
*/
public function getCommand()
{
return 'ADDJOB';
}
/**
* Set arguments for the command
*
* The first two values in the $arguments array must be the queue name and
* the job body. The third value is optional and if present, must be
* an array with further arguments.
* @see $availableArguments
*
* @param array $arguments Arguments
* @throws InvalidCommandArgumentException
*/
public function setArguments(array $arguments)
{
$count = count($arguments);
if (!$this->checkFixedArray($arguments, 2, true) || $count > 3) {
throw new InvalidCommandArgumentException($this, $arguments);
} elseif (!is_string($arguments[0]) || !is_string($arguments[1])) {
throw new InvalidCommandArgumentException($this, $arguments);
} elseif ($count === 3 && (!isset($arguments[2]) || !is_array($arguments[2]))) {
throw new InvalidCommandArgumentException($this, $arguments);
}
$options = (!empty($arguments[2]) ? $arguments[2] : []) + ['timeout' => $this->options['timeout']];
$this->checkOptionsInt($options, ['timeout', 'replicate', 'delay', 'retry', 'ttl', 'maxlen']);
$this->arguments = array_merge(
[$arguments[0], $arguments[1], $options['timeout']],
$this->toArguments(array_diff_key($options, ['timeout'=>null]))
);
}
} | php | MIT | 56cf00d97e739fec861717484657dbef2888df60 | 2026-01-05T05:12:23.969054Z | false |
mariano/disque-php | https://github.com/mariano/disque-php/blob/56cf00d97e739fec861717484657dbef2888df60/src/Command/QStat.php | src/Command/QStat.php | <?php
namespace Disque\Command;
use Disque\Command\Response\KeyValueResponse;
use Disque\Exception;
class QStat extends BaseCommand implements CommandInterface
{
/**
* Tells the argument types for this command
*
* @var int
*/
protected $argumentsType = self::ARGUMENTS_TYPE_STRING;
/**
* Tells which class handles the response
*
* @var int
*/
protected $responseHandler = KeyValueResponse::class;
/**
* Get command
*
* @return string Command
*/
public function getCommand()
{
return 'QSTAT';
}
}
| php | MIT | 56cf00d97e739fec861717484657dbef2888df60 | 2026-01-05T05:12:23.969054Z | false |
mariano/disque-php | https://github.com/mariano/disque-php/blob/56cf00d97e739fec861717484657dbef2888df60/src/Command/Info.php | src/Command/Info.php | <?php
namespace Disque\Command;
use Disque\Exception;
class Info extends BaseCommand implements CommandInterface
{
/**
* Tells the argument types for this command
*
* @var int
*/
protected $argumentsType = self::ARGUMENTS_TYPE_EMPTY;
/**
* Get command
*
* @return string Command
*/
public function getCommand()
{
return 'INFO';
}
} | php | MIT | 56cf00d97e739fec861717484657dbef2888df60 | 2026-01-05T05:12:23.969054Z | false |
mariano/disque-php | https://github.com/mariano/disque-php/blob/56cf00d97e739fec861717484657dbef2888df60/src/Command/QPeek.php | src/Command/QPeek.php | <?php
namespace Disque\Command;
use Disque\Command\Response\JobsWithQueueResponse;
class QPeek extends BaseCommand implements CommandInterface
{
/**
* Tells the argument types for this command
*
* @var int
*/
protected $argumentsType = self::ARGUMENTS_TYPE_STRING_INT;
/**
* Tells which class handles the response
*
* @var int
*/
protected $responseHandler = JobsWithQueueResponse::class;
/**
* Get command
*
* @return string Command
*/
public function getCommand()
{
return 'QPEEK';
}
} | php | MIT | 56cf00d97e739fec861717484657dbef2888df60 | 2026-01-05T05:12:23.969054Z | false |
mariano/disque-php | https://github.com/mariano/disque-php/blob/56cf00d97e739fec861717484657dbef2888df60/src/Command/Show.php | src/Command/Show.php | <?php
namespace Disque\Command;
use Disque\Command\Response\KeyValueResponse;
class Show extends BaseCommand implements CommandInterface
{
/**
* Tells the argument types for this command
*
* @var int
*/
protected $argumentsType = self::ARGUMENTS_TYPE_STRING;
/**
* Tells which class handles the response
*
* @var int
*/
protected $responseHandler = KeyValueResponse::class;
/**
* Get command
*
* @return string Command
*/
public function getCommand()
{
return 'SHOW';
}
} | php | MIT | 56cf00d97e739fec861717484657dbef2888df60 | 2026-01-05T05:12:23.969054Z | false |
mariano/disque-php | https://github.com/mariano/disque-php/blob/56cf00d97e739fec861717484657dbef2888df60/src/Command/Nack.php | src/Command/Nack.php | <?php
namespace Disque\Command;
use Disque\Command\Response\IntResponse;
/**
* Put the job(s) back to the queue immediately and increment the nack counter.
*
* The command should be used when the worker was not able to process a job and
* wants the job to be put back into the queue in order to be processed again.
*
* It is very similar to ENQUEUE but it increments the job nacks counter
* instead of the additional-deliveries counter.
*/
class Nack extends BaseCommand implements CommandInterface
{
/**
* @inheritdoc
*/
protected $argumentsType = self::ARGUMENTS_TYPE_STRINGS;
/**
* @inheritdoc
*/
protected $responseHandler = IntResponse::class;
/**
* @inheritdoc
*/
public function getCommand()
{
return 'NACK';
}
} | php | MIT | 56cf00d97e739fec861717484657dbef2888df60 | 2026-01-05T05:12:23.969054Z | false |
mariano/disque-php | https://github.com/mariano/disque-php/blob/56cf00d97e739fec861717484657dbef2888df60/src/Command/BaseCommand.php | src/Command/BaseCommand.php | <?php
namespace Disque\Command;
use Disque\Command\Argument\InvalidCommandArgumentException;
use Disque\Command\Argument\InvalidOptionException;
use Disque\Command\Argument\StringChecker;
use Disque\Command\Response\StringResponse;
abstract class BaseCommand implements CommandInterface
{
use StringChecker;
/**
* The following constants define the default behavior in case the command
* uses the base method setArguments()
*
* If you override the method completely, then this has no effect.
* @see GetJob
*/
/**
* The command doesn't accept any arguments
* Eg. INFO
*/
const ARGUMENTS_TYPE_EMPTY = 0;
/**
* The command accepts a single argument, a string
* Eg. ACKJOB job_id
*/
const ARGUMENTS_TYPE_STRING = 1;
/**
* The command accepts a single string argument followed by an integer
* Eg. QPEEK queue_name 1
*/
const ARGUMENTS_TYPE_STRING_INT = 2;
/**
* The command accepts only string arguments and there must be at least one
* Eg. FASTACK job_id1 job_id2 ... job_idN
*/
const ARGUMENTS_TYPE_STRINGS = 3;
/**
* Available command options
*
* Provide default argument values.
* If the value for the argument is not provided, is null, or is false,
* the option will not be used.
*
* @var array
*/
protected $options = [];
/**
* Available optional command arguments, and their mapping to options
*
* All available optional arguments must be defined here. If they are
* processed by the method toArguments(), the $this->options variable
* will automatically provide the default values.
*
* @var array
*/
protected $availableArguments = [];
/**
* Arguments
*
* @var array
*/
protected $arguments = [];
/**
* Tells the argument types for this command
*
* @var int
*/
protected $argumentsType = self::ARGUMENTS_TYPE_STRING;
/**
* Tells which class handles the response
*
* @var string
*/
protected $responseHandler = StringResponse::class;
/**
* Get command
*
* @return string Command
*/
abstract public function getCommand();
/**
* Tells if this command blocks while waiting for a response, to avoid
* being affected by connection timeouts.
*
* @return bool If true, this command blocks
*/
public function isBlocking()
{
return false;
}
/**
* Get processed arguments for command
*
* @return array Arguments
*/
public function getArguments()
{
return $this->arguments;
}
/**
* Set arguments for the command
*
* @param array $arguments Arguments
* @return void
* @throws InvalidCommandArgumentException
*/
public function setArguments(array $arguments)
{
switch ($this->argumentsType) {
case self::ARGUMENTS_TYPE_EMPTY:
if (!empty($arguments)) {
throw new InvalidCommandArgumentException($this, $arguments);
}
$arguments = [];
break;
case self::ARGUMENTS_TYPE_STRING:
$this->checkStringArgument($arguments);
$arguments = [$arguments[0]];
break;
case self::ARGUMENTS_TYPE_STRING_INT:
$this->checkStringArgument($arguments, 2);
if (!is_int($arguments[1])) {
throw new InvalidCommandArgumentException($this, $arguments);
}
$arguments = [$arguments[0], (int) $arguments[1]];
break;
case self::ARGUMENTS_TYPE_STRINGS:
$this->checkStringArguments($arguments);
break;
// A fallback in case a non-existing argument type is defined.
// This could be prevented by using an Enum as the argument type
default:
throw new InvalidCommandArgumentException($this, $arguments);
}
$this->arguments = $arguments;
}
/**
* Parse response
*
* @param mixed $body Response body
* @return mixed Parsed response
* @throws Disque\Command\Response\InvalidResponseException
*/
public function parse($body)
{
$responseClass = $this->responseHandler;
$response = new $responseClass();
$response->setCommand($this);
$response->setBody($body);
return $response->parse();
}
/**
* Build command arguments out of options
*
* Client-supplied options are amended with the default options defined
* in $this->options. Options whose value is set to null or false are
* ignored
*
* @param array $options Command options
* @return array Command arguments
* @throws InvalidOptionException
*/
protected function toArguments(array $options)
{
if (empty($options)) {
return [];
} elseif (!empty(array_diff_key($options, $this->availableArguments))) {
throw new InvalidOptionException($this, $options);
}
// Pad, don't overwrite, the client provided options with the default ones
$options += $this->options;
$arguments = [];
foreach ($this->availableArguments as $option => $argument) {
if (!isset($options[$option]) || $options[$option] === false) {
continue;
}
$value = $options[$option];
if (is_array($value)) {
foreach ($value as $currentValue) {
$arguments[] = $argument;
$arguments[] = $currentValue;
}
} else {
$arguments[] = $argument;
if (!is_bool($value)) {
$arguments[] = $value;
}
}
}
return $arguments;
}
} | php | MIT | 56cf00d97e739fec861717484657dbef2888df60 | 2026-01-05T05:12:23.969054Z | false |
mariano/disque-php | https://github.com/mariano/disque-php/blob/56cf00d97e739fec861717484657dbef2888df60/src/Command/GetJob.php | src/Command/GetJob.php | <?php
namespace Disque\Command;
use Disque\Command\Argument\StringChecker;
use Disque\Command\Argument\InvalidOptionException;
use Disque\Command\Response\JobsWithQueueResponse;
use Disque\Command\Response\JobsWithCountersResponse;
class GetJob extends BaseCommand implements CommandInterface
{
use StringChecker;
/**
* Tells which class handles the response
*
* @var int
*/
protected $responseHandler = JobsWithQueueResponse::class;
/**
* Available command options
*
* @var array
*/
protected $options = [
'nohang' => false,
'count' => null,
'timeout' => null,
'withcounters' => false
];
/**
* Available command arguments, and their mapping to options
*
* @var array
*/
protected $availableArguments = [
'nohang' => 'NOHANG',
'timeout' => 'TIMEOUT',
'count' => 'COUNT',
'withcounters' => 'WITHCOUNTERS'
];
/**
* Get command
*
* @return string Command
*/
public function getCommand()
{
return 'GETJOB';
}
/**
* Tells if this command blocks while waiting for a response, to avoid
* being affected by connection timeouts.
*
* @return bool If true, this command blocks
*/
public function isBlocking()
{
$arguments = $this->getArguments();
$options = end($arguments);
if (is_array($options) && !empty($options['nohang'])) {
return false;
}
return true;
}
/**
* Set arguments for the command
*
* The $arguments must contain at least one, possibly more queue names
* to read from. If the last value in the $arguments array is an array,
* it can contain further optional arguments.
* @see $availableArguments
*
* @param array $arguments Arguments
* @throws InvalidOptionException
*/
public function setArguments(array $arguments)
{
$options = [];
$last = end($arguments);
if (is_array($last)) {
$options = $last;
$arguments = array_slice($arguments, 0, -1);
if (
(isset($options['count']) && !is_int($options['count'])) ||
(isset($options['timeout']) && !is_int($options['timeout']))
) {
throw new InvalidOptionException($this, $last);
}
if (!empty($options['withcounters'])) {
// The response will contain NACKs and additional-deliveries
$this->responseHandler = JobsWithCountersResponse::class;
}
$options = $this->toArguments($options);
}
$this->checkStringArguments($arguments);
$this->arguments = array_merge($options, ['FROM'], array_values($arguments));
}
}
| php | MIT | 56cf00d97e739fec861717484657dbef2888df60 | 2026-01-05T05:12:23.969054Z | false |
mariano/disque-php | https://github.com/mariano/disque-php/blob/56cf00d97e739fec861717484657dbef2888df60/src/Command/Pause.php | src/Command/Pause.php | <?php
namespace Disque\Command;
use Disque\Command\Response\StringResponse;
/**
* Pause a queue.
*/
class Pause extends BaseCommand implements CommandInterface
{
/**
* @inheritdoc
*/
protected $responseHandler = StringResponse::class;
/**
* @inheritdoc
*/
public function getCommand()
{
return 'PAUSE';
}
/**
* Set arguments for the command
*
* @param array $arguments Arguments
* @return void
* @throws InvalidCommandArgumentException
*/
public function setArguments(array $arguments)
{
$this->checkStringArgument($arguments, 2);
$this->checkStringArguments($arguments);
$this->arguments = $arguments;
}
} | php | MIT | 56cf00d97e739fec861717484657dbef2888df60 | 2026-01-05T05:12:23.969054Z | false |
mariano/disque-php | https://github.com/mariano/disque-php/blob/56cf00d97e739fec861717484657dbef2888df60/src/Command/Working.php | src/Command/Working.php | <?php
namespace Disque\Command;
use Disque\Command\Response\IntResponse;
class Working extends BaseCommand implements CommandInterface
{
/**
* Tells the argument types for this command
*
* @var int
*/
protected $argumentsType = self::ARGUMENTS_TYPE_STRING;
/**
* Tells which class handles the response
*
* @var int
*/
protected $responseHandler = IntResponse::class;
/**
* Get command
*
* @return string Command
*/
public function getCommand()
{
return 'WORKING';
}
} | php | MIT | 56cf00d97e739fec861717484657dbef2888df60 | 2026-01-05T05:12:23.969054Z | false |
mariano/disque-php | https://github.com/mariano/disque-php/blob/56cf00d97e739fec861717484657dbef2888df60/src/Command/QScan.php | src/Command/QScan.php | <?php
namespace Disque\Command;
use Disque\Command\Argument\ArrayChecker;
use Disque\Command\Argument\OptionChecker;
use Disque\Command\Argument\InvalidCommandArgumentException;
use Disque\Command\Argument\InvalidOptionException;
use Disque\Command\Response\QscanResponse;
class QScan extends BaseCommand implements CommandInterface
{
use ArrayChecker;
use OptionChecker;
/**
* Tells which class handles the response
*
* @var int
*/
protected $responseHandler = QscanResponse::class;
/**
* Available command options
*
* @var array
*/
protected $options = [
'busyloop' => false,
'count' => null,
'minlen' => null,
'maxlen' => null,
'importrate' => null
];
/**
* Available command arguments, and their mapping to options
*
* @var array
*/
protected $availableArguments = [
'busyloop' => 'BUSYLOOP',
'count' => 'COUNT',
'minlen' => 'MINLEN',
'maxlen' => 'MAXLEN',
'importrate' => 'IMPORTRATE'
];
/**
* Get command
*
* @return string Command
*/
public function getCommand()
{
return 'QSCAN';
}
/**
* Set arguments for the command
*
* @param array $arguments Arguments
* @throws InvalidOptionException
*/
public function setArguments(array $arguments)
{
$options = [];
if (!empty($arguments)) {
if (
!$this->checkFixedArray($arguments, count($arguments) > 1 ? 2 : 1) ||
!is_numeric($arguments[0]) ||
(isset($arguments[1]) && !is_array($arguments[1]))
) {
throw new InvalidCommandArgumentException($this, $arguments);
}
if (isset($arguments[1])) {
$options = $arguments[1];
$this->checkOptionsInt($options, ['count', 'minlen', 'maxlen', 'importrate']);
}
}
$this->arguments = array_merge([
!empty($arguments) ? (int) $arguments[0] : 0
], $this->toArguments($options));
}
} | php | MIT | 56cf00d97e739fec861717484657dbef2888df60 | 2026-01-05T05:12:23.969054Z | false |
mariano/disque-php | https://github.com/mariano/disque-php/blob/56cf00d97e739fec861717484657dbef2888df60/src/Command/FastAck.php | src/Command/FastAck.php | <?php
namespace Disque\Command;
use Disque\Command\Response\IntResponse;
class FastAck extends BaseCommand implements CommandInterface
{
/**
* Tells the argument types for this command
*
* @var int
*/
protected $argumentsType = self::ARGUMENTS_TYPE_STRINGS;
/**
* Tells which class handles the response
*
* @var int
*/
protected $responseHandler = IntResponse::class;
/**
* Get command
*
* @return string Command
*/
public function getCommand()
{
return 'FASTACK';
}
} | php | MIT | 56cf00d97e739fec861717484657dbef2888df60 | 2026-01-05T05:12:23.969054Z | false |
mariano/disque-php | https://github.com/mariano/disque-php/blob/56cf00d97e739fec861717484657dbef2888df60/src/Command/Hello.php | src/Command/Hello.php | <?php
namespace Disque\Command;
use Disque\Command\Response\HelloResponse;
class Hello extends BaseCommand implements CommandInterface
{
/**
* Tells the argument types for this command
*
* @var int
*/
protected $argumentsType = self::ARGUMENTS_TYPE_EMPTY;
/**
* Tells which class handles the response
*
* @var int
*/
protected $responseHandler = HelloResponse::class;
/**
* Get command
*
* @return string Command
*/
public function getCommand()
{
return 'HELLO';
}
} | php | MIT | 56cf00d97e739fec861717484657dbef2888df60 | 2026-01-05T05:12:23.969054Z | false |
mariano/disque-php | https://github.com/mariano/disque-php/blob/56cf00d97e739fec861717484657dbef2888df60/src/Command/Response/QscanResponse.php | src/Command/Response/QscanResponse.php | <?php
namespace Disque\Command\Response;
class QscanResponse extends CursorResponse implements ResponseInterface
{
/**
* Parse main body
*
* @param array $body Body
* @return array Parsed body
*/
protected function parseBody(array $body)
{
return ['queues' => $body];
}
} | php | MIT | 56cf00d97e739fec861717484657dbef2888df60 | 2026-01-05T05:12:23.969054Z | false |
mariano/disque-php | https://github.com/mariano/disque-php/blob/56cf00d97e739fec861717484657dbef2888df60/src/Command/Response/BaseResponse.php | src/Command/Response/BaseResponse.php | <?php
namespace Disque\Command\Response;
use Disque\Command\CommandInterface;
abstract class BaseResponse implements ResponseInterface
{
/**
* Command
*
* @var CommandInterface
*/
protected $command;
/**
* Response body
*
* @var mixed
*/
protected $body;
/**
* Set command
*
* @param CommandInterface $command Command
*/
public function setCommand(CommandInterface $command)
{
$this->command = $command;
}
/**
* Set response body
*
* @param mixed $body Response body
* @throws InvalidResponseException
*/
public function setBody($body)
{
$this->body = $body;
}
/**
* Parse response
*
* @return mixed Parsed response
* @throws InvalidResponseException
*/
abstract public function parse();
} | php | MIT | 56cf00d97e739fec861717484657dbef2888df60 | 2026-01-05T05:12:23.969054Z | false |
mariano/disque-php | https://github.com/mariano/disque-php/blob/56cf00d97e739fec861717484657dbef2888df60/src/Command/Response/HelloResponse.php | src/Command/Response/HelloResponse.php | <?php
namespace Disque\Command\Response;
use Disque\Command\Argument\ArrayChecker;
class HelloResponse extends BaseResponse implements ResponseInterface
{
/**
* Array keys
*/
const NODE_ID = 'id';
const NODE_HOST = 'host';
const NODE_PORT = 'port';
const NODE_VERSION = 'version';
const NODE_PRIORITY = 'priority';
const NODES = 'nodes';
/**
* Position indexes in the Disque response
*/
const POS_VERSION = 0;
const POS_ID = 1;
const POS_NODES_START = 2;
const POS_NODE_ID = 0;
const POS_NODE_HOST = 1;
const POS_NODE_PORT = 2;
const POS_NODE_PRIORITY = 3;
use ArrayChecker;
/**
* Set response body
*
* @param mixed $body Response body
* @return void
* @throws InvalidResponseException
*/
public function setBody($body)
{
if (!$this->checkFixedArray($body, 3, true)) {
throw new InvalidResponseException($this->command, $body);
}
foreach (array_slice($body, 2) as $node) {
if (!$this->checkFixedArray($node, 4)) {
throw new InvalidResponseException($this->command, $body);
}
}
parent::setBody($body);
}
/**
* Parse response
*
* @return array Parsed response
*/
public function parse()
{
$nodes = [];
foreach (array_slice($this->body, self::POS_NODES_START) as $node) {
$nodes[] = [
self::NODE_ID => $node[self::POS_NODE_ID],
self::NODE_HOST => $node[self::POS_NODE_HOST],
self::NODE_PORT => $node[self::POS_NODE_PORT],
self::NODE_PRIORITY => $node[self::POS_NODE_PRIORITY]
];
}
return [
self::NODE_VERSION => $this->body[self::POS_VERSION],
self::NODE_ID => $this->body[self::POS_ID],
self::NODES => $nodes
];
}
}
| php | MIT | 56cf00d97e739fec861717484657dbef2888df60 | 2026-01-05T05:12:23.969054Z | false |
mariano/disque-php | https://github.com/mariano/disque-php/blob/56cf00d97e739fec861717484657dbef2888df60/src/Command/Response/BasicTypeResponse.php | src/Command/Response/BasicTypeResponse.php | <?php
namespace Disque\Command\Response;
abstract class BasicTypeResponse extends BaseResponse implements ResponseInterface
{
const TYPE_STRING = 0;
const TYPE_INT = 1;
/**
* Basic data type for this response
*
* @var int
*/
protected $type;
/**
* Set response body
*
* @param mixed $body Response body
* @return void
* @throws InvalidResponseException
*/
public function setBody($body)
{
switch ($this->type) {
case self::TYPE_INT:
$error = !is_numeric($body);
break;
case self::TYPE_STRING:
default:
$error = !is_string($body);
break;
}
if ($error) {
throw new InvalidResponseException($this->command, $body);
}
parent::setBody($body);
}
} | php | MIT | 56cf00d97e739fec861717484657dbef2888df60 | 2026-01-05T05:12:23.969054Z | false |
mariano/disque-php | https://github.com/mariano/disque-php/blob/56cf00d97e739fec861717484657dbef2888df60/src/Command/Response/JobsWithCountersResponse.php | src/Command/Response/JobsWithCountersResponse.php | <?php
namespace Disque\Command\Response;
/**
* Parse a Disque response of GETJOB with the argument WITHCOUNTERS
*/
class JobsWithCountersResponse extends JobsWithQueueResponse implements ResponseInterface
{
const KEY_NACKS = 'nacks';
const KEY_ADDITIONAL_DELIVERIES = 'additional-deliveries';
/**
* GETJOB called with WITHCOUNTERS returns a 7-member array for each job.
* The value on (zero-based) position #3 is always the string "nacks", the
* value on position #5 is always the string "additional-deliveries".
*
* We want to remove these values from the response.
*/
const DISQUE_RESPONSE_KEY_NACKS = 3;
const DISQUE_RESPONSE_KEY_DELIVERIES = 5;
public function __construct()
{
// Note: The order of these calls is important as $jobDetails must
// match the order of the Disque response rows. Nacks go at the end.
parent::__construct();
$this->jobDetails = array_merge(
$this->jobDetails,
[
self::KEY_NACKS,
self::KEY_ADDITIONAL_DELIVERIES
]
);
}
/**
* @inheritdoc
*/
public function setBody($body)
{
if (is_null($body)) {
$body = [];
}
if (!is_array($body)) {
throw new InvalidResponseException($this->command, $body);
}
$jobDetailCount = count($this->jobDetails) + 2;
/**
* Remove superfluous strings from the response
* See the comment for the constants defined above
*/
$filteredBody = array_map(function (array $job) use ($jobDetailCount, $body) {
if (!$this->checkFixedArray($job, $jobDetailCount)) {
throw new InvalidResponseException($this->command, $body);
}
unset($job[self::DISQUE_RESPONSE_KEY_NACKS]);
unset($job[self::DISQUE_RESPONSE_KEY_DELIVERIES]);
/**
* We must reindex the array so it's dense (without holes)
* @see Disque\Command\Argument\ArrayChecker::checkFixedArray()
*/
return array_values($job);
}, $body);
parent::setBody($filteredBody);
}
} | php | MIT | 56cf00d97e739fec861717484657dbef2888df60 | 2026-01-05T05:12:23.969054Z | false |
mariano/disque-php | https://github.com/mariano/disque-php/blob/56cf00d97e739fec861717484657dbef2888df60/src/Command/Response/KeyValueResponse.php | src/Command/Response/KeyValueResponse.php | <?php
namespace Disque\Command\Response;
class KeyValueResponse extends BaseResponse implements ResponseInterface
{
/**
* Set response body
*
* @param mixed $body Response body
* @return void
* @throws InvalidResponseException
*/
public function setBody($body)
{
if ($body !== false && (empty($body) || !is_array($body) || (count($body) % 2) !== 0)) {
throw new InvalidResponseException($this->command, $body);
}
parent::setBody($body);
}
/**
* Parse response
*
* @return array Parsed response
*/
public function parse()
{
if ($this->body === false) {
return null;
}
$result = [];
$key = null;
foreach ($this->body as $value) {
if (!is_null($key)) {
$result[$key] = $value;
$key = null;
} else {
$key = $value;
}
}
return $result;
}
} | php | MIT | 56cf00d97e739fec861717484657dbef2888df60 | 2026-01-05T05:12:23.969054Z | false |
mariano/disque-php | https://github.com/mariano/disque-php/blob/56cf00d97e739fec861717484657dbef2888df60/src/Command/Response/StringResponse.php | src/Command/Response/StringResponse.php | <?php
namespace Disque\Command\Response;
class StringResponse extends BasicTypeResponse implements ResponseInterface
{
/**
* Basic data type for this response
*
* @var int
*/
protected $type = self::TYPE_STRING;
/**
* Parse response
*
* @return string Parsed response
*/
public function parse()
{
return (string) $this->body;
}
} | php | MIT | 56cf00d97e739fec861717484657dbef2888df60 | 2026-01-05T05:12:23.969054Z | false |
mariano/disque-php | https://github.com/mariano/disque-php/blob/56cf00d97e739fec861717484657dbef2888df60/src/Command/Response/ResponseInterface.php | src/Command/Response/ResponseInterface.php | <?php
namespace Disque\Command\Response;
use Disque\Command\CommandInterface;
interface ResponseInterface
{
/**
* Set command
*
* @param CommandInterface $command Command
* @return void
*/
public function setCommand(CommandInterface $command);
/**
* Set response body
*
* @param mixed $body Response body
* @return void
* @throws InvalidResponseException
*/
public function setBody($body);
/**
* Parse response
*
* @return mixed Parsed response
* @throws InvalidResponseException
*/
public function parse();
} | php | MIT | 56cf00d97e739fec861717484657dbef2888df60 | 2026-01-05T05:12:23.969054Z | false |
mariano/disque-php | https://github.com/mariano/disque-php/blob/56cf00d97e739fec861717484657dbef2888df60/src/Command/Response/JobsResponse.php | src/Command/Response/JobsResponse.php | <?php
namespace Disque\Command\Response;
use Disque\Command\Argument\ArrayChecker;
class JobsResponse extends BaseResponse implements ResponseInterface
{
use ArrayChecker;
const KEY_ID = 'id';
const KEY_BODY = 'body';
/**
* The position where a node prefix starts in the job ID
*/
const ID_NODE_PREFIX_START = 2;
/**
* Job details for each job
*
* The values in this array must follow these rules:
* - The number of the values must be the same as the number of rows
* returned from the respective Disque command
* - The order of the values must follow the rows returned by Disque
*
* The values in $jobDetails will be used as keys in the final response
* the command returns.
*
* @see self::parse()
*
* @var array
*/
protected $jobDetails = [];
public function __construct()
{
$this->jobDetails = [self::KEY_ID, self::KEY_BODY];
}
/**
* @inheritdoc
*/
public function setBody($body)
{
if (is_null($body)) {
$body = [];
}
if (!is_array($body)) {
throw new InvalidResponseException($this->command, $body);
}
$jobDetailCount = count($this->jobDetails);
foreach ($body as $job) {
if (!$this->checkFixedArray($job, $jobDetailCount)) {
throw new InvalidResponseException($this->command, $body);
}
$idPosition = array_search(self::KEY_ID, $this->jobDetails);
$id = $job[$idPosition];
if (strpos($id, 'D-') !== 0 || strlen($id) < 10) {
throw new InvalidResponseException($this->command, $body);
}
}
parent::setBody($body);
}
/**
* @inheritdoc
*/
public function parse()
{
$jobs = [];
foreach ($this->body as $job) {
// To describe this crucial moment in detail: $jobDetails as well as
// the $job are numeric arrays with the same number of values.
// array_combine() combines them in a new array so that values
// from $jobDetails become the keys and values from $job the values.
// It's very important that $jobDetails are present in the same
// order as the response from Disque.
$jobs[] = array_combine($this->jobDetails, $job);
}
return $jobs;
}
}
| php | MIT | 56cf00d97e739fec861717484657dbef2888df60 | 2026-01-05T05:12:23.969054Z | false |
mariano/disque-php | https://github.com/mariano/disque-php/blob/56cf00d97e739fec861717484657dbef2888df60/src/Command/Response/InvalidResponseException.php | src/Command/Response/InvalidResponseException.php | <?php
namespace Disque\Command\Response;
use Disque\Command\CommandInterface;
use Disque\DisqueException;
class InvalidResponseException extends DisqueException
{
/**
* Response
*
* @var string
*/
private $response;
public function __construct(CommandInterface $command, $response)
{
parent::__construct(sprintf("Invalid command response. Command %1s got: %2s",
get_class($command),
json_encode($response)
));
$this->response = $response;
}
/**
* Get actual response (if any) that triggered this exception
*
* @return string? Response
*/
public function getResponse()
{
return $this->response;
}
} | php | MIT | 56cf00d97e739fec861717484657dbef2888df60 | 2026-01-05T05:12:23.969054Z | false |
mariano/disque-php | https://github.com/mariano/disque-php/blob/56cf00d97e739fec861717484657dbef2888df60/src/Command/Response/IntResponse.php | src/Command/Response/IntResponse.php | <?php
namespace Disque\Command\Response;
class IntResponse extends BasicTypeResponse implements ResponseInterface
{
/**
* Basic data type for this response
*
* @var int
*/
protected $type = self::TYPE_INT;
/**
* Parse response
*
* @return int Parsed response
*/
public function parse()
{
return (int) $this->body;
}
} | php | MIT | 56cf00d97e739fec861717484657dbef2888df60 | 2026-01-05T05:12:23.969054Z | false |
mariano/disque-php | https://github.com/mariano/disque-php/blob/56cf00d97e739fec861717484657dbef2888df60/src/Command/Response/CursorResponse.php | src/Command/Response/CursorResponse.php | <?php
namespace Disque\Command\Response;
use Disque\Command\Argument\ArrayChecker;
abstract class CursorResponse extends BaseResponse implements ResponseInterface
{
use ArrayChecker;
/**
* Set response body
*
* @param mixed $body Response body
* @return void
* @throws InvalidResponseException
*/
public function setBody($body)
{
if (
!$this->checkFixedArray($body, 2) ||
!is_numeric($body[0]) ||
!is_array($body[1])
) {
throw new InvalidResponseException($this->command, $body);
}
parent::setBody($body);
}
/**
* Parse response
*
* @return array Parsed response. Indexed array with `finished', 'nextCursor`, `queues`
*/
public function parse()
{
$nextCursor = (int) $this->body[0];
return array_merge([
'finished' => (0 === $nextCursor),
'nextCursor' => $nextCursor,
], $this->parseBody((array) $this->body[1]));
}
/**
* Parse main body
*
* @param array $body Body
* @return array Parsed body
*/
abstract protected function parseBody(array $body);
} | php | MIT | 56cf00d97e739fec861717484657dbef2888df60 | 2026-01-05T05:12:23.969054Z | false |
mariano/disque-php | https://github.com/mariano/disque-php/blob/56cf00d97e739fec861717484657dbef2888df60/src/Command/Response/JscanResponse.php | src/Command/Response/JscanResponse.php | <?php
namespace Disque\Command\Response;
class JscanResponse extends CursorResponse implements ResponseInterface
{
/**
* Parse main body
*
* @param array $body Body
* @return array Parsed body
*/
protected function parseBody(array $body)
{
$jobs = [];
if (!empty($body)) {
if (is_string($body[0])) {
foreach ($body as $element) {
$jobs[] = ['id' => $element];
}
} else {
$keyValueResponse = new KeyValueResponse();
$keyValueResponse->setCommand($this->command);
foreach ($body as $element) {
$keyValueResponse->setBody($element);
$jobs[] = $keyValueResponse->parse();
}
}
}
return ['jobs' => $jobs];
}
} | php | MIT | 56cf00d97e739fec861717484657dbef2888df60 | 2026-01-05T05:12:23.969054Z | false |
mariano/disque-php | https://github.com/mariano/disque-php/blob/56cf00d97e739fec861717484657dbef2888df60/src/Command/Response/JobsWithQueueResponse.php | src/Command/Response/JobsWithQueueResponse.php | <?php
namespace Disque\Command\Response;
/**
* Parse a Disque response that contains the queue, job ID and job body
*/
class JobsWithQueueResponse extends JobsResponse implements ResponseInterface
{
const KEY_QUEUE = 'queue';
public function __construct()
{
parent::__construct();
$this->jobDetails = array_merge([self::KEY_QUEUE], $this->jobDetails);
}
}
| php | MIT | 56cf00d97e739fec861717484657dbef2888df60 | 2026-01-05T05:12:23.969054Z | false |
mariano/disque-php | https://github.com/mariano/disque-php/blob/56cf00d97e739fec861717484657dbef2888df60/src/Command/Argument/StringChecker.php | src/Command/Argument/StringChecker.php | <?php
namespace Disque\Command\Argument;
trait StringChecker
{
use ArrayChecker;
/**
* This command, with all its arguments, ready to be sent to Disque
*
* @param array $arguments Arguments
* @param int $numberOfElements Number of elements that must be present in $arguments
* @throws InvalidCommandArgumentException
*/
protected function checkStringArgument(array $arguments, $numberOfElements = 1)
{
if (!$this->checkFixedArray($arguments, $numberOfElements) || !is_string($arguments[0])) {
throw new InvalidCommandArgumentException($this, $arguments);
}
}
/**
* This command, with all its arguments, ready to be sent to Disque
*
* @param array $arguments Arguments
* @throws InvalidCommandArgumentException
*/
protected function checkStringArguments(array $arguments)
{
if (empty($arguments)) {
throw new InvalidCommandArgumentException($this, $arguments);
}
foreach ($arguments as $argument) {
if (!is_string($argument) || $argument === '') {
throw new InvalidCommandArgumentException($this, $arguments);
}
}
}
} | php | MIT | 56cf00d97e739fec861717484657dbef2888df60 | 2026-01-05T05:12:23.969054Z | false |
mariano/disque-php | https://github.com/mariano/disque-php/blob/56cf00d97e739fec861717484657dbef2888df60/src/Command/Argument/ArrayChecker.php | src/Command/Argument/ArrayChecker.php | <?php
namespace Disque\Command\Argument;
trait ArrayChecker
{
/**
* Check that the exact specified $count arguments are defined,
* in a numeric array and that the array is dense, ie. doesn't contain
* any holes in the numeric indexes.
*
* @param mixed $elements Elements (should be an array)
* @param int $count Number of elements expected
* @param bool $atLeast Se to true to check array has at least $count elements
* @return bool Success
*/
protected function checkFixedArray($elements, $count, $atLeast = false)
{
if (
empty($elements) ||
!is_array($elements) ||
(!$atLeast && count($elements) !== $count) ||
($atLeast && count($elements) < $count)
) {
return false;
}
for ($i=0; $i < $count; $i++) {
if (!isset($elements[$i])) {
return false;
}
}
return true;
}
}
| php | MIT | 56cf00d97e739fec861717484657dbef2888df60 | 2026-01-05T05:12:23.969054Z | false |
mariano/disque-php | https://github.com/mariano/disque-php/blob/56cf00d97e739fec861717484657dbef2888df60/src/Command/Argument/InvalidCommandArgumentException.php | src/Command/Argument/InvalidCommandArgumentException.php | <?php
namespace Disque\Command\Argument;
use Disque\Command\CommandInterface;
use Disque\DisqueException;
class InvalidCommandArgumentException extends DisqueException
{
public function __construct(CommandInterface $command, array $arguments)
{
parent::__construct(sprintf("Invalid command arguments. Arguments for command %1s: %2s",
get_class($command),
json_encode($arguments)
));
}
} | php | MIT | 56cf00d97e739fec861717484657dbef2888df60 | 2026-01-05T05:12:23.969054Z | false |
mariano/disque-php | https://github.com/mariano/disque-php/blob/56cf00d97e739fec861717484657dbef2888df60/src/Command/Argument/OptionChecker.php | src/Command/Argument/OptionChecker.php | <?php
namespace Disque\Command\Argument;
use Disque\Command\Argument\InvalidOptionException;
trait OptionChecker
{
/**
* Checks an array so that their keys are ints
*
* @param array $options Options
* @param array $keys Keys to check
* @throw InvalidOptionException
*/
protected function checkOptionsInt(array $options, array $keys)
{
foreach ($keys as $intOption) {
if (isset($options[$intOption]) && !is_int($options[$intOption])) {
throw new InvalidOptionException($this, $options);
}
}
}
/**
* Checks an array so that their keys are strings
*
* @param array $options Options
* @param array $keys Keys to check
* @throw InvalidOptionException
*/
protected function checkOptionsString(array $options, array $keys)
{
foreach ($keys as $intOption) {
if (isset($options[$intOption]) && !is_string($options[$intOption])) {
throw new InvalidOptionException($this, $options);
}
}
}
/**
* Checks an array so that their keys are arrays
*
* @param array $options Options
* @param array $keys Keys to check
* @throw InvalidOptionException
*/
protected function checkOptionsArray(array $options, array $keys)
{
foreach ($keys as $intOption) {
if (isset($options[$intOption]) && !is_array($options[$intOption])) {
throw new InvalidOptionException($this, $options);
}
}
}
} | php | MIT | 56cf00d97e739fec861717484657dbef2888df60 | 2026-01-05T05:12:23.969054Z | false |
mariano/disque-php | https://github.com/mariano/disque-php/blob/56cf00d97e739fec861717484657dbef2888df60/src/Command/Argument/InvalidOptionException.php | src/Command/Argument/InvalidOptionException.php | <?php
namespace Disque\Command\Argument;
use Disque\Command\CommandInterface;
class InvalidOptionException extends InvalidCommandArgumentException
{
public function __construct(CommandInterface $command, array $options)
{
parent::__construct($command, $options);
$this->message = sprintf("Invalid command options. Options for command %1s: %2s",
get_class($command),
json_encode($options)
);
}
} | php | MIT | 56cf00d97e739fec861717484657dbef2888df60 | 2026-01-05T05:12:23.969054Z | false |
mariano/disque-php | https://github.com/mariano/disque-php/blob/56cf00d97e739fec861717484657dbef2888df60/tests/ClientTest.php | tests/ClientTest.php | <?php
namespace Disque\Test;
use DateTime;
use InvalidArgumentException;
use Mockery as m;
use PHPUnit_Framework_TestCase;
use Disque\Client;
use Disque\Command;
use Disque\Command\CommandInterface;
use Disque\Command\InvalidCommandException;
use Disque\Connection\ManagerInterface;
use Disque\Connection\ConnectionException;
use Disque\Connection\Credentials;
use Disque\Queue\Queue;
class MockClient extends Client
{
public function getCommandHandlers()
{
return $this->commandHandlers;
}
public function setConnectionManager(ManagerInterface $manager)
{
$this->connectionManager = $manager;
}
}
class ClientTest extends PHPUnit_Framework_TestCase
{
public function tearDown()
{
parent::tearDown();
m::close();
}
public function testInstance()
{
$c = new Client();
$this->assertInstanceOf(Client::class, $c);
}
public function testConstruct()
{
$c = new MockClient();
$this->assertSame([], $c->getConnectionManager()->getCredentials());
}
public function testConstructNoServers()
{
$c = new MockClient([]);
$this->assertSame([], $c->getConnectionManager()->getCredentials());
}
public function testConstructMultipleServers()
{
$nodes = [
new Credentials('127.0.0.1', '7711'),
new Credentials('127.0.0.1', '7712'),
];
$c = new Client($nodes);
$this->assertEquals(
$nodes,
array_values($c->getConnectionManager()->getCredentials()));
}
public function testCommandsRegistered()
{
$expectedCommands = [
new Command\AckJob(),
new Command\AddJob(),
new Command\DelJob(),
new Command\Dequeue(),
new Command\Enqueue(),
new Command\FastAck(),
new Command\GetJob(),
new Command\Hello(),
new Command\Info(),
new Command\Jscan(),
new Command\Nack(),
new Command\Pause(),
new Command\QLen(),
new Command\QPeek(),
new Command\QScan(),
new Command\QStat(),
new Command\Show(),
new Command\Working()
];
$c = new MockClient();
$commands = $c->getCommandHandlers();
$this->assertCount(count($commands), $expectedCommands);
foreach ($commands as $command) {
$strictComparison = false;
$commandFound = in_array($command, $expectedCommands, $strictComparison);
$this->assertTrue($commandFound);
}
}
public function testCallCommandInvalid()
{
$this->setExpectedException(InvalidCommandException::class, 'Invalid command WRONGCOMMAND');
$c = new Client();
$c->WrongCommand();
}
public function testCallCommandInvalidCaseInsensitive()
{
$this->setExpectedException(InvalidCommandException::class, 'Invalid command WRONGCOMMAND');
$c = new Client();
$c->wrongcommand();
}
public function testCallCommandInvalidNoServers()
{
$this->setExpectedException(ConnectionException::class, 'Not connected');
$c = new Client([]);
$c->hello();
}
public function testConnectCallsManagerConnect()
{
$manager = m::mock(ManagerInterface::class)
->shouldReceive('setOptions')
->with([])
->shouldReceive('connect')
->with()
->andReturn(['test' => 'stuff'])
->once()
->mock();
$c = new MockClient();
$c->setConnectionManager($manager);
$result = $c->connect();
$this->assertSame(['test' => 'stuff'], $result);
}
public function testConnectWithOptionsCallsManager()
{
$manager = m::mock(ManagerInterface::class)
->shouldReceive('setOptions')
->with(['test' => 'stuff'])
->shouldReceive('connect')
->with()
->once()
->mock();
$c = new MockClient();
$c->setConnectionManager($manager);
$c->connect(['test' => 'stuff']);
}
public function testIsConnectedCallsManager()
{
$manager = m::mock(ManagerInterface::class)
->shouldReceive('isConnected')
->with()
->andReturn(true)
->once()
->mock();
$c = new MockClient();
$c->setConnectionManager($manager);
$result = $c->isConnected();
$this->assertTrue($result);
}
public function testCallCommandCustom()
{
$commandName = 'MYCOMMAND';
$commandArgument = 'id';
$commandResponse = 'RESPONSE';
$parsedResponse = 'PARSED RESPONSE';
$command = m::mock(CommandInterface::class)
->shouldReceive('getCommand')
->andReturn($commandName)
->zeroOrMoreTimes()
->shouldReceive('setArguments')
->with([$commandArgument])
->once()
->shouldReceive('parse')
->with($commandResponse)
->andReturn($parsedResponse)
->once()
->mock();
$manager = m::mock(ManagerInterface::class)
->shouldReceive('execute')
->with($command)
->andReturn($commandResponse)
->once()
->mock();
$c = new MockClient();
$c->setConnectionManager($manager);
$c->registerCommand($command);
$result = $c->$commandName($commandArgument);
$this->assertSame($parsedResponse, $result);
}
public function testQueue()
{
$c = new Client();
$queue = $c->queue('queue');
$this->assertInstanceOf(Queue::class, $queue);
}
public function testQueueDifferent()
{
$c = new Client();
$queue = $c->queue('queue');
$this->assertInstanceOf(Queue::class, $queue);
$queue2 = $c->queue('queue2');
$this->assertInstanceOf(Queue::class, $queue);
$this->assertNotSame($queue, $queue2);
}
public function testQueueSame()
{
$c = new Client();
$queue = $c->queue('queue');
$this->assertInstanceOf(Queue::class, $queue);
$queue2 = $c->queue('queue');
$this->assertInstanceOf(Queue::class, $queue);
$this->assertSame($queue, $queue2);
}
} | php | MIT | 56cf00d97e739fec861717484657dbef2888df60 | 2026-01-05T05:12:23.969054Z | false |
mariano/disque-php | https://github.com/mariano/disque-php/blob/56cf00d97e739fec861717484657dbef2888df60/tests/Connection/SocketTest.php | tests/Connection/SocketTest.php | <?php
namespace Disque\Test\Connection;
use Mockery as m;
use PHPUnit_Framework_TestCase;
use Disque\Command;
use Disque\Connection\ConnectionException;
use Disque\Connection\ConnectionInterface;
use Disque\Connection\Response\QueuePausedResponseException;
use Disque\Connection\Response\ResponseException;
use Disque\Connection\Response\TextResponse;
use Disque\Connection\Socket;
class MockSocket extends Socket
{
public function setSocket($socket)
{
$this->socket = $socket;
$this->host = 'localhost';
$this->port = 7711;
}
/**
* Build actual socket
*
* @param string $host Host
* @param int $port Port
* @param float $timeout Timeout
* @return resource Socket
*/
protected function getSocket($host, $port, $timeout)
{
return $this->socket;
}
}
class SocketTest extends PHPUnit_Framework_TestCase
{
public function tearDown()
{
parent::tearDown();
m::close();
}
public function testInstance()
{
$c = new Socket();
$this->assertInstanceOf(ConnectionInterface::class, $c);
}
public function testConnectNoHost()
{
$this->setExpectedException(ConnectionException::class, 'Invalid host or port specified');
$connection = new Socket();
$connection->setHost(null);
$connection->connect();
}
public function testConnectWrongHost()
{
$this->setExpectedException(ConnectionException::class, 'Invalid host or port specified');
$connection = new Socket();
$connection->setHost(128);
$connection->connect();
}
public function testConnectNoPort()
{
$this->setExpectedException(ConnectionException::class, 'Invalid host or port specified');
$connection = new Socket();
$connection->setPort(null);
$connection->connect();
}
public function testConnectWrongPort()
{
$this->setExpectedException(ConnectionException::class, 'Invalid host or port specified');
$connection = new Socket();
$connection->setPort('port');
$connection->connect();
}
public function testIsConnectedFalse()
{
$connection = new Socket();
$this->assertFalse($connection->isConnected());
}
public function testIsConnectedTrue()
{
$socket = fopen('php://memory','rw');
$connection = new MockSocket();
$connection->setSocket($socket);
$this->assertTrue($connection->isConnected());
}
public function testDisconnectNotConnected()
{
$connection = new Socket();
$this->assertFalse($connection->isConnected());
$connection->disconnect();
$this->assertFalse($connection->isConnected());
}
public function testDisconnectConnected()
{
$socket = fopen('php://memory','rw');
$connection = new MockSocket();
$connection->setSocket($socket);
$this->assertTrue($connection->isConnected());
$connection->disconnect();
$this->assertFalse($connection->isConnected());
}
public function testConnectNoSocket()
{
$this->setExpectedException(ConnectionException::class, 'Could not connect to localhost:7711');
$connection = new MockSocket();
$connection->setSocket(null);
$connection->connect();
}
public function testConnectStreamTimeout()
{
$socket = fopen('php://memory','rw');
$connection = new MockSocket();
$connection->setSocket($socket);
$connection->connect(['streamTimeout' => 3000]);
}
public function testSendErrorNoConnection()
{
$this->setExpectedException(ConnectionException::class, 'No connection established');
$connection = new MockSocket();
$connection->send("stuff");
}
public function testSend()
{
$socket = fopen('php://memory','rw');
$connection = new MockSocket();
$connection->setSocket($socket);
rewind($socket);
$data = fgets($socket);
$this->assertFalse($data);
$connection->send('HELLO');
rewind($socket);
$data = fgets($socket);
$this->assertSame('HELLO', $data);
}
public function testReceiveErrorFromClient()
{
$this->setExpectedException(ResponseException::class, 'Error from Disque');
$socket = fopen('php://memory','rw');
fwrite($socket, "-Error from Disque\r\n");
rewind($socket);
$connection = new MockSocket();
$connection->setSocket($socket);
$connection->receive();
}
public function testReceiveErrorPauseFromClient()
{
$this->setExpectedException(QueuePausedResponseException::class, 'PAUSED Queue paused in input, try later');
$socket = fopen('php://memory','rw');
fwrite($socket, "-PAUSED Queue paused in input, try later\r\n");
rewind($socket);
$connection = new MockSocket();
$connection->setSocket($socket);
$connection->receive();
}
public function testReceiveErrorNoConnection()
{
$this->setExpectedException(ConnectionException::class, 'No connection established');
$connection = new MockSocket();
$connection->receive();
}
public function testReceiveErrorNoType()
{
$this->setExpectedException(ConnectionException::class, 'Nothing received while reading from client');
$socket = fopen('php://memory','rw');
$connection = new MockSocket();
$connection->setSocket($socket);
$connection->receive();
}
public function testReceiveErrorInvalidType()
{
$this->setExpectedException(ConnectionException::class, 'Don\'t know how to handle a response of type A');
$socket = fopen('php://memory','rw');
fwrite($socket, "A\r\n");
rewind($socket);
$connection = new MockSocket();
$connection->setSocket($socket);
$connection->receive();
}
public function testReceiveErrorNoData()
{
$this->setExpectedException(ConnectionException::class, 'Nothing received while reading from client');
$socket = fopen('php://memory','rw');
fwrite($socket, "+");
rewind($socket);
$connection = new MockSocket();
$connection->setSocket($socket);
$connection->receive();
}
public function testReceiveErrorEmptyString()
{
$this->setExpectedException(ConnectionException::class, 'Error while reading buffered string from client');
$socket = fopen('php://memory','rw');
fwrite($socket, "$0\r\n");
rewind($socket);
$connection = new MockSocket();
$connection->setSocket($socket);
$connection->receive();
}
/**
* @dataProvider dataProviderForTestReceive
*/
public function testReceive($data, $parsed)
{
$socket = fopen('php://memory','rw');
fwrite($socket, "$data\r\n");
rewind($socket);
$connection = new MockSocket();
$connection->setSocket($socket);
$this->assertEquals($parsed, $connection->receive());
}
public static function dataProviderForTestReceive()
{
$longString = str_repeat('ABC', TextResponse::READ_BUFFER_LENGTH * 10);
return [
[
'data' => '+',
'parsed' => ''
],
[
'data' => '+PONG',
'parsed' => 'PONG'
],
[
'data' => '+' . $longString,
'parsed' => $longString
],
[
'data' => ':128',
'parsed' => 128
],
[
'data' => ':3.14',
'parsed' => 3
],
[
'data' => ':-128',
'parsed' => -128
],
[
'data' => ':0',
'parsed' => 0
],
[
'data' => ':',
'parsed' => 0
],
[
'data' => '$-1',
'parsed' => null
],
[
'data' => '$'.implode("\r\n", [
strlen('hello'),
'hello'
]),
'parsed' => 'hello'
],
[
'data' => '$'.implode("\r\n", [
strlen("hello\nworld"),
"hello\nworld"
]),
'parsed' => "hello\nworld"
],
[
'data' => '$'.implode("\r\n", [
strlen($longString),
$longString
]),
'parsed' => $longString
],
[
'data' => '$'.implode("\r\n", [
strlen("{$longString}\r\n{$longString}\n{$longString}"),
"{$longString}\r\n{$longString}\n{$longString}"
]),
'parsed' => "{$longString}\r\n{$longString}\n{$longString}"
],
[
'data' => '*-1',
'parsed' => null
],
[
'data' => '*0',
'parsed' => []
],
[
'data' => "*1\r\n" . implode("\r\n", [
'+pong'
]),
'parsed' => [
'pong'
]
],
[
'data' => "*2\r\n" . implode("\r\n", [
'+hello',
'+world'
]),
'parsed' => [
'hello',
'world'
]
],
[
'data' => "*3\r\n" . implode("\r\n", [
'+hello',
'+world',
':128'
]),
'parsed' => [
'hello',
'world',
128
]
],
[
'data' => "*4\r\n" . implode("\r\n", [
'+hello',
'+world',
'*-1',
':128'
]),
'parsed' => [
'hello',
'world',
null,
128
]
],
[
'data' => "*4\r\n" . implode("\r\n", [
'+hello',
'+world',
"*3\r\n" . implode("\r\n", [
'$'.implode("\r\n", [
strlen($longString),
$longString
]),
':5',
'+BYE'
]),
':128'
]),
'parsed' => [
'hello',
'world',
[
$longString,
5,
'BYE'
],
128
]
],
];
}
public function testExecuteAck()
{
$command = new Command\AckJob();
$command->setArguments(['id']);
$connection = m::mock(MockSocket::class)
->makePartial()
->shouldReceive('send')
->with("*2\r\n$6\r\nACKJOB\r\n$2\r\nid\r\n")
->once()
->shouldReceive('receive')
->andReturn(['result' => true])
->once()
->mock();
$connection->setSocket(fopen('php://memory','rw'));
$result = $connection->execute($command);
$this->assertSame(['result' => true], $result);
}
public function testExecuteAddUnicode()
{
$command = new Command\AddJob();
$command->setArguments(['queue', '大']);
$connection = m::mock(MockSocket::class)
->makePartial()
->shouldReceive('send')
->with(implode("\r\n", [
'*4',
'$6',
'ADDJOB',
'$5',
'queue',
'$' . strlen('大'),
'大',
'$1',
'0'
]) . "\r\n")
->once()
->shouldReceive('receive')
->andReturn(['result' => true])
->once()
->mock();
$connection->setSocket(fopen('php://memory','rw'));
$result = $connection->execute($command);
$this->assertSame(['result' => true], $result);
}
public function testExecuteHello()
{
$command = new Command\Hello();
$connection = m::mock(MockSocket::class)
->makePartial()
->shouldReceive('send')
->with("*1\r\n$5\r\nHELLO\r\n")
->once()
->shouldReceive('receive')
->andReturn(['result' => true])
->once()
->mock();
$connection->setSocket(fopen('php://memory','rw'));
$result = $connection->execute($command);
$this->assertSame(['result' => true], $result);
}
} | php | MIT | 56cf00d97e739fec861717484657dbef2888df60 | 2026-01-05T05:12:23.969054Z | false |
mariano/disque-php | https://github.com/mariano/disque-php/blob/56cf00d97e739fec861717484657dbef2888df60/tests/Connection/ManagerTest.php | tests/Connection/ManagerTest.php | <?php
namespace Disque\Test\Connection;
use Closure;
use DateTime;
use Disque\Command\Response\HelloResponse;
use Disque\Connection\Factory\ConnectionFactoryInterface;
use Disque\Connection\Factory\SocketFactory;
use Disque\Connection\Node\ConservativeJobCountPrioritizer;
use Disque\Connection\Node\NodePrioritizerInterface;
use InvalidArgumentException;
use Metadata\Tests\Driver\Fixture\C\SubDir\C;
use Mockery as m;
use PHPUnit_Framework_TestCase;
use Disque\Command\Auth;
use Disque\Command\CommandInterface;
use Disque\Command\GetJob;
use Disque\Command\Hello;
use Disque\Connection\AuthenticationException;
use Disque\Connection\BaseConnection;
use Disque\Connection\ConnectionException;
use Disque\Connection\ConnectionInterface;
use Disque\Connection\Manager;
use Disque\Connection\Response\ResponseException;
use Disque\Connection\Socket;
use Disque\Connection\Credentials;
class ManagerTest extends PHPUnit_Framework_TestCase
{
public function tearDown()
{
parent::tearDown();
m::close();
}
public function testAddServer()
{
$m = new Manager();
$s = new Credentials('127.0.0.1', 7712);
$m->addServer($s);
$this->assertEquals([$s], array_values($m->getCredentials()));
}
public function testAddServers()
{
$m = new Manager();
$s1 = new Credentials('127.0.0.1', 7711, 'my_password1');
$m->addServer($s1);
$s2 = new Credentials('127.0.0.1', 7712);
$m->addServer($s2);
$s3 = new Credentials('127.0.0.1', 7713, 'my_password3');
$m->addServer($s3);
$this->assertEquals([$s1, $s2, $s3], array_values($m->getCredentials()));
}
public function testDefaultConnectionFactory()
{
$m = new Manager();
$this->assertSame(SocketFactory::class, get_class($m->getConnectionFactory()));
}
public function testSetConnectionFactory()
{
$connectionFactory = m::mock(ConnectionFactoryInterface::class);
$m = new Manager();
$m->setConnectionFactory($connectionFactory);
$this->assertSame($connectionFactory, $m->getConnectionFactory());
}
public function testSetPriorityStrategy()
{
$priorityStrategy = m::mock(NodePrioritizerInterface::class);
$m = new Manager();
$m->setPriorityStrategy($priorityStrategy);
$this->assertSame($priorityStrategy, $m->getPriorityStrategy());
}
public function testConnectInvalidNoConnection()
{
$this->setExpectedException(ConnectionException::class, 'No servers available');
$m = new Manager();
$m->connect();
}
public function testConnect()
{
$m = new Manager();
$serverAddress = '127.0.0.1';
$serverPort = 7712;
$nodeId = 'id1';
$version = 'v1';
$priority = 10;
$server = new Credentials($serverAddress, $serverPort);
$m->addServer($server);
$helloResponse = [
HelloResponse::POS_VERSION => $version,
HelloResponse::POS_ID => $nodeId,
HelloResponse::POS_NODES_START => [
HelloResponse::POS_NODE_ID => $nodeId,
HelloResponse::POS_NODE_HOST => $serverAddress,
HelloResponse::POS_NODE_PORT => $serverPort,
HelloResponse::POS_NODE_PRIORITY => $priority
]
];
$connection = m::mock(ConnectionInterface::class)
->shouldReceive('isConnected')
->times(2)
->andReturn(false, true)
->shouldReceive('connect')
->once()
->shouldReceive('execute')
->andReturn($helloResponse)
->getMock();
$connectionFactory = m::mock(ConnectionFactoryInterface::class)
->shouldReceive('create')
->with($serverAddress, $serverPort)
->andReturn($connection)
->once()
->getMock();
$m->setConnectionFactory($connectionFactory);
$node = $m->connect();
$this->assertSame($connection, $node->getConnection());
$this->assertSame($nodeId, $node->getId());
$this->assertSame($priority, $node->getPriority());
$this->assertSame($server, $node->getCredentials());
}
public function testConnectWithPasswordMissingPassword()
{
$m = new Manager();
$m->addServer(new Credentials('127.0.0.1', 7711));
$connection = m::mock(ConnectionInterface::class)
->shouldReceive('connect')
->with(null, null)
->once()
->shouldReceive('execute')
->with(m::type(Hello::class))
->andThrow(new AuthenticationException('NOAUTH Authentication Required'))
->once()
->shouldReceive('isConnected')
->once()
->andReturn(false)
->mock();
$connectionFactory = m::mock(ConnectionFactoryInterface::class)
->shouldReceive('create')
->once()
->andReturn($connection)
->getMock();
$m->setConnectionFactory($connectionFactory);
$this->setExpectedException(ConnectionException::class, 'No servers available');
$m->connect();
}
public function testConnectWithPasswordWrongPassword()
{
$m = new Manager();
$m->addServer(new Credentials('127.0.0.1', 7711, 'wrong_password'));
$connection = m::mock(ConnectionInterface::class)
->shouldReceive('isConnected')
->once()
->andReturn(false)
->shouldReceive('connect')
->with(null, null)
->once()
->shouldReceive('execute')
->with(m::type(Auth::class))
->andThrow(new ResponseException('ERR invalid password'))
->once()
->mock();
$connectionFactory = m::mock(ConnectionFactoryInterface::class)
->shouldReceive('create')
->once()
->andReturn($connection)
->getMock();
$m->setConnectionFactory($connectionFactory);
$this->setExpectedException(ConnectionException::class, 'No servers available');
$m->connect();
}
public function testConnectWithPasswordWrongResponse()
{
$m = new Manager();
$m->addServer(new Credentials('127.0.0.1', 7711, 'right_password'));
$connection = m::mock(ConnectionInterface::class)
->shouldReceive('isConnected')
->once()
->andReturn(false)
->shouldReceive('connect')
->with(null, null)
->once()
->shouldReceive('execute')
->with(m::type(Auth::class))
->andReturn('WHATEVER')
->once()
->mock();
$connectionFactory = m::mock(ConnectionFactoryInterface::class)
->shouldReceive('create')
->once()
->andReturn($connection)
->getMock();
$m->setConnectionFactory($connectionFactory);
$this->setExpectedException(ConnectionException::class, 'No servers available');
$m->connect();
}
public function testConnectWithPasswordRightPassword()
{
$address = '127.0.0.1';
$port = 7711;
$port2 = 7712;
$nodeId1 = 'id1';
$nodeId2 = 'id2';
$version = 'v1';
$m = new Manager();
$m->addServer(new Credentials($address, $port, 'right_password'));
$helloResponse = [
$version,
$nodeId1,
[$nodeId1, $address, $port, $version],
[$nodeId2, $address, $port2, $version]
];
$connection = m::mock(ConnectionInterface::class)
->shouldReceive('isConnected')
->times(2)
->andReturn(false, true)
->shouldReceive('connect')
->with(null, null)
->once()
->shouldReceive('execute')
->with(m::type(Auth::class))
->andReturn('OK')
->once()
->shouldReceive('execute')
->with(m::type(Hello::class))
->andReturn($helloResponse)
->mock();
$connection2 = m::mock(ConnectionInterface::class);
$connectionFactory = m::mock(ConnectionFactoryInterface::class)
->shouldReceive('create')
->times(2)
->andReturn($connection, $connection2)
->getMock();
$m->setConnectionFactory($connectionFactory);
$m->connect();
}
public function testFindAvailableConnectionNoneSpecifiedConnectThrowsException()
{
$m = new Manager();
$this->setExpectedException(ConnectionException::class, 'No servers available');
$m->connect();
}
public function testFindAvailableConnectionNoneAvailableConnectThrowsException()
{
$m = new Manager();
$m->addServer(new Credentials('127.0.0.1', 7711));
$connection = m::mock(ConnectionInterface::class)
->shouldReceive('isConnected')
->once()
->andReturn(false)
->shouldReceive('connect')
->andThrow(new ConnectionException('Mocking ConnectionException'))
->once()
->mock();
$connectionFactory = m::mock(ConnectionFactoryInterface::class)
->shouldReceive('create')
->once()
->andReturn($connection)
->getMock();
$m->setConnectionFactory($connectionFactory);
$this->setExpectedException(ConnectionException::class, 'No servers available');
$m->connect();
}
public function testFindAvailableConnectionSucceedsFirst()
{
$serverAddress = '127.0.0.1';
$serverPort = 7712;
$server = new Credentials($serverAddress, $serverPort);
$m = new Manager();
$m->addServer($server);
$nodeId = 'id1';
$version = 'v1';
$priority = 2;
$helloResponse = [
HelloResponse::POS_VERSION => $version,
HelloResponse::POS_ID => $nodeId,
HelloResponse::POS_NODES_START => [
HelloResponse::POS_NODE_ID => $nodeId,
HelloResponse::POS_NODE_HOST => $serverAddress,
HelloResponse::POS_NODE_PORT => $serverPort,
HelloResponse::POS_NODE_PRIORITY => $priority
]
];
$connection = m::mock(ConnectionInterface::class)
->shouldReceive('isConnected')
->times(2)
->andReturn(false, true)
->shouldReceive('connect')
->with(null, null)
->once()
->shouldReceive('execute')
->with(m::type(Hello::class))
->andReturn($helloResponse)
->once()
->mock();
$connectionFactory = m::mock(ConnectionFactoryInterface::class)
->shouldReceive('create')
->once()
->andReturn($connection)
->getMock();
$m->setConnectionFactory($connectionFactory);
$node = $m->connect();
$this->assertSame($connection, $node->getConnection());
$this->assertSame($nodeId, $node->getId());
$this->assertSame($priority, $node->getPriority());
$this->assertSame($server, $node->getCredentials());
}
public function testFindAvailableConnectionSucceedsSecond()
{
$serverAddress = '127.0.0.1';
$serverPort1 = 7711;
$serverPort2 = 7712;
$server1 = new Credentials($serverAddress, $serverPort1);
$server2 = new Credentials($serverAddress, $serverPort2);
$m = new Manager();
$m->addServer($server1);
$m->addServer($server2);
$nodeId = 'id1';
$version = 'v1';
$priority = 5;
$connection = m::mock(ConnectionInterface::class)
->shouldReceive('isConnected')
->times(3)
->andReturn(false, false, true)
->shouldReceive('connect')
->andThrow(new ConnectionException('Mocking ConnectionException'))
->once()
->shouldReceive('connect')
->once()
->shouldReceive('execute')
->with(m::type(Hello::class))
->andReturn([$version, $nodeId, [$nodeId, $serverAddress, $serverPort2, $priority]])
->once()
->mock();
$connectionFactory = m::mock(ConnectionFactoryInterface::class)
->shouldReceive('create')
->times(2)
->andReturn($connection)
->getMock();
$m->setConnectionFactory($connectionFactory);
$node = $m->connect();
$this->assertSame($connection, $node->getConnection());
$this->assertSame($nodeId, $node->getId());
$this->assertSame($priority, $node->getPriority());
$this->assertContains($node->getCredentials(), [$server1, $server2]);
}
public function testCustomConnection()
{
$connection = m::mock(ConnectionInterface::class)
->shouldReceive('isConnected')
->andThrow(ConnectionException::class)
->getMock();
$connectionFactory = m::mock(ConnectionFactoryInterface::class)
->shouldReceive('create')
->andReturn($connection)
->getMock();
$m = new Manager();
$m->addServer(new Credentials('host', 7799));
$m->setConnectionFactory($connectionFactory);
$this->setExpectedException(ConnectionException::class, 'No servers available');
$m->connect();
}
public function testExecuteNotConnected()
{
$m = new Manager();
$this->setExpectedException(ConnectionException::class, 'Not connected');
$m->execute(new Hello());
}
public function testExecuteCallsConnectionExecute()
{
$m = new Manager();
$serverAddress = '127.0.0.1';
$serverPort = 7712;
$nodeId = 'id1';
$version = 'v1';
$server = new Credentials($serverAddress, $serverPort);
$m->addServer($server);
$helloResponse = [
HelloResponse::POS_VERSION => $version,
HelloResponse::POS_ID => $nodeId,
HelloResponse::POS_NODES_START => [
HelloResponse::POS_NODE_ID => $nodeId,
HelloResponse::POS_NODE_HOST => $serverAddress,
HelloResponse::POS_NODE_PORT => $serverPort,
HelloResponse::POS_NODE_PRIORITY => $version
]
];
$expectedResponse = ['test' => 'stuff'];
$connection = m::mock(ConnectionInterface::class)
->shouldReceive('isConnected')
->times(3)
->andReturn(false, true, true)
->shouldReceive('connect')
->once()
->shouldReceive('execute')
->andReturn($helloResponse)
->once()
->shouldReceive('execute')
->andReturn($expectedResponse)
->getMock();
$connectionFactory = m::mock(ConnectionFactoryInterface::class)
->shouldReceive('create')
->with($serverAddress, $serverPort)
->andReturn($connection)
->once()
->getMock();
$m->setConnectionFactory($connectionFactory);
$m->connect();
$result = $m->execute(new Hello());
$this->assertSame($expectedResponse, $result);
}
public function testGetJobSwitchesNode()
{
$node1 = '0f0c644fd3ccb51c2cedbd47fcb6f312646c993c05a0SQ';
$node2 = '0f0c645fd3ccb51c2cedbd47fcb6f312646c993c05a0SQ';
$jobId1 = 'D-' . $node1;
$jobId2 = 'D-' . $node2;
$jobId3 = 'D-' . $node2;
$this->assertNotSame($node1, $node2);
$connection1 = m::mock(ConnectionInterface::class)
->shouldReceive('isConnected')
->once()
->andReturn(false)
->shouldReceive('connect')
->once()
->shouldReceive('isConnected')
->andReturn(true)
->shouldReceive('execute')
->with(m::type(Hello::class))
->andReturn([
'v1',
$node1,
[$node1, '127.0.0.1', 7711, 'v1'],
[$node2, '127.0.0.1', 7712, 'v1']
])
->once()
->shouldReceive('execute')
->with(m::type(GetJob::class))
->andReturn([
['q', $jobId1, 'body1']
])
->once()
->shouldReceive('execute')
->with(m::type(GetJob::class))
->andReturn([
['q2', $jobId2, 'body2'],
])
->once()
->shouldReceive('execute')
->with(m::type(GetJob::class))
->andReturn([
['q', $jobId3, 'body3']
])
->mock();
$connection2 = m::mock(ConnectionInterface::class)
->shouldReceive('isConnected')
->once()
->andReturn(false)
->shouldReceive('connect')
->once()
->shouldReceive('isConnected')
->andReturn(true)
->shouldReceive('execute')
->with(m::type(Hello::class))
->andReturn([
'v1',
$node2,
[$node2, '127.0.0.1', 7712, 'v1'],
[$node1, '127.0.0.1', 7711, 'v1']
])
->mock();
$connectionFactory = m::mock(ConnectionFactoryInterface::class)
->shouldReceive('create')
->once()
->andReturn($connection1)
->shouldReceive('create')
->andReturn($connection2)
->once()
->mock();
$priorityStrategy = new ConservativeJobCountPrioritizer();
$priorityStrategy->setMarginToSwitch(0.001);
$command = new GetJob();
$command->setArguments(['q', 'q2']);
$m = new Manager();
$m->setConnectionFactory($connectionFactory);
$m->setPriorityStrategy($priorityStrategy);
$m->addServer(new Credentials('127.0.0.1', 7711));
$m->connect();
$this->assertSame($node1, $m->getCurrentNode()->getId());
$m->execute($command);
$this->assertSame($node1, $m->getCurrentNode()->getId());
$m->execute($command);
$this->assertSame($node1, $m->getCurrentNode()->getId());
$m->execute($command);
$this->assertSame($node2, $m->getCurrentNode()->getId());
}
public function testGetJobNodeNotInList()
{
$node1 = '0f0c644fd3ccb51c2cedbd47fcb6f312646c993c05a0SQ';
$node2 = '0f0c645fd3ccb51c2cedbd47fcb6f312646c993c05a0SQ';
$jobId1 = 'D-' . $node1;
$jobId2 = 'D-' . $node2;
$jobId3 = 'D-' . $node2;
$this->assertNotSame($node1, $node2);
$connection = m::mock(ConnectionInterface::class)
->shouldReceive('isConnected')
->once()
->andReturn(false)
->shouldReceive('connect')
->once()
->shouldReceive('isConnected')
->andReturn(true)
->shouldReceive('execute')
->with(m::type(Hello::class))
->andReturn([
'v1',
$node1,
[$node1, '127.0.0.1', 7711, 'v1']
])
->once()
->shouldReceive('execute')
->with(m::type(GetJob::class))
->andReturn([
['q', $jobId1, 'body1']
])
->once()
->shouldReceive('execute')
->with(m::type(GetJob::class))
->andReturn([
['q2', $jobId2, 'body2'],
])
->once()
->shouldReceive('execute')
->with(m::type(GetJob::class))
->andReturn([
['q', $jobId3, 'body3']
])
->mock();
$connectionFactory = m::mock(ConnectionFactoryInterface::class)
->shouldReceive('create')
->once()
->andReturn($connection)
->mock();
$priorityStrategy = new ConservativeJobCountPrioritizer();
$priorityStrategy->setMarginToSwitch(0.001);
$command = new GetJob();
$command->setArguments(['q', 'q2']);
$m = new Manager();
$m->setConnectionFactory($connectionFactory);
$m->setPriorityStrategy($priorityStrategy);
$m->addServer(new Credentials('127.0.0.1', 7711));
$m->connect();
$this->assertSame($node1, $m->getCurrentNode()->getId());
$m->execute($command);
$this->assertSame($node1, $m->getCurrentNode()->getId());
$m->execute($command);
$this->assertSame($node1, $m->getCurrentNode()->getId());
$m->execute($command);
$this->assertSame($node1, $m->getCurrentNode()->getId());
}
public function testGetJobSameNode()
{
$node1 = '0f0c644fd3ccb51c2cedbd47fcb6f312646c993c05a0SQ';
$node2 = '0f0c645fd3ccb51c2cedbd47fcb6f312646c993c05a0SQ';
$jobId1 = 'D-' . $node1;
$jobId2 = 'D-' . $node2;
$jobId3 = 'D-' . $node1;
$this->assertNotSame($node1, $node2);
$connection1 = m::mock(ConnectionInterface::class)
->shouldReceive('isConnected')
->once()
->andReturn(false)
->shouldReceive('connect')
->once()
->shouldReceive('isConnected')
->andReturn(true)
->shouldReceive('execute')
->with(m::type(Hello::class))
->andReturn([
'v1',
$node1,
[$node1, '127.0.0.1', 7711, '1'],
[$node2, '127.0.0.1', 7712, '1']
])
->once()
->shouldReceive('execute')
->with(m::type(GetJob::class))
->andReturn([
['q', $jobId1, 'body1']
])
->once()
->shouldReceive('execute')
->with(m::type(GetJob::class))
->andReturn([
['q2', $jobId2, 'body2'],
])
->once()
->shouldReceive('execute')
->with(m::type(GetJob::class))
->andReturn([
['q', $jobId3, 'body3']
])
->mock();
$connection2 = m::mock(ConnectionInterface::class)
->shouldReceive('isConnected')
->andReturn(false)
->mock();
$connectionFactory = m::mock(ConnectionFactoryInterface::class)
->shouldReceive('create')
->once()
->andReturn($connection1)
->shouldReceive('create')
->andReturn($connection2)
->once()
->mock();
$priorityStrategy = new ConservativeJobCountPrioritizer();
$priorityStrategy->setMarginToSwitch(0.001);
$command = new GetJob();
$command->setArguments(['q', 'q2']);
$m = new Manager();
$m->setConnectionFactory($connectionFactory);
$m->setPriorityStrategy($priorityStrategy);
$m->addServer(new Credentials('127.0.0.1', 7711));
$m->connect();
$this->assertSame($node1, $m->getCurrentNode()->getId());
$m->execute($command);
$this->assertSame($node1, $m->getCurrentNode()->getId());
$m->execute($command);
$this->assertSame($node1, $m->getCurrentNode()->getId());
$m->execute($command);
$this->assertSame($node1, $m->getCurrentNode()->getId());
return;
}
public function testGetJobChangeNodeCantConnect()
{
$node1 = '0f0c644fd3ccb51c2cedbd47fcb6f312646c993c05a0SQ';
$node2 = '0f0c645fd3ccb51c2cedbd47fcb6f312646c993c05a0SQ';
$jobId1 = 'D-' . $node1;
$jobId2 = 'D-' . $node2;
$jobId3 = 'D-' . $node2;
$this->assertNotSame($node1, $node2);
$connection1 = m::namedMock('goodConnection', ConnectionInterface::class)
->shouldReceive('isConnected')
->once()
->andReturn(false)
->shouldReceive('connect')
->once()
->shouldReceive('isConnected')
->andReturn(true)
->shouldReceive('execute')
->with(m::type(Hello::class))
->andReturn([
'v1',
$node1,
[$node1, '127.0.0.1', 7711, '1'],
[$node2, '127.0.0.1', 7712, '1']
])
->once()
->shouldReceive('execute')
->with(m::type(GetJob::class))
->andReturn([
['q', $jobId1, 'body1']
])
->once()
->shouldReceive('execute')
->with(m::type(GetJob::class))
->andReturn([
['q2', $jobId2, 'body2'],
])
->once()
->shouldReceive('execute')
->with(m::type(GetJob::class))
->andReturn([
['q', $jobId3, 'body3']
])
->mock();
$connection2 = m::namedMock('badConnection', ConnectionInterface::class)
->shouldReceive('isConnected')
->andReturn(false)
->shouldReceive('connect')
->once()
->andThrow(new ConnectionException('Mocking ConnectionException'))
->mock();
$connectionFactory = m::mock(ConnectionFactoryInterface::class)
->shouldReceive('create')
->with(anything(), 7711)
->once()
->andReturn($connection1)
->shouldReceive('create')
->with(anything(), 7712)
->once()
->andReturn($connection2)
->mock();
$priorityStrategy = new ConservativeJobCountPrioritizer();
$priorityStrategy->setMarginToSwitch(0.001);
$command = new GetJob();
$command->setArguments(['q', 'q2']);
$m = new Manager();
$m->setConnectionFactory($connectionFactory);
$m->setPriorityStrategy($priorityStrategy);
$m->addServer(new Credentials('127.0.0.1', 7711));
$m->connect();
$this->assertSame($node1, $m->getCurrentNode()->getId());
$m->execute($command);
$this->assertSame($node1, $m->getCurrentNode()->getId());
$m->execute($command);
$this->assertSame($node1, $m->getCurrentNode()->getId());
$m->execute($command);
$this->assertSame($node1, $m->getCurrentNode()->getId());
}
/**
* Test that reconnection (eg. calling connect() twice) uses the information
* from the HELLO response, not the initial credentials.
*/
public function testReconnectUsesHello()
{
$node1 = 'node1';
$node2 = 'node2';
$credentialsPort = 7711;
$helloPort = 7712;
$connection = m::namedMock('initialConnection', ConnectionInterface::class)
->shouldReceive('isConnected')
->once()
->andReturn(false)
->shouldReceive('connect')
->once()
->shouldReceive('isConnected')
->andReturn(true)
->once()
->shouldReceive('execute')
->with(m::type(Hello::class))
->andReturn([
'v1',
$node1,
[$node1, '127.0.0.1', $credentialsPort, 1],
[$node2, '127.0.0.1', $helloPort, 1]
])
->once()
->shouldReceive('isConnected')
->andReturn(false)
->mock();
$reconnection = m::namedMock('reconnection', ConnectionInterface::class)
->shouldReceive('isConnected')
->once()
->andReturn(false)
->shouldReceive('connect')
->once()
->shouldReceive('isConnected')
->andReturn(true)
->atLeast(1)
->shouldReceive('execute')
->with(m::type(Hello::class))
->andReturn([
'v1',
$node2,
[$node1, '127.0.0.1', $credentialsPort, 1],
[$node2, '127.0.0.1', $helloPort, 1]
])
->once()
->mock();
$connectionFactory = m::mock(ConnectionFactoryInterface::class)
->shouldReceive('create')
->with(anything(), $credentialsPort)
->andReturn($connection)
->once()
->shouldReceive('create')
->with(anything(), $helloPort)
->andReturn($reconnection)
->once()
->mock();
$prioritizer = m::mock(NodePrioritizerInterface::class)
->shouldReceive('sort')
->andReturnUsing(function ($nodes) use ($node2) {
return [$nodes[$node2]];
})
->once()
->mock();
$manager = new Manager();
$manager->setPriorityStrategy($prioritizer);
// We set just one server initially
$manager->addServer(new Credentials('127.0.0.1', $credentialsPort));
$manager->setConnectionFactory($connectionFactory);
$manager->connect();
$this->assertSame($node1, $manager->getCurrentNode()->getId());
// The reconnection must use the node from the HELLO response
$manager->connect();
$this->assertSame($node2, $manager->getCurrentNode()->getId());
}
/**
* Test reconnection that doesn't succeed with the cluster information
* and falls back to the user-supplied credentials.
* Reconnection should keep the node stats intact.
*/
public function testReconnectFallbackToCredentials()
{
$node1 = 'node1';
$node2 = 'node2';
$credentialsPort = 7711;
$helloPort = 7712;
$hello = [
'v1',
$node1,
[$node1, '127.0.0.1', $credentialsPort, 1],
[$node2, '127.0.0.1', $helloPort, 1]
];
$connection = m::namedMock('initialConnection', ConnectionInterface::class)
->shouldReceive('isConnected')
->once()
->andReturn(false)
->shouldReceive('connect')
->once()
->shouldReceive('isConnected')
->andReturn(true)
->once()
->shouldReceive('execute')
->with(m::type(Hello::class))
->andReturn($hello)
->once()
->shouldReceive('isConnected')
->andReturn(false)
->mock();
$badConnection = m::namedMock('badConnection', ConnectionInterface::class)
->shouldReceive('isConnected')
->andReturn(false)
->shouldReceive('connect')
->andThrow(new ConnectionException())
->once()
->mock();
$reconnection = m::namedMock('reconnection', ConnectionInterface::class)
->shouldReceive('isConnected')
->once()
->andReturn(false)
->shouldReceive('connect')
->once()
->shouldReceive('isConnected')
->andReturn(true)
->once()
->shouldReceive('execute')
->with(m::type(Hello::class))
->andReturn($hello)
->once()
->mock();
$connectionFactory = m::mock(ConnectionFactoryInterface::class)
->shouldReceive('create')
->with(anything(), $credentialsPort)
->andReturn($connection)
->once()
->shouldReceive('create')
->with(anything(), $helloPort)
->andReturn($badConnection)
->once()
->shouldReceive('create')
->with(anything(), $credentialsPort)
->andReturn($reconnection)
->once()
->mock();
$prioritizer = m::mock(NodePrioritizerInterface::class)
->shouldReceive('sort')
->andReturnUsing(function ($nodes) use ($node2) {
return [$nodes[$node2]];
})
->once()
->mock();
$manager = new Manager();
$manager->setPriorityStrategy($prioritizer);
$manager->setConnectionFactory($connectionFactory);
$manager->addServer(new Credentials('127.0.0.1', $credentialsPort));
| php | MIT | 56cf00d97e739fec861717484657dbef2888df60 | 2026-01-05T05:12:23.969054Z | true |
mariano/disque-php | https://github.com/mariano/disque-php/blob/56cf00d97e739fec861717484657dbef2888df60/tests/Connection/PredisTest.php | tests/Connection/PredisTest.php | <?php
namespace Disque\Test\Connection;
use Mockery as m;
use PHPUnit_Framework_TestCase;
use Disque\Command;
use Disque\Connection\ConnectionException;
use Disque\Connection\ConnectionInterface;
use Disque\Connection\Predis;
class MockPredis extends Predis
{
public function setClient($client)
{
$this->client = $client;
}
protected function buildClient($host, $port)
{
return $this->client;
}
}
class PredisTest extends PHPUnit_Framework_TestCase
{
public function tearDown()
{
parent::tearDown();
m::close();
}
public function testInstance()
{
$c = new Predis();
$this->assertInstanceOf(ConnectionInterface::class, $c);
}
public function testIsConnected()
{
$c = new Predis();
$result = $c->isConnected();
$this->assertFalse($result);
}
public function testConnect()
{
$client = m::mock()
->shouldReceive('isConnected')
->andReturn(false)
->once()
->shouldReceive('connect')
->once()
->mock();
$connection = new MockPredis();
$connection->setClient($client);
$connection->connect();
}
public function testDisconnect()
{
$client = m::mock()
->shouldReceive('isConnected')
->andReturn(true)
->once()
->shouldReceive('disconnect')
->once()
->mock();
$connection = new MockPredis();
$connection->setClient($client);
$connection->disconnect();
}
public function testExecuteErrorNoConnection()
{
$this->setExpectedException(ConnectionException::class, 'No connection established');
$connection = new Predis();
$connection->execute(new Command\Hello());
}
public function testExecuteHello()
{
$client = m::mock()
->shouldReceive('isConnected')
->andReturn(true)
->once()
->shouldReceive('executeRaw')
->with(['HELLO'])
->once()
->shouldReceive('isConnected')
->andReturn(false)
->once()
->mock();
$connection = new MockPredis();
$connection->setClient($client);
$connection->execute(new Command\Hello());
}
public function testExecuteAckJob()
{
$command = new Command\AckJob();
$command->setArguments(['id']);
$client = m::mock()
->shouldReceive('isConnected')
->andReturn(true)
->once()
->shouldReceive('executeRaw')
->with(['ACKJOB', 'id'])
->once()
->shouldReceive('isConnected')
->andReturn(false)
->once()
->mock();
$connection = new MockPredis();
$connection->setClient($client);
$connection->execute($command);
}
} | php | MIT | 56cf00d97e739fec861717484657dbef2888df60 | 2026-01-05T05:12:23.969054Z | false |
mariano/disque-php | https://github.com/mariano/disque-php/blob/56cf00d97e739fec861717484657dbef2888df60/tests/Connection/CredentialsTest.php | tests/Connection/CredentialsTest.php | <?php
namespace Disque\Test\Connection;
use Mockery as m;
use Disque\Connection\Credentials;
class CredentialsTest extends \PHPUnit_Framework_TestCase
{
public function tearDown()
{
parent::tearDown();
m::close();
}
public function testInstance()
{
$c = new Credentials('127.0.0.1', 1111);
$this->assertInstanceOf(Credentials::class, $c);
}
public function testGetHost()
{
$host = '127.0.0.1';
$port = 1234;
$c = new Credentials($host, $port);
$this->assertSame($host, $c->getHost());
}
public function testGetPort()
{
$host = '127.0.0.1';
$port = 1234;
$c = new Credentials($host, $port);
$this->assertSame($port, $c->getPort());
}
public function testGetAddress()
{
$host = '127.0.0.1';
$port = 1234;
$address = '127.0.0.1:1234';
$c = new Credentials($host, $port);
$this->assertSame($address, $c->getAddress());
}
public function testDefaultValues()
{
$host = '127.0.0.1';
$port = 1234;
$c = new Credentials($host, $port);
$this->assertNull($c->getPassword());
$this->assertFalse($c->havePassword());
$this->assertNull($c->getConnectionTimeout());
$this->assertNull($c->getResponseTimeout());
}
public function testGetPassword()
{
$host = '127.0.0.1';
$port = 1234;
$password = 'password';
$c = new Credentials($host, $port, $password);
$this->assertSame($password, $c->getPassword());
}
public function testHavePassword()
{
$host = '127.0.0.1';
$port = 1234;
$password1 = null;
$c = new Credentials($host, $port, $password1);
$this->assertFalse($c->havePassword());
$password2 = 'password';
$c2 = new Credentials($host, $port, $password2);
$this->assertTrue($c2->havePassword());
}
public function testGetConnectionTimeout()
{
$host = '127.0.0.1';
$port = 1234;
$password = null;
$connectionTimeout = 1000;
$c = new Credentials($host, $port, $password, $connectionTimeout);
$this->assertSame($connectionTimeout, $c->getConnectionTimeout());
}
public function testGetResponseTimeout()
{
$host = '127.0.0.1';
$port = 1234;
$password = null;
$connectionTimeout = 1000;
$responseTimeout = 2000;
$c = new Credentials($host, $port, $password, $connectionTimeout, $responseTimeout);
$this->assertSame($responseTimeout, $c->getResponseTimeout());
}
}
| php | MIT | 56cf00d97e739fec861717484657dbef2888df60 | 2026-01-05T05:12:23.969054Z | false |
mariano/disque-php | https://github.com/mariano/disque-php/blob/56cf00d97e739fec861717484657dbef2888df60/tests/Connection/Node/RandomPrioritizerTest.php | tests/Connection/Node/RandomPrioritizerTest.php | <?php
namespace Disque\Test\Connection\Node;
use Disque\Connection\Node\Node;
use Disque\Connection\Node\RandomPrioritizer;
use Mockery as m;
class RandomPrioritizerTest extends \PHPUnit_Framework_TestCase
{
public function tearDown()
{
parent::tearDown();
m::close();
}
public function testInstance()
{
$p = new RandomPrioritizer();
$this->assertInstanceOf(RandomPrioritizer::class, $p);
}
public function testSortOneNode()
{
$nodeId1 = 'id1';
$node1 = m::mock(Node::class);
$nodes = [$nodeId1 => $node1];
$possibleResults = [
[$nodeId1 => $node1],
];
$p = new RandomPrioritizer();
$result = $p->sort($nodes, $nodeId1);
$this->assertContains($result, $possibleResults);
}
public function testSortTwoNodes()
{
$nodeId1 = 'id1';
$nodeId2 = 'id2';
$node1 = m::mock(Node::class);
$node2 = m::mock(Node::class);
$nodes = [$nodeId1 => $node1, $nodeId2 => $node2];
$possibleResults = [
[$nodeId1 => $node1, $nodeId2 => $node2],
[$nodeId2 => $node2, $nodeId1 => $node1]
];
$p = new RandomPrioritizer();
$result = $p->sort($nodes, $nodeId1);
$this->assertContains($result, $possibleResults);
}
} | php | MIT | 56cf00d97e739fec861717484657dbef2888df60 | 2026-01-05T05:12:23.969054Z | false |
mariano/disque-php | https://github.com/mariano/disque-php/blob/56cf00d97e739fec861717484657dbef2888df60/tests/Connection/Node/ConservativeJobCountPrioritizerTest.php | tests/Connection/Node/ConservativeJobCountPrioritizerTest.php | <?php
namespace Disque\Test\Connection\Node;
use Disque\Connection\Node\ConservativeJobCountPrioritizer;
use Disque\Connection\Node\Node;
use InvalidArgumentException;
use Mockery as m;
class ConservativeJobCountPrioritizerTest extends \PHPUnit_Framework_TestCase
{
public function tearDown()
{
parent::tearDown();
m::close();
}
public function testInstance()
{
$p = new ConservativeJobCountPrioritizer();
$this->assertInstanceOf(ConservativeJobCountPrioritizer::class, $p);
}
public function testDefaultMarginToSwitch()
{
$p = new ConservativeJobCountPrioritizer();
$this->assertSame(0.05, $p->getMarginToSwitch());
}
public function testSetMarginToSwitch()
{
$marginToSwitch = 0.5;
$p = new ConservativeJobCountPrioritizer();
$p->setMarginToSwitch($marginToSwitch);
$this->assertSame($marginToSwitch, $p->getMarginToSwitch());
}
public function testSetInvalidMarginToSwitch()
{
$marginToSwitch = -0.5;
$p = new ConservativeJobCountPrioritizer();
$this->setExpectedException(InvalidArgumentException::class, 'Margin to switch must not be negative');
$p->setMarginToSwitch($marginToSwitch);
}
public function testSortWithDefaultMarginToSwitch()
{
$nodeId1 = 'id1';
$nodeId2 = 'id2';
$nodeId3 = 'id3';
$node1 = m::mock(Node::class)
->shouldReceive('getJobCount')
->andReturn(100)
->shouldReceive('getId')
->andReturn($nodeId1)
->shouldReceive('getPriority')
->andReturn(1)
->getMock();
$node2 = m::mock(Node::class)
->shouldReceive('getJobCount')
->andReturn(104)
->shouldReceive('getId')
->andReturn($nodeId2)
->shouldReceive('getPriority')
->andReturn(1)
->getMock();
$node3 = m::mock(Node::class)
->shouldReceive('getJobCount')
->andReturn(106)
->shouldReceive('getId')
->andReturn($nodeId3)
->shouldReceive('getPriority')
->andReturn(1)
->getMock();
$nodes = [
$nodeId1 => $node1,
$nodeId2 => $node2
];
$expectedNodes = $nodes;
$p = new ConservativeJobCountPrioritizer();
$resultNodes = $p->sort($nodes, $nodeId1);
$this->assertSame($expectedNodes, $resultNodes);
$nodes2 = [
$nodeId1 => $node1,
$nodeId3 => $node3
];
$expectedNodes2 = [
$nodeId3 => $node3,
$nodeId1 => $node1
];
$resultNodes2 = $p->sort($nodes2, $node1);
$this->assertSame($expectedNodes2, $resultNodes2);
}
public function testSingleNodeIsNotSorted()
{
$nodeId1 = 'id1';
$node1 = m::mock(Node::class);
$nodes = [$nodeId1 => $node1];
$p = new ConservativeJobCountPrioritizer();
$resultNodes = $p->sort($nodes, $nodeId1);
$this->assertSame($nodes, $resultNodes);
}
public function testSortWithCustomMargin()
{
$nodeId1 = 'id1';
$nodeId2 = 'id2';
$nodeId3 = 'id3';
$node1 = m::mock(Node::class)
->shouldReceive('getJobCount')
->andReturn(100)
->shouldReceive('getId')
->andReturn($nodeId1)
->shouldReceive('getPriority')
->andReturn(1)
->getMock();
$node2 = m::mock(Node::class)
->shouldReceive('getJobCount')
->andReturn(149)
->shouldReceive('getId')
->andReturn($nodeId2)
->shouldReceive('getPriority')
->andReturn(1)
->getMock();
$node3 = m::mock(Node::class)
->shouldReceive('getJobCount')
->andReturn(151)
->shouldReceive('getId')
->andReturn($nodeId3)
->shouldReceive('getPriority')
->andReturn(1)
->getMock();
$nodes = [
$nodeId1 => $node1,
$nodeId2 => $node2
];
$expectedNodes = $nodes;
$p = new ConservativeJobCountPrioritizer();
$p->setMarginToSwitch(0.5);
$resultNodes = $p->sort($nodes, $nodeId1);
$this->assertSame($expectedNodes, $resultNodes);
$nodes2 = [
$nodeId1 => $node1,
$nodeId3 => $node3
];
$expectedNodes2 = [
$nodeId3 => $node3,
$nodeId1 => $node1
];
$resultNodes2 = $p->sort($nodes2, $node1);
$this->assertSame($expectedNodes2, $resultNodes2);
}
public function testSortWithDifferentDisquePriority()
{
$nodeId1 = 'id1';
$nodeId2 = 'id2';
$nodeId3 = 'id3';
$node1 = m::mock(Node::class)
->shouldReceive('getJobCount')
->andReturn(100)
->shouldReceive('getId')
->andReturn($nodeId1)
->shouldReceive('getPriority')
->andReturn(1)
->getMock();
$node2 = m::mock(Node::class)
->shouldReceive('getJobCount')
->andReturn(190)
->shouldReceive('getId')
->andReturn($nodeId2)
->shouldReceive('getPriority')
->andReturn(9)
->getMock();
$node3 = m::mock(Node::class)
->shouldReceive('getJobCount')
->andReturn(250)
->shouldReceive('getId')
->andReturn($nodeId3)
->shouldReceive('getPriority')
->andReturn(9)
->getMock();
$nodes = [
$nodeId1 => $node1,
$nodeId2 => $node2
];
$expectedNodes = $nodes;
$p = new ConservativeJobCountPrioritizer();
$resultNodes = $p->sort($nodes, $nodeId1);
$this->assertSame($expectedNodes, $resultNodes);
$nodes2 = [
$nodeId1 => $node1,
$nodeId3 => $node3
];
$expectedNodes2 = [
$nodeId3 => $node3,
$nodeId1 => $node1
];
$resultNodes2 = $p->sort($nodes2, $node1);
$this->assertSame($expectedNodes2, $resultNodes2);
}
public function testDeprioritizeFailingNodes()
{
$nodeId1 = 'id1';
$nodeId2 = 'id2';
$nodeId3 = 'id3';
$node1 = m::mock(Node::class)
->shouldReceive('getJobCount')
->andReturn(100)
->shouldReceive('getId')
->andReturn($nodeId1)
->shouldReceive('getPriority')
->andReturn(1)
->getMock();
// Priority 100 marks this as a failing node. Regardless of its job
// count, it should have the lowest priority when switching.
$node2 = m::mock(Node::class)
->shouldReceive('getJobCount')
->andReturn(9999)
->shouldReceive('getId')
->andReturn($nodeId2)
->shouldReceive('getPriority')
->andReturn(100)
->getMock();
$nodes = [
$nodeId1 => $node1,
$nodeId2 => $node2
];
$expectedNodes = $nodes;
$p = new ConservativeJobCountPrioritizer();
$resultNodes = $p->sort($nodes, $nodeId1);
$this->assertSame($expectedNodes, $resultNodes);
}
}
| php | MIT | 56cf00d97e739fec861717484657dbef2888df60 | 2026-01-05T05:12:23.969054Z | false |
mariano/disque-php | https://github.com/mariano/disque-php/blob/56cf00d97e739fec861717484657dbef2888df60/tests/Connection/Node/NullPrioritizerTest.php | tests/Connection/Node/NullPrioritizerTest.php | <?php
namespace Disque\Test\Connection\Node;
use Disque\Connection\Node\NullPrioritizer;
use Mockery as m;
class NullPrioritizerTest extends \PHPUnit_Framework_TestCase
{
public function tearDown()
{
parent::tearDown();
m::close();
}
public function testInstance()
{
$p = new NullPrioritizer();
$this->assertInstanceOf(NullPrioritizer::class, $p);
}
public function testSortFirstNode()
{
$nodeId1 = 'id1';
$nodeId2 = 'id2';
$nodes = [
$nodeId1 => $nodeId1,
$nodeId2 => $nodeId2
];
$nodesExpected = [
$nodeId1 => $nodeId1,
$nodeId2 => $nodeId2
];
$p = new NullPrioritizer();
$nodesResult = $p->sort($nodes, $nodeId1);
$this->assertSame($nodesExpected, $nodesResult);
}
public function testSortSecondNode()
{
$nodeId1 = 'id1';
$nodeId2 = 'id2';
$nodes = [
$nodeId2 => $nodeId2,
$nodeId1 => $nodeId1
];
$nodesExpected = [
$nodeId1 => $nodeId1,
$nodeId2 => $nodeId2
];
$p = new NullPrioritizer();
$nodesResult = $p->sort($nodes, $nodeId1);
$this->assertSame(array_values($nodesExpected), array_values($nodesResult));
}
}
| php | MIT | 56cf00d97e739fec861717484657dbef2888df60 | 2026-01-05T05:12:23.969054Z | false |
mariano/disque-php | https://github.com/mariano/disque-php/blob/56cf00d97e739fec861717484657dbef2888df60/tests/Connection/Node/NodeTest.php | tests/Connection/Node/NodeTest.php | <?php
namespace Disque\Test\Connection\Node;
use Disque\Command\Auth;
use Disque\Command\Hello;
use Disque\Command\Response\HelloResponse;
use Disque\Command\Response\InvalidResponseException;
use Disque\Connection\AuthenticationException;
use Disque\Connection\ConnectionException;
use Disque\Connection\ConnectionInterface;
use Disque\Connection\Credentials;
use Disque\Connection\Node\Node;
use Disque\Connection\Response\ResponseException;
use Mockery as m;
class NodeTest extends \PHPUnit_Framework_TestCase
{
public function tearDown()
{
parent::tearDown();
m::close();
}
public function testInstance()
{
$credentials = m::mock(Credentials::class);
$connection = m::mock(ConnectionInterface::class);
$n = new Node($credentials, $connection);
$this->assertInstanceOf(Node::class, $n);
}
public function testGetConnection()
{
$credentials = m::mock(Credentials::class);
$connection = m::mock(ConnectionInterface::class);
$n = new Node($credentials, $connection);
$this->assertSame($connection, $n->getConnection());
}
public function testGetCredentials()
{
$credentials = m::mock(Credentials::class);
$connection = m::mock(ConnectionInterface::class);
$n = new Node($credentials, $connection);
$this->assertSame($credentials, $n->getCredentials());
}
public function testDefaultValues()
{
$credentials = m::mock(Credentials::class);
$connection = m::mock(ConnectionInterface::class);
$n = new Node($credentials, $connection);
$this->assertSame(0, $n->getJobCount());
$this->assertSame(0, $n->getTotalJobCount());
$this->assertNull($n->getId());
$this->assertNull($n->getPrefix());
$this->assertSame(1, $n->getPriority());
$this->assertNull($n->getHello());
}
public function testJobCount()
{
$credentials = m::mock(Credentials::class);
$connection = m::mock(ConnectionInterface::class);
$n = new Node($credentials, $connection);
$jobs1 = 2;
$jobs2 = 3;
$totalJobs = $jobs1 + $jobs2;
$n->addJobCount($jobs1);
$n->addJobCount($jobs2);
$this->assertSame($totalJobs, $n->getJobCount());
$this->assertSame($totalJobs, $n->getTotalJobCount());
}
public function testResetJobCount()
{
$credentials = m::mock(Credentials::class);
$connection = m::mock(ConnectionInterface::class);
$n = new Node($credentials, $connection);
$totalJobs = 5;
$n->addJobCount($totalJobs);
$n->resetJobCount();
$this->assertSame(0, $n->getJobCount());
$this->assertSame($totalJobs, $n->getTotalJobCount());
}
public function testSayHello()
{
$address = '127.0.0.1';
$port = 7712;
$nodeId = 'someLongNodeId';
$prefix = 'someLong';
$version = 'v1';
$priority = 1;
$helloResponse = [
HelloResponse::POS_VERSION => $version,
HelloResponse::POS_ID => $nodeId,
HelloResponse::POS_NODES_START => [
HelloResponse::POS_NODE_ID => $nodeId,
HelloResponse::POS_NODE_HOST => $address,
HelloResponse::POS_NODE_PORT => $port,
HelloResponse::POS_NODE_PRIORITY => $priority
]
];
$expectedHello = [
HelloResponse::NODE_VERSION => $version,
HelloResponse::NODE_ID => $nodeId,
HelloResponse::NODES => [
[
HelloResponse::NODE_ID => $nodeId,
HelloResponse::NODE_HOST => $address,
HelloResponse::NODE_PORT => $port,
HelloResponse::NODE_PRIORITY => $priority
]
]
];
$credentials = m::mock(Credentials::class);
$connection = m::mock(ConnectionInterface::class)
->shouldReceive('execute')
->andReturn($helloResponse)
->getMock();
$n = new Node($credentials, $connection);
$hello = $n->sayHello();
$this->assertSame($expectedHello, $hello);
$this->assertNotNull($n->getHello());
$this->assertSame($nodeId, $n->getId());
$this->assertSame($priority, $n->getPriority());
$this->assertSame($prefix, $n->getPrefix());
}
public function testSayHelloAndThenConnect()
{
$address = '127.0.0.1';
$port = 7712;
$nodeId = 'someLongNodeId';
$prefix = 'someLong';
$version = 'v1';
$priority = 1;
$helloResponse = [
HelloResponse::POS_VERSION => $version,
HelloResponse::POS_ID => $nodeId,
HelloResponse::POS_NODES_START => [
HelloResponse::POS_NODE_ID => $nodeId,
HelloResponse::POS_NODE_HOST => $address,
HelloResponse::POS_NODE_PORT => $port,
HelloResponse::POS_NODE_PRIORITY => $priority
]
];
$expectedHello = [
HelloResponse::NODE_VERSION => $version,
HelloResponse::NODE_ID => $nodeId,
HelloResponse::NODES => [
[
HelloResponse::NODE_ID => $nodeId,
HelloResponse::NODE_HOST => $address,
HelloResponse::NODE_PORT => $port,
HelloResponse::NODE_PRIORITY => $priority
]
]
];
$credentials = m::mock(Credentials::class);
$connection = m::mock(ConnectionInterface::class)
->shouldReceive('execute')
->andReturn($helloResponse)
->shouldReceive('isConnected')
->andReturn(true)
->getMock();
$n = new Node($credentials, $connection);
$hello = $n->sayHello();
$this->assertSame($expectedHello, $hello);
$n->connect();
$hello = $n->sayHello();
$this->assertSame($expectedHello, $hello);
}
public function testSayHelloWrongPriority()
{
$address = '127.0.0.1';
$port = 7712;
$nodeId = 'someLongNodeId';
$nodeId2 = 'someLongNodeId2';
$prefix = 'someLong';
$version = 'v1';
$priority = 1;
$helloResponse = [
HelloResponse::POS_VERSION => $version,
HelloResponse::POS_ID => $nodeId,
HelloResponse::POS_NODES_START => [
HelloResponse::POS_NODE_ID => $nodeId2,
HelloResponse::POS_NODE_HOST => $address,
HelloResponse::POS_NODE_PORT => $port,
HelloResponse::POS_NODE_PRIORITY => $priority
]
];
$expectedHello = [
HelloResponse::NODE_VERSION => $version,
HelloResponse::NODE_ID => $nodeId,
HelloResponse::NODES => [
[
HelloResponse::NODE_ID => $nodeId2,
HelloResponse::NODE_HOST => $address,
HelloResponse::NODE_PORT => $port,
HelloResponse::NODE_PRIORITY => $priority
]
]
];
$credentials = m::mock(Credentials::class);
$connection = m::mock(ConnectionInterface::class)
->shouldReceive('execute')
->andReturn($helloResponse)
->getMock();
$n = new Node($credentials, $connection);
$hello = $n->sayHello();
$this->assertSame($expectedHello, $hello);
$this->assertNotNull($n->getHello());
$this->assertSame($nodeId, $n->getId());
$this->assertSame(Node::PRIORITY_FALLBACK, $n->getPriority());
$this->assertSame($prefix, $n->getPrefix());
}
public function testSayHelloConnectionException()
{
$credentials = m::mock(Credentials::class);
$connection = m::mock(ConnectionInterface::class)
->shouldReceive('execute')
->andThrow(new ConnectionException())
->getMock();
$n = new Node($credentials, $connection);
$this->setExpectedException(ConnectionException::class);
$n->sayHello();
}
public function testConnect()
{
$connectionTimeout = 1000;
$responseTimeout = 1000;
$address = '127.0.0.1';
$port = 7712;
$nodeId = 'someLongNodeId';
$version = 'v1';
$helloResponse = [
HelloResponse::POS_VERSION => $version,
HelloResponse::POS_ID => $nodeId,
HelloResponse::POS_NODES_START => [
HelloResponse::POS_NODE_ID => $nodeId,
HelloResponse::POS_NODE_HOST => $address,
HelloResponse::POS_NODE_PORT => $port,
HelloResponse::POS_NODE_PRIORITY => $version
]
];
$expectedHello = [
HelloResponse::NODE_VERSION => $version,
HelloResponse::NODE_ID => $nodeId,
HelloResponse::NODES => [
[
HelloResponse::NODE_ID => $nodeId,
HelloResponse::NODE_HOST => $address,
HelloResponse::NODE_PORT => $port,
HelloResponse::NODE_PRIORITY => $version
]
]
];
$credentials = m::mock(Credentials::class)
->shouldReceive('getConnectionTimeout')
->andReturn($connectionTimeout)
->shouldReceive('getResponseTimeout')
->andReturn($responseTimeout)
->shouldReceive('havePassword')
->andReturn(false)
->getMock();
$connection = m::mock(ConnectionInterface::class)
->shouldReceive('isConnected')
->andReturn(false)
->shouldReceive('connect')
->shouldReceive('execute')
->andReturn($helloResponse)
->getMock();
$n = new Node($credentials, $connection);
$hello = $n->connect();
$this->assertSame($expectedHello, $hello);
}
public function testConnectConnectionException()
{
$connectionTimeout = 1000;
$responseTimeout = 1000;
$credentials = m::mock(Credentials::class)
->shouldReceive('getConnectionTimeout')
->andReturn($connectionTimeout)
->shouldReceive('getResponseTimeout')
->andReturn($responseTimeout)
->getMock();
$connection = m::mock(ConnectionInterface::class)
->shouldReceive('isConnected')
->andReturn(false)
->shouldReceive('connect')
->andThrow(new ConnectionException())
->getMock();
$n = new Node($credentials, $connection);
$this->setExpectedException(ConnectionException::class);
$n->connect();
}
public function testConnectWithPasswordRightPassword()
{
$connectionTimeout = 1000;
$responseTimeout = 1000;
$address = '127.0.0.1';
$port = 7712;
$nodeId = 'someLongNodeId';
$version = 'v1';
$password = 'password';
$helloResponse = [
HelloResponse::POS_VERSION => $version,
HelloResponse::POS_ID => $nodeId,
HelloResponse::POS_NODES_START => [
HelloResponse::POS_NODE_ID => $nodeId,
HelloResponse::POS_NODE_HOST => $address,
HelloResponse::POS_NODE_PORT => $port,
HelloResponse::POS_NODE_PRIORITY => $version
]
];
$expectedHello = [
HelloResponse::NODE_VERSION => $version,
HelloResponse::NODE_ID => $nodeId,
HelloResponse::NODES => [
[
HelloResponse::NODE_ID => $nodeId,
HelloResponse::NODE_HOST => $address,
HelloResponse::NODE_PORT => $port,
HelloResponse::NODE_PRIORITY => $version
]
]
];
$credentials = m::mock(Credentials::class)
->shouldReceive('getConnectionTimeout')
->andReturn($connectionTimeout)
->shouldReceive('getResponseTimeout')
->andReturn($responseTimeout)
->shouldReceive('havePassword')
->andReturn(true)
->shouldReceive('getPassword')
->andReturn($password)
->getMock();
$connection = m::mock(ConnectionInterface::class)
->shouldReceive('isConnected')
->andReturn(false)
->shouldReceive('connect')
->shouldReceive('execute')
->andReturn('OK')
->once()
->shouldReceive('execute')
->andReturn($helloResponse)
->once()
->getMock();
$n = new Node($credentials, $connection);
$hello = $n->connect();
$this->assertSame($expectedHello, $hello);
}
public function testConnectWithPasswordMissingPassword()
{
$connectionTimeout = 1000;
$responseTimeout = 1000;
$credentials = m::mock(Credentials::class)
->shouldReceive('getConnectionTimeout')
->andReturn($connectionTimeout)
->shouldReceive('getResponseTimeout')
->andReturn($responseTimeout)
->shouldReceive('havePassword')
->andReturn(false)
->getMock();
$connection = m::mock(ConnectionInterface::class)
->shouldReceive('isConnected')
->andReturn(false)
->shouldReceive('connect')
->shouldReceive('execute')
->with(m::type(Hello::class))
->andThrow(new ResponseException('NOAUTH Authentication Required'))
->once()
->getMock();
$n = new Node($credentials, $connection);
$this->setExpectedException(AuthenticationException::class);
$n->connect();
}
public function testConnectWithPasswordWrongPassword()
{
$connectionTimeout = 1000;
$responseTimeout = 1000;
$wrongPassword = 'wrongPassword';
$credentials = m::mock(Credentials::class)
->shouldReceive('getConnectionTimeout')
->andReturn($connectionTimeout)
->shouldReceive('getResponseTimeout')
->andReturn($responseTimeout)
->shouldReceive('havePassword')
->andReturn(true)
->shouldReceive('getPassword')
->andReturn($wrongPassword)
->getMock();
$connection = m::mock(ConnectionInterface::class)
->shouldReceive('isConnected')
->andReturn(false)
->shouldReceive('connect')
->shouldReceive('execute')
->with(m::type(Auth::class))
->andReturn('whatever')
->once()
->getMock();
$n = new Node($credentials, $connection);
$this->setExpectedException(AuthenticationException::class);
$n->connect();
}
} | php | MIT | 56cf00d97e739fec861717484657dbef2888df60 | 2026-01-05T05:12:23.969054Z | false |
mariano/disque-php | https://github.com/mariano/disque-php/blob/56cf00d97e739fec861717484657dbef2888df60/tests/Connection/Factory/PredisFactoryTest.php | tests/Connection/Factory/PredisFactoryTest.php | <?php
namespace Disque\Test\Connection\Factory;
use Disque\Connection\Factory\PredisFactory;
use Disque\Connection\Predis;
use Mockery as m;
class PredisFactoryTest extends \PHPUnit_Framework_TestCase
{
public function tearDown()
{
parent::tearDown();
m::close();
}
public function testInstance()
{
$f = new PredisFactory();
$this->assertInstanceOf(PredisFactory::class, $f);
}
public function testCreate()
{
$host = '127.0.0.1';
$port = 7711;
$f = new PredisFactory();
$socket = $f->create($host, $port);
$this->assertInstanceOf(Predis::class, $socket);
}
}
| php | MIT | 56cf00d97e739fec861717484657dbef2888df60 | 2026-01-05T05:12:23.969054Z | false |
mariano/disque-php | https://github.com/mariano/disque-php/blob/56cf00d97e739fec861717484657dbef2888df60/tests/Connection/Factory/SocketFactoryTest.php | tests/Connection/Factory/SocketFactoryTest.php | <?php
namespace Disque\Test\Connection\Factory;
use Disque\Connection\Factory\SocketFactory;
use Disque\Connection\Socket;
use Mockery as m;
class SocketFactoryTest extends \PHPUnit_Framework_TestCase
{
public function tearDown()
{
parent::tearDown();
m::close();
}
public function testInstance()
{
$f = new SocketFactory();
$this->assertInstanceOf(SocketFactory::class, $f);
}
public function testCreate()
{
$host = '127.0.0.1';
$port = 7711;
$f = new SocketFactory();
$socket = $f->create($host, $port);
$this->assertInstanceOf(Socket::class, $socket);
}
}
| php | MIT | 56cf00d97e739fec861717484657dbef2888df60 | 2026-01-05T05:12:23.969054Z | false |
mariano/disque-php | https://github.com/mariano/disque-php/blob/56cf00d97e739fec861717484657dbef2888df60/tests/Queue/QueueTest.php | tests/Queue/QueueTest.php | <?php
namespace Disque\Test\Queue;
use DateTime;
use DateTimeZone;
use Disque\Client;
use Disque\Queue\Job;
use Disque\Queue\JobInterface;
use Disque\Queue\Queue;
use Disque\Queue\Marshal\MarshalerInterface;
use InvalidArgumentException;
use Mockery as m;
use PHPUnit_Framework_TestCase;
use Disque\Command\Response\JobsResponse AS Response;
use Disque\Command\Response\JobsWithCountersResponse AS Counters;
class MockJob extends Job
{
}
class QueueTest extends PHPUnit_Framework_TestCase
{
public function tearDown()
{
parent::tearDown();
m::close();
}
public function testGetName()
{
$name = 'queue';
$q = new Queue(new Client(), $name);
$this->assertSame($name, $q->getName());
}
public function testInstance()
{
$q = new Queue(new Client(), 'queue');
$this->assertInstanceOf(Queue::class, $q);
}
public function testMarshaler()
{
$q = new Queue(new Client(), 'queue');
$q->setMarshaler(m::mock(MarshalerInterface::class));
}
public function testPushConnected()
{
$payload = ['test' => 'stuff'];
$job = m::mock(Job::class.'[setId]')
->shouldReceive('setId')
->with('JOB_ID')
->once()
->mock();
$job->setBody($payload);
$client = m::mock(Client::class)
->shouldReceive('isConnected')
->with()
->andReturn(true)
->once()
->shouldReceive('addJob')
->with('queue', json_encode($payload), [])
->andReturn('JOB_ID')
->mock();
$q = new Queue($client, 'queue');
$result = $q->push($job);
$this->assertSame($job, $result);
}
public function testPushNotConnected()
{
$payload = ['test' => 'stuff'];
$job = m::mock(Job::class.'[setId]')
->shouldReceive('setId')
->with('JOB_ID')
->once()
->mock();
$job->setBody($payload);
$client = m::mock(Client::class)
->shouldReceive('isConnected')
->with()
->andReturn(false)
->once()
->shouldReceive('connect')
->with()
->once()
->shouldReceive('addJob')
->with('queue', json_encode($payload), [])
->andReturn('JOB_ID')
->mock();
$q = new Queue($client, 'queue');
$result = $q->push($job);
$this->assertSame($job, $result);
}
public function testPushWithOptions()
{
$payload = ['test' => 'stuff'];
$job = m::mock(Job::class.'[setId]')
->shouldReceive('setId')
->with('JOB_ID')
->once()
->mock();
$job->setBody($payload);
$client = m::mock(Client::class)
->shouldReceive('isConnected')
->with()
->andReturn(true)
->once()
->shouldReceive('addJob')
->with('queue', json_encode($payload), ['delay' => 3000])
->andReturn('JOB_ID')
->mock();
$q = new Queue($client, 'queue');
$result = $q->push($job, ['delay' => 3000]);
$this->assertSame($job, $result);
}
public function testPushCustomMarshaler()
{
$payload = ['test' => 'stuff'];
$job = m::mock(Job::class.'[setId]')
->shouldReceive('setId')
->with('JOB_ID')
->once()
->mock();
$job->setBody($payload);
$client = m::mock(Client::class)
->shouldReceive('isConnected')
->with()
->andReturn(true)
->once()
->shouldReceive('addJob')
->with('queue', json_encode($payload), [])
->andReturn('JOB_ID')
->mock();
$marshaler = m::mock(MarshalerInterface::class)
->shouldReceive('marshal')
->with($job)
->andReturn(json_encode($payload))
->once()
->mock();
$q = new Queue($client, 'queue');
$q->setMarshaler($marshaler);
$result = $q->push($job);
$this->assertSame($job, $result);
}
public function testProcessedConnected()
{
$job = m::mock(JobInterface::class)
->shouldReceive('getId')
->with()
->andReturn('JOB_ID')
->once()
->mock();
$client = m::mock(Client::class)
->shouldReceive('isConnected')
->with()
->andReturn(true)
->once()
->shouldReceive('ackJob')
->with('JOB_ID')
->mock();
$q = new Queue($client, 'queue');
$q->processed($job);
}
public function testProcessedNotConnected()
{
$job = m::mock(JobInterface::class)
->shouldReceive('getId')
->with()
->andReturn('JOB_ID')
->once()
->mock();
$client = m::mock(Client::class)
->shouldReceive('isConnected')
->with()
->andReturn(false)
->once()
->shouldReceive('connect')
->with()
->once()
->shouldReceive('ackJob')
->with('JOB_ID')
->mock();
$q = new Queue($client, 'queue');
$q->processed($job);
}
public function testFailedConnected()
{
$job = m::mock(JobInterface::class)
->shouldReceive('getId')
->with()
->andReturn('JOB_ID')
->once()
->mock();
$client = m::mock(Client::class)
->shouldReceive('isConnected')
->with()
->andReturn(true)
->once()
->shouldReceive('nack')
->with('JOB_ID')
->mock();
$q = new Queue($client, 'queue');
$q->failed($job);
}
public function testFailedNotConnected()
{
$job = m::mock(JobInterface::class)
->shouldReceive('getId')
->with()
->andReturn('JOB_ID')
->once()
->mock();
$client = m::mock(Client::class)
->shouldReceive('isConnected')
->with()
->andReturn(false)
->once()
->shouldReceive('connect')
->with()
->once()
->shouldReceive('nack')
->with('JOB_ID')
->mock();
$q = new Queue($client, 'queue');
$q->failed($job);
}
public function testPullConnected()
{
$options = ['timeout' => 0, 'count' => 1, 'withcounters' => true];
$payload = ['test' => 'stuff'];
$jobId = 'JOB_ID';
$nacks = 1;
$ad = 2;
$client = m::mock(Client::class)
->shouldReceive('isConnected')
->with()
->andReturn(true)
->once()
->shouldReceive('getJob')
->with('queue', $options)
->andReturn([
[
Response::KEY_ID => $jobId,
Response::KEY_BODY => json_encode($payload),
Counters::KEY_NACKS => $nacks,
Counters::KEY_ADDITIONAL_DELIVERIES => $ad
]
])
->mock();
$q = new Queue($client, 'queue');
$job = $q->pull();
$this->assertSame($jobId, $job->getId());
$this->assertSame($payload, $job->getBody());
$this->assertSame($nacks, $job->getNacks());
$this->assertSame($ad, $job->getAdditionalDeliveries());
}
public function testPullNotConnected()
{
$options = ['timeout' => 0, 'count' => 1, 'withcounters' => true];
$payload = ['test' => 'stuff'];
$jobId = 'JOB_ID';
$nacks = 1;
$ad = 2;
$client = m::mock(Client::class)
->shouldReceive('isConnected')
->with()
->andReturn(false)
->once()
->shouldReceive('connect')
->with()
->once()
->shouldReceive('getJob')
->with('queue', $options)
->andReturn([
[
Response::KEY_ID => $jobId,
Response::KEY_BODY => json_encode($payload),
Counters::KEY_NACKS => $nacks,
Counters::KEY_ADDITIONAL_DELIVERIES => $ad
]
])
->mock();
$q = new Queue($client, 'queue');
$job = $q->pull();
$this->assertInstanceOf(Job::class, $job);
$this->assertSame($jobId, $job->getId());
$this->assertSame($payload, $job->getBody());
$this->assertSame($nacks, $job->getNacks());
$this->assertSame($ad, $job->getAdditionalDeliveries());
}
public function testPullCustomMarshaler()
{
$options = ['timeout' => 0, 'count' => 1, 'withcounters' => true];
$payload = ['test' => 'stuff'];
$jobId = 'JOB_ID';
$nacks = 1;
$ad = 2;
$client = m::mock(Client::class)
->shouldReceive('isConnected')
->with()
->andReturn(true)
->once()
->shouldReceive('getJob')
->with('queue', $options)
->andReturn([
[
Response::KEY_ID => $jobId,
Response::KEY_BODY => json_encode($payload),
Counters::KEY_NACKS => $nacks,
Counters::KEY_ADDITIONAL_DELIVERIES => $ad
]
])
->mock();
$job = new Job();
$marshaler = m::mock(MarshalerInterface::class)
->shouldReceive('unmarshal')
->with(json_encode($payload))
->andReturn($job)
->once()
->mock();
$q = new Queue($client, 'queue');
$q->setMarshaler($marshaler);
$result = $q->pull();
$this->assertSame($job, $result);
}
public function testPullSeveralJobs()
{
$options = ['timeout' => 0, 'count' => 1, 'withcounters' => true];
$payload = ['test' => 'stuff'];
$jobId = 'JOB_ID';
$nacks = 1;
$ad = 2;
$jobId2 = 'JOB_ID2';
$client = m::mock(Client::class)
->shouldReceive('isConnected')
->with()
->andReturn(true)
->once()
->shouldReceive('getJob')
->with('queue', $options)
->andReturn([
[
Response::KEY_ID => $jobId,
Response::KEY_BODY => json_encode($payload),
Counters::KEY_NACKS => $nacks,
Counters::KEY_ADDITIONAL_DELIVERIES => $ad
],
[
Response::KEY_ID => $jobId2,
Response::KEY_BODY => json_encode([]),
Counters::KEY_NACKS => $nacks,
Counters::KEY_ADDITIONAL_DELIVERIES => $ad
],
])
->mock();
$q = new Queue($client, 'queue');
$job = $q->pull();
$this->assertSame($jobId, $job->getId());
$this->assertSame($payload, $job->getBody());
$this->assertSame($nacks, $job->getNacks());
$this->assertSame($ad, $job->getAdditionalDeliveries());
}
public function testPullNoJobs()
{
$options = ['timeout' => 0, 'count' => 1, 'withcounters' => true];
$client = m::mock(Client::class)
->shouldReceive('isConnected')
->with()
->andReturn(true)
->once()
->shouldReceive('getJob')
->with('queue', $options)
->andReturn([])
->mock();
$q = new Queue($client, 'queue');
$job = $q->pull();
$this->assertNull($job);
}
public function testPullNoJobsWithTimeout()
{
$timeout = 3000;
$options = ['timeout' => $timeout, 'count' => 1, 'withcounters' => true];
$client = m::mock(Client::class)
->shouldReceive('isConnected')
->with()
->andReturn(true)
->once()
->shouldReceive('getJob')
->with('queue', $options)
->andReturn([])
->mock();
$q = new Queue($client, 'queue');
$job = $q->pull($timeout);
$this->assertNull($job);
}
public function testScheduleInvalidDateInPast()
{
$this->setExpectedException(InvalidArgumentException::class, 'Specified schedule time has passed');
$date = new DateTime('-10 seconds');
$q = new Queue(m::mock(Client::class), 'queue');
$q->schedule(new Job(), $date);
}
/**
* This and the following tests test scheduling jobs in the future
*
* They depend on the global system time and contain a race condition
* wherein system time can move forward one second between the two DateTime()
* instantiations (the first one in the test, the second one in the
* schedule() method). If that is the case, the resulting delay is one
* second off (eg. 9 seconds instead of the scheduled 10 seconds).
*
* For that reason the mocked method expects either the $delay (10 seconds)
* or $delay - 1 (9 seconds). Both are valid test results.
*/
public function testScheduleDefaultTimeZone()
{
$delay = 10;
$job = new Job();
$queue = m::mock(Queue::class.'[push]', [m::mock(Client::class), 'queue'])
->shouldReceive('push')
->with($job,
anyOf(
['delay' => $delay],
['delay' => $delay - 1]
))
->andReturn($job)
->once()
->mock();
$result = $queue->schedule($job, new DateTime('+' . $delay . ' seconds', new DateTimeZone(Queue::DEFAULT_JOB_TIMEZONE)));
$this->assertSame($job, $result);
}
public function testScheduleDifferentTimeZone()
{
$delay = 10;
$job = new Job();
$queue = m::mock(Queue::class.'[push]', [m::mock(Client::class), 'queue'])
->shouldReceive('push')
->with($job,
anyOf(
['delay' => $delay],
['delay' => $delay - 1]
))
->andReturn($job)
->once()
->mock();
$timeZone = new DateTimeZone('America/Argentina/Buenos_Aires');
$this->assertNotSame(Queue::DEFAULT_JOB_TIMEZONE, $timeZone->getName());
$result = $queue->schedule($job, new DateTime('+' . $delay . ' seconds', $timeZone));
$this->assertSame($job, $result);
}
public function testScheduleWayInTheFuture()
{
$delayDays = 25;
$delay = ($delayDays * 24 * 60 * 60);
$job = new Job();
$queue = m::mock(Queue::class.'[push]', [m::mock(Client::class), 'queue'])
->shouldReceive('push')
->with($job,
anyOf(
['delay' => $delay],
['delay' => $delay - 1]
))
->andReturn($job)
->once()
->mock();
$result = $queue->schedule($job, new DateTime('+' . $delayDays . ' days', new DateTimeZone(Queue::DEFAULT_JOB_TIMEZONE)));
$this->assertSame($job, $result);
}
public function testScheduleWithOptions()
{
$delay = 10;
$job = new Job();
$queue = m::mock(Queue::class.'[push]', [m::mock(Client::class), 'queue'])
->shouldReceive('push')
->with($job,
anyOf(
['retry' => 1000, 'delay' => $delay],
['retry' => 1000, 'delay' => $delay - 1]
))
->andReturn($job)
->once()
->mock();
$when = new DateTime('+' . $delay . ' seconds', new DateTimeZone(Queue::DEFAULT_JOB_TIMEZONE));
$result = $queue->schedule($job, $when, ['retry' => 1000]);
$this->assertSame($job, $result);
}
public function testProcessingConnected()
{
$job = m::mock(JobInterface::class)
->shouldReceive('getId')
->with()
->andReturn('JOB_ID')
->once()
->mock();
$client = m::mock(Client::class)
->shouldReceive('isConnected')
->with()
->andReturn(true)
->once()
->shouldReceive('working')
->with('JOB_ID')
->andReturn(3)
->mock();
$q = new Queue($client, 'queue');
$result = $q->processing($job);
$this->assertSame(3, $result);
}
public function testWorkingNotConnected()
{
$job = m::mock(JobInterface::class)
->shouldReceive('getId')
->with()
->andReturn('JOB_ID')
->once()
->mock();
$client = m::mock(Client::class)
->shouldReceive('isConnected')
->with()
->andReturn(false)
->once()
->shouldReceive('connect')
->with()
->once()
->shouldReceive('working')
->with('JOB_ID')
->andReturn(3)
->mock();
$q = new Queue($client, 'queue');
$result = $q->processing($job);
$this->assertSame(3, $result);
}
} | php | MIT | 56cf00d97e739fec861717484657dbef2888df60 | 2026-01-05T05:12:23.969054Z | false |
mariano/disque-php | https://github.com/mariano/disque-php/blob/56cf00d97e739fec861717484657dbef2888df60/tests/Queue/JobTest.php | tests/Queue/JobTest.php | <?php
namespace Disque\Test\Queue;
use Disque\Queue\Job;
use Disque\Queue\JobInterface;
use PHPUnit_Framework_TestCase;
class JobTest extends PHPUnit_Framework_TestCase
{
public function testInstance()
{
$j = new Job();
$this->assertInstanceOf(JobInterface::class, $j);
}
public function testBodyEmpty()
{
$j = new Job();
$this->assertNull($j->getBody());
}
public function testBodyNotEmpty()
{
$body = ['test' => 'stuff'];
$j = new Job($body);
$this->assertSame($body, $j->getBody());
}
public function nullId()
{
$j = new Job();
$this->assertNull($j->getId());
}
public function idNotNull()
{
$body = '';
$id = 'id';
$j = new Job($body, $id);
$this->assertSame($id, $j->getId());
}
public function emptyQueue()
{
$j = new job();
$this->assertEquals('', $j->getQueue());
}
public function queueSet()
{
$queue = 'queue';
$j = new Job();
$j->setQueue($queue);
$this->assertEquals($queue, $j->getQueue());
}
public function zeroNacks()
{
$j = new Job();
$this->assertSame(0, $j->getNacks());
}
public function nacksSet()
{
$j = new Job();
$nacks = 10;
$j->setNacks($nacks);
$this->assertSame($nacks, $j->getNacks());
}
public function zeroAdditionalDeliveries()
{
$j = new Job();
$this->assertSame(0, $j->getAdditionalDeliveries());
}
public function additionalDeliveriesSet()
{
$j = new Job();
$deliveries = 10;
$j->setAdditionalDeliveries($deliveries);
$this->assertSame($deliveries, $j->getAdditionalDeliveries());
}
}
| php | MIT | 56cf00d97e739fec861717484657dbef2888df60 | 2026-01-05T05:12:23.969054Z | false |
mariano/disque-php | https://github.com/mariano/disque-php/blob/56cf00d97e739fec861717484657dbef2888df60/tests/Queue/Marshaler/JobMarshalerTest.php | tests/Queue/Marshaler/JobMarshalerTest.php | <?php
namespace Disque\Test\Queue\Marshaler;
use Disque\Queue\Job;
use Disque\Queue\JobInterface;
use Disque\Queue\Marshal\JobMarshaler;
use Disque\Queue\Marshal\MarshalerInterface;
use Disque\Queue\Marshal\MarshalException;
use Mockery as m;
use PHPUnit_Framework_TestCase;
class JobMarshalerTest extends PHPUnit_Framework_TestCase
{
public function tearDown()
{
parent::tearDown();
m::close();
}
public function testInstance()
{
$m = new JobMarshaler();
$this->assertInstanceOf(MarshalerInterface::class, $m);
}
public function testMarshalEmpty()
{
$m = new JobMarshaler();
$j = new Job();
$result = $m->marshal($j);
$this->assertSame('null', $result);
}
public function testMarshalNotEmpty()
{
$m = new JobMarshaler();
$j = new Job(['test' => 'stuff']);
$result = $m->marshal($j);
$this->assertSame('{"test":"stuff"}', $result);
}
public function testUnmarshalInvalid()
{
$this->setExpectedException(MarshalException::class, 'Could not deserialize {"wrong"!');
$m = new JobMarshaler();
$m->unmarshal('{"wrong"!');
}
public function testUnmarshalEmpty()
{
$m = new JobMarshaler();
$j = $m->unmarshal('{"test":"stuff"}');
$this->assertInstanceOf(Job::class, $j);
$result = $j->getBody();
$this->assertSame(['test' => 'stuff'], $result);
}
}
| php | MIT | 56cf00d97e739fec861717484657dbef2888df60 | 2026-01-05T05:12:23.969054Z | false |
mariano/disque-php | https://github.com/mariano/disque-php/blob/56cf00d97e739fec861717484657dbef2888df60/tests/Command/AckJobTest.php | tests/Command/AckJobTest.php | <?php
namespace Disque\Test\Command;
use PHPUnit_Framework_TestCase;
use Disque\Command\Argument\InvalidCommandArgumentException;
use Disque\Command\CommandInterface;
use Disque\Command\AckJob;
use Disque\Command\Response\InvalidResponseException;
class AckJobTest extends PHPUnit_Framework_TestCase
{
public function testInstance()
{
$c = new AckJob();
$this->assertInstanceOf(CommandInterface::class, $c);
}
public function testGetCommand()
{
$c = new AckJob();
$result = $c->getCommand();
$this->assertSame('ACKJOB', $result);
}
public function testIsBlocking()
{
$c = new AckJob();
$result = $c->isBlocking();
$this->assertFalse($result);
}
public function testBuildInvalidArgumentsEmpty()
{
$this->setExpectedException(InvalidCommandArgumentException::class, 'Invalid command arguments. Arguments for command Disque\\Command\\AckJob: []');
$c = new AckJob();
$c->setArguments([]);
}
public function testBuildInvalidArgumentsNonStringArray()
{
$this->setExpectedException(InvalidCommandArgumentException::class, 'Invalid command arguments. Arguments for command Disque\\Command\\AckJob: [["test","stuff"]]');
$c = new AckJob();
$c->setArguments([['test','stuff']]);
}
public function testBuildInvalidArgumentsNonStringNumeric()
{
$this->setExpectedException(InvalidCommandArgumentException::class, 'Invalid command arguments. Arguments for command Disque\\Command\\AckJob: [128]');
$c = new AckJob();
$c->setArguments([128]);
}
public function testBuildInvalidArgumentsEmptyValue()
{
$this->setExpectedException(InvalidCommandArgumentException::class, 'Invalid command arguments. Arguments for command Disque\\Command\\AckJob: [""]');
$c = new AckJob();
$c->setArguments([""]);
}
public function testBuild()
{
$c = new AckJob();
$c->setArguments(['id']);
$result = $c->getArguments();
$this->assertSame(['id'], $result);
}
public function testBuildSeveral()
{
$c = new AckJob();
$c->setArguments(['id', 'id2']);
$result = $c->getArguments();
$this->assertSame(['id', 'id2'], $result);
}
public function testParseInvalidNonNumericArray()
{
$this->setExpectedException(InvalidResponseException::class, 'Invalid command response. Command Disque\\Command\\AckJob got: ["test"]');
$c = new AckJob();
$c->parse(['test']);
}
public function testParseInvalidNonNumericString()
{
$this->setExpectedException(InvalidResponseException::class, 'Invalid command response. Command Disque\\Command\\AckJob got: "test"');
$c = new AckJob();
$c->parse('test');
}
public function testParse()
{
$c = new AckJob();
$result = $c->parse('128');
$this->assertSame(128, $result);
}
} | php | MIT | 56cf00d97e739fec861717484657dbef2888df60 | 2026-01-05T05:12:23.969054Z | false |
mariano/disque-php | https://github.com/mariano/disque-php/blob/56cf00d97e739fec861717484657dbef2888df60/tests/Command/EnqueueTest.php | tests/Command/EnqueueTest.php | <?php
namespace Disque\Test\Command;
use PHPUnit_Framework_TestCase;
use Disque\Command\Argument\InvalidCommandArgumentException;
use Disque\Command\CommandInterface;
use Disque\Command\Enqueue;
use Disque\Command\Response\InvalidResponseException;
class EnqueueTest extends PHPUnit_Framework_TestCase
{
public function testInstance()
{
$c = new Enqueue();
$this->assertInstanceOf(CommandInterface::class, $c);
}
public function testGetCommand()
{
$c = new Enqueue();
$result = $c->getCommand();
$this->assertSame('ENQUEUE', $result);
}
public function testIsBlocking()
{
$c = new Enqueue();
$result = $c->isBlocking();
$this->assertFalse($result);
}
public function testBuildInvalidArgumentsEmpty()
{
$this->setExpectedException(InvalidCommandArgumentException::class, 'Invalid command arguments. Arguments for command Disque\\Command\\Enqueue: []');
$c = new Enqueue();
$c->setArguments([]);
}
public function testBuildInvalidArgumentsNonStringArray()
{
$this->setExpectedException(InvalidCommandArgumentException::class, 'Invalid command arguments. Arguments for command Disque\\Command\\Enqueue: [["test","stuff"]]');
$c = new Enqueue();
$c->setArguments([['test','stuff']]);
}
public function testBuildInvalidArgumentsNonStringNumeric()
{
$this->setExpectedException(InvalidCommandArgumentException::class, 'Invalid command arguments. Arguments for command Disque\\Command\\Enqueue: [128]');
$c = new Enqueue();
$c->setArguments([128]);
}
public function testBuildInvalidArgumentsEmptyValue()
{
$this->setExpectedException(InvalidCommandArgumentException::class, 'Invalid command arguments. Arguments for command Disque\\Command\\Enqueue: [""]');
$c = new Enqueue();
$c->setArguments([""]);
}
public function testBuild()
{
$c = new Enqueue();
$c->setArguments(['id']);
$result = $c->getArguments();
$this->assertSame(['id'], $result);
}
public function testBuildSeveral()
{
$c = new Enqueue();
$c->setArguments(['id', 'id2']);
$result = $c->getArguments();
$this->assertSame(['id', 'id2'], $result);
}
public function testParseInvalidNonNumericArray()
{
$this->setExpectedException(InvalidResponseException::class, 'Invalid command response. Command Disque\\Command\\Enqueue got: ["test"]');
$c = new Enqueue();
$c->parse(['test']);
}
public function testParseInvalidNonNumericString()
{
$this->setExpectedException(InvalidResponseException::class, 'Invalid command response. Command Disque\\Command\\Enqueue got: "test"');
$c = new Enqueue();
$c->parse('test');
}
public function testParse()
{
$c = new Enqueue();
$result = $c->parse('128');
$this->assertSame(128, $result);
}
} | php | MIT | 56cf00d97e739fec861717484657dbef2888df60 | 2026-01-05T05:12:23.969054Z | false |
mariano/disque-php | https://github.com/mariano/disque-php/blob/56cf00d97e739fec861717484657dbef2888df60/tests/Command/GetJobTest.php | tests/Command/GetJobTest.php | <?php
namespace Disque\Test\Command;
use PHPUnit_Framework_TestCase;
use Disque\Command\Argument\InvalidCommandArgumentException;
use Disque\Command\Argument\InvalidOptionException;
use Disque\Command\CommandInterface;
use Disque\Command\GetJob;
use Disque\Command\Response\InvalidResponseException;
use Disque\Command\Response\JobsResponse AS Response;
use Disque\Command\Response\JobsWithQueueResponse AS Queue;
use Disque\Command\Response\JobsWithCountersResponse AS Counters;
class GetJobTest extends PHPUnit_Framework_TestCase
{
public function testInstance()
{
$c = new GetJob();
$this->assertInstanceOf(CommandInterface::class, $c);
}
public function testGetCommand()
{
$c = new GetJob();
$result = $c->getCommand();
$this->assertSame('GETJOB', $result);
}
public function testIsBlocking()
{
$c = new GetJob();
$result = $c->isBlocking();
$this->assertTrue($result);
}
public function testBuildInvalidArgumentsEmpty()
{
$this->setExpectedException(InvalidCommandArgumentException::class, 'Invalid command arguments. Arguments for command Disque\\Command\\GetJob: []');
$c = new GetJob();
$c->setArguments([]);
}
public function testBuildInvalidArgumentsEmptyNonString()
{
$this->setExpectedException(InvalidCommandArgumentException::class, 'Invalid command arguments. Arguments for command Disque\\Command\\GetJob: [false,"test","stuff"]');
$c = new GetJob();
$c->setArguments([false, 'test', 'stuff']);
}
public function testBuildInvalidArgumentsArrayNotLast()
{
$this->setExpectedException(InvalidCommandArgumentException::class, 'Invalid command arguments. Arguments for command Disque\\Command\\GetJob: [{"count":10},"q"]');
$c = new GetJob();
$c->setArguments([['count' => 10], 'q']);
}
public function testBuildInvalidOption()
{
$this->setExpectedException(InvalidOptionException::class, 'Invalid command options. Options for command Disque\\Command\\GetJob: {"test":"stuff"}');
$c = new GetJob();
$c->setArguments(['q1', 'q2', ['test' => 'stuff']]);
}
public function testBuildInvalidOptionWithValid()
{
$this->setExpectedException(InvalidOptionException::class, 'Invalid command options. Options for command Disque\\Command\\GetJob: {"test":"stuff","count":10}');
$c = new GetJob();
$c->setArguments(['q1', 'q2', ['test' => 'stuff', 'count' => 10]]);
}
public function testBuildInvalidOptionCountNonNumeric()
{
$this->setExpectedException(InvalidOptionException::class, 'Invalid command options. Options for command Disque\\Command\\GetJob: {"count":"stuff"}');
$c = new GetJob();
$c->setArguments(['q1', 'q2', ['count' => 'stuff']]);
}
public function testBuildInvalidOptionCountNonInt()
{
$this->setExpectedExceptionRegExp(InvalidOptionException::class, '/^Invalid command options. Options for command Disque\\\\Command\\\\GetJob: {"count":3.14\d*}$/');
$c = new GetJob();
$c->setArguments(['q1', 'q2', ['count' => 3.14]]);
}
public function testBuildInvalidOptionTimeoutNonNumeric()
{
$this->setExpectedException(InvalidOptionException::class, 'Invalid command options. Options for command Disque\\Command\\GetJob: {"timeout":"stuff"}');
$c = new GetJob();
$c->setArguments(['q1', 'q2', ['timeout' => 'stuff']]);
}
public function testBuildInvalidOptionTimeoutNonInt()
{
$this->setExpectedExceptionRegExp(InvalidOptionException::class, '/^Invalid command options. Options for command Disque\\\\Command\\\\GetJob: {"timeout":3.14\d*}$/');
$c = new GetJob();
$c->setArguments(['q1', 'q2', ['timeout' => 3.14]]);
}
public function testBuild()
{
$c = new GetJob();
$c->setArguments(['test', 'stuff']);
$result = $c->getArguments();
$this->assertSame(['FROM', 'test', 'stuff'], $result);
}
public function testBuildOptionTimeout()
{
$c = new GetJob();
$c->setArguments(['q1', 'q2', ['timeout' => 3000]]);
$result = $c->getArguments();
$this->assertSame(['TIMEOUT', 3000, 'FROM', 'q1', 'q2'], $result);
}
public function testBuildOptionCount()
{
$c = new GetJob();
$c->setArguments(['q1', 'q2', ['count' => 10]]);
$result = $c->getArguments();
$this->assertSame(['COUNT', 10, 'FROM', 'q1', 'q2'], $result);
}
public function testBuildOptionTimeoutAndCount()
{
$c = new GetJob();
$c->setArguments(['q1', 'q2', ['count' => 10, 'timeout' => 3000]]);
$result = $c->getArguments();
$this->assertSame(['TIMEOUT', 3000, 'COUNT', 10, 'FROM', 'q1', 'q2'], $result);
}
public function testBuildOptionWithCounters()
{
$c = new GetJob();
$c->setArguments(['q1', 'q2', ['withcounters' => true]]);
$result = $c->getArguments();
$this->assertSame(['WITHCOUNTERS', 'FROM', 'q1', 'q2'], $result);
}
public function testBuildOptionWithNohang()
{
$c = new GetJob();
$c->setArguments(['q1', 'q2', ['nohang' => true]]);
$result = $c->getArguments();
$this->assertSame(['NOHANG', 'FROM', 'q1', 'q2'], $result);
}
public function testParseInvalidString()
{
$this->setExpectedException(InvalidResponseException::class, 'Invalid command response. Command Disque\\Command\\GetJob got: "test"');
$c = new GetJob();
$c->parse('test');
}
public function testParseInvalidArrayElementsNonArray()
{
$this->setExpectedException(InvalidResponseException::class, 'Invalid command response. Command Disque\\Command\\GetJob got: ["test","stuff"]');
$c = new GetJob();
$c->parse(['test', 'stuff']);
}
public function testParseInvalidArrayElementsSomeNonArray()
{
$this->setExpectedException(InvalidResponseException::class, 'Invalid command response. Command Disque\\Command\\GetJob got: [["test","stuff","val"],"stuff"]');
$c = new GetJob();
$c->parse([['test', 'stuff', 'val'], 'stuff']);
}
public function testParseInvalidArrayElementsNon0()
{
$this->setExpectedException(InvalidResponseException::class, 'Invalid command response. Command Disque\\Command\\GetJob got: [{"1":"test","2":"stuff","3":"val"}]');
$c = new GetJob();
$c->parse([[1=>'test', 2=>'stuff', 3=>'val']]);
}
public function testParseInvalidArrayElementsNon1()
{
$this->setExpectedException(InvalidResponseException::class, 'Invalid command response. Command Disque\\Command\\GetJob got: [{"0":"test","2":"stuff","3":"val"}]');
$c = new GetJob();
$c->parse([[0=>'test', 2=>'stuff', 3=>'val']]);
}
public function testParseInvalidArrayElementsNon2()
{
$this->setExpectedException(InvalidResponseException::class, 'Invalid command response. Command Disque\\Command\\GetJob got: [{"0":"test","1":"stuff","3":"val"}]');
$c = new GetJob();
$c->parse([[0=>'test', 1=>'stuff', 3=>'val']]);
}
public function testParse()
{
$c = new GetJob();
$queue = 'q';
$id = 'D-0f0c644fd3ccb51c2cedbd47fcb6f312646c993c05a0SQ';
$body = 'lorem ipsum';
$response = [$queue, $id, $body];
$parsedResponse = $c->parse([$response]);
$this->assertSame([
[
Queue::KEY_QUEUE => $queue,
Response::KEY_ID => $id,
Response::KEY_BODY => $body,
]
], $parsedResponse);
}
public function testParseUnicode()
{
$c = new GetJob();
$queue = 'q';
$id = 'D-0f0c644fd3ccb51c2cedbd47fcb6f312646c993c05a0SQ';
$body = '大';
$response = [$queue, $id, $body];
$parsedResponse = $c->parse([$response]);
$this->assertSame([
[
Queue::KEY_QUEUE => $queue,
Response::KEY_ID => $id,
Response::KEY_BODY => $body,
]
], $parsedResponse);
}
public function testParseWithCounters()
{
$c = new GetJob();
// Set the responseHandler to JobsWithCountersResponse
$c->setArguments(['q1', ['withcounters' => true]]);
$queue = 'q';
$id = 'D-0f0c644fd3ccb51c2cedbd47fcb6f312646c993c05a0SQ';
$body = 'lorem ipsum';
$nacks = 1;
$ad = 2;
$response = [$queue, $id, $body, 'nacks', $nacks, 'additional-deliveries', $ad];
$parsedResponse = $c->parse([$response]);
$this->assertSame([
[
Queue::KEY_QUEUE => $queue,
Response::KEY_ID => $id,
Response::KEY_BODY => $body,
Counters::KEY_NACKS => $nacks,
Counters::KEY_ADDITIONAL_DELIVERIES => $ad
]
], $parsedResponse);
}
}
| php | MIT | 56cf00d97e739fec861717484657dbef2888df60 | 2026-01-05T05:12:23.969054Z | false |
mariano/disque-php | https://github.com/mariano/disque-php/blob/56cf00d97e739fec861717484657dbef2888df60/tests/Command/QLenTest.php | tests/Command/QLenTest.php | <?php
namespace Disque\Test\Command;
use PHPUnit_Framework_TestCase;
use Disque\Command\Argument\InvalidCommandArgumentException;
use Disque\Command\CommandInterface;
use Disque\Command\QLen;
use Disque\Command\Response\InvalidResponseException;
class QLenTest extends PHPUnit_Framework_TestCase
{
public function testInstance()
{
$c = new QLen();
$this->assertInstanceOf(CommandInterface::class, $c);
}
public function testGetCommand()
{
$c = new QLen();
$result = $c->getCommand();
$this->assertSame('QLEN', $result);
}
public function testIsBlocking()
{
$c = new QLen();
$result = $c->isBlocking();
$this->assertFalse($result);
}
public function testBuildInvalidArgumentsEmpty()
{
$this->setExpectedException(InvalidCommandArgumentException::class, 'Invalid command arguments. Arguments for command Disque\\Command\\QLen: []');
$c = new QLen();
$c->setArguments([]);
}
public function testBuildInvalidArgumentsEmptyTooMany()
{
$this->setExpectedException(InvalidCommandArgumentException::class, 'Invalid command arguments. Arguments for command Disque\\Command\\QLen: ["test","stuff"]');
$c = new QLen();
$c->setArguments(['test', 'stuff']);
}
public function testBuildInvalidArgumentsEmptyNonNumeric()
{
$this->setExpectedException(InvalidCommandArgumentException::class, 'Invalid command arguments. Arguments for command Disque\\Command\\QLen: {"test":"stuff"}');
$c = new QLen();
$c->setArguments(['test' => 'stuff']);
}
public function testBuildInvalidArgumentsNumericNon0()
{
$this->setExpectedException(InvalidCommandArgumentException::class, 'Invalid command arguments. Arguments for command Disque\\Command\\QLen: {"1":"stuff"}');
$c = new QLen();
$c->setArguments([1 => 'stuff']);
}
public function testBuildInvalidArgumentsNonString()
{
$this->setExpectedException(InvalidCommandArgumentException::class, 'Invalid command arguments. Arguments for command Disque\\Command\\QLen: [false]');
$c = new QLen();
$c->setArguments([false]);
}
public function testBuild()
{
$c = new QLen();
$c->setArguments(['test']);
$result = $c->getArguments();
$this->assertSame(['test'], $result);
}
public function testParseInvalidNonNumericArray()
{
$this->setExpectedException(InvalidResponseException::class, 'Invalid command response. Command Disque\\Command\\QLen got: ["test"]');
$c = new QLen();
$c->parse(['test']);
}
public function testParseInvalidNonNumericString()
{
$this->setExpectedException(InvalidResponseException::class, 'Invalid command response. Command Disque\\Command\\QLen got: "test"');
$c = new QLen();
$c->parse('test');
}
public function testParse()
{
$c = new QLen();
$result = $c->parse('128');
$this->assertSame(128, $result);
}
} | php | MIT | 56cf00d97e739fec861717484657dbef2888df60 | 2026-01-05T05:12:23.969054Z | false |
mariano/disque-php | https://github.com/mariano/disque-php/blob/56cf00d97e739fec861717484657dbef2888df60/tests/Command/FastAckTest.php | tests/Command/FastAckTest.php | <?php
namespace Disque\Test\Command;
use PHPUnit_Framework_TestCase;
use Disque\Command\Argument\InvalidCommandArgumentException;
use Disque\Command\CommandInterface;
use Disque\Command\FastAck;
use Disque\Command\Response\InvalidResponseException;
class FastAckTest extends PHPUnit_Framework_TestCase
{
public function testInstance()
{
$c = new FastAck();
$this->assertInstanceOf(CommandInterface::class, $c);
}
public function testGetCommand()
{
$c = new FastAck();
$result = $c->getCommand();
$this->assertSame('FASTACK', $result);
}
public function testIsBlocking()
{
$c = new FastAck();
$result = $c->isBlocking();
$this->assertFalse($result);
}
public function testBuildInvalidArgumentsEmpty()
{
$this->setExpectedException(InvalidCommandArgumentException::class, 'Invalid command arguments. Arguments for command Disque\\Command\\FastAck: []');
$c = new FastAck();
$c->setArguments([]);
}
public function testBuildInvalidArgumentsNonStringArray()
{
$this->setExpectedException(InvalidCommandArgumentException::class, 'Invalid command arguments. Arguments for command Disque\\Command\\FastAck: [["test","stuff"]]');
$c = new FastAck();
$c->setArguments([['test','stuff']]);
}
public function testBuildInvalidArgumentsNonStringNumeric()
{
$this->setExpectedException(InvalidCommandArgumentException::class, 'Invalid command arguments. Arguments for command Disque\\Command\\FastAck: [128]');
$c = new FastAck();
$c->setArguments([128]);
}
public function testBuildInvalidArgumentsEmptyValue()
{
$this->setExpectedException(InvalidCommandArgumentException::class, 'Invalid command arguments. Arguments for command Disque\\Command\\FastAck: [""]');
$c = new FastAck();
$c->setArguments([""]);
}
public function testBuild()
{
$c = new FastAck();
$c->setArguments(['id']);
$result = $c->getArguments();
$this->assertSame(['id'], $result);
}
public function testBuildSeveral()
{
$c = new FastAck();
$c->setArguments(['id', 'id2']);
$result = $c->getArguments();
$this->assertSame(['id', 'id2'], $result);
}
public function testParseInvalidNonNumericArray()
{
$this->setExpectedException(InvalidResponseException::class, 'Invalid command response. Command Disque\\Command\\FastAck got: ["test"]');
$c = new FastAck();
$c->parse(['test']);
}
public function testParseInvalidNonNumericString()
{
$this->setExpectedException(InvalidResponseException::class, 'Invalid command response. Command Disque\\Command\\FastAck got: "test"');
$c = new FastAck();
$c->parse('test');
}
public function testParse()
{
$c = new FastAck();
$result = $c->parse('128');
$this->assertSame(128, $result);
}
} | php | MIT | 56cf00d97e739fec861717484657dbef2888df60 | 2026-01-05T05:12:23.969054Z | false |
mariano/disque-php | https://github.com/mariano/disque-php/blob/56cf00d97e739fec861717484657dbef2888df60/tests/Command/QPeekTest.php | tests/Command/QPeekTest.php | <?php
namespace Disque\Test\Command;
use PHPUnit_Framework_TestCase;
use Disque\Command\Argument\InvalidCommandArgumentException;
use Disque\Command\CommandInterface;
use Disque\Command\QPeek;
use Disque\Command\Response\InvalidResponseException;
class QPeekTest extends PHPUnit_Framework_TestCase
{
public function testInstance()
{
$c = new QPeek();
$this->assertInstanceOf(CommandInterface::class, $c);
}
public function testGetCommand()
{
$c = new QPeek();
$result = $c->getCommand();
$this->assertSame('QPEEK', $result);
}
public function testIsBlocking()
{
$c = new QPeek();
$result = $c->isBlocking();
$this->assertFalse($result);
}
public function testBuildInvalidArgumentsEmpty()
{
$this->setExpectedException(InvalidCommandArgumentException::class, 'Invalid command arguments. Arguments for command Disque\\Command\\QPeek: []');
$c = new QPeek();
$c->setArguments([]);
}
public function testBuildInvalidArgumentsEmptyTooMany()
{
$this->setExpectedException(InvalidCommandArgumentException::class, 'Invalid command arguments. Arguments for command Disque\\Command\\QPeek: ["test","stuff","arg"]');
$c = new QPeek();
$c->setArguments(['test', 'stuff', 'arg']);
}
public function testBuildInvalidArgumentsEmptyNonNumeric()
{
$this->setExpectedException(InvalidCommandArgumentException::class, 'Invalid command arguments. Arguments for command Disque\\Command\\QPeek: {"test":"stuff","arg":"val"}');
$c = new QPeek();
$c->setArguments(['test' => 'stuff', 'arg' => 'val']);
}
public function testBuildInvalidArgumentsNumericNon0()
{
$this->setExpectedException(InvalidCommandArgumentException::class, 'Invalid command arguments. Arguments for command Disque\\Command\\QPeek: {"1":"stuff","2":"test"}');
$c = new QPeek();
$c->setArguments([1 => 'stuff', 2 => 'test']);
}
public function testBuildInvalidArgumentsNumericNon1()
{
$this->setExpectedException(InvalidCommandArgumentException::class, 'Invalid command arguments. Arguments for command Disque\\Command\\QPeek: {"0":"stuff","2":"test"}');
$c = new QPeek();
$c->setArguments([0 => 'stuff', 2 => 'test']);
}
public function testBuildInvalidArgumentsNonString()
{
$this->setExpectedException(InvalidCommandArgumentException::class, 'Invalid command arguments. Arguments for command Disque\\Command\\QPeek: [false,"test"]');
$c = new QPeek();
$c->setArguments([false, 'test']);
}
public function testBuildInvalidArgumentsNonNumeric()
{
$this->setExpectedException(InvalidCommandArgumentException::class, 'Invalid command arguments. Arguments for command Disque\\Command\\QPeek: ["test","stuff"]');
$c = new QPeek();
$c->setArguments(['test', 'stuff']);
}
public function testBuildInvalidArgumentsNonInt()
{
$this->setExpectedExceptionRegExp(InvalidCommandArgumentException::class, '/^Invalid command arguments. Arguments for command Disque\\\\Command\\\\QPeek: \["test",3.14\d*\]$/');
$c = new QPeek();
$c->setArguments(['test', 3.14]);
}
public function testBuild()
{
$c = new QPeek();
$c->setArguments(['test', 78]);
$result = $c->getArguments();
$this->assertSame(['test', 78], $result);
}
public function testParse()
{
$c = new QPeek();
$result = $c->parse([['queue', 'D-0f0c644fd3ccb51c2cedbd47fcb6f312646c993c05a0SQ', 'stuff']]);
$this->assertSame([
[
'queue' => 'queue',
'id' => 'D-0f0c644fd3ccb51c2cedbd47fcb6f312646c993c05a0SQ',
'body' => 'stuff'
]
], $result);
}
} | php | MIT | 56cf00d97e739fec861717484657dbef2888df60 | 2026-01-05T05:12:23.969054Z | false |
mariano/disque-php | https://github.com/mariano/disque-php/blob/56cf00d97e739fec861717484657dbef2888df60/tests/Command/QScanTest.php | tests/Command/QScanTest.php | <?php
namespace Disque\Test\Command;
use PHPUnit_Framework_TestCase;
use Disque\Command\QScan;
use Disque\Command\Argument\InvalidCommandArgumentException;
use Disque\Command\Argument\InvalidOptionException;
use Disque\Command\CommandInterface;
use Disque\Command\Response\InvalidResponseException;
class QScanTest extends PHPUnit_Framework_TestCase
{
public function testInstance()
{
$c = new QScan();
$this->assertInstanceOf(CommandInterface::class, $c);
}
public function testGetCommand()
{
$c = new QScan();
$result = $c->getCommand();
$this->assertSame('QSCAN', $result);
}
public function testIsBlocking()
{
$c = new QScan();
$result = $c->isBlocking();
$this->assertFalse($result);
}
public function testBuildInvalidArgumentTooMany()
{
$this->setExpectedException(InvalidCommandArgumentException::class, 'Invalid command arguments. Arguments for command Disque\\Command\\QScan: [0,{"count":10},["stuff"]]');
$c = new QScan();
$c->setArguments([0, ['count' => 10], ['stuff']]);
}
public function testBuildInvalidArgument0NotSet()
{
$this->setExpectedException(InvalidCommandArgumentException::class, 'Invalid command arguments. Arguments for command Disque\\Command\\QScan: {"2":0,"1":{"count":10}}');
$c = new QScan();
$c->setArguments([2=>0, 1=>['count' => 10]]);
}
public function testBuildInvalidCursorNotNumeric()
{
$this->setExpectedException(InvalidCommandArgumentException::class, 'Invalid command arguments. Arguments for command Disque\\Command\\QScan: ["test"]');
$c = new QScan();
$c->setArguments(['test']);
}
public function testBuildInvalidArgument1NotSet()
{
$this->setExpectedException(InvalidCommandArgumentException::class, 'Invalid command arguments. Arguments for command Disque\\Command\\QScan: {"0":0,"2":{"count":10}}');
$c = new QScan();
$c->setArguments([0=>0, 2=>['count' => 10]]);
}
public function testBuildInvalidArgumentOptionsNonArray()
{
$this->setExpectedException(InvalidCommandArgumentException::class, 'Invalid command arguments. Arguments for command Disque\\Command\\QScan: [0,"test"]');
$c = new QScan();
$c->setArguments([0, 'test']);
}
public function testBuildInvalidOption()
{
$this->setExpectedException(InvalidOptionException::class, 'Invalid command options. Options for command Disque\\Command\\QScan: {"test":"stuff"}');
$c = new QScan();
$c->setArguments([0, ['test' => 'stuff']]);
}
public function testBuildInvalidOptionWithValid()
{
$this->setExpectedException(InvalidOptionException::class, 'Invalid command options. Options for command Disque\\Command\\QScan: {"test":"stuff","count":10}');
$c = new QScan();
$c->setArguments([0, ['test' => 'stuff', 'count' => 10]]);
}
public function testBuildInvalidOptionMinlenNonNumeric()
{
$this->setExpectedException(InvalidOptionException::class, 'Invalid command options. Options for command Disque\\Command\\QScan: {"minlen":"stuff"}');
$c = new QScan();
$c->setArguments([0, ['minlen' => 'stuff']]);
}
public function testBuildInvalidOptionMinlenNonInt()
{
$this->setExpectedExceptionRegExp(InvalidOptionException::class, '/^Invalid command options. Options for command Disque\\\\Command\\\\QScan: {"minlen":3.14\d*}$/');
$c = new QScan();
$c->setArguments([0, ['minlen' => 3.14]]);
}
public function testBuildInvalidOptionMaxlenNonNumeric()
{
$this->setExpectedException(InvalidOptionException::class, 'Invalid command options. Options for command Disque\\Command\\QScan: {"maxlen":"stuff"}');
$c = new QScan();
$c->setArguments([0, ['maxlen' => 'stuff']]);
}
public function testBuildInvalidOptionMaxlenNonInt()
{
$this->setExpectedExceptionRegExp(InvalidOptionException::class, '/^Invalid command options. Options for command Disque\\\\Command\\\\QScan: {"maxlen":3.14\d*}$/');
$c = new QScan();
$c->setArguments([0, ['maxlen' => 3.14]]);
}
public function testBuildInvalidOptionImportrateNonNumeric()
{
$this->setExpectedException(InvalidOptionException::class, 'Invalid command options. Options for command Disque\\Command\\QScan: {"importrate":"stuff"}');
$c = new QScan();
$c->setArguments([0, ['importrate' => 'stuff']]);
}
public function testBuildInvalidOptionImportrateNonInt()
{
$this->setExpectedExceptionRegExp(InvalidOptionException::class, '/^Invalid command options. Options for command Disque\\\\Command\\\\QScan: {"importrate":3.14\d*}$/');
$c = new QScan();
$c->setArguments([0, ['importrate' => 3.14]]);
}
public function testBuildNoArguments()
{
$c = new QScan();
$c->setArguments([]);
$result = $c->getArguments();
$this->assertSame([0], $result);
}
public function testBuildOptionCount()
{
$c = new QScan();
$c->setArguments([0, ['count' => 10]]);
$result = $c->getArguments();
$this->assertSame([0, 'COUNT', 10], $result);
}
public function testBuildOptionMinlen()
{
$c = new QScan();
$c->setArguments([0, ['minlen' => 3000]]);
$result = $c->getArguments();
$this->assertSame([0, 'MINLEN', 3000], $result);
}
public function testBuildOptionBusyloop()
{
$c = new QScan();
$c->setArguments([0, ['busyloop' => true]]);
$result = $c->getArguments();
$this->assertSame([0, 'BUSYLOOP'], $result);
}
public function testBuildOptionBusyloopAndMinlen()
{
$c = new QScan();
$c->setArguments([0, ['busyloop' => true, 'minlen' => 3000]]);
$result = $c->getArguments();
$this->assertSame([0, 'BUSYLOOP', 'MINLEN', 3000], $result);
}
public function testBuildOptionMaxlen()
{
$c = new QScan();
$c->setArguments([0, ['maxlen' => 5]]);
$result = $c->getArguments();
$this->assertSame([0, 'MAXLEN', 5], $result);
}
public function testBuildOptionImportrate()
{
$c = new QScan();
$c->setArguments([0, ['importrate' => 3000]]);
$result = $c->getArguments();
$this->assertSame([0, 'IMPORTRATE', 3000], $result);
}
public function testBuildCursor()
{
$c = new QScan();
$c->setArguments([1]);
$result = $c->getArguments();
$this->assertSame([1], $result);
}
public function testBuildCursorAndOptions()
{
$c = new QScan();
$c->setArguments([1, ['count' => 10, 'maxlen' => 3]]);
$result = $c->getArguments();
$this->assertSame([1, 'COUNT', 10, 'MAXLEN', 3], $result);
}
public function testParseInvalidNonArray()
{
$this->setExpectedException(InvalidResponseException::class, 'Invalid command response. Command Disque\\Command\\QScan got: 10');
$c = new QScan();
$c->parse(10);
}
public function testParseWithNextCursor()
{
$c = new QScan();
$result = $c->parse(['1', ['queue1', 'queue2']]);
$this->assertSame([
'finished' => false,
'nextCursor' => 1,
'queues' => [
'queue1',
'queue2'
]
], $result);
}
public function testParseFinished()
{
$c = new QScan();
$result = $c->parse(['0', ['queue1', 'queue2']]);
$this->assertSame([
'finished' => true,
'nextCursor' => 0,
'queues' => [
'queue1',
'queue2'
]
], $result);
}
} | php | MIT | 56cf00d97e739fec861717484657dbef2888df60 | 2026-01-05T05:12:23.969054Z | false |
mariano/disque-php | https://github.com/mariano/disque-php/blob/56cf00d97e739fec861717484657dbef2888df60/tests/Command/DequeueTest.php | tests/Command/DequeueTest.php | <?php
namespace Disque\Test\Command;
use PHPUnit_Framework_TestCase;
use Disque\Command\Argument\InvalidCommandArgumentException;
use Disque\Command\CommandInterface;
use Disque\Command\Dequeue;
use Disque\Command\Response\InvalidResponseException;
class DequeueTest extends PHPUnit_Framework_TestCase
{
public function testInstance()
{
$c = new Dequeue();
$this->assertInstanceOf(CommandInterface::class, $c);
}
public function testGetCommand()
{
$c = new Dequeue();
$result = $c->getCommand();
$this->assertSame('DEQUEUE', $result);
}
public function testIsBlocking()
{
$c = new Dequeue();
$result = $c->isBlocking();
$this->assertFalse($result);
}
public function testBuildInvalidArgumentsEmpty()
{
$this->setExpectedException(InvalidCommandArgumentException::class, 'Invalid command arguments. Arguments for command Disque\\Command\\Dequeue: []');
$c = new Dequeue();
$c->setArguments([]);
}
public function testBuildInvalidArgumentsNonStringArray()
{
$this->setExpectedException(InvalidCommandArgumentException::class, 'Invalid command arguments. Arguments for command Disque\\Command\\Dequeue: [["test","stuff"]]');
$c = new Dequeue();
$c->setArguments([['test','stuff']]);
}
public function testBuildInvalidArgumentsNonStringNumeric()
{
$this->setExpectedException(InvalidCommandArgumentException::class, 'Invalid command arguments. Arguments for command Disque\\Command\\Dequeue: [128]');
$c = new Dequeue();
$c->setArguments([128]);
}
public function testBuildInvalidArgumentsEmptyValue()
{
$this->setExpectedException(InvalidCommandArgumentException::class, 'Invalid command arguments. Arguments for command Disque\\Command\\Dequeue: [""]');
$c = new Dequeue();
$c->setArguments([""]);
}
public function testBuild()
{
$c = new Dequeue();
$c->setArguments(['id']);
$result = $c->getArguments();
$this->assertSame(['id'], $result);
}
public function testBuildSeveral()
{
$c = new Dequeue();
$c->setArguments(['id', 'id2']);
$result = $c->getArguments();
$this->assertSame(['id', 'id2'], $result);
}
public function testParseInvalidNonNumericArray()
{
$this->setExpectedException(InvalidResponseException::class, 'Invalid command response. Command Disque\\Command\\Dequeue got: ["test"]');
$c = new Dequeue();
$c->parse(['test']);
}
public function testParseInvalidNonNumericString()
{
$this->setExpectedException(InvalidResponseException::class, 'Invalid command response. Command Disque\\Command\\Dequeue got: "test"');
$c = new Dequeue();
$c->parse('test');
}
public function testParse()
{
$c = new Dequeue();
$result = $c->parse('128');
$this->assertSame(128, $result);
}
} | php | MIT | 56cf00d97e739fec861717484657dbef2888df60 | 2026-01-05T05:12:23.969054Z | false |
mariano/disque-php | https://github.com/mariano/disque-php/blob/56cf00d97e739fec861717484657dbef2888df60/tests/Command/ShowTest.php | tests/Command/ShowTest.php | <?php
namespace Disque\Test\Command;
use PHPUnit_Framework_TestCase;
use Disque\Command\Argument\InvalidCommandArgumentException;
use Disque\Command\CommandInterface;
use Disque\Command\Show;
use Disque\Command\Response\InvalidResponseException;
class ShowTest extends PHPUnit_Framework_TestCase
{
public function testInstance()
{
$c = new Show();
$this->assertInstanceOf(CommandInterface::class, $c);
}
public function testGetCommand()
{
$c = new Show();
$result = $c->getCommand();
$this->assertSame('SHOW', $result);
}
public function testIsBlocking()
{
$c = new Show();
$result = $c->isBlocking();
$this->assertFalse($result);
}
public function testBuildInvalidArgumentsEmpty()
{
$this->setExpectedException(InvalidCommandArgumentException::class, 'Invalid command arguments. Arguments for command Disque\\Command\\Show: []');
$c = new Show();
$c->setArguments([]);
}
public function testBuildInvalidArgumentsEmptyTooMany()
{
$this->setExpectedException(InvalidCommandArgumentException::class, 'Invalid command arguments. Arguments for command Disque\\Command\\Show: ["test","stuff"]');
$c = new Show();
$c->setArguments(['test', 'stuff']);
}
public function testBuildInvalidArgumentsEmptyNonNumeric()
{
$this->setExpectedException(InvalidCommandArgumentException::class, 'Invalid command arguments. Arguments for command Disque\\Command\\Show: {"test":"stuff"}');
$c = new Show();
$c->setArguments(['test' => 'stuff']);
}
public function testBuildInvalidArgumentsNumericNon0()
{
$this->setExpectedException(InvalidCommandArgumentException::class, 'Invalid command arguments. Arguments for command Disque\\Command\\Show: {"1":"stuff"}');
$c = new Show();
$c->setArguments([1 => 'stuff']);
}
public function testBuildInvalidArgumentsNonString()
{
$this->setExpectedException(InvalidCommandArgumentException::class, 'Invalid command arguments. Arguments for command Disque\\Command\\Show: [false]');
$c = new Show();
$c->setArguments([false]);
}
public function testBuild()
{
$c = new Show();
$c->setArguments(['test']);
$result = $c->getArguments();
$this->assertSame(['test'], $result);
}
public function testParseInvalidNonArrayString()
{
$this->setExpectedException(InvalidResponseException::class, 'Invalid command response. Command Disque\\Command\\Show got: "test"');
$c = new Show();
$c->parse('test');
}
public function testParseInvalidEmptyArray()
{
$this->setExpectedException(InvalidResponseException::class, 'Invalid command response. Command Disque\\Command\\Show got: []');
$c = new Show();
$c->parse([]);
}
public function testParseInvalidOddArray()
{
$this->setExpectedException(InvalidResponseException::class, 'Invalid command response. Command Disque\\Command\\Show got: ["odd","elements","array"]');
$c = new Show();
$c->parse(['odd','elements','array']);
}
public function testParseEmpty()
{
$c = new Show();
$result = $c->parse(false);
$this->assertNull($result);
}
public function testParse()
{
$c = new Show();
$result = $c->parse([
'key1',
'value1',
'key2',
'value2'
]);
$this->assertSame([
'key1' => 'value1',
'key2' => 'value2'
], $result);
}
} | php | MIT | 56cf00d97e739fec861717484657dbef2888df60 | 2026-01-05T05:12:23.969054Z | false |
mariano/disque-php | https://github.com/mariano/disque-php/blob/56cf00d97e739fec861717484657dbef2888df60/tests/Command/JScanTest.php | tests/Command/JScanTest.php | <?php
namespace Disque\Test\Command;
use PHPUnit_Framework_TestCase;
use Disque\Command\JScan;
use Disque\Command\Argument\InvalidCommandArgumentException;
use Disque\Command\Argument\InvalidOptionException;
use Disque\Command\CommandInterface;
use Disque\Command\Response\InvalidResponseException;
class JScanTest extends PHPUnit_Framework_TestCase
{
public function testInstance()
{
$c = new JScan();
$this->assertInstanceOf(CommandInterface::class, $c);
}
public function testGetCommand()
{
$c = new JScan();
$result = $c->getCommand();
$this->assertSame('JSCAN', $result);
}
public function testIsBlocking()
{
$c = new JScan();
$result = $c->isBlocking();
$this->assertFalse($result);
}
public function testBuildInvalidArgumentTooMany()
{
$this->setExpectedException(InvalidCommandArgumentException::class, 'Invalid command arguments. Arguments for command Disque\\Command\\JScan: [0,{"count":10},["stuff"]]');
$c = new JScan();
$c->setArguments([0, ['count' => 10], ['stuff']]);
}
public function testBuildInvalidArgument0NotSet()
{
$this->setExpectedException(InvalidCommandArgumentException::class, 'Invalid command arguments. Arguments for command Disque\\Command\\JScan: {"2":0,"1":{"count":10}}');
$c = new JScan();
$c->setArguments([2=>0, 1=>['count' => 10]]);
}
public function testBuildInvalidCursorNotNumeric()
{
$this->setExpectedException(InvalidCommandArgumentException::class, 'Invalid command arguments. Arguments for command Disque\\Command\\JScan: ["test"]');
$c = new JScan();
$c->setArguments(['test']);
}
public function testBuildInvalidArgument1NotSet()
{
$this->setExpectedException(InvalidCommandArgumentException::class, 'Invalid command arguments. Arguments for command Disque\\Command\\JScan: {"0":0,"2":{"count":10}}');
$c = new JScan();
$c->setArguments([0=>0, 2=>['count' => 10]]);
}
public function testBuildInvalidArgumentOptionsNonArray()
{
$this->setExpectedException(InvalidCommandArgumentException::class, 'Invalid command arguments. Arguments for command Disque\\Command\\JScan: [0,"test"]');
$c = new JScan();
$c->setArguments([0, 'test']);
}
public function testBuildInvalidOption()
{
$this->setExpectedException(InvalidOptionException::class, 'Invalid command options. Options for command Disque\\Command\\JScan: {"test":"stuff"}');
$c = new JScan();
$c->setArguments([0, ['test' => 'stuff']]);
}
public function testBuildInvalidOptionWithValid()
{
$this->setExpectedException(InvalidOptionException::class, 'Invalid command options. Options for command Disque\\Command\\JScan: {"test":"stuff","count":10}');
$c = new JScan();
$c->setArguments([0, ['test' => 'stuff', 'count' => 10]]);
}
public function testBuildInvalidOptionCountNonNumeric()
{
$this->setExpectedException(InvalidOptionException::class, 'Invalid command options. Options for command Disque\\Command\\JScan: {"count":"stuff"}');
$c = new JScan();
$c->setArguments([0, ['count' => 'stuff']]);
}
public function testBuildInvalidOptionCountNonInt()
{
$this->setExpectedExceptionRegExp(InvalidOptionException::class, '/^Invalid command options. Options for command Disque\\\\Command\\\\JScan: {"count":3.14\d*}$/');
$c = new JScan();
$c->setArguments([0, ['count' => 3.14]]);
}
public function testBuildInvalidOptionQueueNonString()
{
$this->setExpectedException(InvalidOptionException::class, 'Invalid command options. Options for command Disque\\Command\\JScan: {"queue":["urgent","low"]}');
$c = new JScan();
$c->setArguments([0, ['queue' => ["urgent", "low"]]]);
}
public function testBuildInvalidOptionStateNonArray()
{
$this->setExpectedException(InvalidOptionException::class, 'Invalid command options. Options for command Disque\\Command\\JScan: {"state":"acked"}');
$c = new JScan();
$c->setArguments([0, ['state' => 'acked']]);
}
public function testBuildInvalidOptionReplyNonString()
{
$this->setExpectedException(InvalidOptionException::class, 'Invalid command options. Options for command Disque\\Command\\JScan: {"reply":10}');
$c = new JScan();
$c->setArguments([0, ['reply' => 10]]);
}
public function testBuildNoArguments()
{
$c = new JScan();
$c->setArguments([]);
$result = $c->getArguments();
$this->assertSame([0], $result);
}
public function testBuildOptionCount()
{
$c = new JScan();
$c->setArguments([0, ['count' => 10]]);
$result = $c->getArguments();
$this->assertSame([0, 'COUNT', 10], $result);
}
public function testBuildOptionBusyloop()
{
$c = new JScan();
$c->setArguments([0, ['busyloop' => true]]);
$result = $c->getArguments();
$this->assertSame([0, 'BUSYLOOP'], $result);
}
public function testBuildOptionBusyloopAndCount()
{
$c = new JScan();
$c->setArguments([0, ['busyloop' => true, 'count' => 10]]);
$result = $c->getArguments();
$this->assertSame([0, 'BUSYLOOP', 'COUNT', 10], $result);
}
public function testBuildOptionQueue()
{
$c = new JScan();
$c->setArguments([0, ['queue' => 'urgent']]);
$result = $c->getArguments();
$this->assertSame([0, 'QUEUE', 'urgent'], $result);
}
public function testBuildOptionState()
{
$c = new JScan();
$c->setArguments([0, ['state' => ['wait-repl', 'active', 'queued', 'acked']]]);
$result = $c->getArguments();
$this->assertSame([0, 'STATE', 'wait-repl', 'STATE', 'active', 'STATE', 'queued', 'STATE', 'acked'], $result);
}
public function testBuildOptionReplyAll()
{
$c = new JScan();
$c->setArguments([0, ['reply' => 'all']]);
$result = $c->getArguments();
$this->assertSame([0, 'REPLY', 'all'], $result);
}
public function testBuildCursor()
{
$c = new JScan();
$c->setArguments([1]);
$result = $c->getArguments();
$this->assertSame([1], $result);
}
public function testBuildCursorAndOptions()
{
$c = new JScan();
$c->setArguments([1, ['count' => 10, 'queue' => 'urgent']]);
$result = $c->getArguments();
$this->assertSame([1, 'COUNT', 10, 'QUEUE', 'urgent'], $result);
}
public function testParseInvalidNonArray()
{
$this->setExpectedException(InvalidResponseException::class, 'Invalid command response. Command Disque\\Command\\JScan got: 10');
$c = new JScan();
$c->parse(10);
}
public function testParseWithNextCursor()
{
$c = new JScan();
$result = $c->parse(['1', ['D-01832ef7-7WpBQYzbmzaDw1QKykdGxlUi-05a1', 'D-19e14a24-dozLy1rAQPKa2kwIyEDnp5bT-05a1']]);
$this->assertSame([
'finished' => false,
'nextCursor' => 1,
'jobs' => [
['id' => 'D-01832ef7-7WpBQYzbmzaDw1QKykdGxlUi-05a1'],
['id' => 'D-19e14a24-dozLy1rAQPKa2kwIyEDnp5bT-05a1']
]
], $result);
}
public function testParseFinished()
{
$c = new JScan();
$result = $c->parse(['0', ['D-01832ef7-7WpBQYzbmzaDw1QKykdGxlUi-05a1', 'D-19e14a24-dozLy1rAQPKa2kwIyEDnp5bT-05a1']]);
$this->assertSame([
'finished' => true,
'nextCursor' => 0,
'jobs' => [
['id' => 'D-01832ef7-7WpBQYzbmzaDw1QKykdGxlUi-05a1'],
['id' => 'D-19e14a24-dozLy1rAQPKa2kwIyEDnp5bT-05a1']
]
], $result);
}
public function testParseDetailed()
{
$c = new JScan();
$result = $c->parse(['0', [
[
'id',
'D-01832ef7-7WpBQYzbmzaDw1QKykdGxlUi-05a1',
'queue',
'urgent',
'state',
'queued',
'repl',
2,
'ttl',
81110,
'ctime',
1462891579255000000,
'delay',
0,
'retry',
3,
'nacks',
0,
'additional-deliveries',
0,
'nodes-delivered',
[
'19e14a243511654800d052e0c6fefb54b955e59c',
'01832ef70ba88ff7dc935731fe35841612a9edf8'
],
'nodes-confirmed',
[],
'next-requeue-within',
784,
'next-awake-within',
284,
'body',
'{"name":"Claudia"}'
]
]]);
$this->assertSame([
'finished' => true,
'nextCursor' => 0,
'jobs' => [
[
'id' => 'D-01832ef7-7WpBQYzbmzaDw1QKykdGxlUi-05a1',
'queue' => 'urgent',
'state' => 'queued',
'repl' => 2,
'ttl' => 81110,
'ctime' => 1462891579255000000,
'delay' => 0,
'retry' => 3,
'nacks' => 0,
'additional-deliveries' => 0,
'nodes-delivered' => [
'19e14a243511654800d052e0c6fefb54b955e59c',
'01832ef70ba88ff7dc935731fe35841612a9edf8'
],
'nodes-confirmed' => [],
'next-requeue-within' => 784,
'next-awake-within' => 284,
'body' => '{"name":"Claudia"}'
],
]
], $result);
}
} | php | MIT | 56cf00d97e739fec861717484657dbef2888df60 | 2026-01-05T05:12:23.969054Z | false |
mariano/disque-php | https://github.com/mariano/disque-php/blob/56cf00d97e739fec861717484657dbef2888df60/tests/Command/HelloTest.php | tests/Command/HelloTest.php | <?php
namespace Disque\Test\Command;
use PHPUnit_Framework_TestCase;
use Disque\Command\Argument\InvalidCommandArgumentException;
use Disque\Command\CommandInterface;
use Disque\Command\Hello;
use Disque\Command\Response\InvalidResponseException;
class HelloTest extends PHPUnit_Framework_TestCase
{
public function testInstance()
{
$c = new Hello();
$this->assertInstanceOf(CommandInterface::class, $c);
}
public function testGetCommand()
{
$c = new Hello();
$result = $c->getCommand();
$this->assertSame('HELLO', $result);
}
public function testIsBlocking()
{
$c = new Hello();
$result = $c->isBlocking();
$this->assertFalse($result);
}
public function testBuildInvalidArguments()
{
$this->setExpectedException(InvalidCommandArgumentException::class, 'Invalid command arguments. Arguments for command Disque\\Command\\Hello: ["test"]');
$c = new Hello();
$c->setArguments(['test']);
}
public function testBuild()
{
$c = new Hello();
$c->setArguments([]);
$result = $c->getArguments();
$this->assertSame([], $result);
}
public function testParseInvalidNonArray()
{
$this->setExpectedException(InvalidResponseException::class, 'Invalid command response. Command Disque\\Command\\Hello got: "test"');
$c = new Hello();
$c->parse('test');
}
public function testParseInvalidEmptyArray()
{
$this->setExpectedException(InvalidResponseException::class, 'Invalid command response. Command Disque\\Command\\Hello got: []');
$c = new Hello();
$c->parse([]);
}
public function testParseInvalidArrayTooShort()
{
$this->setExpectedException(InvalidResponseException::class, 'Invalid command response. Command Disque\\Command\\Hello got: ["test"]');
$c = new Hello();
$c->parse(['test']);
}
public function testParseInvalidArray0NotSet()
{
$this->setExpectedException(InvalidResponseException::class, 'Invalid command response. Command Disque\\Command\\Hello got: {"test":"stuff","1":"more","2":"elements"}');
$c = new Hello();
$c->parse(['test'=>'stuff',1=>'more',2=>'elements']);
}
public function testParseInvalidArray1NotSet()
{
$this->setExpectedException(InvalidResponseException::class, 'Invalid command response. Command Disque\\Command\\Hello got: {"test":"stuff","0":"more","2":"elements"}');
$c = new Hello();
$c->parse(['test'=>'stuff',0=>'more',2=>'elements']);
}
public function testParseInvalidArray2NotSet()
{
$this->setExpectedException(InvalidResponseException::class, 'Invalid command response. Command Disque\\Command\\Hello got: {"test":"stuff","0":"more","1":"elements"}');
$c = new Hello();
$c->parse(['test'=>'stuff',0=>'more',1=>'elements']);
}
public function testParseInvalidNodeNotArray()
{
$this->setExpectedException(InvalidResponseException::class, 'Invalid command response. Command Disque\\Command\\Hello got: ["version","id","test"]');
$c = new Hello();
$c->parse(['version', 'id', 'test']);
}
public function testParseInvalidNodeEmpty()
{
$this->setExpectedException(InvalidResponseException::class, 'Invalid command response. Command Disque\\Command\\Hello got: ["version","id",[]]');
$c = new Hello();
$c->parse(['version', 'id', []]);
}
public function testParseInvalidNodeTooShort()
{
$this->setExpectedException(InvalidResponseException::class, 'Invalid command response. Command Disque\\Command\\Hello got: ["version","id",["one","two","three"]]');
$c = new Hello();
$c->parse(['version', 'id', ['one', 'two', 'three']]);
}
public function testParseInvalidNodeTooLong()
{
$this->setExpectedException(InvalidResponseException::class, 'Invalid command response. Command Disque\\Command\\Hello got: ["version","id",["one","two","three","four","five"]]');
$c = new Hello();
$c->parse(['version', 'id', ['one', 'two', 'three', 'four', 'five']]);
}
public function testParseInvalidNode0NotSet()
{
$this->setExpectedException(InvalidResponseException::class, 'Invalid command response. Command Disque\\Command\\Hello got: ["version","id",{"1":"one","2":"two","3":"three","4":"four"}]');
$c = new Hello();
$c->parse(['version', 'id', [1=>'one', 2=>'two', 3=>'three', 4=>'four']]);
}
public function testParseInvalidNode1NotSet()
{
$this->setExpectedException(InvalidResponseException::class, 'Invalid command response. Command Disque\\Command\\Hello got: ["version","id",{"0":"one","2":"two","3":"three","4":"four"}]');
$c = new Hello();
$c->parse(['version', 'id', [0=>'one', 2=>'two', 3=>'three', 4=>'four']]);
}
public function testParseInvalidNode2NotSet()
{
$this->setExpectedException(InvalidResponseException::class, 'Invalid command response. Command Disque\\Command\\Hello got: ["version","id",{"0":"one","1":"two","3":"three","4":"four"}]');
$c = new Hello();
$c->parse(['version', 'id', [0=>'one', 1=>'two', 3=>'three', 4=>'four']]);
}
public function testParseInvalidNode3NotSet()
{
$this->setExpectedException(InvalidResponseException::class, 'Invalid command response. Command Disque\\Command\\Hello got: ["version","id",{"0":"one","1":"two","2":"three","4":"four"}]');
$c = new Hello();
$c->parse(['version', 'id', [0=>'one', 1=>'two', 2=>'three', 4=>'four']]);
}
public function testParse()
{
$c = new Hello();
$result = $c->parse(['version', 'id', ['id', 'host', 'port', 'pri']]);
$this->assertSame([
'version' => 'version',
'id' => 'id',
'nodes' => [
[
'id' => 'id',
'host' => 'host',
'port' => 'port',
'priority' => 'pri'
]
]
], $result);
}
}
| php | MIT | 56cf00d97e739fec861717484657dbef2888df60 | 2026-01-05T05:12:23.969054Z | false |
mariano/disque-php | https://github.com/mariano/disque-php/blob/56cf00d97e739fec861717484657dbef2888df60/tests/Command/DelJobTest.php | tests/Command/DelJobTest.php | <?php
namespace Disque\Test\Command;
use PHPUnit_Framework_TestCase;
use Disque\Command\Argument\InvalidCommandArgumentException;
use Disque\Command\CommandInterface;
use Disque\Command\DelJob;
use Disque\Command\Response\InvalidResponseException;
class DelJobTest extends PHPUnit_Framework_TestCase
{
public function testInstance()
{
$c = new DelJob();
$this->assertInstanceOf(CommandInterface::class, $c);
}
public function testGetCommand()
{
$c = new DelJob();
$result = $c->getCommand();
$this->assertSame('DELJOB', $result);
}
public function testIsBlocking()
{
$c = new DelJob();
$result = $c->isBlocking();
$this->assertFalse($result);
}
public function testBuildInvalidArgumentsEmpty()
{
$this->setExpectedException(InvalidCommandArgumentException::class, 'Invalid command arguments. Arguments for command Disque\\Command\\DelJob: []');
$c = new DelJob();
$c->setArguments([]);
}
public function testBuildInvalidArgumentsNonStringArray()
{
$this->setExpectedException(InvalidCommandArgumentException::class, 'Invalid command arguments. Arguments for command Disque\\Command\\DelJob: [["test","stuff"]]');
$c = new DelJob();
$c->setArguments([['test','stuff']]);
}
public function testBuildInvalidArgumentsNonStringNumeric()
{
$this->setExpectedException(InvalidCommandArgumentException::class, 'Invalid command arguments. Arguments for command Disque\\Command\\DelJob: [128]');
$c = new DelJob();
$c->setArguments([128]);
}
public function testBuildInvalidArgumentsEmptyValue()
{
$this->setExpectedException(InvalidCommandArgumentException::class, 'Invalid command arguments. Arguments for command Disque\\Command\\DelJob: [""]');
$c = new DelJob();
$c->setArguments([""]);
}
public function testBuild()
{
$c = new DelJob();
$c->setArguments(['id']);
$result = $c->getArguments();
$this->assertSame(['id'], $result);
}
public function testBuildSeveral()
{
$c = new DelJob();
$c->setArguments(['id', 'id2']);
$result = $c->getArguments();
$this->assertSame(['id', 'id2'], $result);
}
public function testParseInvalidNonNumericArray()
{
$this->setExpectedException(InvalidResponseException::class, 'Invalid command response. Command Disque\\Command\\DelJob got: ["test"]');
$c = new DelJob();
$c->parse(['test']);
}
public function testParseInvalidNonNumericString()
{
$this->setExpectedException(InvalidResponseException::class, 'Invalid command response. Command Disque\\Command\\DelJob got: "test"');
$c = new DelJob();
$c->parse('test');
}
public function testParse()
{
$c = new DelJob();
$result = $c->parse('128');
$this->assertSame(128, $result);
}
} | php | MIT | 56cf00d97e739fec861717484657dbef2888df60 | 2026-01-05T05:12:23.969054Z | false |
mariano/disque-php | https://github.com/mariano/disque-php/blob/56cf00d97e739fec861717484657dbef2888df60/tests/Command/NackTest.php | tests/Command/NackTest.php | <?php
namespace Disque\Test\Command;
use PHPUnit_Framework_TestCase;
use Disque\Command\Argument\InvalidCommandArgumentException;
use Disque\Command\CommandInterface;
use Disque\Command\Nack;
use Disque\Command\Response\InvalidResponseException;
class NackTest extends PHPUnit_Framework_TestCase
{
public function testInstance()
{
$c = new Nack();
$this->assertInstanceOf(CommandInterface::class, $c);
}
public function testGetCommand()
{
$c = new Nack();
$result = $c->getCommand();
$this->assertSame('NACK', $result);
}
public function testIsBlocking()
{
$c = new Nack();
$result = $c->isBlocking();
$this->assertFalse($result);
}
public function testBuildInvalidArgumentsEmpty()
{
$this->setExpectedException(InvalidCommandArgumentException::class, 'Invalid command arguments. Arguments for command Disque\\Command\\Nack: []');
$c = new Nack();
$c->setArguments([]);
}
public function testBuildInvalidArgumentsNonStringArray()
{
$this->setExpectedException(InvalidCommandArgumentException::class, 'Invalid command arguments. Arguments for command Disque\\Command\\Nack: [["test","stuff"]]');
$c = new Nack();
$c->setArguments([['test','stuff']]);
}
public function testBuildInvalidArgumentsNonStringNumeric()
{
$this->setExpectedException(InvalidCommandArgumentException::class, 'Invalid command arguments. Arguments for command Disque\\Command\\Nack: [128]');
$c = new Nack();
$c->setArguments([128]);
}
public function testBuildInvalidArgumentsEmptyValue()
{
$this->setExpectedException(InvalidCommandArgumentException::class, 'Invalid command arguments. Arguments for command Disque\\Command\\Nack: [""]');
$c = new Nack();
$c->setArguments([""]);
}
public function testBuild()
{
$c = new Nack();
$c->setArguments(['id']);
$result = $c->getArguments();
$this->assertSame(['id'], $result);
}
public function testBuildSeveral()
{
$c = new Nack();
$c->setArguments(['id', 'id2']);
$result = $c->getArguments();
$this->assertSame(['id', 'id2'], $result);
}
public function testParseInvalidNonNumericArray()
{
$this->setExpectedException(InvalidResponseException::class, 'Invalid command response. Command Disque\\Command\\Nack got: ["test"]');
$c = new Nack();
$c->parse(['test']);
}
public function testParseInvalidNonNumericString()
{
$this->setExpectedException(InvalidResponseException::class, 'Invalid command response. Command Disque\\Command\\Nack got: "test"');
$c = new Nack();
$c->parse('test');
}
public function testParse()
{
$c = new Nack();
$result = $c->parse('128');
$this->assertSame(128, $result);
}
} | php | MIT | 56cf00d97e739fec861717484657dbef2888df60 | 2026-01-05T05:12:23.969054Z | false |
mariano/disque-php | https://github.com/mariano/disque-php/blob/56cf00d97e739fec861717484657dbef2888df60/tests/Command/InfoTest.php | tests/Command/InfoTest.php | <?php
namespace Disque\Test\Command;
use PHPUnit_Framework_TestCase;
use Disque\Command\Argument\InvalidCommandArgumentException;
use Disque\Command\CommandInterface;
use Disque\Command\Info;
use Disque\Command\Response\InvalidResponseException;
class InfoTest extends PHPUnit_Framework_TestCase
{
public function testInstance()
{
$c = new Info();
$this->assertInstanceOf(CommandInterface::class, $c);
}
public function testGetCommand()
{
$c = new Info();
$result = $c->getCommand();
$this->assertSame('INFO', $result);
}
public function testIsBlocking()
{
$c = new Info();
$result = $c->isBlocking();
$this->assertFalse($result);
}
public function testBuildInvalidArguments()
{
$this->setExpectedException(InvalidCommandArgumentException::class, 'Invalid command arguments. Arguments for command Disque\\Command\\Info: ["test"]');
$c = new Info();
$c->setArguments(['test']);
}
public function testBuild()
{
$c = new Info();
$c->setArguments([]);
$result = $c->getArguments();
$this->assertSame([], $result);
}
public function testParseInvalidNonString()
{
$this->setExpectedException(InvalidResponseException::class, 'Invalid command response. Command Disque\\Command\\Info got: ["test"]');
$c = new Info();
$c->parse(['test']);
}
public function testParse()
{
$c = new Info();
$result = $c->parse('test');
$this->assertSame('test', $result);
}
} | php | MIT | 56cf00d97e739fec861717484657dbef2888df60 | 2026-01-05T05:12:23.969054Z | false |
mariano/disque-php | https://github.com/mariano/disque-php/blob/56cf00d97e739fec861717484657dbef2888df60/tests/Command/AddJobTest.php | tests/Command/AddJobTest.php | <?php
namespace Disque\Test\Command;
use PHPUnit_Framework_TestCase;
use Disque\Command\AddJob;
use Disque\Command\Argument\InvalidCommandArgumentException;
use Disque\Command\Argument\InvalidOptionException;
use Disque\Command\CommandInterface;
use Disque\Command\Response\InvalidResponseException;
class AddJobTest extends PHPUnit_Framework_TestCase
{
public function testInstance()
{
$c = new AddJob();
$this->assertInstanceOf(CommandInterface::class, $c);
}
public function testGetCommand()
{
$c = new AddJob();
$result = $c->getCommand();
$this->assertSame('ADDJOB', $result);
}
public function testIsBlocking()
{
$c = new AddJob();
$result = $c->isBlocking();
$this->assertFalse($result);
}
public function testBuildInvalidArgumentsEmpty()
{
$this->setExpectedException(InvalidCommandArgumentException::class, 'Invalid command arguments. Arguments for command Disque\\Command\\AddJob: []');
$c = new AddJob();
$c->setArguments([]);
}
public function testBuildInvalidArgumentsTooFew()
{
$this->setExpectedException(InvalidCommandArgumentException::class, 'Invalid command arguments. Arguments for command Disque\\Command\\AddJob: ["test"]');
$c = new AddJob();
$c->setArguments(['test']);
}
public function testBuildInvalidArgumentsTooMany()
{
$this->setExpectedException(InvalidCommandArgumentException::class, 'Invalid command arguments. Arguments for command Disque\\Command\\AddJob: ["test","stuff","more","elements"]');
$c = new AddJob();
$c->setArguments(['test','stuff','more','elements']);
}
public function testBuildInvalidArguments0NotSet()
{
$this->setExpectedException(InvalidCommandArgumentException::class, 'Invalid command arguments. Arguments for command Disque\\Command\\AddJob: {"1":"test","2":"stuff"}');
$c = new AddJob();
$c->setArguments([1=>'test', 2=>'stuff']);
}
public function testBuildInvalidArguments1NotSet()
{
$this->setExpectedException(InvalidCommandArgumentException::class, 'Invalid command arguments. Arguments for command Disque\\Command\\AddJob: {"0":"test","2":"stuff"}');
$c = new AddJob();
$c->setArguments([0=>'test', 2=>'stuff']);
}
public function testBuildInvalidArguments0NonString()
{
$this->setExpectedException(InvalidCommandArgumentException::class, 'Invalid command arguments. Arguments for command Disque\\Command\\AddJob: [true,"stuff"]');
$c = new AddJob();
$c->setArguments([true, "stuff"]);
}
public function testBuildInvalidArguments1NonString()
{
$this->setExpectedException(InvalidCommandArgumentException::class, 'Invalid command arguments. Arguments for command Disque\\Command\\AddJob: ["test",10]');
$c = new AddJob();
$c->setArguments(["test", 10]);
}
public function testBuildInvalidArguments2NotSet()
{
$this->setExpectedException(InvalidCommandArgumentException::class, 'Invalid command arguments. Arguments for command Disque\\Command\\AddJob: {"0":"test","1":"stuff","3":{"timeout":3000}}');
$c = new AddJob();
$c->setArguments([0=>'test', 1=>'stuff', 3=>['timeout' => 3000]]);
}
public function testBuildInvalidArguments2NonArray()
{
$this->setExpectedException(InvalidCommandArgumentException::class, 'Invalid command arguments. Arguments for command Disque\\Command\\AddJob: ["test","stuff","more"]');
$c = new AddJob();
$c->setArguments(['test', 'stuff', 'more']);
}
public function testBuildInvalidOption()
{
$this->setExpectedException(InvalidOptionException::class, 'Invalid command options. Options for command Disque\\Command\\AddJob: {"test":"stuff"}');
$c = new AddJob();
$c->setArguments(['q', 'j', ['test' => 'stuff']]);
}
public function testBuildInvalidOptionWithValid()
{
$this->setExpectedException(InvalidOptionException::class, 'Invalid command options. Options for command Disque\\Command\\AddJob: {"test":"stuff","count":10}');
$c = new AddJob();
$c->setArguments(['q', 'j', ['test' => 'stuff', 'count' => 10]]);
}
public function testBuildInvalidOptionTimeoutNonNumeric()
{
$this->setExpectedException(InvalidOptionException::class, 'Invalid command options. Options for command Disque\\Command\\AddJob: {"timeout":"stuff"}');
$c = new AddJob();
$c->setArguments(['q', 'j', ['timeout' => 'stuff']]);
}
public function testBuildInvalidOptionTimeoutNonInt()
{
$this->setExpectedExceptionRegExp(InvalidOptionException::class, '/^Invalid command options. Options for command Disque\\\\Command\\\\AddJob: {"timeout":3.14\d*}$/');
$c = new AddJob();
$c->setArguments(['q', 'j', ['timeout' => 3.14]]);
}
public function testBuildInvalidOptionReplicateNonNumeric()
{
$this->setExpectedException(InvalidOptionException::class, 'Invalid command options. Options for command Disque\\Command\\AddJob: {"replicate":"stuff","timeout":0}');
$c = new AddJob();
$c->setArguments(['q', 'j', ['replicate' => 'stuff']]);
}
public function testBuildInvalidOptionReplicateNonInt()
{
$this->setExpectedExceptionRegExp(InvalidOptionException::class, '/^Invalid command options. Options for command Disque\\\\Command\\\\AddJob: {"replicate":3.14\d*,"timeout":0}$/');
$c = new AddJob();
$c->setArguments(['q', 'j', ['replicate' => 3.14]]);
}
public function testBuildInvalidOptionDelayNonNumeric()
{
$this->setExpectedException(InvalidOptionException::class, 'Invalid command options. Options for command Disque\\Command\\AddJob: {"delay":"stuff","timeout":0}');
$c = new AddJob();
$c->setArguments(['q', 'j', ['delay' => 'stuff']]);
}
public function testBuildInvalidOptionDelayNonInt()
{
$this->setExpectedExceptionRegExp(InvalidOptionException::class, '/^Invalid command options. Options for command Disque\\\\Command\\\\AddJob: {"delay":3.14\d*,"timeout":0}$/');
$c = new AddJob();
$c->setArguments(['q', 'j', ['delay' => 3.14]]);
}
public function testBuildInvalidOptionRetryNonNumeric()
{
$this->setExpectedException(InvalidOptionException::class, 'Invalid command options. Options for command Disque\\Command\\AddJob: {"retry":"stuff","timeout":0}');
$c = new AddJob();
$c->setArguments(['q', 'j', ['retry' => 'stuff']]);
}
public function testBuildInvalidOptionRetryNonInt()
{
$this->setExpectedExceptionRegExp(InvalidOptionException::class, '/^Invalid command options. Options for command Disque\\\\Command\\\\AddJob: {"retry":3.14\d*,"timeout":0}$/');
$c = new AddJob();
$c->setArguments(['q', 'j', ['retry' => 3.14]]);
}
public function testBuildInvalidOptionTtlNonNumeric()
{
$this->setExpectedException(InvalidOptionException::class, 'Invalid command options. Options for command Disque\\Command\\AddJob: {"ttl":"stuff","timeout":0}');
$c = new AddJob();
$c->setArguments(['q', 'j', ['ttl' => 'stuff']]);
}
public function testBuildInvalidOptionTtlNonInt()
{
$this->setExpectedExceptionRegExp(InvalidOptionException::class, '/^Invalid command options. Options for command Disque\\\\Command\\\\AddJob: {"ttl":3.14\d*,"timeout":0}$/');
$c = new AddJob();
$c->setArguments(['q', 'j', ['ttl' => 3.14]]);
}
public function testBuildInvalidOptionMaxlenNonNumeric()
{
$this->setExpectedException(InvalidOptionException::class, 'Invalid command options. Options for command Disque\\Command\\AddJob: {"maxlen":"stuff","timeout":0}');
$c = new AddJob();
$c->setArguments(['q', 'j', ['maxlen' => 'stuff']]);
}
public function testBuildInvalidOptionMaxlenNonInt()
{
$this->setExpectedExceptionRegExp(InvalidOptionException::class, '/^Invalid command options. Options for command Disque\\\\Command\\\\AddJob: {"maxlen":3.14\d*,"timeout":0}$/');
$c = new AddJob();
$c->setArguments(['q', 'j', ['maxlen' => 3.14]]);
}
public function testBuild()
{
$c = new AddJob();
$c->setArguments(['queue', 'job']);
$result = $c->getArguments();
$this->assertSame(['queue', 'job', 0], $result);
}
public function testBuildEmptyOptions()
{
$c = new AddJob();
$c->setArguments(['queue', 'job', []]);
$result = $c->getArguments();
$this->assertSame(['queue', 'job', 0], $result);
}
public function testBuildOptionTimeout()
{
$c = new AddJob();
$c->setArguments(['queue', 'job', ['timeout' => 3000]]);
$result = $c->getArguments();
$this->assertSame(['queue', 'job', 3000], $result);
}
public function testBuildOptionAsync()
{
$c = new AddJob();
$c->setArguments(['queue', 'job', ['async' => true]]);
$result = $c->getArguments();
$this->assertSame(['queue', 'job', 0, 'ASYNC'], $result);
}
public function testBuildOptionAsyncAndTimeout()
{
$c = new AddJob();
$c->setArguments(['queue', 'job', ['async' => true, 'timeout' => 3000]]);
$result = $c->getArguments();
$this->assertSame(['queue', 'job', 3000, 'ASYNC'], $result);
}
public function testBuildOptionReplicate()
{
$c = new AddJob();
$c->setArguments(['queue', 'job', ['replicate' => 5]]);
$result = $c->getArguments();
$this->assertSame(['queue', 'job', 0, 'REPLICATE', 5], $result);
}
public function testBuildOptionDelay()
{
$c = new AddJob();
$c->setArguments(['queue', 'job', ['delay' => 3000]]);
$result = $c->getArguments();
$this->assertSame(['queue', 'job', 0, 'DELAY', 3000], $result);
}
public function testBuildOptionRetry()
{
$c = new AddJob();
$c->setArguments(['queue', 'job', ['retry' => 3]]);
$result = $c->getArguments();
$this->assertSame(['queue', 'job', 0, 'RETRY', 3], $result);
}
public function testBuildOptionTtl()
{
$c = new AddJob();
$c->setArguments(['queue', 'job', ['ttl' => 5000]]);
$result = $c->getArguments();
$this->assertSame(['queue', 'job', 0, 'TTL', 5000], $result);
}
public function testBuildOptionMaxlen()
{
$c = new AddJob();
$c->setArguments(['queue', 'job', ['maxlen' => 5]]);
$result = $c->getArguments();
$this->assertSame(['queue', 'job', 0, 'MAXLEN', 5], $result);
}
public function testBuildUnicode()
{
$c = new AddJob();
$c->setArguments(['queue', '大']);
$result = $c->getArguments();
$this->assertSame(['queue', '大', 0], $result);
}
public function testParseInvalidNonString()
{
$this->setExpectedException(InvalidResponseException::class, 'Invalid command response. Command Disque\\Command\\AddJob got: 10');
$c = new AddJob();
$c->parse(10);
}
public function testParseInvalidNonStringBoolTrue()
{
$this->setExpectedException(InvalidResponseException::class, 'Invalid command response. Command Disque\\Command\\AddJob got: true');
$c = new AddJob();
$c->parse(true);
}
public function testParse()
{
$c = new AddJob();
$result = $c->parse('id');
$this->assertSame('id', $result);
}
} | php | MIT | 56cf00d97e739fec861717484657dbef2888df60 | 2026-01-05T05:12:23.969054Z | false |
mariano/disque-php | https://github.com/mariano/disque-php/blob/56cf00d97e739fec861717484657dbef2888df60/tests/Command/PauseTest.php | tests/Command/PauseTest.php | <?php
namespace Disque\Test\Command;
use PHPUnit_Framework_TestCase;
use Disque\Command\Argument\InvalidCommandArgumentException;
use Disque\Command\CommandInterface;
use Disque\Command\Pause;
use Disque\Command\Response\InvalidResponseException;
class PauseTest extends PHPUnit_Framework_TestCase
{
public function testInstance()
{
$c = new Pause();
$this->assertInstanceOf(CommandInterface::class, $c);
}
public function testGetCommand()
{
$c = new Pause();
$result = $c->getCommand();
$this->assertSame('PAUSE', $result);
}
public function testIsBlocking()
{
$c = new Pause();
$result = $c->isBlocking();
$this->assertFalse($result);
}
public function testBuildInvalidArgumentsEmpty()
{
$this->setExpectedException(InvalidCommandArgumentException::class, 'Invalid command arguments. Arguments for command Disque\\Command\\Pause: []');
$c = new Pause();
$c->setArguments([]);
}
public function testBuildInvalidArgumentsNonStringArray()
{
$this->setExpectedException(InvalidCommandArgumentException::class, 'Invalid command arguments. Arguments for command Disque\\Command\\Pause: [["test","stuff"]]');
$c = new Pause();
$c->setArguments([['test','stuff']]);
}
public function testBuildInvalidArgumentsNonStringNumeric()
{
$this->setExpectedException(InvalidCommandArgumentException::class, 'Invalid command arguments. Arguments for command Disque\\Command\\Pause: [128]');
$c = new Pause();
$c->setArguments([128]);
}
public function testBuildInvalidArgumentsEmptyValue()
{
$this->setExpectedException(InvalidCommandArgumentException::class, 'Invalid command arguments. Arguments for command Disque\\Command\\Pause: [""]');
$c = new Pause();
$c->setArguments([""]);
}
public function testBuildInvalidArgumentsNoOptions()
{
$this->setExpectedException(InvalidCommandArgumentException::class, 'Invalid command arguments. Arguments for command Disque\\Command\\Pause: ["queue"]');
$c = new Pause();
$c->setArguments(['queue']);
}
public function testBuildWithOptions()
{
$c = new Pause();
$c->setArguments(['queue', 'in']);
$result = $c->getArguments();
$this->assertSame(['queue', 'in'], $result);
}
public function testParseInvalidNoStringArray()
{
$this->setExpectedException(InvalidResponseException::class, 'Invalid command response. Command Disque\\Command\\Pause got: ["test"]');
$c = new Pause();
$c->parse(['test']);
}
public function testParseInvalidNonString()
{
$this->setExpectedException(InvalidResponseException::class, 'Invalid command response. Command Disque\\Command\\Pause got: 128');
$c = new Pause();
$c->parse(128);
}
public function testParse()
{
$c = new Pause();
$result = $c->parse('none');
$this->assertSame('none', $result);
}
} | php | MIT | 56cf00d97e739fec861717484657dbef2888df60 | 2026-01-05T05:12:23.969054Z | false |
mariano/disque-php | https://github.com/mariano/disque-php/blob/56cf00d97e739fec861717484657dbef2888df60/tests/Command/WorkingTest.php | tests/Command/WorkingTest.php | <?php
namespace Disque\Test\Command;
use PHPUnit_Framework_TestCase;
use Disque\Command\Argument\InvalidCommandArgumentException;
use Disque\Command\CommandInterface;
use Disque\Command\Working;
use Disque\Command\Response\InvalidResponseException;
class WorkingTest extends PHPUnit_Framework_TestCase
{
public function testInstance()
{
$c = new Working();
$this->assertInstanceOf(CommandInterface::class, $c);
}
public function testGetCommand()
{
$c = new Working();
$result = $c->getCommand();
$this->assertSame('WORKING', $result);
}
public function testIsBlocking()
{
$c = new Working();
$result = $c->isBlocking();
$this->assertFalse($result);
}
public function testBuildInvalidArgumentsEmpty()
{
$this->setExpectedException(InvalidCommandArgumentException::class, 'Invalid command arguments. Arguments for command Disque\\Command\\Working: []');
$c = new Working();
$c->setArguments([]);
}
public function testBuildInvalidArgumentsEmptyTooMany()
{
$this->setExpectedException(InvalidCommandArgumentException::class, 'Invalid command arguments. Arguments for command Disque\\Command\\Working: ["test","stuff"]');
$c = new Working();
$c->setArguments(['test', 'stuff']);
}
public function testBuildInvalidArgumentsEmptyNonNumeric()
{
$this->setExpectedException(InvalidCommandArgumentException::class, 'Invalid command arguments. Arguments for command Disque\\Command\\Working: {"test":"stuff"}');
$c = new Working();
$c->setArguments(['test' => 'stuff']);
}
public function testBuildInvalidArgumentsNumericNon0()
{
$this->setExpectedException(InvalidCommandArgumentException::class, 'Invalid command arguments. Arguments for command Disque\\Command\\Working: {"1":"stuff"}');
$c = new Working();
$c->setArguments([1 => 'stuff']);
}
public function testBuildInvalidArgumentsNonString()
{
$this->setExpectedException(InvalidCommandArgumentException::class, 'Invalid command arguments. Arguments for command Disque\\Command\\Working: [false]');
$c = new Working();
$c->setArguments([false]);
}
public function testBuild()
{
$c = new Working();
$c->setArguments(['test']);
$result = $c->getArguments();
$this->assertSame(['test'], $result);
}
public function testParseInvalidNonNumericArray()
{
$this->setExpectedException(InvalidResponseException::class, 'Invalid command response. Command Disque\\Command\\Working got: ["test"]');
$c = new Working();
$c->parse(['test']);
}
public function testParseInvalidNonNumericString()
{
$this->setExpectedException(InvalidResponseException::class, 'Invalid command response. Command Disque\\Command\\Working got: "test"');
$c = new Working();
$c->parse('test');
}
public function testParse()
{
$c = new Working();
$result = $c->parse('128');
$this->assertSame(128, $result);
}
} | php | MIT | 56cf00d97e739fec861717484657dbef2888df60 | 2026-01-05T05:12:23.969054Z | false |
mariano/disque-php | https://github.com/mariano/disque-php/blob/56cf00d97e739fec861717484657dbef2888df60/tests/Command/QStatTest.php | tests/Command/QStatTest.php | <?php
namespace Disque\Test\Command;
use PHPUnit_Framework_TestCase;
use Disque\Command\Argument\InvalidCommandArgumentException;
use Disque\Command\CommandInterface;
use Disque\Command\QStat;
use Disque\Command\Response\InvalidResponseException;
class QStatTest extends PHPUnit_Framework_TestCase
{
public function testInstance()
{
$c = new QStat();
$this->assertInstanceOf(CommandInterface::class, $c);
}
public function testGetCommand()
{
$c = new QStat();
$result = $c->getCommand();
$this->assertSame('QSTAT', $result);
}
public function testIsBlocking()
{
$c = new QStat();
$result = $c->isBlocking();
$this->assertFalse($result);
}
public function testBuildInvalidArgumentsEmpty()
{
$this->setExpectedException(InvalidCommandArgumentException::class, 'Invalid command arguments. Arguments for command Disque\\Command\\QStat: []');
$c = new QStat();
$c->setArguments([]);
}
public function testBuildInvalidArgumentsEmptyTooMany()
{
$this->setExpectedException(InvalidCommandArgumentException::class, 'Invalid command arguments. Arguments for command Disque\\Command\\QStat: ["test","stuff"]');
$c = new QStat();
$c->setArguments(['test', 'stuff']);
}
public function testBuildInvalidArgumentsEmptyNonNumeric()
{
$this->setExpectedException(InvalidCommandArgumentException::class, 'Invalid command arguments. Arguments for command Disque\\Command\\QStat: {"test":"stuff"}');
$c = new QStat();
$c->setArguments(['test' => 'stuff']);
}
public function testBuildInvalidArgumentsNumericNon0()
{
$this->setExpectedException(InvalidCommandArgumentException::class, 'Invalid command arguments. Arguments for command Disque\\Command\\QStat: {"1":"stuff"}');
$c = new QStat();
$c->setArguments([1 => 'stuff']);
}
public function testBuildInvalidArgumentsNonString()
{
$this->setExpectedException(InvalidCommandArgumentException::class, 'Invalid command arguments. Arguments for command Disque\\Command\\QStat: [false]');
$c = new QStat();
$c->setArguments([false]);
}
public function testBuild()
{
$c = new QStat();
$c->setArguments(['test']);
$result = $c->getArguments();
$this->assertSame(['test'], $result);
}
public function testParseInvalidNonNumericArray()
{
$this->setExpectedException(InvalidResponseException::class, 'Invalid command response. Command Disque\\Command\\QStat got: ["test"]');
$c = new QStat();
$c->parse(['test']);
}
public function testParseInvalidNonNumericString()
{
$this->setExpectedException(InvalidResponseException::class, 'Invalid command response. Command Disque\\Command\\QStat got: "test"');
$c = new QStat();
$c->parse('test');
}
public function testParse()
{
$c = new QStat();
$result = $c->parse(['name', 'test', 'len', 1]);
$this->assertSame([
'name' => 'test',
'len' => 1
], $result);
}
}
| php | MIT | 56cf00d97e739fec861717484657dbef2888df60 | 2026-01-05T05:12:23.969054Z | false |
mariano/disque-php | https://github.com/mariano/disque-php/blob/56cf00d97e739fec861717484657dbef2888df60/tests/Command/AuthTest.php | tests/Command/AuthTest.php | <?php
namespace Disque\Test\Command;
use PHPUnit_Framework_TestCase;
use Disque\Command\Argument\InvalidCommandArgumentException;
use Disque\Command\CommandInterface;
use Disque\Command\Auth;
use Disque\Command\Response\InvalidResponseException;
class AuthTest extends PHPUnit_Framework_TestCase
{
public function testInstance()
{
$c = new Auth();
$this->assertInstanceOf(CommandInterface::class, $c);
}
public function testGetCommand()
{
$c = new Auth();
$result = $c->getCommand();
$this->assertSame('AUTH', $result);
}
public function testIsBlocking()
{
$c = new Auth();
$result = $c->isBlocking();
$this->assertFalse($result);
}
public function testBuildInvalidArgumentsEmpty()
{
$this->setExpectedException(InvalidCommandArgumentException::class, 'Invalid command arguments. Arguments for command Disque\\Command\\Auth: []');
$c = new Auth();
$c->setArguments([]);
}
public function testBuildInvalidArgumentsEmptyTooMany()
{
$this->setExpectedException(InvalidCommandArgumentException::class, 'Invalid command arguments. Arguments for command Disque\\Command\\Auth: ["test","stuff"]');
$c = new Auth();
$c->setArguments(['test', 'stuff']);
}
public function testBuildInvalidArgumentsEmptyNonNumeric()
{
$this->setExpectedException(InvalidCommandArgumentException::class, 'Invalid command arguments. Arguments for command Disque\\Command\\Auth: {"test":"stuff"}');
$c = new Auth();
$c->setArguments(['test' => 'stuff']);
}
public function testBuildInvalidArgumentsNumericNon0()
{
$this->setExpectedException(InvalidCommandArgumentException::class, 'Invalid command arguments. Arguments for command Disque\\Command\\Auth: {"1":"stuff"}');
$c = new Auth();
$c->setArguments([1 => 'stuff']);
}
public function testBuildInvalidArgumentsNonString()
{
$this->setExpectedException(InvalidCommandArgumentException::class, 'Invalid command arguments. Arguments for command Disque\\Command\\Auth: [false]');
$c = new Auth();
$c->setArguments([false]);
}
public function testBuild()
{
$c = new Auth();
$c->setArguments(['test']);
$result = $c->getArguments();
$this->assertSame(['test'], $result);
}
public function testParseInvalidNonString()
{
$this->setExpectedException(InvalidResponseException::class, 'Invalid command response. Command Disque\\Command\\Auth got: 10');
$c = new Auth();
$c->parse(10);
}
public function testParseInvalidNonStringBoolTrue()
{
$this->setExpectedException(InvalidResponseException::class, 'Invalid command response. Command Disque\\Command\\Auth got: true');
$c = new Auth();
$c->parse(true);
}
public function testParse()
{
$c = new Auth();
$result = $c->parse('OK');
$this->assertSame('OK', $result);
}
} | php | MIT | 56cf00d97e739fec861717484657dbef2888df60 | 2026-01-05T05:12:23.969054Z | false |
mariano/disque-php | https://github.com/mariano/disque-php/blob/56cf00d97e739fec861717484657dbef2888df60/tests/Command/Response/JobsWithQueueResponseTest.php | tests/Command/Response/JobsWithQueueResponseTest.php | <?php
namespace Disque\Test\Command\Response;
use PHPUnit_Framework_TestCase;
use Disque\Command\Hello;
use Disque\Command\Response\ResponseInterface;
use Disque\Command\Response\JobsWithQueueResponse;
use Disque\Command\Response\InvalidResponseException;
class JobsWithQueueResponseTest extends PHPUnit_Framework_TestCase
{
public function testInstance()
{
$r = new JobsWithQueueResponse();
$this->assertInstanceOf(ResponseInterface::class, $r);
}
public function testInvalidBodyNotArrayString()
{
$this->setExpectedException(InvalidResponseException::class, 'Invalid command response. Command Disque\\Command\\Hello got: "test"');
$r = new JobsWithQueueResponse();
$r->setCommand(new Hello());
$r->setBody('test');
}
public function testInvalidBodyNotArrayNumeric()
{
$this->setExpectedException(InvalidResponseException::class, 'Invalid command response. Command Disque\\Command\\Hello got: 128');
$r = new JobsWithQueueResponse();
$r->setCommand(new Hello());
$r->setBody(128);
}
public function testInvalidBodyElementsNotArray()
{
$this->setExpectedException(InvalidResponseException::class, 'Invalid command response. Command Disque\\Command\\Hello got: ["test"]');
$r = new JobsWithQueueResponse();
$r->setCommand(new Hello());
$r->setBody(['test']);
}
public function testInvalidBodyNotEnoughElementsInJob()
{
$this->setExpectedException(InvalidResponseException::class, 'Invalid command response. Command Disque\\Command\\Hello got: [["id","body"]]');
$r = new JobsWithQueueResponse();
$r->setCommand(new Hello());
$r->setBody([['id','body']]);
}
public function testInvalidBodyTooManyElementsInJob()
{
$this->setExpectedException(InvalidResponseException::class, 'Invalid command response. Command Disque\\Command\\Hello got: [["queue","id","body","test"]]');
$r = new JobsWithQueueResponse();
$r->setCommand(new Hello());
$r->setBody([['queue', 'id', 'body', 'test']]);
}
public function testParseInvalidArrayElementsNon0()
{
$this->setExpectedException(InvalidResponseException::class, 'Invalid command response. Command Disque\\Command\\Hello got: [{"1":"test","2":"stuff","3":"more"}]');
$r = new JobsWithQueueResponse();
$r->setCommand(new Hello());
$r->setBody([[1=>'test', 2=>'stuff', 3=>'more']]);
}
public function testParseInvalidArrayElementsNon1()
{
$this->setExpectedException(InvalidResponseException::class, 'Invalid command response. Command Disque\\Command\\Hello got: [{"0":"test","2":"stuff","3":"more"}]');
$r = new JobsWithQueueResponse();
$r->setCommand(new Hello());
$r->setBody([[0=>'test', 2=>'stuff', 3=>'more']]);
}
public function testParseInvalidArrayElementsNon2()
{
$this->setExpectedException(InvalidResponseException::class, 'Invalid command response. Command Disque\\Command\\Hello got: [{"0":"test","1":"stuff","3":"more"}]');
$r = new JobsWithQueueResponse();
$r->setCommand(new Hello());
$r->setBody([[0=>'test', 1=>'stuff', 3=>'more']]);
}
public function testInvalidBodyInvalidJobIDPrefix()
{
$this->setExpectedException(InvalidResponseException::class, 'Invalid command response. Command Disque\\Command\\Hello got: [["queue","XX01234567890","body"]]');
$r = new JobsWithQueueResponse();
$r->setCommand(new Hello());
$r->setBody([['queue', 'XX01234567890', 'body']]);
}
public function testInvalidBodyInvalidJobIDLength()
{
$this->setExpectedException(InvalidResponseException::class, 'Invalid command response. Command Disque\\Command\\Hello got: [["queue","D-012345","body"]]');
$r = new JobsWithQueueResponse();
$r->setCommand(new Hello());
$r->setBody([['queue', 'D-012345', 'body']]);
}
public function testParseNoJob()
{
$r = new JobsWithQueueResponse();
$r->setCommand(new Hello());
$r->setBody(null);
$result = $r->parse();
$this->assertSame([], $result);
}
public function testParseOneJob()
{
$r = new JobsWithQueueResponse();
$r->setCommand(new Hello());
$r->setBody([['queue', 'D-0f0c644fd3ccb51c2cedbd47fcb6f312646c993c05a0SQ', 'body']]);
$result = $r->parse();
$this->assertSame([
[
'queue' => 'queue',
'id' => 'D-0f0c644fd3ccb51c2cedbd47fcb6f312646c993c05a0SQ',
'body' => 'body'
]
], $result);
}
public function testParseTwoJobs()
{
$r = new JobsWithQueueResponse();
$r->setCommand(new Hello());
$r->setBody([
['queue', 'D-0f0c644fd3ccb51c2cedbd47fcb6f312646c993c05a0SQ', 'body'],
['queue2', 'D-0f0c644fd3ccb51c2cedbd47fcb6f312646c993c05a1SQ', 'body2']
]);
$result = $r->parse();
$this->assertSame([
[
'queue' => 'queue',
'id' => 'D-0f0c644fd3ccb51c2cedbd47fcb6f312646c993c05a0SQ',
'body' => 'body'
],
[
'queue' => 'queue2',
'id' => 'D-0f0c644fd3ccb51c2cedbd47fcb6f312646c993c05a1SQ',
'body' => 'body2'
],
], $result);
}
} | php | MIT | 56cf00d97e739fec861717484657dbef2888df60 | 2026-01-05T05:12:23.969054Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.