🍲dfcv🏰dd⋉(● ∸ ●)⋊@% PNG %k25u25%fgd5n! PNG %k25u25%fgd5n!PK\X]aD/ )predis/src/Transaction/MultiExecState.phpnu[flags = 0; } /** * Sets the internal state flags. * * @param int $flags Set of flags */ public function set($flags) { $this->flags = $flags; } /** * Gets the internal state flags. * * @return int */ public function get() { return $this->flags; } /** * Sets one or more flags. * * @param int $flags Set of flags */ public function flag($flags) { $this->flags |= $flags; } /** * Resets one or more flags. * * @param int $flags Set of flags */ public function unflag($flags) { $this->flags &= ~$flags; } /** * Returns if the specified flag or set of flags is set. * * @param int $flags Flag * * @return bool */ public function check($flags) { return ($this->flags & $flags) === $flags; } /** * Resets the state of a transaction. */ public function reset() { $this->flags = 0; } /** * Returns the state of the RESET flag. * * @return bool */ public function isReset() { return $this->flags === 0; } /** * Returns the state of the INITIALIZED flag. * * @return bool */ public function isInitialized() { return $this->check(self::INITIALIZED); } /** * Returns the state of the INSIDEBLOCK flag. * * @return bool */ public function isExecuting() { return $this->check(self::INSIDEBLOCK); } /** * Returns the state of the CAS flag. * * @return bool */ public function isCAS() { return $this->check(self::CAS); } /** * Returns if WATCH is allowed in the current state. * * @return bool */ public function isWatchAllowed() { return $this->check(self::INITIALIZED) && !$this->check(self::CAS); } /** * Returns the state of the WATCH flag. * * @return bool */ public function isWatching() { return $this->check(self::WATCH); } /** * Returns the state of the DISCARDED flag. * * @return bool */ public function isDiscarded() { return $this->check(self::DISCARDED); } } PK\X]e ::4predis/src/Transaction/AbortedMultiExecException.phpnu[transaction = $transaction; } /** * Returns the transaction that generated the exception. * * @return MultiExec */ public function getTransaction() { return $this->transaction; } } PK\X]>|6|6$predis/src/Transaction/MultiExec.phpnu[assertClient($client); $this->client = $client; $this->state = new MultiExecState(); $this->configure($client, $options ?: []); $this->reset(); } /** * Checks if the passed client instance satisfies the required conditions * needed to initialize the transaction object. * * @param ClientInterface $client Client instance used by the transaction object. * * @throws NotSupportedException */ private function assertClient(ClientInterface $client) { if ($client->getConnection() instanceof ClusterInterface) { throw new NotSupportedException( 'Cannot initialize a MULTI/EXEC transaction over cluster connections.' ); } if (!$client->getCommandFactory()->supports('MULTI', 'EXEC', 'DISCARD')) { throw new NotSupportedException( 'MULTI, EXEC and DISCARD are not supported by the current command factory.' ); } } /** * Configures the transaction using the provided options. * * @param ClientInterface $client Underlying client instance. * @param array $options Array of options for the transaction. **/ protected function configure(ClientInterface $client, array $options) { if (isset($options['exceptions'])) { $this->exceptions = (bool) $options['exceptions']; } else { $this->exceptions = $client->getOptions()->exceptions; } if (isset($options['cas'])) { $this->modeCAS = (bool) $options['cas']; } if (isset($options['watch']) && $keys = $options['watch']) { $this->watchKeys = $keys; } if (isset($options['retry'])) { $this->attempts = (int) $options['retry']; } } /** * Resets the state of the transaction. */ protected function reset() { $this->state->reset(); $this->commands = new SplQueue(); } /** * Initializes the transaction context. */ protected function initialize() { if ($this->state->isInitialized()) { return; } if ($this->modeCAS) { $this->state->flag(MultiExecState::CAS); } if ($this->watchKeys) { $this->watch($this->watchKeys); } $cas = $this->state->isCAS(); $discarded = $this->state->isDiscarded(); if (!$cas || ($cas && $discarded)) { $this->call('MULTI'); if ($discarded) { $this->state->unflag(MultiExecState::CAS); } } $this->state->unflag(MultiExecState::DISCARDED); $this->state->flag(MultiExecState::INITIALIZED); } /** * Dynamically invokes a Redis command with the specified arguments. * * @param string $method Command ID. * @param array $arguments Arguments for the command. * * @return mixed */ public function __call($method, $arguments) { return $this->executeCommand( $this->client->createCommand($method, $arguments) ); } /** * Executes a Redis command bypassing the transaction logic. * * @param string $commandID Command ID. * @param array $arguments Arguments for the command. * * @return mixed * @throws ServerException */ protected function call($commandID, array $arguments = []) { try { $response = $this->client->executeCommand( $this->client->createCommand($commandID, $arguments) ); } catch (ServerException $exception) { if (!$this->client->getConnection() instanceof RelayConnection) { throw $exception; } if (strcasecmp($commandID, 'EXEC') != 0) { throw $exception; } if (!strpos($exception->getMessage(), 'RELAY_ERR_REDIS')) { throw $exception; } return null; } if ($response instanceof ErrorResponseInterface) { throw new ServerException($response->getMessage()); } return $response; } /** * Executes the specified Redis command. * * @param CommandInterface $command Command instance. * * @return $this|mixed * @throws AbortedMultiExecException * @throws CommunicationException */ public function executeCommand(CommandInterface $command) { $this->initialize(); if ($this->state->isCAS()) { return $this->client->executeCommand($command); } $response = $this->client->getConnection()->executeCommand($command); if ($response instanceof StatusResponse && $response == 'QUEUED') { $this->commands->enqueue($command); } elseif ($response instanceof Relay) { $this->commands->enqueue($command); } elseif ($response instanceof ErrorResponseInterface) { throw new AbortedMultiExecException($this, $response->getMessage()); } else { $this->onProtocolError('The server did not return a +QUEUED status response.'); } return $this; } /** * Executes WATCH against one or more keys. * * @param string|array $keys One or more keys. * * @return mixed * @throws NotSupportedException * @throws ClientException */ public function watch($keys) { if (!$this->client->getCommandFactory()->supports('WATCH')) { throw new NotSupportedException('WATCH is not supported by the current command factory.'); } if ($this->state->isWatchAllowed()) { throw new ClientException('Sending WATCH after MULTI is not allowed.'); } $response = $this->call('WATCH', is_array($keys) ? $keys : [$keys]); $this->state->flag(MultiExecState::WATCH); return $response; } /** * Finalizes the transaction by executing MULTI on the server. * * @return MultiExec */ public function multi() { if ($this->state->check(MultiExecState::INITIALIZED | MultiExecState::CAS)) { $this->state->unflag(MultiExecState::CAS); $this->call('MULTI'); } else { $this->initialize(); } return $this; } /** * Executes UNWATCH. * * @return MultiExec * @throws NotSupportedException */ public function unwatch() { if (!$this->client->getCommandFactory()->supports('UNWATCH')) { throw new NotSupportedException( 'UNWATCH is not supported by the current command factory.' ); } $this->state->unflag(MultiExecState::WATCH); $this->__call('UNWATCH', []); return $this; } /** * Resets the transaction by UNWATCH-ing the keys that are being WATCHed and * DISCARD-ing pending commands that have been already sent to the server. * * @return MultiExec */ public function discard() { if ($this->state->isInitialized()) { $this->call($this->state->isCAS() ? 'UNWATCH' : 'DISCARD'); $this->reset(); $this->state->flag(MultiExecState::DISCARDED); } return $this; } /** * Executes the whole transaction. * * @return mixed */ public function exec() { return $this->execute(); } /** * Checks the state of the transaction before execution. * * @param mixed $callable Callback for execution. * * @throws InvalidArgumentException * @throws ClientException */ private function checkBeforeExecution($callable) { if ($this->state->isExecuting()) { throw new ClientException( 'Cannot invoke "execute" or "exec" inside an active transaction context.' ); } if ($callable) { if (!is_callable($callable)) { throw new InvalidArgumentException('The argument must be a callable object.'); } if (!$this->commands->isEmpty()) { $this->discard(); throw new ClientException( 'Cannot execute a transaction block after using fluent interface.' ); } } elseif ($this->attempts) { $this->discard(); throw new ClientException( 'Automatic retries are supported only when a callable block is provided.' ); } } /** * Handles the actual execution of the whole transaction. * * @param mixed $callable Optional callback for execution. * * @return array * @throws CommunicationException * @throws AbortedMultiExecException * @throws ServerException */ public function execute($callable = null) { $this->checkBeforeExecution($callable); $execResponse = null; $attempts = $this->attempts; do { if ($callable) { $this->executeTransactionBlock($callable); } if ($this->commands->isEmpty()) { if ($this->state->isWatching()) { $this->discard(); } return; } $execResponse = $this->call('EXEC'); // The additional `false` check is needed for Relay, // let's hope it won't break anything if ($execResponse === null || $execResponse === false) { if ($attempts === 0) { throw new AbortedMultiExecException( $this, 'The current transaction has been aborted by the server.' ); } $this->reset(); continue; } break; } while ($attempts-- > 0); $response = []; $commands = $this->commands; $size = count($execResponse); if ($size !== count($commands)) { $this->onProtocolError('EXEC returned an unexpected number of response items.'); } for ($i = 0; $i < $size; ++$i) { $cmdResponse = $execResponse[$i]; if ($this->exceptions && $cmdResponse instanceof ErrorResponseInterface) { throw new ServerException($cmdResponse->getMessage()); } if ($cmdResponse instanceof RelayException) { if ($this->exceptions) { throw new ServerException($cmdResponse->getMessage(), $cmdResponse->getCode(), $cmdResponse); } $commands->dequeue(); $response[$i] = new Error($cmdResponse->getMessage()); continue; } $response[$i] = $commands->dequeue()->parseResponse($cmdResponse); } return $response; } /** * Passes the current transaction object to a callable block for execution. * * @param mixed $callable Callback. * * @throws CommunicationException * @throws ServerException */ protected function executeTransactionBlock($callable) { $exception = null; $this->state->flag(MultiExecState::INSIDEBLOCK); try { call_user_func($callable, $this); } catch (CommunicationException $exception) { // NOOP } catch (ServerException $exception) { // NOOP } catch (Exception $exception) { $this->discard(); } $this->state->unflag(MultiExecState::INSIDEBLOCK); if ($exception) { throw $exception; } } /** * Helper method for protocol errors encountered inside the transaction. * * @param string $message Error message. */ private function onProtocolError($message) { // Since a MULTI/EXEC block cannot be initialized when using aggregate // connections we can safely assume that Predis\Client::getConnection() // will return a Predis\Connection\NodeConnectionInterface instance. CommunicationException::handle(new ProtocolException( $this->client->getConnection(), $message )); } } PK\X]Q*predis/src/Collection/Iterator/ListKey.phpnu[requiredCommand($client, 'LRANGE'); if ((false === $count = filter_var($count, FILTER_VALIDATE_INT)) || $count < 0) { throw new InvalidArgumentException('The $count argument must be a positive integer.'); } $this->client = $client; $this->key = $key; $this->count = $count; $this->reset(); } /** * Ensures that the client instance supports the specified Redis command * required to fetch elements from the server to perform the iteration. * * @param ClientInterface $client Client connected to Redis. * @param string $commandID Command ID. * * @throws NotSupportedException */ protected function requiredCommand(ClientInterface $client, $commandID) { if (!$client->getCommandFactory()->supports($commandID)) { throw new NotSupportedException("'$commandID' is not supported by the current command factory."); } } /** * Resets the inner state of the iterator. */ protected function reset() { $this->valid = true; $this->fetchmore = true; $this->elements = []; $this->position = -1; $this->current = null; } /** * Fetches a new set of elements from the remote collection, effectively * advancing the iteration process. * * @return array */ protected function executeCommand() { return $this->client->lrange($this->key, $this->position + 1, $this->position + $this->count); } /** * Populates the local buffer of elements fetched from the server during the * iteration. */ protected function fetch() { $elements = $this->executeCommand(); if (count($elements) < $this->count) { $this->fetchmore = false; } $this->elements = $elements; } /** * Extracts next values for key() and current(). */ protected function extractNext() { ++$this->position; $this->current = array_shift($this->elements); } /** * @return void */ #[ReturnTypeWillChange] public function rewind() { $this->reset(); $this->next(); } /** * @return mixed */ #[ReturnTypeWillChange] public function current() { return $this->current; } /** * @return int|null */ #[ReturnTypeWillChange] public function key() { return $this->position; } /** * @return void */ #[ReturnTypeWillChange] public function next() { if (!$this->elements && $this->fetchmore) { $this->fetch(); } if ($this->elements) { $this->extractNext(); } else { $this->valid = false; } } /** * @return bool */ #[ReturnTypeWillChange] public function valid() { return $this->valid; } } PK\X]uT  /predis/src/Collection/Iterator/SortedSetKey.phpnu[= 2.8) wrapped in a fully-rewindable PHP iterator. * * @see http://redis.io/commands/scan */ class SortedSetKey extends CursorBasedIterator { protected $key; /** * {@inheritdoc} */ public function __construct(ClientInterface $client, $key, $match = null, $count = null) { $this->requiredCommand($client, 'ZSCAN'); parent::__construct($client, $match, $count); $this->key = $key; } /** * {@inheritdoc} */ protected function executeCommand() { return $this->client->zscan($this->key, $this->cursor, $this->getScanOptions()); } /** * {@inheritdoc} */ protected function extractNext() { $this->position = key($this->elements); $this->current = current($this->elements); unset($this->elements[$this->position]); } } PK\X]lC+predis/src/Collection/Iterator/Keyspace.phpnu[= 2.8) wrapped in a fully-rewindable PHP iterator. * * @see http://redis.io/commands/scan */ class Keyspace extends CursorBasedIterator { /** * {@inheritdoc} */ public function __construct(ClientInterface $client, $match = null, $count = null) { $this->requiredCommand($client, 'SCAN'); parent::__construct($client, $match, $count); } /** * {@inheritdoc} */ protected function executeCommand() { return $this->client->scan($this->cursor, $this->getScanOptions()); } } PK\X]oc)predis/src/Collection/Iterator/SetKey.phpnu[= 2.8) wrapped in a fully-rewindable PHP iterator. * * @see http://redis.io/commands/scan */ class SetKey extends CursorBasedIterator { protected $key; /** * {@inheritdoc} */ public function __construct(ClientInterface $client, $key, $match = null, $count = null) { $this->requiredCommand($client, 'SSCAN'); parent::__construct($client, $match, $count); $this->key = $key; } /** * {@inheritdoc} */ protected function executeCommand() { return $this->client->sscan($this->key, $this->cursor, $this->getScanOptions()); } } PK\X]&t*predis/src/Collection/Iterator/HashKey.phpnu[= 2.8) wrapped in a fully-rewindable PHP iterator. * * @see http://redis.io/commands/scan */ class HashKey extends CursorBasedIterator { protected $key; /** * {@inheritdoc} */ public function __construct(ClientInterface $client, $key, $match = null, $count = null) { $this->requiredCommand($client, 'HSCAN'); parent::__construct($client, $match, $count); $this->key = $key; } /** * {@inheritdoc} */ protected function executeCommand() { return $this->client->hscan($this->key, $this->cursor, $this->getScanOptions()); } /** * {@inheritdoc} */ protected function extractNext() { $this->position = key($this->elements); $this->current = current($this->elements); unset($this->elements[$this->position]); } } PK\X]- DD6predis/src/Collection/Iterator/CursorBasedIterator.phpnu[client = $client; $this->match = $match; $this->count = $count; $this->reset(); } /** * Ensures that the client supports the specified Redis command required to * fetch elements from the server to perform the iteration. * * @param ClientInterface $client Client connected to Redis. * @param string $commandID Command ID. * * @throws NotSupportedException */ protected function requiredCommand(ClientInterface $client, $commandID) { if (!$client->getCommandFactory()->supports($commandID)) { throw new NotSupportedException("'$commandID' is not supported by the current command factory."); } } /** * Resets the inner state of the iterator. */ protected function reset() { $this->valid = true; $this->fetchmore = true; $this->elements = []; $this->cursor = 0; $this->position = -1; $this->current = null; } /** * Returns an array of options for the `SCAN` command. * * @return array */ protected function getScanOptions() { $options = []; if (strlen(strval($this->match)) > 0) { $options['MATCH'] = $this->match; } if ($this->count > 0) { $options['COUNT'] = $this->count; } return $options; } /** * Fetches a new set of elements from the remote collection, effectively * advancing the iteration process. * * @return array */ abstract protected function executeCommand(); /** * Populates the local buffer of elements fetched from the server during * the iteration. */ protected function fetch() { [$cursor, $elements] = $this->executeCommand(); if (!$cursor) { $this->fetchmore = false; } $this->cursor = $cursor; $this->elements = $elements; } /** * Extracts next values for key() and current(). */ protected function extractNext() { ++$this->position; $this->current = array_shift($this->elements); } /** * @return void */ #[ReturnTypeWillChange] public function rewind() { $this->reset(); $this->next(); } /** * @return mixed */ #[ReturnTypeWillChange] public function current() { return $this->current; } /** * @return int|null */ #[ReturnTypeWillChange] public function key() { return $this->position; } /** * @return void */ #[ReturnTypeWillChange] public function next() { tryFetch: if (!$this->elements && $this->fetchmore) { $this->fetch(); } if ($this->elements) { $this->extractNext(); } elseif ($this->cursor) { goto tryFetch; } else { $this->valid = false; } } /** * @return bool */ #[ReturnTypeWillChange] public function valid() { return $this->valid; } } PK\X]577&predis/src/PubSub/AbstractConsumer.phpnu[stop(true); } /** * Checks if the specified flag is valid based on the state of the consumer. * * @param int $value Flag. * * @return bool */ protected function isFlagSet($value) { return ($this->statusFlags & $value) === $value; } /** * Subscribes to the specified channels. * * @param string ...$channel One or more channel names. */ public function subscribe($channel /* , ... */) { $this->writeRequest(self::SUBSCRIBE, func_get_args()); $this->statusFlags |= self::STATUS_SUBSCRIBED; } /** * Unsubscribes from the specified channels. * * @param string ...$channel One or more channel names. */ public function unsubscribe(...$channel) { $this->writeRequest(self::UNSUBSCRIBE, func_get_args()); } /** * Subscribes to the specified channels using a pattern. * * @param string ...$pattern One or more channel name patterns. */ public function psubscribe(...$pattern) { $this->writeRequest(self::PSUBSCRIBE, func_get_args()); $this->statusFlags |= self::STATUS_PSUBSCRIBED; } /** * Unsubscribes from the specified channels using a pattern. * * @param string ...$pattern One or more channel name patterns. */ public function punsubscribe(...$pattern) { $this->writeRequest(self::PUNSUBSCRIBE, func_get_args()); } /** * PING the server with an optional payload that will be echoed as a * PONG message in the pub/sub loop. * * @param string $payload Optional PING payload. */ public function ping($payload = null) { $this->writeRequest('PING', [$payload]); } /** * Closes the context by unsubscribing from all the subscribed channels. The * context can be forcefully closed by dropping the underlying connection. * * @param bool $drop Indicates if the context should be closed by dropping the connection. * * @return bool Returns false when there are no pending messages. */ public function stop($drop = false) { if (!$this->valid()) { return false; } if ($drop) { $this->invalidate(); $this->disconnect(); } else { if ($this->isFlagSet(self::STATUS_SUBSCRIBED)) { $this->unsubscribe(); } if ($this->isFlagSet(self::STATUS_PSUBSCRIBED)) { $this->punsubscribe(); } } return !$drop; } /** * Closes the underlying connection when forcing a disconnection. */ abstract protected function disconnect(); /** * Writes a Redis command on the underlying connection. * * @param string $method Command ID. * @param array $arguments Arguments for the command. */ abstract protected function writeRequest($method, $arguments); /** * @return void */ #[ReturnTypeWillChange] public function rewind() { // NOOP } /** * Returns the last message payload retrieved from the server and generated * by one of the active subscriptions. * * @return array */ #[ReturnTypeWillChange] public function current() { return $this->getValue(); } /** * @return int|null */ #[ReturnTypeWillChange] public function key() { return $this->position; } /** * @return int|null */ #[ReturnTypeWillChange] public function next() { if ($this->valid()) { ++$this->position; } return $this->position; } /** * Checks if the the consumer is still in a valid state to continue. * * @return bool */ #[ReturnTypeWillChange] public function valid() { $isValid = $this->isFlagSet(self::STATUS_VALID); $subscriptionFlags = self::STATUS_SUBSCRIBED | self::STATUS_PSUBSCRIBED; $hasSubscriptions = ($this->statusFlags & $subscriptionFlags) > 0; return $isValid && $hasSubscriptions; } /** * Resets the state of the consumer. */ protected function invalidate() { $this->statusFlags = 0; // 0b0000; } /** * Waits for a new message from the server generated by one of the active * subscriptions and returns it when available. * * @return array */ abstract protected function getValue(); } PK\X]j~$predis/src/PubSub/DispatcherLoop.phpnu[callbacks = []; $this->pubsub = $pubsub; } /** * Checks if the passed argument is a valid callback. * * @param mixed $callable A callback. * * @throws InvalidArgumentException */ protected function assertCallback($callable) { if (!is_callable($callable)) { throw new InvalidArgumentException('The given argument must be a callable object.'); } } /** * Returns the underlying PUB / SUB context. * * @return Consumer */ public function getPubSubConsumer() { return $this->pubsub; } /** * Sets a callback that gets invoked upon new subscriptions. * * @param mixed $callable A callback. */ public function subscriptionCallback($callable = null) { if (isset($callable)) { $this->assertCallback($callable); } $this->subscriptionCallback = $callable; } /** * Sets a callback that gets invoked when a message is received on a * channel that does not have an associated callback. * * @param mixed $callable A callback. */ public function defaultCallback($callable = null) { if (isset($callable)) { $this->assertCallback($callable); } $this->subscriptionCallback = $callable; } /** * Binds a callback to a channel. * * @param string $channel Channel name. * @param callable $callback A callback. */ public function attachCallback($channel, $callback) { $callbackName = $this->getPrefixKeys() . $channel; $this->assertCallback($callback); $this->callbacks[$callbackName] = $callback; $this->pubsub->subscribe($channel); } /** * Stops listening to a channel and removes the associated callback. * * @param string $channel Redis channel. */ public function detachCallback($channel) { $callbackName = $this->getPrefixKeys() . $channel; if (isset($this->callbacks[$callbackName])) { unset($this->callbacks[$callbackName]); $this->pubsub->unsubscribe($channel); } } /** * Starts the dispatcher loop. */ public function run() { foreach ($this->pubsub as $message) { $kind = $message->kind; if ($kind !== Consumer::MESSAGE && $kind !== Consumer::PMESSAGE) { if (isset($this->subscriptionCallback)) { $callback = $this->subscriptionCallback; call_user_func($callback, $message, $this); } continue; } if (isset($this->callbacks[$message->channel])) { $callback = $this->callbacks[$message->channel]; call_user_func($callback, $message->payload, $this); } elseif (isset($this->defaultCallback)) { $callback = $this->defaultCallback; call_user_func($callback, $message, $this); } } } /** * Terminates the dispatcher loop. */ public function stop() { $this->pubsub->stop(); } /** * Return the prefix used for keys. * * @return string */ protected function getPrefixKeys() { $options = $this->pubsub->getClient()->getOptions(); if (isset($options->prefix)) { return $options->prefix->getPrefix(); } return ''; } } PK\X]U #predis/src/PubSub/RelayConsumer.phpnu[statusFlags |= self::STATUS_SUBSCRIBED; $command = $this->client->createCommand('subscribe', [ $channels, function ($relay, $channel, $message) use ($callback) { $callback((object) [ 'kind' => is_null($message) ? self::SUBSCRIBE : self::MESSAGE, 'channel' => $channel, 'payload' => $message, ], $relay); }, ]); $this->client->getConnection()->executeCommand($command); $this->invalidate(); } /** * Subscribes to the specified channels using a pattern. * * @param string ...$pattern One or more channel name patterns. * @param callable $callback The message callback. */ public function psubscribe(...$pattern) // @phpstan-ignore-line { $patterns = func_get_args(); $callback = array_pop($patterns); $this->statusFlags |= self::STATUS_PSUBSCRIBED; $command = $this->client->createCommand('psubscribe', [ $patterns, function ($relay, $pattern, $channel, $message) use ($callback) { $callback((object) [ 'kind' => is_null($message) ? self::PSUBSCRIBE : self::PMESSAGE, 'pattern' => $pattern, 'channel' => $channel, 'payload' => $message, ], $relay); }, ]); $this->client->getConnection()->executeCommand($command); $this->invalidate(); } /** * {@inheritDoc} */ protected function genericSubscribeInit($subscribeAction) { if (isset($this->options[$subscribeAction])) { throw new NotSupportedException('Relay does not support Pub/Sub constructor options.'); } } /** * {@inheritDoc} */ public function ping($payload = null) { throw new NotSupportedException('Relay does not support PING in Pub/Sub.'); } /** * {@inheritDoc} */ public function stop($drop = false) { return false; } /** * {@inheritDoc} */ public function __destruct() { // NOOP } } PK\X]k0predis/src/PubSub/Consumer.phpnu[checkCapabilities($client); $this->options = $options ?: []; $this->client = $client; $this->genericSubscribeInit('subscribe'); $this->genericSubscribeInit('psubscribe'); } /** * Returns the underlying client instance used by the pub/sub iterator. * * @return ClientInterface */ public function getClient() { return $this->client; } /** * Checks if the client instance satisfies the required conditions needed to * initialize a PUB/SUB consumer. * * @param ClientInterface $client Client instance used by the consumer. * * @throws NotSupportedException */ protected function checkCapabilities(ClientInterface $client) { if ($client->getConnection() instanceof ClusterInterface) { throw new NotSupportedException( 'Cannot initialize a PUB/SUB consumer over cluster connections.' ); } $commands = ['publish', 'subscribe', 'unsubscribe', 'psubscribe', 'punsubscribe']; if (!$client->getCommandFactory()->supports(...$commands)) { throw new NotSupportedException( 'PUB/SUB commands are not supported by the current command factory.' ); } } /** * This method shares the logic to handle both SUBSCRIBE and PSUBSCRIBE. * * @param string $subscribeAction Type of subscription. */ protected function genericSubscribeInit($subscribeAction) { if (isset($this->options[$subscribeAction])) { $this->$subscribeAction($this->options[$subscribeAction]); } } /** * {@inheritdoc} */ protected function writeRequest($method, $arguments) { $this->client->getConnection()->writeRequest( $this->client->createCommand($method, Command::normalizeArguments($arguments) ) ); } /** * {@inheritdoc} */ protected function disconnect() { $this->client->disconnect(); } /** * {@inheritdoc} */ protected function getValue() { $response = $this->client->getConnection()->read(); switch ($response[0]) { case self::SUBSCRIBE: case self::UNSUBSCRIBE: case self::PSUBSCRIBE: case self::PUNSUBSCRIBE: if ($response[2] === 0) { $this->invalidate(); } // The missing break here is intentional as we must process // subscriptions and unsubscriptions as standard messages. // no break case self::MESSAGE: return (object) [ 'kind' => $response[0], 'channel' => $response[1], 'payload' => $response[2], ]; case self::PMESSAGE: return (object) [ 'kind' => $response[0], 'pattern' => $response[1], 'channel' => $response[2], 'payload' => $response[3], ]; case self::PONG: return (object) [ 'kind' => $response[0], 'payload' => $response[1], ]; default: throw new ClientException( "Unknown message type '{$response[0]}' received in the PUB/SUB context." ); } } } PK\X]c%!NN.predis/src/Connection/Cluster/RedisCluster.phpnu[= 3.0.0). * * This connection backend offers smart support for redis-cluster by handling * automatic slots map (re)generation upon -MOVED or -ASK responses returned by * Redis when redirecting a client to a different node. * * The cluster can be pre-initialized using only a subset of the actual nodes in * the cluster, Predis will do the rest by adjusting the slots map and creating * the missing underlying connection instances on the fly. * * It is possible to pre-associate connections to a slots range with the "slots" * parameter in the form "$first-$last". This can greatly reduce runtime node * guessing and redirections. * * It is also possible to ask for the full and updated slots map directly to one * of the nodes and optionally enable such a behaviour upon -MOVED redirections. * Asking for the cluster configuration to Redis is actually done by issuing a * CLUSTER SLOTS command to a random node in the pool. */ class RedisCluster implements ClusterInterface, IteratorAggregate, Countable { private $useClusterSlots = true; private $pool = []; private $slots = []; private $slotmap; private $strategy; private $connections; private $retryLimit = 5; private $retryInterval = 10; /** * @param FactoryInterface $connections Optional connection factory. * @param StrategyInterface|null $strategy Optional cluster strategy. */ public function __construct( FactoryInterface $connections, ?StrategyInterface $strategy = null ) { $this->connections = $connections; $this->strategy = $strategy ?: new RedisClusterStrategy(); $this->slotmap = new SlotMap(); } /** * Sets the maximum number of retries for commands upon server failure. * * -1 = unlimited retry attempts * 0 = no retry attempts (fails immediately) * n = fail only after n retry attempts * * @param int $retry Number of retry attempts. */ public function setRetryLimit($retry) { $this->retryLimit = (int) $retry; } /** * Sets the initial retry interval (milliseconds). * * @param int $retryInterval Milliseconds between retries. */ public function setRetryInterval($retryInterval) { $this->retryInterval = (int) $retryInterval; } /** * Returns the retry interval (milliseconds). * * @return int Milliseconds between retries. */ public function getRetryInterval() { return (int) $this->retryInterval; } /** * {@inheritdoc} */ public function isConnected() { foreach ($this->pool as $connection) { if ($connection->isConnected()) { return true; } } return false; } /** * {@inheritdoc} */ public function connect() { if ($connection = $this->getRandomConnection()) { $connection->connect(); } } /** * {@inheritdoc} */ public function disconnect() { foreach ($this->pool as $connection) { $connection->disconnect(); } } /** * {@inheritdoc} */ public function add(NodeConnectionInterface $connection) { $this->pool[(string) $connection] = $connection; $this->slotmap->reset(); } /** * {@inheritdoc} */ public function remove(NodeConnectionInterface $connection) { if (false !== $id = array_search($connection, $this->pool, true)) { $this->slotmap->reset(); $this->slots = array_diff($this->slots, [$connection]); unset($this->pool[$id]); return true; } return false; } /** * Removes a connection instance by using its identifier. * * @param string $connectionID Connection identifier. * * @return bool True if the connection was in the pool. */ public function removeById($connectionID) { if (isset($this->pool[$connectionID])) { $this->slotmap->reset(); $this->slots = array_diff($this->slots, [$connectionID]); unset($this->pool[$connectionID]); return true; } return false; } /** * Generates the current slots map by guessing the cluster configuration out * of the connection parameters of the connections in the pool. * * Generation is based on the same algorithm used by Redis to generate the * cluster, so it is most effective when all of the connections supplied on * initialization have the "slots" parameter properly set accordingly to the * current cluster configuration. */ public function buildSlotMap() { $this->slotmap->reset(); foreach ($this->pool as $connectionID => $connection) { $parameters = $connection->getParameters(); if (!isset($parameters->slots)) { continue; } foreach (explode(',', $parameters->slots) as $slotRange) { $slots = explode('-', $slotRange, 2); if (!isset($slots[1])) { $slots[1] = $slots[0]; } $this->slotmap->setSlots($slots[0], $slots[1], $connectionID); } } } /** * Queries the specified node of the cluster to fetch the updated slots map. * * When the connection fails, this method tries to execute the same command * on a different connection picked at random from the pool of known nodes, * up until the retry limit is reached. * * @param NodeConnectionInterface $connection Connection to a node of the cluster. * * @return mixed */ private function queryClusterNodeForSlotMap(NodeConnectionInterface $connection) { $retries = 0; $retryAfter = $this->retryInterval; $command = RawCommand::create('CLUSTER', 'SLOTS'); while ($retries <= $this->retryLimit) { try { $response = $connection->executeCommand($command); break; } catch (ConnectionException $exception) { $connection = $exception->getConnection(); $connection->disconnect(); $this->remove($connection); if ($retries === $this->retryLimit) { throw $exception; } if (!$connection = $this->getRandomConnection()) { throw new ClientException('No connections left in the pool for `CLUSTER SLOTS`'); } usleep($retryAfter * 1000); $retryAfter *= 2; ++$retries; } } return $response; } /** * Generates an updated slots map fetching the cluster configuration using * the CLUSTER SLOTS command against the specified node or a random one from * the pool. * * @param NodeConnectionInterface|null $connection Optional connection instance. */ public function askSlotMap(?NodeConnectionInterface $connection = null) { if (!$connection && !$connection = $this->getRandomConnection()) { return; } $this->slotmap->reset(); $response = $this->queryClusterNodeForSlotMap($connection); foreach ($response as $slots) { // We only support master servers for now, so we ignore subsequent // elements in the $slots array identifying slaves. [$start, $end, $master] = $slots; if ($master[0] === '') { $this->slotmap->setSlots($start, $end, (string) $connection); } else { $this->slotmap->setSlots($start, $end, "{$master[0]}:{$master[1]}"); } } } /** * Guesses the correct node associated to a given slot using a precalculated * slots map, falling back to the same logic used by Redis to initialize a * cluster (best-effort). * * @param int $slot Slot index. * * @return string Connection ID. */ protected function guessNode($slot) { if (!$this->pool) { throw new ClientException('No connections available in the pool'); } if ($this->slotmap->isEmpty()) { $this->buildSlotMap(); } if ($node = $this->slotmap[$slot]) { return $node; } $count = count($this->pool); $index = min((int) ($slot / (int) (16384 / $count)), $count - 1); $nodes = array_keys($this->pool); return $nodes[$index]; } /** * Creates a new connection instance from the given connection ID. * * @param string $connectionID Identifier for the connection. * * @return NodeConnectionInterface */ protected function createConnection($connectionID) { $separator = strrpos($connectionID, ':'); return $this->connections->create([ 'host' => substr($connectionID, 0, $separator), 'port' => substr($connectionID, $separator + 1), ]); } /** * {@inheritdoc} */ public function getConnectionByCommand(CommandInterface $command) { $slot = $this->strategy->getSlot($command); if (!isset($slot)) { throw new NotSupportedException( "Cannot use '{$command->getId()}' with redis-cluster." ); } if (isset($this->slots[$slot])) { return $this->slots[$slot]; } else { return $this->getConnectionBySlot($slot); } } /** * Returns the connection currently associated to a given slot. * * @param int $slot Slot index. * * @return NodeConnectionInterface * @throws OutOfBoundsException */ public function getConnectionBySlot($slot) { if (!SlotMap::isValid($slot)) { throw new OutOfBoundsException("Invalid slot [$slot]."); } if (isset($this->slots[$slot])) { return $this->slots[$slot]; } $connectionID = $this->guessNode($slot); if (!$connection = $this->getConnectionById($connectionID)) { $connection = $this->createConnection($connectionID); $this->pool[$connectionID] = $connection; } return $this->slots[$slot] = $connection; } /** * {@inheritdoc} */ public function getConnectionById($connectionID) { return $this->pool[$connectionID] ?? null; } /** * Returns a random connection from the pool. * * @return NodeConnectionInterface|null */ protected function getRandomConnection() { if (!$this->pool) { return null; } return $this->pool[array_rand($this->pool)]; } /** * Permanently associates the connection instance to a new slot. * The connection is added to the connections pool if not yet included. * * @param NodeConnectionInterface $connection Connection instance. * @param int $slot Target slot index. */ protected function move(NodeConnectionInterface $connection, $slot) { $this->pool[(string) $connection] = $connection; $this->slots[(int) $slot] = $connection; $this->slotmap[(int) $slot] = $connection; } /** * Handles -ERR responses returned by Redis. * * @param CommandInterface $command Command that generated the -ERR response. * @param ErrorResponseInterface $error Redis error response object. * * @return mixed */ protected function onErrorResponse(CommandInterface $command, ErrorResponseInterface $error) { $details = explode(' ', $error->getMessage(), 2); switch ($details[0]) { case 'MOVED': return $this->onMovedResponse($command, $details[1]); case 'ASK': return $this->onAskResponse($command, $details[1]); default: return $error; } } /** * Handles -MOVED responses by executing again the command against the node * indicated by the Redis response. * * @param CommandInterface $command Command that generated the -MOVED response. * @param string $details Parameters of the -MOVED response. * * @return mixed */ protected function onMovedResponse(CommandInterface $command, $details) { [$slot, $connectionID] = explode(' ', $details, 2); // Handle connection ID in the form of "IP:port (details about exception)" // by trimming everything after first space (including the space) $startPositionOfExtraDetails = strpos($connectionID, ' '); if ($startPositionOfExtraDetails !== false) { $connectionID = substr($connectionID, 0, $startPositionOfExtraDetails); } if (!$connection = $this->getConnectionById($connectionID)) { $connection = $this->createConnection($connectionID); } if ($this->useClusterSlots) { $this->askSlotMap($connection); } $this->move($connection, $slot); return $this->executeCommand($command); } /** * Handles -ASK responses by executing again the command against the node * indicated by the Redis response. * * @param CommandInterface $command Command that generated the -ASK response. * @param string $details Parameters of the -ASK response. * * @return mixed */ protected function onAskResponse(CommandInterface $command, $details) { [$slot, $connectionID] = explode(' ', $details, 2); if (!$connection = $this->getConnectionById($connectionID)) { $connection = $this->createConnection($connectionID); } $connection->executeCommand(RawCommand::create('ASKING')); return $connection->executeCommand($command); } /** * Ensures that a command is executed one more time on connection failure. * * The connection to the node that generated the error is evicted from the * pool before trying to fetch an updated slots map from another node. If * the new slots map points to an unreachable server the client gives up and * throws the exception as the nodes participating in the cluster may still * have to agree that something changed in the configuration of the cluster. * * @param CommandInterface $command Command instance. * @param string $method Actual method. * * @return mixed */ private function retryCommandOnFailure(CommandInterface $command, $method) { $retries = 0; $retryAfter = $this->retryInterval; while ($retries <= $this->retryLimit) { try { $response = $this->getConnectionByCommand($command)->$method($command); if ($response instanceof ErrorResponse) { $message = $response->getMessage(); if (strpos($message, 'CLUSTERDOWN') !== false) { throw new ServerException($message); } } break; } catch (Throwable $exception) { usleep($retryAfter * 1000); $retryAfter *= 2; if ($exception instanceof ConnectionException) { $connection = $exception->getConnection(); if ($connection) { $connection->disconnect(); $this->remove($connection); } } if ($retries === $this->retryLimit) { throw $exception; } if ($this->useClusterSlots) { $this->askSlotMap(); } ++$retries; } } return $response; } /** * {@inheritdoc} */ public function writeRequest(CommandInterface $command) { $this->retryCommandOnFailure($command, __FUNCTION__); } /** * {@inheritdoc} */ public function readResponse(CommandInterface $command) { return $this->retryCommandOnFailure($command, __FUNCTION__); } /** * {@inheritdoc} */ public function executeCommand(CommandInterface $command) { $response = $this->retryCommandOnFailure($command, __FUNCTION__); if ($response instanceof ErrorResponseInterface) { return $this->onErrorResponse($command, $response); } return $response; } /** * @return int */ #[ReturnTypeWillChange] public function count() { return count($this->pool); } /** * @return Traversable */ #[ReturnTypeWillChange] public function getIterator() { if ($this->slotmap->isEmpty()) { $this->useClusterSlots ? $this->askSlotMap() : $this->buildSlotMap(); } $connections = []; foreach ($this->slotmap->getNodes() as $node) { if (!$connection = $this->getConnectionById($node)) { $this->add($connection = $this->createConnection($node)); } $connections[] = $connection; } return new ArrayIterator($connections); } /** * Returns the underlying slot map. * * @return SlotMap */ public function getSlotMap() { return $this->slotmap; } /** * Returns the underlying command hash strategy used to hash commands by * using keys found in their arguments. * * @return StrategyInterface */ public function getClusterStrategy() { return $this->strategy; } /** * Returns the underlying connection factory used to create new connection * instances to Redis nodes indicated by redis-cluster. * * @return FactoryInterface */ public function getConnectionFactory() { return $this->connections; } /** * Enables automatic fetching of the current slots map from one of the nodes * using the CLUSTER SLOTS command. This option is enabled by default as * asking the current slots map to Redis upon -MOVED responses may reduce * overhead by eliminating the trial-and-error nature of the node guessing * procedure, mostly when targeting many keys that would end up in a lot of * redirections. * * The slots map can still be manually fetched using the askSlotMap() * method whether or not this option is enabled. * * @param bool $value Enable or disable the use of CLUSTER SLOTS. */ public function useClusterSlots($value) { $this->useClusterSlots = (bool) $value; } } PK\X]2predis/src/Connection/Cluster/ClusterInterface.phpnu[strategy = $strategy ?: new PredisStrategy(); $this->distributor = $this->strategy->getDistributor(); } /** * {@inheritdoc} */ public function isConnected() { foreach ($this->pool as $connection) { if ($connection->isConnected()) { return true; } } return false; } /** * {@inheritdoc} */ public function connect() { foreach ($this->pool as $connection) { $connection->connect(); } } /** * {@inheritdoc} */ public function disconnect() { foreach ($this->pool as $connection) { $connection->disconnect(); } } /** * {@inheritdoc} */ public function add(NodeConnectionInterface $connection) { $parameters = $connection->getParameters(); $this->pool[(string) $connection] = $connection; if (isset($parameters->alias)) { $this->aliases[$parameters->alias] = $connection; } $this->distributor->add($connection, $parameters->weight); } /** * {@inheritdoc} */ public function remove(NodeConnectionInterface $connection) { if (false !== $id = array_search($connection, $this->pool, true)) { unset($this->pool[$id]); $this->distributor->remove($connection); if ($this->aliases && $alias = $connection->getParameters()->alias) { unset($this->aliases[$alias]); } return true; } return false; } /** * {@inheritdoc} */ public function getConnectionByCommand(CommandInterface $command) { $slot = $this->strategy->getSlot($command); if (!isset($slot)) { throw new NotSupportedException( "Cannot use '{$command->getId()}' over clusters of connections." ); } return $this->distributor->getBySlot($slot); } /** * {@inheritdoc} */ public function getConnectionById($id) { return $this->pool[$id] ?? null; } /** * Returns a connection instance by its alias. * * @param string $alias Connection alias. * * @return NodeConnectionInterface|null */ public function getConnectionByAlias($alias) { return $this->aliases[$alias] ?? null; } /** * Retrieves a connection instance by slot. * * @param string $slot Slot name. * * @return NodeConnectionInterface|null */ public function getConnectionBySlot($slot) { return $this->distributor->getBySlot($slot); } /** * Retrieves a connection instance from the cluster using a key. * * @param string $key Key string. * * @return NodeConnectionInterface */ public function getConnectionByKey($key) { $hash = $this->strategy->getSlotByKey($key); return $this->distributor->getBySlot($hash); } /** * Returns the underlying command hash strategy used to hash commands by * using keys found in their arguments. * * @return StrategyInterface */ public function getClusterStrategy() { return $this->strategy; } /** * @return int */ #[ReturnTypeWillChange] public function count() { return count($this->pool); } /** * @return Traversable */ #[ReturnTypeWillChange] public function getIterator() { return new ArrayIterator($this->pool); } /** * {@inheritdoc} */ public function writeRequest(CommandInterface $command) { $this->getConnectionByCommand($command)->writeRequest($command); } /** * {@inheritdoc} */ public function readResponse(CommandInterface $command) { return $this->getConnectionByCommand($command)->readResponse($command); } /** * {@inheritdoc} */ public function executeCommand(CommandInterface $command) { return $this->getConnectionByCommand($command)->executeCommand($command); } } PK\X]i tRtR9predis/src/Connection/Replication/SentinelReplication.phpnu[ * @author Ville Mattila */ class SentinelReplication implements ReplicationInterface { /** * @var NodeConnectionInterface */ protected $master; /** * @var NodeConnectionInterface[] */ protected $slaves = []; /** * @var NodeConnectionInterface[] */ protected $pool = []; /** * @var NodeConnectionInterface */ protected $current; /** * @var string */ protected $service; /** * @var ConnectionFactoryInterface */ protected $connectionFactory; /** * @var ReplicationStrategy */ protected $strategy; /** * @var NodeConnectionInterface[] */ protected $sentinels = []; /** * @var int */ protected $sentinelIndex = 0; /** * @var NodeConnectionInterface */ protected $sentinelConnection; /** * @var float */ protected $sentinelTimeout = 0.100; /** * Max number of automatic retries of commands upon server failure. * * -1 = unlimited retry attempts * 0 = no retry attempts (fails immediately) * n = fail only after n retry attempts * * @var int */ protected $retryLimit = 20; /** * Time to wait in milliseconds before fetching a new configuration from one * of the sentinel servers. * * @var int */ protected $retryWait = 1000; /** * Flag for automatic fetching of available sentinels. * * @var bool */ protected $updateSentinels = false; /** * @param string $service Name of the service for autodiscovery. * @param array $sentinels Sentinel servers connection parameters. * @param ConnectionFactoryInterface $connectionFactory Connection factory instance. * @param ReplicationStrategy|null $strategy Replication strategy instance. */ public function __construct( $service, array $sentinels, ConnectionFactoryInterface $connectionFactory, ?ReplicationStrategy $strategy = null ) { $this->sentinels = $sentinels; $this->service = $service; $this->connectionFactory = $connectionFactory; $this->strategy = $strategy ?: new ReplicationStrategy(); } /** * Sets a default timeout for connections to sentinels. * * When "timeout" is present in the connection parameters of sentinels, its * value overrides the default sentinel timeout. * * @param float $timeout Timeout value. */ public function setSentinelTimeout($timeout) { $this->sentinelTimeout = (float) $timeout; } /** * Sets the maximum number of retries for commands upon server failure. * * -1 = unlimited retry attempts * 0 = no retry attempts (fails immediately) * n = fail only after n retry attempts * * @param int $retry Number of retry attempts. */ public function setRetryLimit($retry) { $this->retryLimit = (int) $retry; } /** * Sets the time to wait (in milliseconds) before fetching a new configuration * from one of the sentinels. * * @param float $milliseconds Time to wait before the next attempt. */ public function setRetryWait($milliseconds) { $this->retryWait = (float) $milliseconds; } /** * Set automatic fetching of available sentinels. * * @param bool $update Enable or disable automatic updates. */ public function setUpdateSentinels($update) { $this->updateSentinels = (bool) $update; } /** * Resets the current connection. */ protected function reset() { $this->current = null; } /** * Wipes the current list of master and slaves nodes. */ protected function wipeServerList() { $this->reset(); $this->master = null; $this->slaves = []; $this->pool = []; } /** * {@inheritdoc} */ public function add(NodeConnectionInterface $connection) { $parameters = $connection->getParameters(); $role = $parameters->role; if ('master' === $role) { $this->master = $connection; } elseif ('sentinel' === $role) { $this->sentinels[] = $connection; // sentinels are not considered part of the pool. return; } else { // everything else is considered a slave. $this->slaves[] = $connection; } $this->pool[(string) $connection] = $connection; $this->reset(); } /** * {@inheritdoc} */ public function remove(NodeConnectionInterface $connection) { if ($connection === $this->master) { $this->master = null; } elseif (false !== $id = array_search($connection, $this->slaves, true)) { unset($this->slaves[$id]); } elseif (false !== $id = array_search($connection, $this->sentinels, true)) { unset($this->sentinels[$id]); return true; } else { return false; } unset($this->pool[(string) $connection]); $this->reset(); return true; } /** * Creates a new connection to a sentinel server. * * @return NodeConnectionInterface */ protected function createSentinelConnection($parameters) { if ($parameters instanceof NodeConnectionInterface) { return $parameters; } if (is_string($parameters)) { $parameters = Parameters::parse($parameters); } if (is_array($parameters)) { // NOTE: sentinels do not accept AUTH and SELECT commands so we must // explicitly set them to NULL to avoid problems when using default // parameters set via client options. Actually AUTH is supported for // sentinels starting with Redis 5 but we have to differentiate from // sentinels passwords and nodes passwords, this will be implemented // in a later release. $parameters['database'] = null; $parameters['username'] = null; // don't leak password from between configurations // https://github.com/predis/predis/pull/807/#discussion_r985764770 if (!isset($parameters['password'])) { $parameters['password'] = null; } if (!isset($parameters['timeout'])) { $parameters['timeout'] = $this->sentinelTimeout; } } return $this->connectionFactory->create($parameters); } /** * Returns the current sentinel connection. * * If there is no active sentinel connection, a new connection is created. * * @return NodeConnectionInterface */ public function getSentinelConnection() { if (!$this->sentinelConnection) { if ($this->sentinelIndex >= count($this->sentinels)) { $this->sentinelIndex = 0; throw new \Predis\ClientException('No sentinel server available for autodiscovery.'); } $sentinel = $this->sentinels[$this->sentinelIndex]; ++$this->sentinelIndex; $this->sentinelConnection = $this->createSentinelConnection($sentinel); } return $this->sentinelConnection; } /** * Fetches an updated list of sentinels from a sentinel. */ public function updateSentinels() { SENTINEL_QUERY: { $sentinel = $this->getSentinelConnection(); try { $payload = $sentinel->executeCommand( RawCommand::create('SENTINEL', 'sentinels', $this->service) ); $this->sentinels = []; $this->sentinelIndex = 0; // NOTE: sentinel server does not return itself, so we add it back. $this->sentinels[] = $sentinel->getParameters()->toArray(); foreach ($payload as $sentinel) { $this->sentinels[] = [ 'host' => $sentinel[3], 'port' => $sentinel[5], 'role' => 'sentinel', ]; } } catch (ConnectionException $exception) { $this->sentinelConnection = null; goto SENTINEL_QUERY; } } } /** * Fetches the details for the master and slave servers from a sentinel. */ public function querySentinel() { $this->wipeServerList(); $this->updateSentinels(); $this->getMaster(); $this->getSlaves(); } /** * Handles error responses returned by redis-sentinel. * * @param NodeConnectionInterface $sentinel Connection to a sentinel server. * @param ErrorResponseInterface $error Error response. */ private function handleSentinelErrorResponse(NodeConnectionInterface $sentinel, ErrorResponseInterface $error) { if ($error->getErrorType() === 'IDONTKNOW') { throw new ConnectionException($sentinel, $error->getMessage()); } else { throw new ServerException($error->getMessage()); } } /** * Fetches the details for the master server from a sentinel. * * @param NodeConnectionInterface $sentinel Connection to a sentinel server. * @param string $service Name of the service. * * @return array */ protected function querySentinelForMaster(NodeConnectionInterface $sentinel, $service) { $payload = $sentinel->executeCommand( RawCommand::create('SENTINEL', 'get-master-addr-by-name', $service) ); if ($payload === null) { throw new ServerException('ERR No such master with that name'); } if ($payload instanceof ErrorResponseInterface) { $this->handleSentinelErrorResponse($sentinel, $payload); } return [ 'host' => $payload[0], 'port' => $payload[1], 'role' => 'master', ]; } /** * Fetches the details for the slave servers from a sentinel. * * @param NodeConnectionInterface $sentinel Connection to a sentinel server. * @param string $service Name of the service. * * @return array */ protected function querySentinelForSlaves(NodeConnectionInterface $sentinel, $service) { $slaves = []; $payload = $sentinel->executeCommand( RawCommand::create('SENTINEL', 'slaves', $service) ); if ($payload instanceof ErrorResponseInterface) { $this->handleSentinelErrorResponse($sentinel, $payload); } foreach ($payload as $slave) { $flags = explode(',', $slave[9]); if (array_intersect($flags, ['s_down', 'o_down', 'disconnected'])) { continue; } // ensure `master-link-status` is ok if (isset($slave[31]) && $slave[31] === 'err') { continue; } $slaves[] = [ 'host' => $slave[3], 'port' => $slave[5], 'role' => 'slave', ]; } return $slaves; } /** * {@inheritdoc} */ public function getCurrent() { return $this->current; } /** * {@inheritdoc} */ public function getMaster() { if ($this->master) { return $this->master; } if ($this->updateSentinels) { $this->updateSentinels(); } SENTINEL_QUERY: { $sentinel = $this->getSentinelConnection(); try { $masterParameters = $this->querySentinelForMaster($sentinel, $this->service); $masterConnection = $this->connectionFactory->create($masterParameters); $this->add($masterConnection); } catch (ConnectionException $exception) { $this->sentinelConnection = null; goto SENTINEL_QUERY; } } return $masterConnection; } /** * {@inheritdoc} */ public function getSlaves() { if ($this->slaves) { return array_values($this->slaves); } if ($this->updateSentinels) { $this->updateSentinels(); } SENTINEL_QUERY: { $sentinel = $this->getSentinelConnection(); try { $slavesParameters = $this->querySentinelForSlaves($sentinel, $this->service); foreach ($slavesParameters as $slaveParameters) { $this->add($this->connectionFactory->create($slaveParameters)); } } catch (ConnectionException $exception) { $this->sentinelConnection = null; goto SENTINEL_QUERY; } } return array_values($this->slaves); } /** * Returns a random slave. * * @return NodeConnectionInterface|null */ protected function pickSlave() { $slaves = $this->getSlaves(); return $slaves ? $slaves[rand(1, count($slaves)) - 1] : null; } /** * Returns the connection instance in charge for the given command. * * @param CommandInterface $command Command instance. * * @return NodeConnectionInterface */ private function getConnectionInternal(CommandInterface $command) { if (!$this->current) { if ($this->strategy->isReadOperation($command) && $slave = $this->pickSlave()) { $this->current = $slave; } else { $this->current = $this->getMaster(); } return $this->current; } if ($this->current === $this->master) { return $this->current; } if (!$this->strategy->isReadOperation($command)) { $this->current = $this->getMaster(); } return $this->current; } /** * Asserts that the specified connection matches an expected role. * * @param NodeConnectionInterface $connection Connection to a redis server. * @param string $role Expected role of the server ("master", "slave" or "sentinel"). * * @throws RoleException|ConnectionException */ protected function assertConnectionRole(NodeConnectionInterface $connection, $role) { $role = strtolower($role); $actualRole = $connection->executeCommand(RawCommand::create('ROLE')); if ($actualRole instanceof Error) { throw new ConnectionException($connection, $actualRole->getMessage()); } if ($role !== $actualRole[0]) { throw new RoleException($connection, "Expected $role but got $actualRole[0] [$connection]"); } } /** * {@inheritdoc} */ public function getConnectionByCommand(CommandInterface $command) { $connection = $this->getConnectionInternal($command); if (!$connection->isConnected()) { // When we do not have any available slave in the pool we can expect // read-only operations to hit the master server. $expectedRole = $this->strategy->isReadOperation($command) && $this->slaves ? 'slave' : 'master'; $this->assertConnectionRole($connection, $expectedRole); } return $connection; } /** * {@inheritdoc} */ public function getConnectionById($id) { return $this->pool[$id] ?? null; } /** * Returns a connection by its role. * * @param string $role Connection role (`master`, `slave` or `sentinel`) * * @return NodeConnectionInterface|null */ public function getConnectionByRole($role) { if ($role === 'master') { return $this->getMaster(); } elseif ($role === 'slave') { return $this->pickSlave(); } elseif ($role === 'sentinel') { return $this->getSentinelConnection(); } else { return null; } } /** * Switches the internal connection in use by the backend. * * Sentinel connections are not considered as part of the pool, meaning that * trying to switch to a sentinel will throw an exception. * * @param NodeConnectionInterface $connection Connection instance in the pool. */ public function switchTo(NodeConnectionInterface $connection) { if ($connection && $connection === $this->current) { return; } if ($connection !== $this->master && !in_array($connection, $this->slaves, true)) { throw new InvalidArgumentException('Invalid connection or connection not found.'); } $connection->connect(); if ($this->current) { $this->current->disconnect(); } $this->current = $connection; } /** * {@inheritdoc} */ public function switchToMaster() { $connection = $this->getConnectionByRole('master'); $this->switchTo($connection); } /** * {@inheritdoc} */ public function switchToSlave() { $connection = $this->getConnectionByRole('slave'); $this->switchTo($connection); } /** * {@inheritdoc} */ public function isConnected() { return $this->current ? $this->current->isConnected() : false; } /** * {@inheritdoc} */ public function connect() { if (!$this->current) { if (!$this->current = $this->pickSlave()) { $this->current = $this->getMaster(); } } $this->current->connect(); } /** * {@inheritdoc} */ public function disconnect() { foreach ($this->pool as $connection) { $connection->disconnect(); } } /** * Retries the execution of a command upon server failure after asking a new * configuration to one of the sentinels. * * @param CommandInterface $command Command instance. * @param string $method Actual method. * * @return mixed */ private function retryCommandOnFailure(CommandInterface $command, $method) { $retries = 0; while ($retries <= $this->retryLimit) { try { $response = $this->getConnectionByCommand($command)->$method($command); break; } catch (CommunicationException $exception) { $this->wipeServerList(); $exception->getConnection()->disconnect(); if ($retries === $this->retryLimit) { throw $exception; } usleep($this->retryWait * 1000); ++$retries; } } return $response; } /** * {@inheritdoc} */ public function writeRequest(CommandInterface $command) { $this->retryCommandOnFailure($command, __FUNCTION__); } /** * {@inheritdoc} */ public function readResponse(CommandInterface $command) { return $this->retryCommandOnFailure($command, __FUNCTION__); } /** * {@inheritdoc} */ public function executeCommand(CommandInterface $command) { return $this->retryCommandOnFailure($command, __FUNCTION__); } /** * Returns the underlying replication strategy. * * @return ReplicationStrategy */ public function getReplicationStrategy() { return $this->strategy; } /** * {@inheritdoc} */ public function __sleep() { return [ 'master', 'slaves', 'pool', 'service', 'sentinels', 'connectionFactory', 'strategy', ]; } } PK\X]P(99<predis/src/Connection/Replication/MasterSlaveReplication.phpnu[strategy = $strategy ?: new ReplicationStrategy(); } /** * Configures the automatic discovery of the replication configuration on failure. * * @param bool $value Enable or disable auto discovery. */ public function setAutoDiscovery($value) { if (!$this->connectionFactory) { throw new ClientException('Automatic discovery requires a connection factory'); } $this->autoDiscovery = (bool) $value; } /** * Sets the connection factory used to create the connections by the auto * discovery procedure. * * @param FactoryInterface $connectionFactory Connection factory instance. */ public function setConnectionFactory(FactoryInterface $connectionFactory) { $this->connectionFactory = $connectionFactory; } /** * Resets the connection state. */ protected function reset() { $this->current = null; } /** * {@inheritdoc} */ public function add(NodeConnectionInterface $connection) { $parameters = $connection->getParameters(); if ('master' === $parameters->role) { $this->master = $connection; } else { // everything else is considered a slvave. $this->slaves[] = $connection; } if (isset($parameters->alias)) { $this->aliases[$parameters->alias] = $connection; } $this->pool[(string) $connection] = $connection; $this->reset(); } /** * {@inheritdoc} */ public function remove(NodeConnectionInterface $connection) { if ($connection === $this->master) { $this->master = null; } elseif (false !== $id = array_search($connection, $this->slaves, true)) { unset($this->slaves[$id]); } else { return false; } unset($this->pool[(string) $connection]); if ($this->aliases && $alias = $connection->getParameters()->alias) { unset($this->aliases[$alias]); } $this->reset(); return true; } /** * {@inheritdoc} */ public function getConnectionByCommand(CommandInterface $command) { if (!$this->current) { if ($this->strategy->isReadOperation($command) && $slave = $this->pickSlave()) { $this->current = $slave; } else { $this->current = $this->getMasterOrDie(); } return $this->current; } if ($this->current === $master = $this->getMasterOrDie()) { return $master; } if (!$this->strategy->isReadOperation($command) || !$this->slaves) { $this->current = $master; } return $this->current; } /** * {@inheritdoc} */ public function getConnectionById($id) { return $this->pool[$id] ?? null; } /** * Returns a connection instance by its alias. * * @param string $alias Connection alias. * * @return NodeConnectionInterface|null */ public function getConnectionByAlias($alias) { return $this->aliases[$alias] ?? null; } /** * Returns a connection by its role. * * @param string $role Connection role (`master` or `slave`) * * @return NodeConnectionInterface|null */ public function getConnectionByRole($role) { if ($role === 'master') { return $this->getMaster(); } elseif ($role === 'slave') { return $this->pickSlave(); } return null; } /** * Switches the internal connection in use by the backend. * * @param NodeConnectionInterface $connection Connection instance in the pool. */ public function switchTo(NodeConnectionInterface $connection) { if ($connection && $connection === $this->current) { return; } if ($connection !== $this->master && !in_array($connection, $this->slaves, true)) { throw new InvalidArgumentException('Invalid connection or connection not found.'); } $this->current = $connection; } /** * {@inheritdoc} */ public function switchToMaster() { if (!$connection = $this->getConnectionByRole('master')) { throw new InvalidArgumentException('Invalid connection or connection not found.'); } $this->switchTo($connection); } /** * {@inheritdoc} */ public function switchToSlave() { if (!$connection = $this->getConnectionByRole('slave')) { throw new InvalidArgumentException('Invalid connection or connection not found.'); } $this->switchTo($connection); } /** * {@inheritdoc} */ public function getCurrent() { return $this->current; } /** * {@inheritdoc} */ public function getMaster() { return $this->master; } /** * Returns the connection associated to the master server. * * @return NodeConnectionInterface */ private function getMasterOrDie() { if (!$connection = $this->getMaster()) { throw new MissingMasterException('No master server available for replication'); } return $connection; } /** * {@inheritdoc} */ public function getSlaves() { return $this->slaves; } /** * Returns the underlying replication strategy. * * @return ReplicationStrategy */ public function getReplicationStrategy() { return $this->strategy; } /** * Returns a random slave. * * @return NodeConnectionInterface|null */ protected function pickSlave() { if (!$this->slaves) { return null; } return $this->slaves[array_rand($this->slaves)]; } /** * {@inheritdoc} */ public function isConnected() { return $this->current ? $this->current->isConnected() : false; } /** * {@inheritdoc} */ public function connect() { if (!$this->current) { if (!$this->current = $this->pickSlave()) { if (!$this->current = $this->getMaster()) { throw new ClientException('No available connection for replication'); } } } $this->current->connect(); } /** * {@inheritdoc} */ public function disconnect() { foreach ($this->pool as $connection) { $connection->disconnect(); } } /** * Handles response from INFO. * * @param string $response * * @return array */ private function handleInfoResponse($response) { $info = []; foreach (preg_split('/\r?\n/', $response) as $row) { if (strpos($row, ':') === false) { continue; } [$k, $v] = explode(':', $row, 2); $info[$k] = $v; } return $info; } /** * Fetches the replication configuration from one of the servers. */ public function discover() { if (!$this->connectionFactory) { throw new ClientException('Discovery requires a connection factory'); } while (true) { try { if ($connection = $this->getMaster()) { $this->discoverFromMaster($connection, $this->connectionFactory); break; } elseif ($connection = $this->pickSlave()) { $this->discoverFromSlave($connection, $this->connectionFactory); break; } else { throw new ClientException('No connection available for discovery'); } } catch (ConnectionException $exception) { $this->remove($connection); } } } /** * Discovers the replication configuration by contacting the master node. * * @param NodeConnectionInterface $connection Connection to the master node. * @param FactoryInterface $connectionFactory Connection factory instance. */ protected function discoverFromMaster(NodeConnectionInterface $connection, FactoryInterface $connectionFactory) { $response = $connection->executeCommand(RawCommand::create('INFO', 'REPLICATION')); $replication = $this->handleInfoResponse($response); if ($replication['role'] !== 'master') { throw new ClientException("Role mismatch (expected master, got slave) [$connection]"); } $this->slaves = []; foreach ($replication as $k => $v) { $parameters = null; if (strpos($k, 'slave') === 0 && preg_match('/ip=(?P.*),port=(?P\d+)/', $v, $parameters)) { $slaveConnection = $connectionFactory->create([ 'host' => $parameters['host'], 'port' => $parameters['port'], 'role' => 'slave', ]); $this->add($slaveConnection); } } } /** * Discovers the replication configuration by contacting one of the slaves. * * @param NodeConnectionInterface $connection Connection to one of the slaves. * @param FactoryInterface $connectionFactory Connection factory instance. */ protected function discoverFromSlave(NodeConnectionInterface $connection, FactoryInterface $connectionFactory) { $response = $connection->executeCommand(RawCommand::create('INFO', 'REPLICATION')); $replication = $this->handleInfoResponse($response); if ($replication['role'] !== 'slave') { throw new ClientException("Role mismatch (expected slave, got master) [$connection]"); } $masterConnection = $connectionFactory->create([ 'host' => $replication['master_host'], 'port' => $replication['master_port'], 'role' => 'master', ]); $this->add($masterConnection); $this->discoverFromMaster($masterConnection, $connectionFactory); } /** * Retries the execution of a command upon slave failure. * * @param CommandInterface $command Command instance. * @param string $method Actual method. * * @return mixed */ private function retryCommandOnFailure(CommandInterface $command, $method) { while (true) { try { $connection = $this->getConnectionByCommand($command); $response = $connection->$method($command); if ($response instanceof ResponseErrorInterface && $response->getErrorType() === 'LOADING') { throw new ConnectionException($connection, "Redis is loading the dataset in memory [$connection]"); } break; } catch (ConnectionException $exception) { $connection = $exception->getConnection(); $connection->disconnect(); if ($connection === $this->master && !$this->autoDiscovery) { // Throw immediately when master connection is failing, even // when the command represents a read-only operation, unless // automatic discovery has been enabled. throw $exception; } else { // Otherwise remove the failing slave and attempt to execute // the command again on one of the remaining slaves... $this->remove($connection); } // ... that is, unless we have no more connections to use. if (!$this->slaves && !$this->master) { throw $exception; } elseif ($this->autoDiscovery) { $this->discover(); } } catch (MissingMasterException $exception) { if ($this->autoDiscovery) { $this->discover(); } else { throw $exception; } } } return $response; } /** * {@inheritdoc} */ public function writeRequest(CommandInterface $command) { $this->retryCommandOnFailure($command, __FUNCTION__); } /** * {@inheritdoc} */ public function readResponse(CommandInterface $command) { return $this->retryCommandOnFailure($command, __FUNCTION__); } /** * {@inheritdoc} */ public function executeCommand(CommandInterface $command) { return $this->retryCommandOnFailure($command, __FUNCTION__); } /** * {@inheritdoc} */ public function __sleep() { return ['master', 'slaves', 'pool', 'aliases', 'strategy']; } } PK\X]'o:predis/src/Connection/Replication/ReplicationInterface.phpnu[parameters->persistent) && $this->parameters->persistent) { return; } $this->disconnect(); } /** * {@inheritdoc} */ protected function assertParameters(ParametersInterface $parameters) { switch ($parameters->scheme) { case 'tcp': case 'redis': case 'unix': case 'tls': case 'rediss': break; default: throw new InvalidArgumentException("Invalid scheme: '$parameters->scheme'."); } return $parameters; } /** * {@inheritdoc} */ protected function createResource() { switch ($this->parameters->scheme) { case 'tcp': case 'redis': return $this->tcpStreamInitializer($this->parameters); case 'unix': return $this->unixStreamInitializer($this->parameters); case 'tls': case 'rediss': return $this->tlsStreamInitializer($this->parameters); default: throw new InvalidArgumentException("Invalid scheme: '{$this->parameters->scheme}'."); } } /** * Creates a connected stream socket resource. * * @param ParametersInterface $parameters Connection parameters. * @param string $address Address for stream_socket_client(). * @param int $flags Flags for stream_socket_client(). * * @return resource */ protected function createStreamSocket(ParametersInterface $parameters, $address, $flags) { $timeout = (isset($parameters->timeout) ? (float) $parameters->timeout : 5.0); $context = stream_context_create(['socket' => ['tcp_nodelay' => (bool) $parameters->tcp_nodelay]]); if (!$resource = @stream_socket_client($address, $errno, $errstr, $timeout, $flags, $context)) { $this->onConnectionError(trim($errstr), $errno); } if (isset($parameters->read_write_timeout)) { $rwtimeout = (float) $parameters->read_write_timeout; $rwtimeout = $rwtimeout > 0 ? $rwtimeout : -1; $timeoutSeconds = floor($rwtimeout); $timeoutUSeconds = ($rwtimeout - $timeoutSeconds) * 1000000; stream_set_timeout($resource, $timeoutSeconds, $timeoutUSeconds); } return $resource; } /** * Initializes a TCP stream resource. * * @param ParametersInterface $parameters Initialization parameters for the connection. * * @return resource */ protected function tcpStreamInitializer(ParametersInterface $parameters) { if (!filter_var($parameters->host, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6)) { $address = "tcp://$parameters->host:$parameters->port"; } else { $address = "tcp://[$parameters->host]:$parameters->port"; } $flags = STREAM_CLIENT_CONNECT; if (isset($parameters->async_connect) && $parameters->async_connect) { $flags |= STREAM_CLIENT_ASYNC_CONNECT; } if (isset($parameters->persistent)) { if (false !== $persistent = filter_var($parameters->persistent, FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE)) { $flags |= STREAM_CLIENT_PERSISTENT; if ($persistent === null) { $address = "{$address}/{$parameters->persistent}"; } } } return $this->createStreamSocket($parameters, $address, $flags); } /** * Initializes a UNIX stream resource. * * @param ParametersInterface $parameters Initialization parameters for the connection. * * @return resource */ protected function unixStreamInitializer(ParametersInterface $parameters) { if (!isset($parameters->path)) { throw new InvalidArgumentException('Missing UNIX domain socket path.'); } $flags = STREAM_CLIENT_CONNECT; if (isset($parameters->persistent)) { if (false !== $persistent = filter_var($parameters->persistent, FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE)) { $flags |= STREAM_CLIENT_PERSISTENT; if ($persistent === null) { throw new InvalidArgumentException( 'Persistent connection IDs are not supported when using UNIX domain sockets.' ); } } } return $this->createStreamSocket($parameters, "unix://{$parameters->path}", $flags); } /** * Initializes a SSL-encrypted TCP stream resource. * * @param ParametersInterface $parameters Initialization parameters for the connection. * * @return resource */ protected function tlsStreamInitializer(ParametersInterface $parameters) { $resource = $this->tcpStreamInitializer($parameters); $metadata = stream_get_meta_data($resource); // Detect if crypto mode is already enabled for this stream (PHP >= 7.0.0). if (isset($metadata['crypto'])) { return $resource; } if (isset($parameters->ssl) && is_array($parameters->ssl)) { $options = $parameters->ssl; } else { $options = []; } if (!isset($options['crypto_type'])) { $options['crypto_type'] = STREAM_CRYPTO_METHOD_TLS_CLIENT; } if (!stream_context_set_option($resource, ['ssl' => $options])) { $this->onConnectionError('Error while setting SSL context options'); } if (!stream_socket_enable_crypto($resource, true, $options['crypto_type'])) { $this->onConnectionError('Error while switching to encrypted communication'); } return $resource; } /** * {@inheritdoc} */ public function connect() { if (parent::connect() && $this->initCommands) { foreach ($this->initCommands as $command) { $response = $this->executeCommand($command); if ($response instanceof ErrorResponseInterface && $command->getId() === 'CLIENT') { // Do nothing on CLIENT SETINFO command failure } elseif ($response instanceof ErrorResponseInterface) { $this->onConnectionError("`{$command->getId()}` failed: {$response->getMessage()}", 0); } } } } /** * {@inheritdoc} */ public function disconnect() { if ($this->isConnected()) { $resource = $this->getResource(); if (is_resource($resource)) { fclose($resource); } parent::disconnect(); } } /** * Performs a write operation over the stream of the buffer containing a * command serialized with the Redis wire protocol. * * @param string $buffer Representation of a command in the Redis wire protocol. */ protected function write($buffer) { $socket = $this->getResource(); while (($length = strlen($buffer)) > 0) { $written = is_resource($socket) ? @fwrite($socket, $buffer) : false; if ($length === $written) { return; } if ($written === false || $written === 0) { $this->onConnectionError('Error while writing bytes to the server.'); } $buffer = substr($buffer, $written); } } /** * {@inheritdoc} */ public function read() { $socket = $this->getResource(); $chunk = fgets($socket); if ($chunk === false || $chunk === '') { $this->onConnectionError('Error while reading line from the server.'); } $prefix = $chunk[0]; $payload = substr($chunk, 1, -2); switch ($prefix) { case '+': return StatusResponse::get($payload); case '$': $size = (int) $payload; if ($size === -1) { return; } $bulkData = ''; $bytesLeft = ($size += 2); do { $chunk = is_resource($socket) ? fread($socket, min($bytesLeft, 4096)) : false; if ($chunk === false || $chunk === '') { $this->onConnectionError('Error while reading bytes from the server.'); } $bulkData .= $chunk; $bytesLeft = $size - strlen($bulkData); } while ($bytesLeft > 0); return substr($bulkData, 0, -2); case '*': $count = (int) $payload; if ($count === -1) { return; } $multibulk = []; for ($i = 0; $i < $count; ++$i) { $multibulk[$i] = $this->read(); } return $multibulk; case ':': $integer = (int) $payload; return $integer == $payload ? $integer : $payload; case '-': return new ErrorResponse($payload); default: $this->onProtocolError("Unknown response prefix: '$prefix'."); return; } } /** * {@inheritdoc} */ public function writeRequest(CommandInterface $command) { $commandID = $command->getId(); $arguments = $command->getArguments(); $cmdlen = strlen($commandID); $reqlen = count($arguments) + 1; $buffer = "*{$reqlen}\r\n\${$cmdlen}\r\n{$commandID}\r\n"; foreach ($arguments as $argument) { $arglen = strlen(strval($argument)); $buffer .= "\${$arglen}\r\n{$argument}\r\n"; } $this->write($buffer); } } PK\X]!883predis/src/Connection/PhpiredisStreamConnection.phpnu[assertExtensions(); parent::__construct($parameters); $this->reader = $this->createReader(); } /** * {@inheritdoc} */ public function __destruct() { parent::__destruct(); phpiredis_reader_destroy($this->reader); } /** * {@inheritdoc} */ public function disconnect() { phpiredis_reader_reset($this->reader); parent::disconnect(); } /** * Checks if the phpiredis extension is loaded in PHP. */ private function assertExtensions() { if (!extension_loaded('phpiredis')) { throw new NotSupportedException( 'The "phpiredis" extension is required by this connection backend.' ); } } /** * {@inheritdoc} */ protected function assertParameters(ParametersInterface $parameters) { switch ($parameters->scheme) { case 'tcp': case 'redis': case 'unix': break; case 'tls': case 'rediss': throw new InvalidArgumentException('SSL encryption is not supported by this connection backend.'); default: throw new InvalidArgumentException("Invalid scheme: '$parameters->scheme'."); } return $parameters; } /** * {@inheritdoc} */ protected function createStreamSocket(ParametersInterface $parameters, $address, $flags) { $socket = null; $timeout = (isset($parameters->timeout) ? (float) $parameters->timeout : 5.0); $context = stream_context_create(['socket' => ['tcp_nodelay' => (bool) $parameters->tcp_nodelay]]); if (!$resource = @stream_socket_client($address, $errno, $errstr, $timeout, $flags, $context)) { $this->onConnectionError(trim($errstr), $errno); } if (isset($parameters->read_write_timeout) && function_exists('socket_import_stream')) { $rwtimeout = (float) $parameters->read_write_timeout; $rwtimeout = $rwtimeout > 0 ? $rwtimeout : -1; $timeout = [ 'sec' => $timeoutSeconds = floor($rwtimeout), 'usec' => ($rwtimeout - $timeoutSeconds) * 1000000, ]; $socket = $socket ?: socket_import_stream($resource); @socket_set_option($socket, SOL_SOCKET, SO_SNDTIMEO, $timeout); @socket_set_option($socket, SOL_SOCKET, SO_RCVTIMEO, $timeout); } if (isset($parameters->tcp_nodelay) && function_exists('socket_import_stream')) { $socket = $socket ?: socket_import_stream($resource); socket_set_option($socket, SOL_TCP, TCP_NODELAY, (int) $parameters->tcp_nodelay); } return $resource; } /** * Creates a new instance of the protocol reader resource. * * @return resource */ private function createReader() { $reader = phpiredis_reader_create(); phpiredis_reader_set_status_handler($reader, $this->getStatusHandler()); phpiredis_reader_set_error_handler($reader, $this->getErrorHandler()); return $reader; } /** * Returns the underlying protocol reader resource. * * @return resource */ protected function getReader() { return $this->reader; } /** * Returns the handler used by the protocol reader for inline responses. * * @return Closure */ protected function getStatusHandler() { static $statusHandler; if (!$statusHandler) { $statusHandler = function ($payload) { return StatusResponse::get($payload); }; } return $statusHandler; } /** * Returns the handler used by the protocol reader for error responses. * * @return Closure */ protected function getErrorHandler() { static $errorHandler; if (!$errorHandler) { $errorHandler = function ($errorMessage) { return new ErrorResponse($errorMessage); }; } return $errorHandler; } /** * {@inheritdoc} */ public function read() { $socket = $this->getResource(); $reader = $this->reader; while (PHPIREDIS_READER_STATE_INCOMPLETE === $state = phpiredis_reader_get_state($reader)) { $buffer = stream_socket_recvfrom($socket, 4096); if ($buffer === false || $buffer === '') { $this->onConnectionError('Error while reading bytes from the server.'); } phpiredis_reader_feed($reader, $buffer); } if ($state === PHPIREDIS_READER_STATE_COMPLETE) { return phpiredis_reader_get_reply($reader); } else { $this->onProtocolError(phpiredis_reader_get_error($reader)); return; } } /** * {@inheritdoc} */ public function writeRequest(CommandInterface $command) { $arguments = $command->getArguments(); array_unshift($arguments, $command->getId()); $this->write(phpiredis_format_command($arguments)); } /** * {@inheritdoc} */ public function __wakeup() { $this->assertExtensions(); $this->reader = $this->createReader(); } } PK\X]0-predis/src/Connection/ConnectionException.phpnu[client->onFlushed($callback); } /** * Registers a new `invalidated` event listener. * * @param callable $callback * @param string|null $pattern * @return bool */ public function onInvalidated(?callable $callback, ?string $pattern = null) { return $this->client->onInvalidated($callback, $pattern); } /** * Dispatches all pending events. * * @return int|false */ public function dispatchEvents() { return $this->client->dispatchEvents(); } /** * Adds ignore pattern(s). Matching keys will not be cached in memory. * * @param string $pattern,... * @return int */ public function addIgnorePatterns(string ...$pattern) { return $this->client->addIgnorePatterns(...$pattern); } /** * Adds allow pattern(s). Only matching keys will be cached in memory. * * @param string $pattern,... * @return int */ public function addAllowPatterns(string ...$pattern) { return $this->client->addAllowPatterns(...$pattern); } /** * Returns the connection's endpoint identifier. * * @return string|false */ public function endpointId() { return $this->client->endpointId(); } /** * Returns a unique representation of the underlying socket connection identifier. * * @return string|false */ public function socketId() { return $this->client->socketId(); } /** * Returns information about the license. * * @return array */ public function license() { return $this->client->license(); } /** * Returns statistics about Relay. * * @return array> */ public function stats() { return $this->client->stats(); } /** * Returns the number of bytes allocated, or `0` in client-only mode. * * @return int */ public function maxMemory() { return $this->client->maxMemory(); } /** * Flushes Relay's in-memory cache of all databases. * When given an endpoint, only that connection will be flushed. * When given an endpoint and database index, only that database * for that connection will be flushed. * * @param ?string $endpointId * @param ?int $db * @return bool */ public function flushMemory(?string $endpointId = null, ?int $db = null) { return $this->client->flushMemory($endpointId, $db); } } PK\X]X:.:.3predis/src/Connection/PhpiredisSocketConnection.phpnu[assertExtensions(); parent::__construct($parameters); $this->reader = $this->createReader(); } /** * Disconnects from the server and destroys the underlying resource and the * protocol reader resource when PHP's garbage collector kicks in. */ public function __destruct() { parent::__destruct(); phpiredis_reader_destroy($this->reader); } /** * Checks if the socket and phpiredis extensions are loaded in PHP. */ protected function assertExtensions() { if (!extension_loaded('sockets')) { throw new NotSupportedException( 'The "sockets" extension is required by this connection backend.' ); } if (!extension_loaded('phpiredis')) { throw new NotSupportedException( 'The "phpiredis" extension is required by this connection backend.' ); } } /** * {@inheritdoc} */ protected function assertParameters(ParametersInterface $parameters) { switch ($parameters->scheme) { case 'tcp': case 'redis': case 'unix': break; default: throw new InvalidArgumentException("Invalid scheme: '$parameters->scheme'."); } if (isset($parameters->persistent)) { throw new NotSupportedException( 'Persistent connections are not supported by this connection backend.' ); } return $parameters; } /** * Creates a new instance of the protocol reader resource. * * @return resource */ private function createReader() { $reader = phpiredis_reader_create(); phpiredis_reader_set_status_handler($reader, $this->getStatusHandler()); phpiredis_reader_set_error_handler($reader, $this->getErrorHandler()); return $reader; } /** * Returns the underlying protocol reader resource. * * @return resource */ protected function getReader() { return $this->reader; } /** * Returns the handler used by the protocol reader for inline responses. * * @return Closure */ protected function getStatusHandler() { static $statusHandler; if (!$statusHandler) { $statusHandler = function ($payload) { return StatusResponse::get($payload); }; } return $statusHandler; } /** * Returns the handler used by the protocol reader for error responses. * * @return Closure */ protected function getErrorHandler() { static $errorHandler; if (!$errorHandler) { $errorHandler = function ($errorMessage) { return new ErrorResponse($errorMessage); }; } return $errorHandler; } /** * Helper method used to throw exceptions on socket errors. */ private function emitSocketError() { $errno = socket_last_error(); $errstr = socket_strerror($errno); $this->disconnect(); $this->onConnectionError(trim($errstr), $errno); } /** * Gets the address of an host from connection parameters. * * @param ParametersInterface $parameters Parameters used to initialize the connection. * * @return string */ protected static function getAddress(ParametersInterface $parameters) { if (filter_var($host = $parameters->host, FILTER_VALIDATE_IP)) { return $host; } if ($host === $address = gethostbyname($host)) { return false; } return $address; } /** * {@inheritdoc} */ protected function createResource() { $parameters = $this->parameters; if ($parameters->scheme === 'unix') { $address = $parameters->path; $domain = AF_UNIX; $protocol = 0; } else { if (false === $address = self::getAddress($parameters)) { $this->onConnectionError("Cannot resolve the address of '$parameters->host'."); } $domain = filter_var($address, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6) ? AF_INET6 : AF_INET; $protocol = SOL_TCP; } if (false === $socket = @socket_create($domain, SOCK_STREAM, $protocol)) { $this->emitSocketError(); } $this->setSocketOptions($socket, $parameters); $this->connectWithTimeout($socket, $address, $parameters); return $socket; } /** * Sets options on the socket resource from the connection parameters. * * @param resource $socket Socket resource. * @param ParametersInterface $parameters Parameters used to initialize the connection. */ private function setSocketOptions($socket, ParametersInterface $parameters) { if ($parameters->scheme !== 'unix') { if (!socket_set_option($socket, SOL_TCP, TCP_NODELAY, 1)) { $this->emitSocketError(); } if (!socket_set_option($socket, SOL_SOCKET, SO_REUSEADDR, 1)) { $this->emitSocketError(); } } if (isset($parameters->read_write_timeout)) { $rwtimeout = (float) $parameters->read_write_timeout; $timeoutSec = floor($rwtimeout); $timeoutUsec = ($rwtimeout - $timeoutSec) * 1000000; $timeout = [ 'sec' => $timeoutSec, 'usec' => $timeoutUsec, ]; if (!socket_set_option($socket, SOL_SOCKET, SO_SNDTIMEO, $timeout)) { $this->emitSocketError(); } if (!socket_set_option($socket, SOL_SOCKET, SO_RCVTIMEO, $timeout)) { $this->emitSocketError(); } } } /** * Opens the actual connection to the server with a timeout. * * @param resource $socket Socket resource. * @param string $address IP address (DNS-resolved from hostname) * @param ParametersInterface $parameters Parameters used to initialize the connection. * * @return void */ private function connectWithTimeout($socket, $address, ParametersInterface $parameters) { socket_set_nonblock($socket); if (@socket_connect($socket, $address, (int) $parameters->port) === false) { $error = socket_last_error(); if ($error != SOCKET_EINPROGRESS && $error != SOCKET_EALREADY) { $this->emitSocketError(); } } socket_set_block($socket); $null = null; $selectable = [$socket]; $timeout = (isset($parameters->timeout) ? (float) $parameters->timeout : 5.0); $timeoutSecs = floor($timeout); $timeoutUSecs = ($timeout - $timeoutSecs) * 1000000; $selected = socket_select($selectable, $selectable, $null, $timeoutSecs, $timeoutUSecs); if ($selected === 2) { $this->onConnectionError('Connection refused.', SOCKET_ECONNREFUSED); } if ($selected === 0) { $this->onConnectionError('Connection timed out.', SOCKET_ETIMEDOUT); } if ($selected === false) { $this->emitSocketError(); } } /** * {@inheritdoc} */ public function connect() { if (parent::connect() && $this->initCommands) { foreach ($this->initCommands as $command) { $response = $this->executeCommand($command); if ($response instanceof ErrorResponseInterface) { $this->onConnectionError("`{$command->getId()}` failed: {$response->getMessage()}", 0); } } } } /** * {@inheritdoc} */ public function disconnect() { if ($this->isConnected()) { phpiredis_reader_reset($this->reader); socket_close($this->getResource()); parent::disconnect(); } } /** * {@inheritdoc} */ protected function write($buffer) { $socket = $this->getResource(); while (($length = strlen($buffer)) > 0) { $written = socket_write($socket, $buffer, $length); if ($length === $written) { return; } if ($written === false) { $this->onConnectionError('Error while writing bytes to the server.'); } $buffer = substr($buffer, $written); } } /** * {@inheritdoc} */ public function read() { $socket = $this->getResource(); $reader = $this->reader; while (PHPIREDIS_READER_STATE_INCOMPLETE === $state = phpiredis_reader_get_state($reader)) { if (@socket_recv($socket, $buffer, 4096, 0) === false || $buffer === '' || $buffer === null) { $this->emitSocketError(); } phpiredis_reader_feed($reader, $buffer); } if ($state === PHPIREDIS_READER_STATE_COMPLETE) { return phpiredis_reader_get_reply($reader); } else { $this->onProtocolError(phpiredis_reader_get_error($reader)); return; } } /** * {@inheritdoc} */ public function writeRequest(CommandInterface $command) { $arguments = $command->getArguments(); array_unshift($arguments, $command->getId()); $this->write(phpiredis_format_command($arguments)); } /** * {@inheritdoc} */ public function __wakeup() { $this->assertExtensions(); $this->reader = $this->createReader(); } } PK\X]fqЛ6predis/src/Connection/CompositeConnectionInterface.phpnu[assertExtensions(); if ($parameters->scheme !== 'http') { throw new InvalidArgumentException("Invalid scheme: '{$parameters->scheme}'."); } $this->parameters = $parameters; $this->resource = $this->createCurl(); $this->reader = $this->createReader(); } /** * Frees the underlying cURL and protocol reader resources when the garbage * collector kicks in. */ public function __destruct() { curl_close($this->resource); phpiredis_reader_destroy($this->reader); } /** * Helper method used to throw on unsupported methods. * * @param string $method Name of the unsupported method. * * @throws NotSupportedException */ private function throwNotSupportedException($method) { $class = __CLASS__; throw new NotSupportedException("The method $class::$method() is not supported."); } /** * Checks if the cURL and phpiredis extensions are loaded in PHP. */ private function assertExtensions() { if (!extension_loaded('curl')) { throw new NotSupportedException( 'The "curl" extension is required by this connection backend.' ); } if (!extension_loaded('phpiredis')) { throw new NotSupportedException( 'The "phpiredis" extension is required by this connection backend.' ); } } /** * Initializes cURL. * * @return resource */ private function createCurl() { $parameters = $this->getParameters(); $timeout = (isset($parameters->timeout) ? (float) $parameters->timeout : 5.0) * 1000; if (filter_var($host = $parameters->host, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6)) { $host = "[$host]"; } $options = [ CURLOPT_FAILONERROR => true, CURLOPT_CONNECTTIMEOUT_MS => $timeout, CURLOPT_URL => "$parameters->scheme://$host:$parameters->port", CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_POST => true, CURLOPT_WRITEFUNCTION => [$this, 'feedReader'], ]; if (isset($parameters->user, $parameters->pass)) { $options[CURLOPT_USERPWD] = "{$parameters->user}:{$parameters->pass}"; } curl_setopt_array($resource = curl_init(), $options); return $resource; } /** * Initializes the phpiredis protocol reader. * * @return resource */ private function createReader() { $reader = phpiredis_reader_create(); phpiredis_reader_set_status_handler($reader, $this->getStatusHandler()); phpiredis_reader_set_error_handler($reader, $this->getErrorHandler()); return $reader; } /** * Returns the handler used by the protocol reader for inline responses. * * @return Closure */ protected function getStatusHandler() { static $statusHandler; if (!$statusHandler) { $statusHandler = function ($payload) { return StatusResponse::get($payload); }; } return $statusHandler; } /** * Returns the handler used by the protocol reader for error responses. * * @return Closure */ protected function getErrorHandler() { static $errorHandler; if (!$errorHandler) { $errorHandler = function ($errorMessage) { return new ErrorResponse($errorMessage); }; } return $errorHandler; } /** * Feeds the phpredis reader resource with the data read from the network. * * @param resource $resource Reader resource. * @param string $buffer Buffer of data read from a connection. * * @return int */ protected function feedReader($resource, $buffer) { phpiredis_reader_feed($this->reader, $buffer); return strlen($buffer); } /** * {@inheritdoc} */ public function connect() { // NOOP } /** * {@inheritdoc} */ public function disconnect() { // NOOP } /** * {@inheritdoc} */ public function isConnected() { return true; } /** * Checks if the specified command is supported by this connection class. * * @param CommandInterface $command Command instance. * * @return string * @throws NotSupportedException */ protected function getCommandId(CommandInterface $command) { switch ($commandID = $command->getId()) { case 'AUTH': case 'SELECT': case 'MULTI': case 'EXEC': case 'WATCH': case 'UNWATCH': case 'DISCARD': case 'MONITOR': throw new NotSupportedException("Command '$commandID' is not allowed by Webdis."); default: return $commandID; } } /** * {@inheritdoc} */ public function writeRequest(CommandInterface $command) { $this->throwNotSupportedException(__FUNCTION__); } /** * {@inheritdoc} */ public function readResponse(CommandInterface $command) { $this->throwNotSupportedException(__FUNCTION__); } /** * {@inheritdoc} */ public function executeCommand(CommandInterface $command) { $resource = $this->resource; $commandId = $this->getCommandId($command); if ($arguments = $command->getArguments()) { $arguments = implode('/', array_map('urlencode', $arguments)); $serializedCommand = "$commandId/$arguments.raw"; } else { $serializedCommand = "$commandId.raw"; } curl_setopt($resource, CURLOPT_POSTFIELDS, $serializedCommand); if (curl_exec($resource) === false) { $error = trim(curl_error($resource)); $errno = curl_errno($resource); throw new ConnectionException($this, "$error{$this->getParameters()}]", $errno); } if (phpiredis_reader_get_state($this->reader) !== PHPIREDIS_READER_STATE_COMPLETE) { throw new ProtocolException($this, phpiredis_reader_get_error($this->reader)); } return phpiredis_reader_get_reply($this->reader); } /** * {@inheritdoc} */ public function getResource() { return $this->resource; } /** * {@inheritdoc} */ public function getParameters() { return $this->parameters; } /** * {@inheritdoc} */ public function addConnectCommand(CommandInterface $command) { $this->throwNotSupportedException(__FUNCTION__); } /** * {@inheritdoc} */ public function read() { $this->throwNotSupportedException(__FUNCTION__); } /** * {@inheritdoc} */ public function __toString() { return "{$this->parameters->host}:{$this->parameters->port}"; } /** * {@inheritdoc} */ public function __sleep() { return ['parameters']; } /** * {@inheritdoc} */ public function __wakeup() { $this->assertExtensions(); $this->resource = $this->createCurl(); $this->reader = $this->createReader(); } } PK\X] j 3predis/src/Connection/CompositeStreamConnection.phpnu[parameters = $this->assertParameters($parameters); $this->protocol = $protocol ?: new TextProtocolProcessor(); } /** * {@inheritdoc} */ public function getProtocol() { return $this->protocol; } /** * {@inheritdoc} */ public function writeBuffer($buffer) { $this->write($buffer); } /** * {@inheritdoc} */ public function readBuffer($length) { if ($length <= 0) { throw new InvalidArgumentException('Length parameter must be greater than 0.'); } $value = ''; $socket = $this->getResource(); do { $chunk = fread($socket, $length); if ($chunk === false || $chunk === '') { $this->onConnectionError('Error while reading bytes from the server.'); } $value .= $chunk; } while (($length -= strlen($chunk)) > 0); return $value; } /** * {@inheritdoc} */ public function readLine() { $value = ''; $socket = $this->getResource(); do { $chunk = fgets($socket); if ($chunk === false || $chunk === '') { $this->onConnectionError('Error while reading line from the server.'); } $value .= $chunk; } while (substr($value, -2) !== "\r\n"); return substr($value, 0, -2); } /** * {@inheritdoc} */ public function writeRequest(CommandInterface $command) { $this->protocol->write($this, $command); } /** * {@inheritdoc} */ public function read() { return $this->protocol->read($this); } /** * {@inheritdoc} */ public function __sleep() { return array_merge(parent::__sleep(), ['protocol']); } } PK\X]!predis/src/Connection/Factory.phpnu[ 'Predis\Connection\StreamConnection', 'unix' => 'Predis\Connection\StreamConnection', 'tls' => 'Predis\Connection\StreamConnection', 'redis' => 'Predis\Connection\StreamConnection', 'rediss' => 'Predis\Connection\StreamConnection', 'http' => 'Predis\Connection\WebdisConnection', ]; /** * Checks if the provided argument represents a valid connection class * implementing Predis\Connection\NodeConnectionInterface. Optionally, * callable objects are used for lazy initialization of connection objects. * * @param mixed $initializer FQN of a connection class or a callable for lazy initialization. * * @return mixed * @throws InvalidArgumentException */ protected function checkInitializer($initializer) { if (is_callable($initializer)) { return $initializer; } $class = new ReflectionClass($initializer); if (!$class->isSubclassOf('Predis\Connection\NodeConnectionInterface')) { throw new InvalidArgumentException( 'A connection initializer must be a valid connection class or a callable object.' ); } return $initializer; } /** * {@inheritdoc} */ public function define($scheme, $initializer) { $this->schemes[$scheme] = $this->checkInitializer($initializer); } /** * {@inheritdoc} */ public function undefine($scheme) { unset($this->schemes[$scheme]); } /** * {@inheritdoc} */ public function create($parameters) { if (!$parameters instanceof ParametersInterface) { $parameters = $this->createParameters($parameters); } $scheme = $parameters->scheme; if (!isset($this->schemes[$scheme])) { throw new InvalidArgumentException("Unknown connection scheme: '$scheme'."); } $initializer = $this->schemes[$scheme]; if (is_callable($initializer)) { $connection = call_user_func($initializer, $parameters, $this); } else { $connection = new $initializer($parameters); $this->prepareConnection($connection); } if (!$connection instanceof NodeConnectionInterface) { throw new UnexpectedValueException( 'Objects returned by connection initializers must implement ' . "'Predis\Connection\NodeConnectionInterface'." ); } return $connection; } /** * Assigns a default set of parameters applied to new connections. * * The set of parameters passed to create a new connection have precedence * over the default values set for the connection factory. * * @param array $parameters Set of connection parameters. */ public function setDefaultParameters(array $parameters) { $this->defaults = $parameters; } /** * Returns the default set of parameters applied to new connections. * * @return array */ public function getDefaultParameters() { return $this->defaults; } /** * Creates a connection parameters instance from the supplied argument. * * @param mixed $parameters Original connection parameters. * * @return ParametersInterface */ protected function createParameters($parameters) { if (is_string($parameters)) { $parameters = Parameters::parse($parameters); } else { $parameters = $parameters ?: []; } if ($this->defaults) { $parameters += $this->defaults; } return new Parameters($parameters); } /** * Prepares a connection instance after its initialization. * * @param NodeConnectionInterface $connection Connection instance. */ protected function prepareConnection(NodeConnectionInterface $connection) { $parameters = $connection->getParameters(); if (isset($parameters->password) && strlen($parameters->password)) { $cmdAuthArgs = isset($parameters->username) && strlen($parameters->username) ? [$parameters->username, $parameters->password] : [$parameters->password]; $connection->addConnectCommand( new RawCommand('AUTH', $cmdAuthArgs) ); } if (($parameters->client_info ?? false) && !$connection instanceof RelayConnection) { $connection->addConnectCommand( new RawCommand('CLIENT', ['SETINFO', 'LIB-NAME', 'predis']) ); $connection->addConnectCommand( new RawCommand('CLIENT', ['SETINFO', 'LIB-VER', Client::VERSION]) ); } if (isset($parameters->database) && strlen($parameters->database)) { $connection->addConnectCommand( new RawCommand('SELECT', [$parameters->database]) ); } } } PK\X]͑N""1predis/src/Connection/NodeConnectionInterface.phpnu[assertExtensions(); $this->parameters = $this->assertParameters($parameters); $this->client = $this->createClient(); } /** * {@inheritdoc} */ public function isConnected() { return $this->client->isConnected(); } /** * {@inheritdoc} */ public function disconnect() { if ($this->client->isConnected()) { $this->client->close(); } } /** * Checks if the Relay extension is loaded in PHP. */ private function assertExtensions() { if (!extension_loaded('relay')) { throw new NotSupportedException( 'The "relay" extension is required by this connection backend.' ); } } /** * {@inheritdoc} */ protected function assertParameters(ParametersInterface $parameters) { if (!in_array($parameters->scheme, ['tcp', 'tls', 'unix', 'redis', 'rediss'])) { throw new InvalidArgumentException("Invalid scheme: '{$parameters->scheme}'."); } if (!in_array($parameters->serializer, [null, 'php', 'igbinary', 'msgpack', 'json'])) { throw new InvalidArgumentException("Invalid serializer: '{$parameters->serializer}'."); } if (!in_array($parameters->compression, [null, 'lzf', 'lz4', 'zstd'])) { throw new InvalidArgumentException("Invalid compression algorithm: '{$parameters->compression}'."); } return $parameters; } /** * Creates a new instance of the client. * * @return Relay */ private function createClient() { $client = new Relay(); // throw when errors occur and return `null` for non-existent keys $client->setOption(Relay::OPT_PHPREDIS_COMPATIBILITY, false); // use reply literals $client->setOption(Relay::OPT_REPLY_LITERAL, true); // disable Relay's command/connection retry $client->setOption(Relay::OPT_MAX_RETRIES, 0); // whether to use in-memory caching $client->setOption(Relay::OPT_USE_CACHE, $this->parameters->cache ?? true); // set data serializer $client->setOption(Relay::OPT_SERIALIZER, constant(sprintf( '%s::SERIALIZER_%s', Relay::class, strtoupper($this->parameters->serializer ?? 'none') ))); // set data compression algorithm $client->setOption(Relay::OPT_COMPRESSION, constant(sprintf( '%s::COMPRESSION_%s', Relay::class, strtoupper($this->parameters->compression ?? 'none') ))); return $client; } /** * Returns the underlying client. * * @return Relay */ public function getClient() { return $this->client; } /** * {@inheritdoc} */ public function getIdentifier() { try { return $this->client->endpointId(); } catch (RelayException $ex) { return parent::getIdentifier(); } } /** * {@inheritdoc} */ protected function createStreamSocket(ParametersInterface $parameters, $address, $flags) { $timeout = isset($parameters->timeout) ? (float) $parameters->timeout : 5.0; $retry_interval = 0; $read_timeout = 5.0; if (isset($parameters->read_write_timeout)) { $read_timeout = (float) $parameters->read_write_timeout; $read_timeout = $read_timeout > 0 ? $read_timeout : 0; } try { $this->client->connect( $parameters->path ?? $parameters->host, isset($parameters->path) ? 0 : $parameters->port, $timeout, null, $retry_interval, $read_timeout ); } catch (RelayException $ex) { $this->onConnectionError($ex->getMessage(), $ex->getCode()); } return $this->client; } /** * {@inheritdoc} */ public function executeCommand(CommandInterface $command) { if (!$this->client->isConnected()) { $this->getResource(); } try { $name = $command->getId(); // When using compression or a serializer, we'll need a dedicated // handler for `Predis\Command\RawCommand` calls, currently both // parameters are unsupported until a future Relay release return in_array($name, $this->atypicalCommands) ? $this->client->{$name}(...$command->getArguments()) : $this->client->rawCommand($name, ...$command->getArguments()); } catch (RelayException $ex) { $exception = $this->onCommandError($ex, $command); if ($exception instanceof ErrorResponseInterface) { return $exception; } throw $exception; } } /** * {@inheritdoc} */ public function onCommandError(RelayException $exception, CommandInterface $command) { $code = $exception->getCode(); $message = $exception->getMessage(); if (strpos($message, 'RELAY_ERR_IO') !== false) { return new ConnectionException($this, $message, $code, $exception); } if (strpos($message, 'RELAY_ERR_REDIS') !== false) { return new ServerException($message, $code, $exception); } if (strpos($message, 'RELAY_ERR_WRONGTYPE') !== false && strpos($message, "Got reply-type 'status'") !== false) { $message = 'Operation against a key holding the wrong kind of value'; } return new ClientException($message, $code, $exception); } /** * Applies the configured serializer and compression to given value. * * @param mixed $value * @return string */ public function pack($value) { return $this->client->_pack($value); } /** * Deserializes and decompresses to given value. * * @param mixed $value * @return string */ public function unpack($value) { return $this->client->_unpack($value); } /** * {@inheritdoc} */ public function writeRequest(CommandInterface $command) { throw new NotSupportedException('The "relay" extension does not support writing requests.'); } /** * {@inheritdoc} */ public function readResponse(CommandInterface $command) { throw new NotSupportedException('The "relay" extension does not support reading responses.'); } /** * {@inheritdoc} */ public function __destruct() { $this->disconnect(); } /** * {@inheritdoc} */ public function __wakeup() { $this->assertExtensions(); $this->client = $this->createClient(); } } PK\X]wD9o$predis/src/Connection/Parameters.phpnu[ 'tcp', 'host' => '127.0.0.1', 'port' => 6379, ]; /** * Set of connection parameters already filtered * for NULL or 0-length string values. * * @var array */ protected $parameters; /** * @param array $parameters Named array of connection parameters. */ public function __construct(array $parameters = []) { $this->parameters = $this->filter($parameters + static::$defaults); } /** * Filters parameters removing entries with NULL or 0-length string values. * * @params array $parameters Array of parameters to be filtered * * @return array */ protected function filter(array $parameters) { return array_filter($parameters, function ($value) { return $value !== null && $value !== ''; }); } /** * Creates a new instance by supplying the initial parameters either in the * form of an URI string or a named array. * * @param array|string $parameters Set of connection parameters. * * @return Parameters */ public static function create($parameters) { if (is_string($parameters)) { $parameters = static::parse($parameters); } return new static($parameters ?: []); } /** * Parses an URI string returning an array of connection parameters. * * When using the "redis" and "rediss" schemes the URI is parsed according * to the rules defined by the provisional registration documents approved * by IANA. If the URI has a password in its "user-information" part or a * database number in the "path" part these values override the values of * "password" and "database" if they are present in the "query" part. * * @see http://www.iana.org/assignments/uri-schemes/prov/redis * @see http://www.iana.org/assignments/uri-schemes/prov/rediss * * @param string $uri URI string. * * @return array * @throws InvalidArgumentException */ public static function parse($uri) { if (stripos($uri, 'unix://') === 0) { // parse_url() can parse unix:/path/to/sock so we do not need the // unix:///path/to/sock hack, we will support it anyway until 2.0. $uri = str_ireplace('unix://', 'unix:', $uri); } if (!$parsed = parse_url($uri)) { throw new InvalidArgumentException("Invalid parameters URI: $uri"); } if ( isset($parsed['host']) && false !== strpos($parsed['host'], '[') && false !== strpos($parsed['host'], ']') ) { $parsed['host'] = substr($parsed['host'], 1, -1); } if (isset($parsed['query'])) { parse_str($parsed['query'], $queryarray); unset($parsed['query']); $parsed = array_merge($parsed, $queryarray); } if (stripos($uri, 'redis') === 0) { if (isset($parsed['user'])) { if (strlen($parsed['user'])) { $parsed['username'] = $parsed['user']; } unset($parsed['user']); } if (isset($parsed['pass'])) { if (strlen($parsed['pass'])) { $parsed['password'] = $parsed['pass']; } unset($parsed['pass']); } if (isset($parsed['path']) && preg_match('/^\/(\d+)(\/.*)?/', $parsed['path'], $path)) { $parsed['database'] = $path[1]; if (isset($path[2])) { $parsed['path'] = $path[2]; } else { unset($parsed['path']); } } } return $parsed; } /** * {@inheritdoc} */ public function toArray() { return $this->parameters; } /** * {@inheritdoc} */ public function __get($parameter) { if (isset($this->parameters[$parameter])) { return $this->parameters[$parameter]; } } /** * {@inheritdoc} */ public function __isset($parameter) { return isset($this->parameters[$parameter]); } /** * {@inheritdoc} */ public function __toString() { if ($this->scheme === 'unix') { return "$this->scheme:$this->path"; } if (filter_var($this->host, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6)) { return "$this->scheme://[$this->host]:$this->port"; } return "$this->scheme://$this->host:$this->port"; } /** * {@inheritdoc} */ public function __sleep() { return ['parameters']; } } PK\X]m ,predis/src/Connection/AbstractConnection.phpnu[parameters = $this->assertParameters($parameters); } /** * Disconnects from the server and destroys the underlying resource when * PHP's garbage collector kicks in. */ public function __destruct() { $this->disconnect(); } /** * Checks some of the parameters used to initialize the connection. * * @param ParametersInterface $parameters Initialization parameters for the connection. * * @return ParametersInterface * @throws InvalidArgumentException */ abstract protected function assertParameters(ParametersInterface $parameters); /** * Creates the underlying resource used to communicate with Redis. * * @return mixed */ abstract protected function createResource(); /** * {@inheritdoc} */ public function isConnected() { return isset($this->resource); } /** * {@inheritdoc} */ public function connect() { if (!$this->isConnected()) { $this->resource = $this->createResource(); return true; } return false; } /** * {@inheritdoc} */ public function disconnect() { unset($this->resource); } /** * {@inheritdoc} */ public function addConnectCommand(CommandInterface $command) { $this->initCommands[] = $command; } /** * {@inheritdoc} */ public function getInitCommands(): array { return $this->initCommands; } /** * {@inheritdoc} */ public function executeCommand(CommandInterface $command) { $this->writeRequest($command); return $this->readResponse($command); } /** * {@inheritdoc} */ public function readResponse(CommandInterface $command) { return $this->read(); } /** * Helper method to handle connection errors. * * @param string $message Error message. * @param int $code Error code. */ protected function onConnectionError($message, $code = 0) { CommunicationException::handle( new ConnectionException($this, "$message [{$this->getParameters()}]", $code) ); } /** * Helper method to handle protocol errors. * * @param string $message Error message. */ protected function onProtocolError($message) { CommunicationException::handle( new ProtocolException($this, "$message [{$this->getParameters()}]") ); } /** * {@inheritdoc} */ public function getResource() { if (isset($this->resource)) { return $this->resource; } $this->connect(); return $this->resource; } /** * {@inheritdoc} */ public function getParameters() { return $this->parameters; } /** * Gets an identifier for the connection. * * @return string */ protected function getIdentifier() { if ($this->parameters->scheme === 'unix') { return $this->parameters->path; } return "{$this->parameters->host}:{$this->parameters->port}"; } /** * {@inheritdoc} */ public function __toString() { if (!isset($this->cachedId)) { $this->cachedId = $this->getIdentifier(); } return $this->cachedId; } /** * {@inheritdoc} */ public function __sleep() { return ['parameters', 'initCommands']; } } PK\X]G.$$6predis/src/Connection/AggregateConnectionInterface.phpnu[> 8) ^ ord($value[$i])]) & 0xFFFF; } return $crc; } } PK\X]nx*predis/src/Cluster/Hash/PhpiredisCRC16.phpnu[ */ class HashRing implements DistributorInterface, HashGeneratorInterface { public const DEFAULT_REPLICAS = 128; public const DEFAULT_WEIGHT = 100; private $ring; private $ringKeys; private $ringKeysCount; private $replicas; private $nodeHashCallback; private $nodes = []; /** * @param int $replicas Number of replicas in the ring. * @param mixed $nodeHashCallback Callback returning a string used to calculate the hash of nodes. */ public function __construct($replicas = self::DEFAULT_REPLICAS, $nodeHashCallback = null) { $this->replicas = $replicas; $this->nodeHashCallback = $nodeHashCallback; } /** * Adds a node to the ring with an optional weight. * * @param mixed $node Node object. * @param int $weight Weight for the node. */ public function add($node, $weight = null) { // In case of collisions in the hashes of the nodes, the node added // last wins, thus the order in which nodes are added is significant. $this->nodes[] = [ 'object' => $node, 'weight' => (int) $weight ?: $this::DEFAULT_WEIGHT, ]; $this->reset(); } /** * {@inheritdoc} */ public function remove($node) { // A node is removed by resetting the ring so that it's recreated from // scratch, in order to reassign possible hashes with collisions to the // right node according to the order in which they were added in the // first place. for ($i = 0; $i < count($this->nodes); ++$i) { if ($this->nodes[$i]['object'] === $node) { array_splice($this->nodes, $i, 1); $this->reset(); break; } } } /** * Resets the distributor. */ private function reset() { unset( $this->ring, $this->ringKeys, $this->ringKeysCount ); } /** * Returns the initialization status of the distributor. * * @return bool */ private function isInitialized() { return isset($this->ringKeys); } /** * Calculates the total weight of all the nodes in the distributor. * * @return int */ private function computeTotalWeight() { $totalWeight = 0; foreach ($this->nodes as $node) { $totalWeight += $node['weight']; } return $totalWeight; } /** * Initializes the distributor. */ private function initialize() { if ($this->isInitialized()) { return; } if (!$this->nodes) { throw new EmptyRingException('Cannot initialize an empty hashring.'); } $this->ring = []; $totalWeight = $this->computeTotalWeight(); $nodesCount = count($this->nodes); foreach ($this->nodes as $node) { $weightRatio = $node['weight'] / $totalWeight; $this->addNodeToRing($this->ring, $node, $nodesCount, $this->replicas, $weightRatio); } ksort($this->ring, SORT_NUMERIC); $this->ringKeys = array_keys($this->ring); $this->ringKeysCount = count($this->ringKeys); } /** * Implements the logic needed to add a node to the hashring. * * @param array $ring Source hashring. * @param mixed $node Node object to be added. * @param int $totalNodes Total number of nodes. * @param int $replicas Number of replicas in the ring. * @param float $weightRatio Weight ratio for the node. */ protected function addNodeToRing(&$ring, $node, $totalNodes, $replicas, $weightRatio) { $nodeObject = $node['object']; $nodeHash = $this->getNodeHash($nodeObject); $replicas = (int) round($weightRatio * $totalNodes * $replicas); for ($i = 0; $i < $replicas; ++$i) { $key = $this->hash("$nodeHash:$i"); $ring[$key] = $nodeObject; } } /** * {@inheritdoc} */ protected function getNodeHash($nodeObject) { if (!isset($this->nodeHashCallback)) { return (string) $nodeObject; } return call_user_func($this->nodeHashCallback, $nodeObject); } /** * {@inheritdoc} */ public function hash($value) { return crc32($value); } /** * {@inheritdoc} */ public function getByHash($hash) { return $this->ring[$this->getSlot($hash)]; } /** * {@inheritdoc} */ public function getBySlot($slot) { $this->initialize(); if (isset($this->ring[$slot])) { return $this->ring[$slot]; } } /** * {@inheritdoc} */ public function getSlot($hash) { $this->initialize(); $ringKeys = $this->ringKeys; $upper = $this->ringKeysCount - 1; $lower = 0; while ($lower <= $upper) { $index = ($lower + $upper) >> 1; $item = $ringKeys[$index]; if ($item > $hash) { $upper = $index - 1; } elseif ($item < $hash) { $lower = $index + 1; } else { return $item; } } return $ringKeys[$this->wrapAroundStrategy($upper, $lower, $this->ringKeysCount)]; } /** * {@inheritdoc} */ public function get($value) { $hash = $this->hash($value); return $this->getByHash($hash); } /** * Implements a strategy to deal with wrap-around errors during binary searches. * * @param int $upper * @param int $lower * @param int $ringKeysCount * * @return int */ protected function wrapAroundStrategy($upper, $lower, $ringKeysCount) { // Binary search for the last item in ringkeys with a value less or // equal to the key. If no such item exists, return the last item. return $upper >= 0 ? $upper : $ringKeysCount - 1; } /** * {@inheritdoc} */ public function getHashGenerator() { return $this; } } PK\X];$$7predis/src/Cluster/Distributor/DistributorInterface.phpnu[ */ class KetamaRing extends HashRing { public const DEFAULT_REPLICAS = 160; /** * @param mixed $nodeHashCallback Callback returning a string used to calculate the hash of nodes. */ public function __construct($nodeHashCallback = null) { parent::__construct($this::DEFAULT_REPLICAS, $nodeHashCallback); } /** * {@inheritdoc} */ protected function addNodeToRing(&$ring, $node, $totalNodes, $replicas, $weightRatio) { $nodeObject = $node['object']; $nodeHash = $this->getNodeHash($nodeObject); $replicas = (int) floor($weightRatio * $totalNodes * ($replicas / 4)); for ($i = 0; $i < $replicas; ++$i) { $unpackedDigest = unpack('V4', md5("$nodeHash-$i", true)); foreach ($unpackedDigest as $key) { $ring[$key] = $nodeObject; } } } /** * {@inheritdoc} */ public function hash($value) { $hash = unpack('V', md5($value, true)); return $hash[1]; } /** * {@inheritdoc} */ protected function wrapAroundStrategy($upper, $lower, $ringKeysCount) { // Binary search for the first item in ringkeys with a value greater // or equal to the key. If no such item exists, return the first item. return $lower < $ringKeysCount ? $lower : 0; } } PK\X]5predis/src/Cluster/Distributor/EmptyRingException.phpnu[distributor = $distributor ?: new HashRing(); } /** * {@inheritdoc} */ public function getSlotByKey($key) { $key = $this->extractKeyTag($key); $hash = $this->distributor->hash($key); return $this->distributor->getSlot($hash); } /** * {@inheritdoc} */ protected function checkSameSlotForKeys(array $keys) { if (!$count = count($keys)) { return false; } $currentKey = $this->extractKeyTag($keys[0]); for ($i = 1; $i < $count; ++$i) { $nextKey = $this->extractKeyTag($keys[$i]); if ($currentKey !== $nextKey) { return false; } $currentKey = $nextKey; } return true; } /** * {@inheritdoc} */ public function getDistributor() { return $this->distributor; } } PK\X]/^ = =&predis/src/Cluster/ClusterStrategy.phpnu[commands = $this->getDefaultCommands(); } /** * Returns the default map of supported commands with their handlers. * * @return array */ protected function getDefaultCommands() { $getKeyFromFirstArgument = [$this, 'getKeyFromFirstArgument']; $getKeyFromAllArguments = [$this, 'getKeyFromAllArguments']; return [ /* commands operating on the key space */ 'EXISTS' => $getKeyFromAllArguments, 'DEL' => $getKeyFromAllArguments, 'TYPE' => $getKeyFromFirstArgument, 'EXPIRE' => $getKeyFromFirstArgument, 'EXPIREAT' => $getKeyFromFirstArgument, 'PERSIST' => $getKeyFromFirstArgument, 'PEXPIRE' => $getKeyFromFirstArgument, 'PEXPIREAT' => $getKeyFromFirstArgument, 'TTL' => $getKeyFromFirstArgument, 'PTTL' => $getKeyFromFirstArgument, 'SORT' => [$this, 'getKeyFromSortCommand'], 'DUMP' => $getKeyFromFirstArgument, 'RESTORE' => $getKeyFromFirstArgument, 'FLUSHDB' => [$this, 'getFakeKey'], /* commands operating on string values */ 'APPEND' => $getKeyFromFirstArgument, 'DECR' => $getKeyFromFirstArgument, 'DECRBY' => $getKeyFromFirstArgument, 'GET' => $getKeyFromFirstArgument, 'GETBIT' => $getKeyFromFirstArgument, 'MGET' => $getKeyFromAllArguments, 'SET' => $getKeyFromFirstArgument, 'GETRANGE' => $getKeyFromFirstArgument, 'GETSET' => $getKeyFromFirstArgument, 'INCR' => $getKeyFromFirstArgument, 'INCRBY' => $getKeyFromFirstArgument, 'INCRBYFLOAT' => $getKeyFromFirstArgument, 'SETBIT' => $getKeyFromFirstArgument, 'SETEX' => $getKeyFromFirstArgument, 'MSET' => [$this, 'getKeyFromInterleavedArguments'], 'MSETNX' => [$this, 'getKeyFromInterleavedArguments'], 'SETNX' => $getKeyFromFirstArgument, 'SETRANGE' => $getKeyFromFirstArgument, 'STRLEN' => $getKeyFromFirstArgument, 'SUBSTR' => $getKeyFromFirstArgument, 'BITOP' => [$this, 'getKeyFromBitOp'], 'BITCOUNT' => $getKeyFromFirstArgument, 'BITFIELD' => $getKeyFromFirstArgument, /* commands operating on lists */ 'LINSERT' => $getKeyFromFirstArgument, 'LINDEX' => $getKeyFromFirstArgument, 'LLEN' => $getKeyFromFirstArgument, 'LPOP' => $getKeyFromFirstArgument, 'RPOP' => $getKeyFromFirstArgument, 'RPOPLPUSH' => $getKeyFromAllArguments, 'BLPOP' => [$this, 'getKeyFromBlockingListCommands'], 'BRPOP' => [$this, 'getKeyFromBlockingListCommands'], 'BRPOPLPUSH' => [$this, 'getKeyFromBlockingListCommands'], 'LPUSH' => $getKeyFromFirstArgument, 'LPUSHX' => $getKeyFromFirstArgument, 'RPUSH' => $getKeyFromFirstArgument, 'RPUSHX' => $getKeyFromFirstArgument, 'LRANGE' => $getKeyFromFirstArgument, 'LREM' => $getKeyFromFirstArgument, 'LSET' => $getKeyFromFirstArgument, 'LTRIM' => $getKeyFromFirstArgument, /* commands operating on sets */ 'SADD' => $getKeyFromFirstArgument, 'SCARD' => $getKeyFromFirstArgument, 'SDIFF' => $getKeyFromAllArguments, 'SDIFFSTORE' => $getKeyFromAllArguments, 'SINTER' => $getKeyFromAllArguments, 'SINTERSTORE' => $getKeyFromAllArguments, 'SUNION' => $getKeyFromAllArguments, 'SUNIONSTORE' => $getKeyFromAllArguments, 'SISMEMBER' => $getKeyFromFirstArgument, 'SMEMBERS' => $getKeyFromFirstArgument, 'SSCAN' => $getKeyFromFirstArgument, 'SPOP' => $getKeyFromFirstArgument, 'SRANDMEMBER' => $getKeyFromFirstArgument, 'SREM' => $getKeyFromFirstArgument, /* commands operating on sorted sets */ 'ZADD' => $getKeyFromFirstArgument, 'ZCARD' => $getKeyFromFirstArgument, 'ZCOUNT' => $getKeyFromFirstArgument, 'ZINCRBY' => $getKeyFromFirstArgument, 'ZINTERSTORE' => [$this, 'getKeyFromZsetAggregationCommands'], 'ZRANGE' => $getKeyFromFirstArgument, 'ZRANGEBYSCORE' => $getKeyFromFirstArgument, 'ZRANK' => $getKeyFromFirstArgument, 'ZREM' => $getKeyFromFirstArgument, 'ZREMRANGEBYRANK' => $getKeyFromFirstArgument, 'ZREMRANGEBYSCORE' => $getKeyFromFirstArgument, 'ZREVRANGE' => $getKeyFromFirstArgument, 'ZREVRANGEBYSCORE' => $getKeyFromFirstArgument, 'ZREVRANK' => $getKeyFromFirstArgument, 'ZSCORE' => $getKeyFromFirstArgument, 'ZUNIONSTORE' => [$this, 'getKeyFromZsetAggregationCommands'], 'ZSCAN' => $getKeyFromFirstArgument, 'ZLEXCOUNT' => $getKeyFromFirstArgument, 'ZRANGEBYLEX' => $getKeyFromFirstArgument, 'ZREMRANGEBYLEX' => $getKeyFromFirstArgument, 'ZREVRANGEBYLEX' => $getKeyFromFirstArgument, /* commands operating on hashes */ 'HDEL' => $getKeyFromFirstArgument, 'HEXISTS' => $getKeyFromFirstArgument, 'HGET' => $getKeyFromFirstArgument, 'HGETALL' => $getKeyFromFirstArgument, 'HMGET' => $getKeyFromFirstArgument, 'HMSET' => $getKeyFromFirstArgument, 'HINCRBY' => $getKeyFromFirstArgument, 'HINCRBYFLOAT' => $getKeyFromFirstArgument, 'HKEYS' => $getKeyFromFirstArgument, 'HLEN' => $getKeyFromFirstArgument, 'HSET' => $getKeyFromFirstArgument, 'HSETNX' => $getKeyFromFirstArgument, 'HVALS' => $getKeyFromFirstArgument, 'HSCAN' => $getKeyFromFirstArgument, 'HSTRLEN' => $getKeyFromFirstArgument, /* commands operating on HyperLogLog */ 'PFADD' => $getKeyFromFirstArgument, 'PFCOUNT' => $getKeyFromAllArguments, 'PFMERGE' => $getKeyFromAllArguments, /* scripting */ 'EVAL' => [$this, 'getKeyFromScriptingCommands'], 'EVALSHA' => [$this, 'getKeyFromScriptingCommands'], /* server */ 'INFO' => [$this, 'getFakeKey'], /* commands performing geospatial operations */ 'GEOADD' => $getKeyFromFirstArgument, 'GEOHASH' => $getKeyFromFirstArgument, 'GEOPOS' => $getKeyFromFirstArgument, 'GEODIST' => $getKeyFromFirstArgument, 'GEORADIUS' => [$this, 'getKeyFromGeoradiusCommands'], 'GEORADIUSBYMEMBER' => [$this, 'getKeyFromGeoradiusCommands'], /* cluster */ 'CLUSTER' => [$this, 'getFakeKey'], ]; } /** * Returns the list of IDs for the supported commands. * * @return array */ public function getSupportedCommands() { return array_keys($this->commands); } /** * Sets an handler for the specified command ID. * * The signature of the callback must have a single parameter of type * Predis\Command\CommandInterface. * * When the callback argument is omitted or NULL, the previously associated * handler for the specified command ID is removed. * * @param string $commandID Command ID. * @param mixed $callback A valid callable object, or NULL to unset the handler. * * @throws InvalidArgumentException */ public function setCommandHandler($commandID, $callback = null) { $commandID = strtoupper($commandID); if (!isset($callback)) { unset($this->commands[$commandID]); return; } if (!is_callable($callback)) { throw new InvalidArgumentException( 'The argument must be a callable object or NULL.' ); } $this->commands[$commandID] = $callback; } /** * Get fake key for commands with no key argument. * * @return string */ protected function getFakeKey(): string { return 'key'; } /** * Extracts the key from the first argument of a command instance. * * @param CommandInterface $command Command instance. * * @return string */ protected function getKeyFromFirstArgument(CommandInterface $command) { return $command->getArgument(0); } /** * Extracts the key from a command with multiple keys only when all keys in * the arguments array produce the same hash. * * @param CommandInterface $command Command instance. * * @return string|null */ protected function getKeyFromAllArguments(CommandInterface $command) { $arguments = $command->getArguments(); if (!$this->checkSameSlotForKeys($arguments)) { return null; } return $arguments[0]; } /** * Extracts the key from a command with multiple keys only when all keys in * the arguments array produce the same hash. * * @param CommandInterface $command Command instance. * * @return string|null */ protected function getKeyFromInterleavedArguments(CommandInterface $command) { $arguments = $command->getArguments(); $keys = []; for ($i = 0; $i < count($arguments); $i += 2) { $keys[] = $arguments[$i]; } if (!$this->checkSameSlotForKeys($keys)) { return null; } return $arguments[0]; } /** * Extracts the key from SORT command. * * @param CommandInterface $command Command instance. * * @return string|null */ protected function getKeyFromSortCommand(CommandInterface $command) { $arguments = $command->getArguments(); $firstKey = $arguments[0]; if (1 === $argc = count($arguments)) { return $firstKey; } $keys = [$firstKey]; for ($i = 1; $i < $argc; ++$i) { if (strtoupper($arguments[$i]) === 'STORE') { $keys[] = $arguments[++$i]; } } if (!$this->checkSameSlotForKeys($keys)) { return null; } return $firstKey; } /** * Extracts the key from BLPOP and BRPOP commands. * * @param CommandInterface $command Command instance. * * @return string|null */ protected function getKeyFromBlockingListCommands(CommandInterface $command) { $arguments = $command->getArguments(); if (!$this->checkSameSlotForKeys(array_slice($arguments, 0, count($arguments) - 1))) { return null; } return $arguments[0]; } /** * Extracts the key from BITOP command. * * @param CommandInterface $command Command instance. * * @return string|null */ protected function getKeyFromBitOp(CommandInterface $command) { $arguments = $command->getArguments(); if (!$this->checkSameSlotForKeys(array_slice($arguments, 1, count($arguments)))) { return null; } return $arguments[1]; } /** * Extracts the key from GEORADIUS and GEORADIUSBYMEMBER commands. * * @param CommandInterface $command Command instance. * * @return string|null */ protected function getKeyFromGeoradiusCommands(CommandInterface $command) { $arguments = $command->getArguments(); $argc = count($arguments); $startIndex = $command->getId() === 'GEORADIUS' ? 5 : 4; if ($argc > $startIndex) { $keys = [$arguments[0]]; for ($i = $startIndex; $i < $argc; ++$i) { $argument = strtoupper($arguments[$i]); if ($argument === 'STORE' || $argument === 'STOREDIST') { $keys[] = $arguments[++$i]; } } if (!$this->checkSameSlotForKeys($keys)) { return null; } } return $arguments[0]; } /** * Extracts the key from ZINTERSTORE and ZUNIONSTORE commands. * * @param CommandInterface $command Command instance. * * @return string|null */ protected function getKeyFromZsetAggregationCommands(CommandInterface $command) { $arguments = $command->getArguments(); $keys = array_merge([$arguments[0]], array_slice($arguments, 2, $arguments[1])); if (!$this->checkSameSlotForKeys($keys)) { return null; } return $arguments[0]; } /** * Extracts the key from EVAL and EVALSHA commands. * * @param CommandInterface $command Command instance. * * @return string|null */ protected function getKeyFromScriptingCommands(CommandInterface $command) { $keys = $command instanceof ScriptCommand ? $command->getKeys() : array_slice($args = $command->getArguments(), 2, $args[1]); if (!$keys || !$this->checkSameSlotForKeys($keys)) { return null; } return $keys[0]; } /** * {@inheritdoc} */ public function getSlot(CommandInterface $command) { $slot = $command->getSlot(); if (!isset($slot) && isset($this->commands[$cmdID = $command->getId()])) { $key = call_user_func($this->commands[$cmdID], $command); if (isset($key)) { $slot = $this->getSlotByKey($key); $command->setSlot($slot); } } return $slot; } /** * Checks if the specified array of keys will generate the same hash. * * @param array $keys Array of keys. * * @return bool */ protected function checkSameSlotForKeys(array $keys) { if (!$count = count($keys)) { return false; } $currentSlot = $this->getSlotByKey($keys[0]); for ($i = 1; $i < $count; ++$i) { $nextSlot = $this->getSlotByKey($keys[$i]); if ($currentSlot !== $nextSlot) { return false; } $currentSlot = $nextSlot; } return true; } /** * Returns only the hashable part of a key (delimited by "{...}"), or the * whole key if a key tag is not found in the string. * * @param string $key A key. * * @return string */ protected function extractKeyTag($key) { if (false !== $start = strpos($key, '{')) { if (false !== ($end = strpos($key, '}', $start)) && $end !== ++$start) { $key = substr($key, $start, $end - $start); } } return $key; } } PK\X])=  predis/src/Cluster/SlotMap.phpnu[= 0x0000 && $slot <= 0x3FFF; } /** * Checks if the given slot range is valid. * * @param int $first Initial slot of the range. * @param int $last Last slot of the range. * * @return bool */ public static function isValidRange($first, $last) { return $first >= 0x0000 && $first <= 0x3FFF && $last >= 0x0000 && $last <= 0x3FFF && $first <= $last; } /** * Resets the slot map. */ public function reset() { $this->slots = []; } /** * Checks if the slot map is empty. * * @return bool */ public function isEmpty() { return empty($this->slots); } /** * Returns the current slot map as a dictionary of $slot => $node. * * The order of the slots in the dictionary is not guaranteed. * * @return array */ public function toArray() { return $this->slots; } /** * Returns the list of unique nodes in the slot map. * * @return array */ public function getNodes() { return array_keys(array_flip($this->slots)); } /** * Assigns the specified slot range to a node. * * @param int $first Initial slot of the range. * @param int $last Last slot of the range. * @param NodeConnectionInterface|string $connection ID or connection instance. * * @throws OutOfBoundsException */ public function setSlots($first, $last, $connection) { if (!static::isValidRange($first, $last)) { throw new OutOfBoundsException("Invalid slot range $first-$last for `$connection`"); } $this->slots += array_fill($first, $last - $first + 1, (string) $connection); } /** * Returns the specified slot range. * * @param int $first Initial slot of the range. * @param int $last Last slot of the range. * * @return array */ public function getSlots($first, $last) { if (!static::isValidRange($first, $last)) { throw new OutOfBoundsException("Invalid slot range $first-$last"); } return array_intersect_key($this->slots, array_fill($first, $last - $first + 1, null)); } /** * Checks if the specified slot is assigned. * * @param int $slot Slot index. * * @return bool */ #[ReturnTypeWillChange] public function offsetExists($slot) { return isset($this->slots[$slot]); } /** * Returns the node assigned to the specified slot. * * @param int $slot Slot index. * * @return string|null */ #[ReturnTypeWillChange] public function offsetGet($slot) { return $this->slots[$slot] ?? null; } /** * Assigns the specified slot to a node. * * @param int $slot Slot index. * @param NodeConnectionInterface|string $connection ID or connection instance. * * @return void */ #[ReturnTypeWillChange] public function offsetSet($slot, $connection) { if (!static::isValid($slot)) { throw new OutOfBoundsException("Invalid slot $slot for `$connection`"); } $this->slots[(int) $slot] = (string) $connection; } /** * Returns the node assigned to the specified slot. * * @param int $slot Slot index. * * @return void */ #[ReturnTypeWillChange] public function offsetUnset($slot) { unset($this->slots[$slot]); } /** * Returns the current number of assigned slots. * * @return int */ #[ReturnTypeWillChange] public function count() { return count($this->slots); } /** * Returns an iterator over the slot map. * * @return Traversable */ #[ReturnTypeWillChange] public function getIterator() { return new ArrayIterator($this->slots); } } PK\X]/j$predis/src/Cluster/RedisStrategy.phpnu[hashGenerator = $hashGenerator ?: new CRC16(); } /** * {@inheritdoc} */ public function getSlotByKey($key) { $key = $this->extractKeyTag($key); return $this->hashGenerator->hash($key) & 0x3FFF; } /** * {@inheritdoc} */ public function getDistributor() { $class = get_class($this); throw new NotSupportedException("$class does not provide an external distributor"); } } PK\X].-  (predis/src/Cluster/StrategyInterface.phpnu[gDDIpredis/src/Command/Strategy/ContainerCommands/Functions/StatsStrategy.phpnu[separator = $separator; } /** * {@inheritDoc} */ public function resolve(string $commandId, string $subcommandId): SubcommandStrategyInterface { $subcommandStrategyClass = ucwords($subcommandId) . 'Strategy'; $commandDirectoryName = ucwords($commandId); if (!is_null($this->separator)) { $subcommandStrategyClass = str_replace($this->separator, '', $subcommandStrategyClass); $commandDirectoryName = str_replace($this->separator, '', $commandDirectoryName); } if (class_exists( $containerCommandClass = self::CONTAINER_COMMANDS_NAMESPACE . '\\' . $commandDirectoryName . '\\' . $subcommandStrategyClass )) { return new $containerCommandClass(); } throw new InvalidArgumentException('Non-existing container command given'); } } PK\X]TF)predis/src/Command/Traits/To/ServerTo.phpnu[= $argumentsLength) { parent::setArguments($arguments); return; } /** @var To|null $toArgument */ $toArgument = $arguments[static::$toArgumentPositionOffset]; if (null === $toArgument) { array_splice($arguments, static::$toArgumentPositionOffset, 1, [false]); parent::setArguments($arguments); return; } $argumentsBefore = array_slice($arguments, 0, static::$toArgumentPositionOffset); $argumentsAfter = array_slice($arguments, static::$toArgumentPositionOffset + 1); parent::setArguments(array_merge( $argumentsBefore, $toArgument->toArray(), $argumentsAfter )); } } PK\X]g66*predis/src/Command/Traits/From/GeoFrom.phpnu[getFromArgumentPositionOffset($arguments); if (null === $argumentPositionOffset) { throw new InvalidArgumentException('Invalid FROM argument value given'); } $fromArgumentObject = $arguments[$argumentPositionOffset]; $argumentsBefore = array_slice($arguments, 0, $argumentPositionOffset); $argumentsAfter = array_slice($arguments, $argumentPositionOffset + 1); parent::setArguments(array_merge( $argumentsBefore, $fromArgumentObject->toArray(), $argumentsAfter )); } private function getFromArgumentPositionOffset(array $arguments): ?int { foreach ($arguments as $i => $value) { if ($value instanceof FromInterface) { return $i; } } return null; } } PK\X].C2predis/src/Command/Traits/Expire/ExpireOptions.phpnu[ 'NX', 'xx' => 'XX', 'gt' => 'GT', 'lt' => 'LT', ]; public function setArguments(array $arguments) { $value = array_pop($arguments); if (null === $value) { parent::setArguments($arguments); return; } if (in_array(strtoupper($value), self::$argumentEnum, true)) { $arguments[] = self::$argumentEnum[strtolower($value)]; } else { $arguments[] = $value; } parent::setArguments($arguments); } } PK\X]X/predis/src/Command/Traits/Limit/LimitObject.phpnu[getLimitArgumentPositionOffset($arguments); if (null === $argumentPositionOffset) { parent::setArguments($arguments); return; } $limitObject = $arguments[$argumentPositionOffset]; $argumentsBefore = array_slice($arguments, 0, $argumentPositionOffset); $argumentsAfter = array_slice($arguments, $argumentPositionOffset + 1); parent::setArguments(array_merge( $argumentsBefore, $limitObject->toArray(), $argumentsAfter )); } private function getLimitArgumentPositionOffset(array $arguments): ?int { foreach ($arguments as $i => $value) { if ($value instanceof LimitInterface) { return $i; } } return null; } } PK\X])predis/src/Command/Traits/Limit/Limit.phpnu[= $argumentsLength || false === $arguments[static::$limitArgumentPositionOffset] ) { parent::setArguments($argumentsBefore); return; } $argument = $arguments[static::$limitArgumentPositionOffset]; $argumentsAfter = array_slice($arguments, static::$limitArgumentPositionOffset + 1); if (true === $argument) { parent::setArguments(array_merge($argumentsBefore, [self::$limitModifier], $argumentsAfter)); return; } if (!is_int($argument)) { throw new UnexpectedValueException('Wrong limit argument type'); } parent::setArguments(array_merge($argumentsBefore, [self::$limitModifier], [$argument], $argumentsAfter)); } } PK\X]=%predis/src/Command/Traits/Get/Get.phpnu[= $argumentsLength) { parent::setArguments($arguments); return; } if (!is_array($arguments[static::$getArgumentPositionOffset])) { throw new UnexpectedValueException('Wrong get argument type'); } $patterns = []; foreach ($arguments[static::$getArgumentPositionOffset] as $pattern) { $patterns[] = self::$getModifier; $patterns[] = $pattern; } $argumentsBeforeKeys = array_slice($arguments, 0, static::$getArgumentPositionOffset); $argumentsAfterKeys = array_slice($arguments, static::$getArgumentPositionOffset + 1); parent::setArguments(array_merge($argumentsBeforeKeys, $patterns, $argumentsAfterKeys)); } } PK\X]:@X+predis/src/Command/Traits/With/WithDist.phpnu[= $argumentsLength || false === $arguments[static::$withDistArgumentPositionOffset] ) { parent::setArguments($arguments); return; } $argument = $arguments[static::$withDistArgumentPositionOffset]; if (true === $argument) { $argument = 'WITHDIST'; } else { throw new UnexpectedValueException('Wrong WITHDIST argument type'); } $argumentsBefore = array_slice($arguments, 0, static::$withDistArgumentPositionOffset); $argumentsAfter = array_slice($arguments, static::$withDistArgumentPositionOffset + 1); parent::setArguments(array_merge($argumentsBefore, [$argument], $argumentsAfter)); } } PK\X]r!,predis/src/Command/Traits/With/WithCoord.phpnu[= $argumentsLength || false === $arguments[static::$withCoordArgumentPositionOffset] ) { parent::setArguments($arguments); return; } $argument = $arguments[static::$withCoordArgumentPositionOffset]; if (true === $argument) { $argument = 'WITHCOORD'; } else { throw new UnexpectedValueException('Wrong WITHCOORD argument type'); } $argumentsBefore = array_slice($arguments, 0, static::$withCoordArgumentPositionOffset); $argumentsAfter = array_slice($arguments, static::$withCoordArgumentPositionOffset + 1); parent::setArguments(array_merge($argumentsBefore, [$argument], $argumentsAfter)); } } PK\X]ޝz-predis/src/Command/Traits/With/WithValues.phpnu[= $argumentsLength || false === $arguments[static::$withHashArgumentPositionOffset] ) { parent::setArguments($arguments); return; } $argument = $arguments[static::$withHashArgumentPositionOffset]; if (true === $argument) { $argument = 'WITHHASH'; } else { throw new UnexpectedValueException('Wrong WITHHASH argument type'); } $argumentsBefore = array_slice($arguments, 0, static::$withHashArgumentPositionOffset); $argumentsAfter = array_slice($arguments, static::$withHashArgumentPositionOffset + 1); parent::setArguments(array_merge($argumentsBefore, [$argument], $argumentsAfter)); } } PK\X]*܅-predis/src/Command/Traits/With/WithScores.phpnu[isWithScoreModifier()) { $result = []; for ($i = 0, $iMax = count($data); $i < $iMax; ++$i) { if (is_array($data[$i])) { $result[$data[$i][0]] = $data[$i][1]; // Relay } elseif (array_key_exists($i + 1, $data)) { $result[$data[$i]] = $data[++$i]; } } return $result; } return $data; } } PK\X]T/predis/src/Command/Traits/Json/NxXxArgument.phpnu[ 'NX', 'xx' => 'XX', ]; public function setArguments(array $arguments) { $argumentsLength = count($arguments); if (static::$nxXxArgumentPositionOffset >= $argumentsLength) { parent::setArguments($arguments); return; } if (null === $arguments[static::$nxXxArgumentPositionOffset]) { array_splice($arguments, static::$nxXxArgumentPositionOffset, 1, [false]); parent::setArguments($arguments); return; } $argument = $arguments[static::$nxXxArgumentPositionOffset]; if (!in_array(strtoupper($argument), self::$argumentEnum, true)) { $enumValues = implode(', ', array_keys(self::$argumentEnum)); throw new UnexpectedValueException("Argument accepts only: {$enumValues} values"); } $argumentsBefore = array_slice($arguments, 0, static::$nxXxArgumentPositionOffset); $argumentsAfter = array_slice($arguments, static::$nxXxArgumentPositionOffset + 1); parent::setArguments(array_merge( $argumentsBefore, [self::$argumentEnum[strtolower($argument)]], $argumentsAfter )); } } PK\X]EgDȰ(predis/src/Command/Traits/Json/Space.phpnu[= $argumentsLength) { parent::setArguments($arguments); return; } if ($arguments[static::$spaceArgumentPositionOffset] === '') { array_splice($arguments, static::$spaceArgumentPositionOffset, 1, [false]); parent::setArguments($arguments); return; } $argument = $arguments[static::$spaceArgumentPositionOffset]; if (!is_string($argument)) { throw new UnexpectedValueException('Space argument value should be a string'); } $argumentsBefore = array_slice($arguments, 0, static::$spaceArgumentPositionOffset); $argumentsAfter = array_slice($arguments, static::$spaceArgumentPositionOffset + 1); parent::setArguments(array_merge( $argumentsBefore, [self::$spaceModifier], [$argument], $argumentsAfter )); } } PK\X]p!*predis/src/Command/Traits/Json/Newline.phpnu[= $argumentsLength) { parent::setArguments($arguments); return; } if ($arguments[static::$newlineArgumentPositionOffset] === '') { array_splice($arguments, static::$newlineArgumentPositionOffset, 1, [false]); parent::setArguments($arguments); return; } $argument = $arguments[static::$newlineArgumentPositionOffset]; if (!is_string($argument)) { throw new UnexpectedValueException('Newline argument value should be a string'); } $argumentsBefore = array_slice($arguments, 0, static::$newlineArgumentPositionOffset); $argumentsAfter = array_slice($arguments, static::$newlineArgumentPositionOffset + 1); parent::setArguments(array_merge( $argumentsBefore, [self::$newlineModifier], [$argument], $argumentsAfter )); } } PK\X]/5)predis/src/Command/Traits/Json/Indent.phpnu[= $argumentsLength) { parent::setArguments($arguments); return; } if ($arguments[static::$indentArgumentPositionOffset] === '') { array_splice($arguments, static::$indentArgumentPositionOffset, 1, [false]); parent::setArguments($arguments); return; } $argument = $arguments[static::$indentArgumentPositionOffset]; if (!is_string($argument)) { throw new UnexpectedValueException('Indent argument value should be a string'); } $argumentsBefore = array_slice($arguments, 0, static::$indentArgumentPositionOffset); $argumentsAfter = array_slice($arguments, static::$indentArgumentPositionOffset + 1); parent::setArguments(array_merge( $argumentsBefore, [self::$indentModifier], [$argument], $argumentsAfter )); } } PK\X] $$&predis/src/Command/Traits/By/GeoBy.phpnu[getByArgumentPositionOffset($arguments); if (null === $argumentPositionOffset) { throw new InvalidArgumentException('Invalid BY argument value given'); } $byArgumentObject = $arguments[$argumentPositionOffset]; $argumentsBefore = array_slice($arguments, 0, $argumentPositionOffset); $argumentsAfter = array_slice($arguments, $argumentPositionOffset + 1); parent::setArguments(array_merge( $argumentsBefore, $byArgumentObject->toArray(), $argumentsAfter )); } private function getByArgumentPositionOffset(array $arguments): ?int { foreach ($arguments as $i => $value) { if ($value instanceof ByInterface) { return $i; } } return null; } } PK\X]99-predis/src/Command/Traits/By/ByLexByScore.phpnu[ 'BYLEX', 'byscore' => 'BYSCORE', ]; public function setArguments(array $arguments) { $argument = $arguments[static::$byLexByScoreArgumentPositionOffset]; if (false === $argument) { parent::setArguments($arguments); return; } if (is_string($argument) && in_array(strtoupper($argument), self::$argumentsEnum)) { $argument = self::$argumentsEnum[$argument]; } else { throw new UnexpectedValueException('By argument accepts only "bylex" and "byscore" values'); } $argumentsBefore = array_slice($arguments, 0, static::$byLexByScoreArgumentPositionOffset); $argumentsAfter = array_slice($arguments, static::$byLexByScoreArgumentPositionOffset + 1); parent::setArguments(array_merge($argumentsBefore, [$argument], $argumentsAfter)); } } PK\X]Pq44+predis/src/Command/Traits/By/ByArgument.phpnu[= $argumentsLength || null === $arguments[static::$byArgumentPositionOffset]) { parent::setArguments($arguments); return; } $argument = $arguments[static::$byArgumentPositionOffset]; $argumentsBefore = array_slice($arguments, 0, static::$byArgumentPositionOffset); $argumentsAfter = array_slice($arguments, static::$byArgumentPositionOffset + 1); parent::setArguments(array_merge($argumentsBefore, [$this->byModifier, $argument], $argumentsAfter)); } } PK\X]OO5predis/src/Command/Traits/BloomFilters/BucketSize.phpnu[= $argumentsLength) { parent::setArguments($arguments); return; } if ($arguments[static::$bucketSizeArgumentPositionOffset] === -1) { array_splice($arguments, static::$bucketSizeArgumentPositionOffset, 1, [false]); parent::setArguments($arguments); return; } if ($arguments[static::$bucketSizeArgumentPositionOffset] < 1) { throw new UnexpectedValueException('Wrong bucket size argument value or position offset'); } $argument = $arguments[static::$bucketSizeArgumentPositionOffset]; $argumentsBefore = array_slice($arguments, 0, static::$bucketSizeArgumentPositionOffset); $argumentsAfter = array_slice($arguments, static::$bucketSizeArgumentPositionOffset + 1); parent::setArguments(array_merge( $argumentsBefore, [self::$bucketSizeModifier], [$argument], $argumentsAfter )); } } PK\X]BFT  4predis/src/Command/Traits/BloomFilters/Expansion.phpnu[= $argumentsLength) { parent::setArguments($arguments); return; } if ($arguments[static::$expansionArgumentPositionOffset] === -1) { array_splice($arguments, static::$expansionArgumentPositionOffset, 1, [false]); parent::setArguments($arguments); return; } if ($arguments[static::$expansionArgumentPositionOffset] < 1) { throw new UnexpectedValueException('Wrong expansion argument value or position offset'); } $argument = $arguments[static::$expansionArgumentPositionOffset]; $argumentsBefore = array_slice($arguments, 0, static::$expansionArgumentPositionOffset); $argumentsAfter = array_slice($arguments, static::$expansionArgumentPositionOffset + 1); parent::setArguments(array_merge( $argumentsBefore, [self::$expansionModifier], [$argument], $argumentsAfter )); } } PK\X]Xss8predis/src/Command/Traits/BloomFilters/MaxIterations.phpnu[= $argumentsLength) { parent::setArguments($arguments); return; } if ($arguments[static::$maxIterationsArgumentPositionOffset] === -1) { array_splice($arguments, static::$maxIterationsArgumentPositionOffset, 1, [false]); parent::setArguments($arguments); return; } if ($arguments[static::$maxIterationsArgumentPositionOffset] < 1) { throw new UnexpectedValueException('Wrong max iterations argument value or position offset'); } $argument = $arguments[static::$maxIterationsArgumentPositionOffset]; $argumentsBefore = array_slice($arguments, 0, static::$maxIterationsArgumentPositionOffset); $argumentsAfter = array_slice($arguments, static::$maxIterationsArgumentPositionOffset + 1); parent::setArguments(array_merge( $argumentsBefore, [self::$maxIterationsModifier], [$argument], $argumentsAfter )); } } PK\X];0predis/src/Command/Traits/BloomFilters/Error.phpnu[= $argumentsLength) { parent::setArguments($arguments); return; } if ($arguments[static::$errorArgumentPositionOffset] === -1) { array_splice($arguments, static::$errorArgumentPositionOffset, 1, [false]); parent::setArguments($arguments); return; } if ($arguments[static::$errorArgumentPositionOffset] < 0) { throw new UnexpectedValueException('Wrong error argument value or position offset'); } $argument = $arguments[static::$errorArgumentPositionOffset]; $argumentsBefore = array_slice($arguments, 0, static::$errorArgumentPositionOffset); $argumentsAfter = array_slice($arguments, static::$errorArgumentPositionOffset + 1); parent::setArguments(array_merge( $argumentsBefore, [self::$errorModifier], [$argument], $argumentsAfter )); } } PK\X]TJWW0predis/src/Command/Traits/BloomFilters/Items.phpnu[= $argumentsLength) { parent::setArguments($arguments); return; } $argument = $arguments[static::$itemsArgumentPositionOffset]; $argumentsBefore = array_slice($arguments, 0, static::$itemsArgumentPositionOffset); $argumentsAfter = array_slice($arguments, static::$itemsArgumentPositionOffset + 1); parent::setArguments(array_merge( $argumentsBefore, [self::$itemsModifier], [$argument], $argumentsAfter )); } } PK\X]43predis/src/Command/Traits/BloomFilters/NoCreate.phpnu[= $argumentsLength || false === $arguments[static::$noCreateArgumentPositionOffset] ) { parent::setArguments($arguments); return; } $argument = $arguments[static::$noCreateArgumentPositionOffset]; if (true === $argument) { $argument = 'NOCREATE'; } else { throw new UnexpectedValueException('Wrong NOCREATE argument type'); } $argumentsBefore = array_slice($arguments, 0, static::$noCreateArgumentPositionOffset); $argumentsAfter = array_slice($arguments, static::$noCreateArgumentPositionOffset + 1); parent::setArguments(array_merge($argumentsBefore, [$argument], $argumentsAfter)); } } PK\X] 663predis/src/Command/Traits/BloomFilters/Capacity.phpnu[= $argumentsLength) { parent::setArguments($arguments); return; } if ($arguments[static::$capacityArgumentPositionOffset] === -1) { array_splice($arguments, static::$capacityArgumentPositionOffset, 1, [false]); parent::setArguments($arguments); return; } if ($arguments[static::$capacityArgumentPositionOffset] < 1) { throw new UnexpectedValueException('Wrong capacity argument value or position offset'); } $argument = $arguments[static::$capacityArgumentPositionOffset]; $argumentsBefore = array_slice($arguments, 0, static::$capacityArgumentPositionOffset); $argumentsAfter = array_slice($arguments, static::$capacityArgumentPositionOffset + 1); parent::setArguments(array_merge( $argumentsBefore, [self::$capacityModifier], [$argument], $argumentsAfter )); } } PK\X]t%predis/src/Command/Traits/Sorting.phpnu[ 'ASC', 'desc' => 'DESC', ]; public function setArguments(array $arguments) { $argumentsLength = count($arguments); if (static::$sortArgumentPositionOffset >= $argumentsLength) { parent::setArguments($arguments); return; } $argument = $arguments[static::$sortArgumentPositionOffset]; if (null === $argument) { array_splice($arguments, static::$sortArgumentPositionOffset, 1, [false]); parent::setArguments($arguments); return; } if (!in_array(strtoupper($argument), self::$sortingEnum, true)) { $enumValues = implode(', ', array_keys(self::$sortingEnum)); throw new UnexpectedValueException("Sorting argument accepts only: {$enumValues} values"); } $argumentsBefore = array_slice($arguments, 0, static::$sortArgumentPositionOffset); $argumentsAfter = array_slice($arguments, static::$sortArgumentPositionOffset + 1); parent::setArguments(array_merge( $argumentsBefore, [self::$sortingEnum[$argument]], $argumentsAfter )); } } PK\X]  ,predis/src/Command/Traits/MinMaxModifier.phpnu[ 'MIN', 'max' => 'MAX', ]; public function resolveModifier(int $offset, array &$arguments): void { if ($offset >= count($arguments)) { $arguments[$offset] = $this->modifierEnum['min']; return; } if (!is_string($arguments[$offset]) || !array_key_exists($arguments[$offset], $this->modifierEnum)) { throw new UnexpectedValueException('Wrong type of modifier given'); } $arguments[$offset] = $this->modifierEnum[$arguments[$offset]]; } } PK\X]ٕQQ%predis/src/Command/Traits/BitByte.phpnu[ 'BIT', 'byte' => 'BYTE', ]; public function setArguments(array $arguments) { $value = array_pop($arguments); if (null === $value) { parent::setArguments($arguments); return; } if (in_array(strtoupper($value), self::$argumentEnum, true)) { $arguments[] = self::$argumentEnum[$value]; } else { $arguments[] = $value; } parent::setArguments($arguments); } } PK\X]Rꌿ#predis/src/Command/Traits/Count.phpnu[= $argumentsLength) { parent::setArguments($arguments); return; } if ($arguments[static::$countArgumentPositionOffset] === -1) { array_splice($arguments, static::$countArgumentPositionOffset, 1, [false]); parent::setArguments($arguments); return; } if ($arguments[static::$countArgumentPositionOffset] < 1) { throw new UnexpectedValueException('Wrong count argument value or position offset'); } $countArgument = $arguments[static::$countArgumentPositionOffset]; $argumentsBefore = array_slice($arguments, 0, static::$countArgumentPositionOffset); $argumentsAfter = array_slice($arguments, static::$countArgumentPositionOffset + 2); if (!$any) { $argumentsAfter = array_slice($arguments, static::$countArgumentPositionOffset + 1); parent::setArguments(array_merge( $argumentsBefore, [$this->countModifier], [$countArgument], $argumentsAfter )); return; } parent::setArguments(array_merge( $argumentsBefore, [$this->countModifier], [$countArgument], [$this->anyModifier], $argumentsAfter )); } } PK\X]<'predis/src/Command/Traits/Storedist.phpnu[= $argumentsLength || false === $arguments[static::$storeDistArgumentPositionOffset] ) { parent::setArguments($arguments); return; } $argument = $arguments[static::$storeDistArgumentPositionOffset]; if (true === $argument) { $argument = 'STOREDIST'; } else { throw new UnexpectedValueException('Wrong STOREDIST argument type'); } $argumentsBefore = array_slice($arguments, 0, static::$storeDistArgumentPositionOffset); $argumentsAfter = array_slice($arguments, static::$storeDistArgumentPositionOffset + 1); parent::setArguments(array_merge($argumentsBefore, [$argument], $argumentsAfter)); } } PK\X]f55!predis/src/Command/Traits/Rev.phpnu[= $argumentsLength) { parent::setArguments($arguments); return; } if (!is_numeric($arguments[static::$dbArgumentPositionOffset])) { throw new UnexpectedValueException('DB argument should be a valid numeric value'); } if ($arguments[static::$dbArgumentPositionOffset] < 0) { array_splice($arguments, static::$dbArgumentPositionOffset, 1); parent::setArguments($arguments); return; } $argument = $arguments[static::$dbArgumentPositionOffset]; $argumentsBefore = array_slice($arguments, 0, static::$dbArgumentPositionOffset); $argumentsAfter = array_slice($arguments, static::$dbArgumentPositionOffset + 1); parent::setArguments(array_merge( $argumentsBefore, [$this->dbModifier], [$argument], $argumentsAfter )); } } PK\X]]iVll"predis/src/Command/Traits/Keys.phpnu[ $argumentsLength || !is_array($arguments[static::$keysArgumentPositionOffset]) ) { throw new UnexpectedValueException('Wrong keys argument type or position offset'); } $keysArgument = $arguments[static::$keysArgumentPositionOffset]; $argumentsBeforeKeys = array_slice($arguments, 0, static::$keysArgumentPositionOffset); $argumentsAfterKeys = array_slice($arguments, static::$keysArgumentPositionOffset + 1); if ($withNumkeys) { $numkeys = count($keysArgument); parent::setArguments(array_merge($argumentsBeforeKeys, [$numkeys], $keysArgument, $argumentsAfterKeys)); return; } parent::setArguments(array_merge($argumentsBeforeKeys, $keysArgument, $argumentsAfterKeys)); } } PK\X]}]%predis/src/Command/Traits/Replace.phpnu[= $argumentsLength) { parent::setArguments($arguments); return; } if (!is_array($arguments[static::$weightsArgumentPositionOffset])) { throw new UnexpectedValueException('Wrong weights argument type'); } $weightsArray = $arguments[static::$weightsArgumentPositionOffset]; if (empty($weightsArray)) { unset($arguments[static::$weightsArgumentPositionOffset]); parent::setArguments($arguments); return; } $argumentsBefore = array_slice($arguments, 0, static::$weightsArgumentPositionOffset); $argumentsAfter = array_slice($arguments, static::$weightsArgumentPositionOffset + 1); parent::setArguments(array_merge( $argumentsBefore, [self::$weightsModifier], $weightsArray, $argumentsAfter )); } } PK\X]3QQ'predis/src/Command/Traits/LeftRight.phpnu[ 'LEFT', 'right' => 'RIGHT', ]; public function setArguments(array $arguments) { $argumentsLength = count($arguments); if (static::$leftRightArgumentPositionOffset >= $argumentsLength) { $arguments[] = 'LEFT'; parent::setArguments($arguments); return; } $argument = $arguments[static::$leftRightArgumentPositionOffset]; if (is_string($argument) && in_array(strtoupper($argument), self::$leftRightEnum, true)) { $argument = self::$leftRightEnum[$argument]; } else { $enumValues = implode(', ', array_keys(self::$leftRightEnum)); throw new UnexpectedValueException("Left/Right argument accepts only: {$enumValues} values"); } $argumentsBefore = array_slice($arguments, 0, static::$leftRightArgumentPositionOffset); $argumentsAfter = array_slice($arguments, static::$leftRightArgumentPositionOffset + 1); parent::setArguments(array_merge( $argumentsBefore, [$argument], $argumentsAfter )); } } PK\X]| 'predis/src/Command/Traits/Aggregate.phpnu[ 'MIN', 'max' => 'MAX', 'sum' => 'SUM', ]; /** * @var string */ private static $aggregateModifier = 'AGGREGATE'; public function setArguments(array $arguments) { $argumentsLength = count($arguments); if (static::$aggregateArgumentPositionOffset >= $argumentsLength) { parent::setArguments($arguments); return; } $argument = $arguments[static::$aggregateArgumentPositionOffset]; if (is_string($argument) && in_array(strtoupper($argument), self::$aggregateValuesEnum)) { $argument = self::$aggregateValuesEnum[$argument]; } else { $enumValues = implode(', ', array_keys(self::$aggregateValuesEnum)); throw new UnexpectedValueException("Aggregate argument accepts only: {$enumValues} values"); } $argumentsBefore = array_slice($arguments, 0, static::$aggregateArgumentPositionOffset); $argumentsAfter = array_slice($arguments, static::$aggregateArgumentPositionOffset + 1); parent::setArguments(array_merge( $argumentsBefore, [self::$aggregateModifier], [$argument], $argumentsAfter )); } } PK\X]|v%predis/src/Command/Traits/Timeout.phpnu[= $argumentsLength) { parent::setArguments($arguments); return; } if ($arguments[static::$timeoutArgumentPositionOffset] === -1) { array_splice($arguments, static::$timeoutArgumentPositionOffset, 1, [false]); parent::setArguments($arguments); return; } if ($arguments[static::$timeoutArgumentPositionOffset] < 1) { throw new UnexpectedValueException('Wrong timeout argument value or position offset'); } $argument = $arguments[static::$timeoutArgumentPositionOffset]; $argumentsBefore = array_slice($arguments, 0, static::$timeoutArgumentPositionOffset); $argumentsAfter = array_slice($arguments, static::$timeoutArgumentPositionOffset + 1); parent::setArguments(array_merge( $argumentsBefore, [self::$timeoutModifier], [$argument], $argumentsAfter )); } } PK\X]h WW"predis/src/Command/Redis/LMPOP.phpnu[setCount($arguments); $arguments = $this->getArguments(); $this->setLeftRight($arguments); $arguments = $this->getArguments(); $this->setKeys($arguments); $this->filterArguments(); } public function parseResponse($data) { if (null === $data) { return null; } return [$data[0] => $data[1]]; } } PK\X]޳.predis/src/Command/Redis/GEORADIUSBYMEMBER.phpnu[setSorting($arguments); $arguments = $this->getArguments(); $this->setGetArgument($arguments); $arguments = $this->getArguments(); $this->setLimit($arguments); $arguments = $this->getArguments(); $this->setBy($arguments); $this->filterArguments(); } } PK\X]o#"predis/src/Command/Redis/MULTI.phpnu[ true]; $lastType = 'array'; } if ($lastType === 'array') { $options = $this->prepareOptions(array_pop($arguments)); $arguments = array_merge($arguments, $options); } } parent::setArguments($arguments); } /** * Returns a list of options and modifiers compatible with Redis. * * @param array $options List of options. * * @return array */ protected function prepareOptions($options) { $opts = array_change_key_case($options, CASE_UPPER); $finalizedOpts = []; if (!empty($opts['WITHSCORES'])) { $finalizedOpts[] = 'WITHSCORES'; } return $finalizedOpts; } /** * Checks for the presence of the WITHSCORES modifier. * * @return bool */ protected function withScores() { $arguments = $this->getArguments(); if (count($arguments) < 4) { return false; } return strtoupper($arguments[3]) === 'WITHSCORES'; } /** * {@inheritdoc} */ public function parseResponse($data) { if ($this->withScores()) { $result = []; for ($i = 0; $i < count($data); ++$i) { if (is_array($data[$i])) { $result[$data[$i][0]] = $data[$i][1]; // Relay } else { $result[$data[$i]] = $data[++$i]; } } return $result; } return $data; } } PK\X]tPTT$predis/src/Command/Redis/GEOHASH.phpnu[toArray(); } parent::setArguments(array_merge( [$index, $query], $commandArguments )); } } PK\X]M88-predis/src/Command/Redis/Search/FTTAGVALS.phpnu[toArray(); } $terms = array_slice($arguments, 3); parent::setArguments(array_merge( [$index, $synonymGroupId], $commandArguments, $terms )); } } PK\X]w(o~~,predis/src/Command/Redis/Search/FTCREATE.phpnu[toArray() : []; $schema = array_reduce($schema, static function (array $carry, FieldInterface $field) { return array_merge($carry, $field->toArray()); }, []); array_unshift($schema, 'SCHEMA'); parent::setArguments(array_merge( [$index], $commandArguments, $schema )); } } PK\X]&,,-predis/src/Command/Redis/Search/FTPROFILE.phpnu[toArray() )); } } PK\X] 0`.predis/src/Command/Redis/Search/FTALIASADD.phpnu[toArray() : []; parent::setArguments(array_merge( [$index, $query], $commandArguments )); } } PK\X]}},predis/src/Command/Redis/Search/FTSUGADD.phpnu[toArray() : []; parent::setArguments(array_merge( [$key, $string, $score], $commandArguments )); } } PK\X]Y#/predis/src/Command/Redis/Search/FTAGGREGATE.phpnu[toArray() : []; parent::setArguments(array_merge( [$index, $query], $commandArguments )); } } PK\X]c55,predis/src/Command/Redis/Search/FTSUGLEN.phpnu[toArray() : []; parent::setArguments(array_merge( [$key, $prefix], $commandArguments )); } } PK\X]e%,predis/src/Command/Redis/Search/FTCURSOR.phpnu[toArray() : []; parent::setArguments(array_merge( [$subcommand, $index, $cursorId], $commandArguments )); } } PK\X]z<"".predis/src/Command/Redis/Search/FTALIASDEL.phpnu[toArray(); } parent::setArguments(array_merge( [$index, $query], $commandArguments )); } } PK\X]bv+predis/src/Command/Redis/Search/FTALTER.phpnu[toArray() : []; $schema = array_reduce($schema, static function (array $carry, FieldInterface $field) { return array_merge($carry, $field->toArray()); }, []); array_unshift($schema, 'SCHEMA', 'ADD'); parent::setArguments(array_merge( [$index], $commandArguments, $schema )); } } PK\X]T&&-predis/src/Command/Redis/Search/FTSYNDUMP.phpnu[toArray(); } parent::setArguments(array_merge( [$index], $commandArguments )); } } PK\X]xr-predis/src/Command/Redis/Search/FTDICTADD.phpnu[ predis/src/Command/Redis/GET.phpnu[setByLexByScoreArgument($arguments); $arguments = $this->getArguments(); $this->setReversedArgument($arguments); $arguments = $this->getArguments(); $this->setLimitArguments($arguments); $this->filterArguments(); } } PK\X],Un::$predis/src/Command/Redis/HEXPIRE.phpnu[flagsEnum, true)) { $processedArguments[] = strtoupper($arguments[3]); } else { throw new UnexpectedValueException('Unsupported flag value'); } } if (array_key_exists(2, $arguments) && null !== $arguments[2]) { array_push($processedArguments, 'FIELDS', count($arguments[2])); $processedArguments = array_merge($processedArguments, $arguments[2]); } parent::setArguments($processedArguments); } } PK\X]J!predis/src/Command/Redis/QUIT.phpnu[toArray() : []; parent::setArguments(array_merge( [$key], $commandArguments )); } } PK\X]xxWW-predis/src/Command/Redis/TimeSeries/TSGET.phpnu[toArray() : []; parent::setArguments(array_merge( [$key], $commandArguments )); } } PK\X]7>>4predis/src/Command/Redis/TimeSeries/TSQUERYINDEX.phpnu[toArray() : []; parent::setArguments(array_merge( [$key], $commandArguments )); } } PK\X]j]''4predis/src/Command/Redis/TimeSeries/TSDELETERULE.phpnu[toArray() : []; parent::setArguments(array_merge( [$key, $fromTimestamp, $toTimestamp], $commandArguments )); } } PK\X]` 0predis/src/Command/Redis/TimeSeries/TSINCRBY.phpnu[toArray() : []; parent::setArguments(array_merge( [$key, $value], $commandArguments )); } } PK\X]>0predis/src/Command/Redis/TimeSeries/TSDECRBY.phpnu[toArray() : []; parent::setArguments(array_merge( [$key, $value], $commandArguments )); } } PK\X]]]-predis/src/Command/Redis/TimeSeries/TSADD.phpnu[toArray() : []; parent::setArguments(array_merge( [$key, $timestamp, $value], $commandArguments )); } } PK\X]nY660predis/src/Command/Redis/TimeSeries/TSCREATE.phpnu[toArray() : []; parent::setArguments(array_merge( [$key], $commandArguments )); } } PK\X]toArray(); array_push($processedArguments, 'FILTER', ...$arguments); parent::setArguments(array_merge( $commandArguments, $processedArguments )); } } PK\X]e2predis/src/Command/Redis/TimeSeries/TSREVRANGE.phpnu[toArray(); parent::setArguments(array_merge( [$fromTimestamp, $toTimestamp], $commandArguments )); } } PK\X]z_  #predis/src/Command/Redis/EXISTS.phpnu[w"predis/src/Command/Redis/SSCAN.phpnu[prepareOptions(array_pop($arguments)); $arguments = array_merge($arguments, $options); } parent::setArguments($arguments); } /** * Returns a list of options and modifiers compatible with Redis. * * @param array $options List of options. * * @return array */ protected function prepareOptions($options) { $options = array_change_key_case($options, CASE_UPPER); $normalized = []; if (!empty($options['MATCH'])) { $normalized[] = 'MATCH'; $normalized[] = $options['MATCH']; } if (!empty($options['COUNT'])) { $normalized[] = 'COUNT'; $normalized[] = $options['COUNT']; } return $normalized; } } PK\X]r!predis/src/Command/Redis/DUMP.phpnu[ $score) { $arguments[] = $score; $arguments[] = $member; } } parent::setArguments($arguments); } } PK\X]D(predis/src/Command/Redis/ZUNIONSTORE.phpnu[setAggregate($arguments); $arguments = $this->getArguments(); $this->setWeights($arguments); $arguments = $this->getArguments(); $this->setKeys($arguments); } } PK\X]t"predis/src/Command/Redis/BITOP.phpnu[ $entry) { $log[$index] = [ 'id' => $entry[0], 'timestamp' => $entry[1], 'duration' => $entry[2], 'command' => $entry[3], ]; } return $log; } return $data; } } PK\X];2\\$predis/src/Command/Redis/HGETALL.phpnu[parseNewResponseFormat($lines); } else { return $this->parseOldResponseFormat($lines); } } /** * {@inheritdoc} */ public function parseNewResponseFormat($lines) { $info = []; $current = null; foreach ($lines as $row) { if ($row === '') { continue; } if (preg_match('/^# (\w+)$/', $row, $matches)) { $info[$matches[1]] = []; $current = &$info[$matches[1]]; continue; } [$k, $v] = $this->parseRow($row); $current[$k] = $v; } return $info; } /** * {@inheritdoc} */ public function parseOldResponseFormat($lines) { $info = []; foreach ($lines as $row) { if (strpos($row, ':') === false) { continue; } [$k, $v] = $this->parseRow($row); $info[$k] = $v; } return $info; } /** * Parses a single row of the response and returns the key-value pair. * * @param string $row Single row of the response. * * @return array */ protected function parseRow($row) { if (preg_match('/^module:name/', $row)) { return $this->parseModuleRow($row); } [$k, $v] = explode(':', $row, 2); if (preg_match('/^db\d+$/', $k)) { $v = $this->parseDatabaseStats($v); } return [$k, $v]; } /** * Extracts the statistics of each logical DB from the string buffer. * * @param string $str Response buffer. * * @return array */ protected function parseDatabaseStats($str) { $db = []; foreach (explode(',', $str) as $dbvar) { [$dbvk, $dbvv] = explode('=', $dbvar); $db[trim($dbvk)] = $dbvv; } return $db; } /** * Parsing module rows because of different format. * * @param string $row * @return array */ protected function parseModuleRow(string $row): array { [$moduleKeyword, $moduleData] = explode(':', $row); $explodedData = explode(',', $moduleData); $parsedData = []; foreach ($explodedData as $moduleDataRow) { [$k, $v] = explode('=', $moduleDataRow); if ($k === 'name') { $parsedData[0] = $v; continue; } $parsedData[1][$k] = $v; } return $parsedData; } } PK\X]t7$predis/src/Command/Redis/EVAL_RO.phpnu[ 1) { $result = []; for ($i = 0, $iMax = count($data); $i < $iMax; ++$i) { if (array_key_exists($i + 1, $data)) { $result[(string) $data[$i]] = $data[++$i]; } } return $result; } return $data; } } PK\X]! 444predis/src/Command/Redis/CountMinSketch/CMSMERGE.phpnu[getArguments(), CASE_UPPER); switch (strtoupper($args[0])) { case 'LIST': return $this->parseClientList($data); case 'KILL': case 'GETNAME': case 'SETNAME': default: return $data; } // @codeCoverageIgnore } /** * Parses the response to CLIENT LIST and returns a structured list. * * @param string $data Response buffer. * * @return array */ protected function parseClientList($data) { $clients = []; foreach (explode("\n", $data, -1) as $clientData) { $client = []; foreach (explode(' ', $clientData) as $kv) { @[$k, $v] = explode('=', $kv); $client[$k] = $v; } $clients[] = $client; } return $clients; } } PK\X]R<<'predis/src/Command/Redis/SMISMEMBER.phpnu[setDB($arguments); $arguments = $this->getArguments(); $this->setReplace($arguments); } } PK\X]~b3 %predis/src/Command/Redis/LASTSAVE.phpnu[ $value) { if ($index < 2) { continue; } if (false === $value || null === $value) { unset($arguments[$index]); } } parent::setArguments($arguments); } } PK\X]-K$predis/src/Command/Redis/ZPOPMAX.phpnu[getArgument(0); } } PK\X]'v  #predis/src/Command/Redis/RENAME.phpnu[filterArguments(); } public function parseResponse($data) { if ($this->isWithCountModifier()) { $result = []; for ($i = 0, $iMax = count($data); $i < $iMax; ++$i) { if (array_key_exists($i + 1, $data)) { $result[(string) $data[$i]] = $data[++$i]; } } return $result; } return $data; } /** * Checks for the presence of the WITHCOUNT modifier. * * @return bool */ private function isWithCountModifier(): bool { $arguments = $this->getArguments(); $lastArgument = (!empty($arguments)) ? $arguments[count($arguments) - 1] : null; return is_string($lastArgument) && strtoupper($lastArgument) === 'WITHCOUNT'; } } PK\X]k9VV+predis/src/Command/Redis/TopK/TOPKQUERY.phpnu[getArguments(); for ($i = 3; $i < count($arguments); ++$i) { switch (strtoupper($arguments[$i])) { case 'WITHSCORES': return true; case 'LIMIT': $i += 2; break; } } return false; } } PK\X]2&predis/src/Command/Redis/PEXPIREAT.phpnu[setLimit($arguments); $arguments = $this->getArguments(); $this->setKeys($arguments); } } PK\X] "predis/src/Command/Redis/ZMPOP.phpnu[setCount($arguments); $arguments = $this->getArguments(); $this->resolveModifier(static::$modifierArgumentPositionOffset, $arguments); $this->setKeys($arguments); $arguments = $this->getArguments(); parent::setArguments($arguments); } public function parseResponse($data) { $key = array_shift($data); if (null === $key) { return [$key]; } $data = $data[0]; $parsedData = []; for ($i = 0, $iMax = count($data); $i < $iMax; $i++) { for ($j = 0, $jMax = count($data[$i]); $j < $jMax; ++$j) { if ($data[$i][$j + 1] ?? false) { $parsedData[$data[$i][$j]] = $data[$i][++$j]; } } } return array_combine([$key], [$parsedData]); } } PK\X]#&>(predis/src/Command/Redis/PEXPIRETIME.phpnu[setKeys($arguments, false); } public function parseResponse($data) { $key = array_shift($data); if (null === $key) { return [$key]; } return array_combine([$key], [[$data[0] => $data[1]]]); } } PK\X]5'!predis/src/Command/Redis/INCR.phpnu[setTimeout($arguments); $arguments = $this->getArguments(); $this->setTo($arguments); $this->filterArguments(); } } PK\X]ԫUb$predis/src/Command/Redis/ZINCRBY.phpnu[getArgument(0))) { case 'numsub': return self::processNumsub($data); default: return $data; } } /** * Returns the processed response to PUBSUB NUMSUB. * * @param array $channels List of channels * * @return array */ protected static function processNumsub(array $channels) { $processed = []; $count = count($channels); for ($i = 0; $i < $count; ++$i) { $processed[$channels[$i]] = $channels[++$i]; } return $processed; } } PK\X]&%predis/src/Command/Redis/HPEXPIRE.phpnu[b/predis/src/Command/Redis/TDigest/TDIGESTMAX.phpnu[getArgument(0); $argument = is_null($argument) ? null : strtolower($argument); switch ($argument) { case 'masters': case 'slaves': return self::processMastersOrSlaves($data); default: return $data; } } /** * Returns a processed response to SENTINEL MASTERS or SENTINEL SLAVES. * * @param array $servers List of Redis servers. * * @return array */ protected static function processMastersOrSlaves(array $servers) { foreach ($servers as $idx => $node) { $processed = []; $count = count($node); for ($i = 0; $i < $count; ++$i) { $processed[$node[$i]] = $node[++$i]; } $servers[$idx] = $processed; } return $servers; } } PK\X]ь$predis/src/Command/Redis/HINCRBY.phpnu[setStoreDist($arguments); $arguments = $this->getArguments(); $this->setCount($arguments, $arguments[6] ?? false); $arguments = $this->getArguments(); $this->setSorting($arguments); $arguments = $this->getArguments(); $this->setFrom($arguments); $arguments = $this->getArguments(); $this->setBy($arguments); $this->filterArguments(); } } PK\X]K@$  #predis/src/Command/Redis/LINDEX.phpnu[ 2) { for ($i = 2, $iMax = count($arguments); $i < $iMax; $i++) { $processedArguments[] = $arguments[$i]; } } parent::setArguments($processedArguments); } } PK\X]e!predis/src/Command/Redis/MOVE.phpnu[setLimit($arguments); $arguments = $this->getArguments(); $this->setKeys($arguments); } } PK\X]a~!predis/src/Command/Redis/XADD.phpnu[ $val) { $args[] = $key; $args[] = $val; } } parent::setArguments($args); } } PK\X]P P &predis/src/Command/Redis/GEOSEARCH.phpnu[setSorting($arguments); $arguments = $this->getArguments(); $this->setWithCoord($arguments); $arguments = $this->getArguments(); $this->setWithDist($arguments); $arguments = $this->getArguments(); $this->setWithHash($arguments); $arguments = $this->getArguments(); $this->setCount($arguments, $arguments[5] ?? false); $arguments = $this->getArguments(); $this->setFrom($arguments); $arguments = $this->getArguments(); $this->setBy($arguments); $this->filterArguments(); } public function parseResponse($data) { $parsedData = []; $itemKey = ''; foreach ($data as $item) { if (!is_array($item)) { $parsedData[] = $item; continue; } foreach ($item as $key => $itemRow) { if ($key === 0) { $itemKey = $itemRow; continue; } if (is_string($itemRow)) { $parsedData[$itemKey]['dist'] = round((float) $itemRow, 5); } elseif (is_int($itemRow)) { $parsedData[$itemKey]['hash'] = $itemRow; } else { $parsedData[$itemKey]['lng'] = round($itemRow[0], 5); $parsedData[$itemKey]['lat'] = round($itemRow[1], 5); } } } return $parsedData; } } PK\X]I  #predis/src/Command/Redis/DBSIZE.phpnu[ 'EX', 'px' => 'PX', 'exat' => 'EXAT', 'pxat' => 'PXAT', 'persist' => 'PERSIST', ]; public function getId() { return 'GETEX'; } public function setArguments(array $arguments) { if (!array_key_exists(1, $arguments) || $arguments[1] === '') { parent::setArguments([$arguments[0]]); return; } if (!in_array(strtoupper($arguments[1]), self::$modifierEnum)) { $enumValues = implode(', ', array_keys(self::$modifierEnum)); throw new UnexpectedValueException("Modifier argument accepts only: {$enumValues} values"); } if ($arguments[1] === 'persist') { parent::setArguments([$arguments[0], self::$modifierEnum[$arguments[1]]]); return; } $arguments[1] = self::$modifierEnum[$arguments[1]]; if (!array_key_exists(2, $arguments)) { throw new UnexpectedValueException('You should provide value for current modifier'); } parent::setArguments($arguments); } } PK\X]&predis/src/Command/Redis/RPOPLPUSH.phpnu[setExpansion($arguments); $arguments = $this->getArguments(); $this->setMaxIterations($arguments); $arguments = $this->getArguments(); $this->setBucketSize($arguments); $this->filterArguments(); } } PK\X]4_2predis/src/Command/Redis/CuckooFilter/CFINSERT.phpnu[setNoCreate($arguments); $arguments = $this->getArguments(); $this->setItems($arguments); $arguments = $this->getArguments(); $this->setCapacity($arguments); $this->filterArguments(); } } PK\X]ڠ`0predis/src/Command/Redis/CuckooFilter/CFINFO.phpnu[ 1) { $result = []; for ($i = 0, $iMax = count($data); $i < $iMax; ++$i) { if (array_key_exists($i + 1, $data)) { $result[(string) $data[$i]] = $data[++$i]; } } return $result; } return $data; } } PK\X],ic332predis/src/Command/Redis/CuckooFilter/CFEXISTS.phpnu[prepareOptions(array_pop($arguments)); $arguments = array_merge($arguments, $options); } parent::setArguments($arguments); } /** * Returns a list of options and modifiers compatible with Redis. * * @param array $options List of options. * * @return array */ protected function prepareOptions($options) { $options = array_change_key_case($options, CASE_UPPER); $normalized = []; if (!empty($options['MATCH'])) { $normalized[] = 'MATCH'; $normalized[] = $options['MATCH']; } if (!empty($options['COUNT'])) { $normalized[] = 'COUNT'; $normalized[] = $options['COUNT']; } return $normalized; } } PK\X]u-predis/src/Command/Redis/ZREVRANGEBYSCORE.phpnu[setExpansion($arguments); $this->filterArguments(); } } PK\X]R_43predis/src/Command/Redis/BloomFilter/BFSCANDUMP.phpnu[ 'CAPACITY', 'size' => 'SIZE', 'filters' => 'FILTERS', 'items' => 'ITEMS', 'expansion' => 'EXPANSION', ]; public function getId() { return 'BF.INFO'; } public function setArguments(array $arguments) { if (isset($arguments[1])) { $modifier = array_pop($arguments); if ($modifier === '') { parent::setArguments($arguments); return; } if (!in_array(strtoupper($modifier), $this->modifierEnum)) { $enumValues = implode(', ', array_keys($this->modifierEnum)); throw new UnexpectedValueException("Argument accepts only: {$enumValues} values"); } $arguments[] = $this->modifierEnum[strtolower($modifier)]; } parent::setArguments($arguments); } public function parseResponse($data) { if (count($data) > 1) { $result = []; for ($i = 0, $iMax = count($data); $i < $iMax; ++$i) { if (array_key_exists($i + 1, $data)) { $result[(string) $data[$i]] = $data[++$i]; } } return $result; } return $data; } } PK\X]wACC1predis/src/Command/Redis/BloomFilter/BFEXISTS.phpnu[setNoCreate($arguments); $arguments = $this->getArguments(); if (array_key_exists(5, $arguments) && $arguments[5]) { $arguments[5] = 'NONSCALING'; } $this->setItems($arguments); $arguments = $this->getArguments(); $this->setExpansion($arguments); $arguments = $this->getArguments(); $this->setErrorRate($arguments); $arguments = $this->getArguments(); $this->setCapacity($arguments); $this->filterArguments(); } } PK\X]7t6predis/src/Command/Redis/Container/Search/FTCURSOR.phpnu[client = $client; } /** * {@inheritDoc} */ public function __call(string $subcommandID, array $arguments) { array_unshift($arguments, strtoupper($subcommandID)); return $this->client->executeCommand( $this->client->createCommand($this->getContainerCommandId(), $arguments) ); } abstract public function getContainerCommandId(): string; } PK\X]ЯYa a 7predis/src/Command/Redis/Container/ContainerFactory.phpnu[ FunctionContainer::class, ]; /** * Creates container command. * * @param ClientInterface $client * @param string $containerCommandID * @return ContainerInterface */ public static function create(ClientInterface $client, string $containerCommandID): ContainerInterface { $containerCommandID = strtoupper($containerCommandID); $commandModule = self::resolveCommandModuleByPrefix($containerCommandID); if (null !== $commandModule) { if (class_exists($containerClass = self::CONTAINER_NAMESPACE . '\\' . $commandModule . '\\' . $containerCommandID)) { return new $containerClass($client); } throw new UnexpectedValueException('Given module container command is not supported.'); } if (class_exists($containerClass = self::CONTAINER_NAMESPACE . '\\' . $containerCommandID)) { return new $containerClass($client); } if (array_key_exists($containerCommandID, self::$specialMappings)) { $containerClass = self::$specialMappings[$containerCommandID]; return new $containerClass($client); } throw new UnexpectedValueException('Given container command is not supported.'); } /** * @param string $commandID * @return string|null */ private static function resolveCommandModuleByPrefix(string $commandID): ?string { $modules = ClientConfiguration::getModules(); foreach ($modules as $module) { if (preg_match("/^{$module['commandPrefix']}/", $commandID)) { return $module['name']; } } return null; } } PK\X]=lQmzz.predis/src/Command/Redis/Container/CLUSTER.phpnu[ $value) { $modifier = strtoupper($modifier); if ($modifier === 'COPY' && $value == true) { $arguments[] = $modifier; } if ($modifier === 'REPLACE' && $value == true) { $arguments[] = $modifier; } } } parent::setArguments($arguments); } } PK\X]\R'predis/src/Command/Redis/HRANDFIELD.phpnu[strategyResolver = new SubcommandStrategyResolver(); } public function getId() { return 'FUNCTION'; } public function setArguments(array $arguments) { $strategy = $this->strategyResolver->resolve('functions', strtolower($arguments[0])); $arguments = $strategy->processArguments($arguments); parent::setArguments($arguments); $this->filterArguments(); } } PK\X]UU*predis/src/Command/Redis/Json/JSONMSET.phpnu[setSpace($arguments); $arguments = $this->getArguments(); $this->setNewline($arguments); $arguments = $this->getArguments(); $this->setIndent($arguments); $this->filterArguments(); } } PK\X]ɸBB+predis/src/Command/Redis/Json/JSONCLEAR.phpnu[setSubcommand($arguments); $this->filterArguments(); } } PK\X]b*predis/src/Command/Redis/Json/JSONMGET.phpnu[>/predis/src/Command/Redis/Json/JSONNUMINCRBY.phpnu[>/predis/src/Command/Redis/Json/JSONSTRAPPEND.phpnu[X)predis/src/Command/Redis/HINCRBYFLOAT.phpnu[prepareOptions(array_pop($arguments)); $arguments = array_merge($arguments, $options); } $this->arguments = $arguments; parent::setArguments($arguments); } /** * Returns a list of options and modifiers compatible with Redis. * * @param array $options List of options. * * @return array */ protected function prepareOptions($options) { $options = array_change_key_case($options, CASE_UPPER); $normalized = []; if (!empty($options['MATCH'])) { $normalized[] = 'MATCH'; $normalized[] = $options['MATCH']; } if (!empty($options['COUNT'])) { $normalized[] = 'COUNT'; $normalized[] = $options['COUNT']; } if (!empty($options['NOVALUES']) && true === $options['NOVALUES']) { $normalized[] = 'NOVALUES'; } return $normalized; } /** * {@inheritdoc} */ public function parseResponse($data) { if (!in_array('NOVALUES', $this->arguments, true)) { if (is_array($data)) { $fields = $data[1]; $result = []; for ($i = 0; $i < count($fields); ++$i) { $result[$fields[$i]] = $fields[++$i]; } $data[1] = $result; } } return $data; } } PK\X]B  #predis/src/Command/Redis/SUBSTR.phpnu[filterArguments(); } public function parseResponse($data) { if (is_array($data)) { if ($data !== array_values($data)) { return $data; // Relay } return [$data[0] => $data[1], $data[2] => $data[3]]; } return $data; } } PK\X]3P(predis/src/Command/Redis/SRANDMEMBER.phpnu[ $v) { $flattenedKVs[] = $k; $flattenedKVs[] = $v; } $arguments = $flattenedKVs; } parent::setArguments($arguments); } } PK\X]%predis/src/Command/Redis/EXPIREAT.phpnu[setKeys($arguments); $arguments = $this->getArguments(); $this->setWithScore($arguments); } } PK\X] (predis/src/Command/Redis/UNSUBSCRIBE.phpnu[getArgument(0)); } } PK\X]rSpMM"predis/src/Command/Redis/ZSCAN.phpnu[prepareOptions(array_pop($arguments)); $arguments = array_merge($arguments, $options); } parent::setArguments($arguments); } /** * Returns a list of options and modifiers compatible with Redis. * * @param array $options List of options. * * @return array */ protected function prepareOptions($options) { $options = array_change_key_case($options, CASE_UPPER); $normalized = []; if (!empty($options['MATCH'])) { $normalized[] = 'MATCH'; $normalized[] = $options['MATCH']; } if (!empty($options['COUNT'])) { $normalized[] = 'COUNT'; $normalized[] = $options['COUNT']; } return $normalized; } /** * {@inheritdoc} */ public function parseResponse($data) { if (is_array($data)) { $members = $data[1]; $result = []; for ($i = 0; $i < count($members); ++$i) { $result[$members[$i]] = (float) $members[++$i]; } $data[1] = $result; } return $data; } } PK\X];%predis/src/Command/Redis/GETRANGE.phpnu[ $v) { $flattenedKVs[] = $k; $flattenedKVs[] = $v; } $arguments = $flattenedKVs; } parent::setArguments($arguments); } } PK\X]G  #predis/src/Command/Redis/SELECT.phpnu["predis/src/Command/Redis/PFADD.phpnu[setCommonOptions('VECTOR', $fieldName, $alias); array_push($this->fieldArguments, $algorithm, count($attributeNameValueDictionary)); $this->fieldArguments = array_merge($this->fieldArguments, $attributeNameValueDictionary); } /** * {@inheritDoc} */ public function toArray(): array { return $this->fieldArguments; } } PK\X]Apredis/src/Command/Argument/Search/SchemaFields/GeoShapeField.phpnu[fieldArguments[] = $identifier; if ($alias !== '') { $this->fieldArguments[] = 'AS'; $this->fieldArguments[] = $alias; } $this->fieldArguments[] = 'GEOSHAPE'; if (null !== $coordSystem) { $this->fieldArguments[] = $coordSystem; } if ($sortable === self::SORTABLE) { $this->fieldArguments[] = 'SORTABLE'; } elseif ($sortable === self::SORTABLE_UNF) { $this->fieldArguments[] = 'SORTABLE'; $this->fieldArguments[] = 'UNF'; } if ($noIndex) { $this->fieldArguments[] = 'NOINDEX'; } } } PK\X]/q__<predis/src/Command/Argument/Search/SchemaFields/TagField.phpnu[setCommonOptions('TAG', $identifier, $alias, $sortable, $noIndex, $allowsMissing); if ($separator !== ',') { $this->fieldArguments[] = 'SEPARATOR'; $this->fieldArguments[] = $separator; } if ($caseSensitive) { $this->fieldArguments[] = 'CASESENSITIVE'; } if ($allowsEmpty) { $this->fieldArguments[] = 'INDEXEMPTY'; } } } PK\X]K Bpredis/src/Command/Argument/Search/SchemaFields/FieldInterface.phpnu[fieldArguments[] = $identifier; if ($alias !== '') { $this->fieldArguments[] = 'AS'; $this->fieldArguments[] = $alias; } $this->fieldArguments[] = $fieldType; if ($sortable === self::SORTABLE) { $this->fieldArguments[] = 'SORTABLE'; } elseif ($sortable === self::SORTABLE_UNF) { $this->fieldArguments[] = 'SORTABLE'; $this->fieldArguments[] = 'UNF'; } if ($noIndex) { $this->fieldArguments[] = 'NOINDEX'; } if ($allowsMissing) { $this->fieldArguments[] = 'INDEXMISSING'; } } /** * {@inheritDoc} */ public function toArray(): array { return $this->fieldArguments; } } PK\X]52N]]<predis/src/Command/Argument/Search/SchemaFields/GeoField.phpnu[setCommonOptions('GEO', $identifier, $alias, $sortable, $noIndex, $allowsMissing); } } PK\X]`L=predis/src/Command/Argument/Search/SchemaFields/TextField.phpnu[setCommonOptions('TEXT', $identifier, $alias, $sortable, $noIndex, $allowsMissing); if ($noStem) { $this->fieldArguments[] = 'NOSTEM'; } if ($phonetic !== '') { $this->fieldArguments[] = 'PHONETIC'; $this->fieldArguments[] = $phonetic; } if ($weight !== 1) { $this->fieldArguments[] = 'WEIGHT'; $this->fieldArguments[] = $weight; } if ($withSuffixTrie) { $this->fieldArguments[] = 'WITHSUFFIXTRIE'; } if ($allowsEmpty) { $this->fieldArguments[] = 'INDEXEMPTY'; } } } PK\X]4qee@predis/src/Command/Argument/Search/SchemaFields/NumericField.phpnu[setCommonOptions('NUMERIC', $identifier, $alias, $sortable, $noIndex, $allowsMissing); } } PK\X]6cc6predis/src/Command/Argument/Search/SugGetArguments.phpnu[arguments[] = 'FUZZY'; return $this; } /** * Limits the results to a maximum of num (default: 5). * * @param int $num * @return $this */ public function max(int $num): self { array_push($this->arguments, 'MAX', $num); return $this; } } PK\X]/bb6predis/src/Command/Argument/Search/CreateArguments.phpnu[ 'HASH', 'json' => 'JSON', ]; /** * Specify data type for given index. To index JSON you must have the RedisJSON module to be installed. * * @param string $modifier * @return $this */ public function on(string $modifier = 'HASH'): self { if (in_array(strtoupper($modifier), $this->supportedDataTypesEnum)) { $this->arguments[] = 'ON'; $this->arguments[] = $this->supportedDataTypesEnum[strtolower($modifier)]; return $this; } $enumValues = implode(', ', array_values($this->supportedDataTypesEnum)); throw new InvalidArgumentException("Wrong modifier value given. Currently supports: {$enumValues}"); } /** * Adds one or more prefixes into index. * * @param array $prefixes * @return $this */ public function prefix(array $prefixes): self { $this->arguments[] = 'PREFIX'; $this->arguments[] = count($prefixes); $this->arguments = array_merge($this->arguments, $prefixes); return $this; } /** * Document attribute set as document language. * * @param string $languageAttribute * @return $this */ public function languageField(string $languageAttribute): self { $this->arguments[] = 'LANGUAGE_FIELD'; $this->arguments[] = $languageAttribute; return $this; } /** * Default score for documents in the index. * * @param float $defaultScore * @return $this */ public function score(float $defaultScore = 1.0): self { $this->arguments[] = 'SCORE'; $this->arguments[] = $defaultScore; return $this; } /** * Document attribute that used as the document rank based on the user ranking. * * @param string $scoreAttribute * @return $this */ public function scoreField(string $scoreAttribute): self { $this->arguments[] = 'SCORE_FIELD'; $this->arguments[] = $scoreAttribute; return $this; } /** * Forces RediSearch to encode indexes as if there were more than 32 text attributes. * * @return $this */ public function maxTextFields(): self { $this->arguments[] = 'MAXTEXTFIELDS'; return $this; } /** * Does not store term offsets for documents. * * @return $this */ public function noOffsets(): self { $this->arguments[] = 'NOOFFSETS'; return $this; } /** * Creates a lightweight temporary index that expires after a specified period of inactivity, in seconds. * * @param int $seconds * @return $this */ public function temporary(int $seconds): self { $this->arguments[] = 'TEMPORARY'; $this->arguments[] = $seconds; return $this; } /** * Conserves storage space and memory by disabling highlighting support. * * @return $this */ public function noHl(): self { $this->arguments[] = 'NOHL'; return $this; } /** * Does not store attribute bits for each term. * * @return $this */ public function noFields(): self { $this->arguments[] = 'NOFIELDS'; return $this; } /** * Avoids saving the term frequencies in the index. * * @return $this */ public function noFreqs(): self { $this->arguments[] = 'NOFREQS'; return $this; } /** * Sets the index with a custom stopword list, to be ignored during indexing and search time. * * @param array $stopWords * @return $this */ public function stopWords(array $stopWords): self { $this->arguments[] = 'STOPWORDS'; $this->arguments[] = count($stopWords); $this->arguments = array_merge($this->arguments, $stopWords); return $this; } } PK\X]196predis/src/Command/Argument/Search/CursorArguments.phpnu[arguments, 'COUNT', $readSize); return $this; } /** * {@inheritDoc} */ public function toArray(): array { return $this->arguments; } } PK\X]}W6predis/src/Command/Argument/Search/CommonArguments.phpnu[arguments[] = 'LANGUAGE'; $this->arguments[] = $defaultLanguage; return $this; } /** * Selects the dialect version under which to execute the query. * If not specified, the query will execute under the default dialect version * set during module initial loading or via FT.CONFIG SET command. * * @param string $dialect * @return $this */ public function dialect(string $dialect): self { $this->arguments[] = 'DIALECT'; $this->arguments[] = $dialect; return $this; } /** * If set, does not scan and index. * * @return $this */ public function skipInitialScan(): self { $this->arguments[] = 'SKIPINITIALSCAN'; return $this; } /** * Adds an arbitrary, binary safe payload that is exposed to custom scoring functions. * * @param string $payload * @return $this */ public function payload(string $payload): self { $this->arguments[] = 'PAYLOAD'; $this->arguments[] = $payload; return $this; } /** * Also returns the relative internal score of each document. * * @return $this */ public function withScores(): self { $this->arguments[] = 'WITHSCORES'; return $this; } /** * Retrieves optional document payloads. * * @return $this */ public function withPayloads(): self { $this->arguments[] = 'WITHPAYLOADS'; return $this; } /** * Does not try to use stemming for query expansion but searches the query terms verbatim. * * @return $this */ public function verbatim(): self { $this->arguments[] = 'VERBATIM'; return $this; } /** * Overrides the timeout parameter of the module. * * @param int $timeout * @return $this */ public function timeout(int $timeout): self { $this->arguments[] = 'TIMEOUT'; $this->arguments[] = $timeout; return $this; } /** * Adds an arbitrary, binary safe payload that is exposed to custom scoring functions. * * @param int $offset * @param int $num * @return $this */ public function limit(int $offset, int $num): self { array_push($this->arguments, 'LIMIT', $offset, $num); return $this; } /** * Adds filter expression into index. * * @param string $filter * @return $this */ public function filter(string $filter): self { $this->arguments[] = 'FILTER'; $this->arguments[] = $filter; return $this; } /** * Defines one or more value parameters. Each parameter has a name and a value. * * Example: ['name1', 'value1', 'name2', 'value2'...] * * @param array $nameValuesDictionary * @return $this */ public function params(array $nameValuesDictionary): self { $this->arguments[] = 'PARAMS'; $this->arguments[] = count($nameValuesDictionary); $this->arguments = array_merge($this->arguments, $nameValuesDictionary); return $this; } /** * {@inheritDoc} */ public function toArray(): array { return $this->arguments; } } PK\X]1F7predis/src/Command/Argument/Search/ProfileArguments.phpnu[arguments[] = 'SEARCH'; return $this; } /** * Adds aggregate context. * * @return $this */ public function aggregate(): self { $this->arguments[] = 'AGGREGATE'; return $this; } /** * Removes details of reader iterator. * * @return $this */ public function limited(): self { $this->arguments[] = 'LIMITED'; return $this; } /** * Is query string, as if sent to FT.SEARCH. * * @param string $query * @return $this */ public function query(string $query): self { $this->arguments[] = 'QUERY'; $this->arguments[] = $query; return $this; } /** * {@inheritDoc} */ public function toArray(): array { return $this->arguments; } } PK\X]%"":predis/src/Command/Argument/Search/SpellcheckArguments.phpnu[ 'INCLUDE', 'exclude' => 'EXCLUDE', ]; /** * Is maximum Levenshtein distance for spelling suggestions (default: 1, max: 4). * * @return $this */ public function distance(int $distance): self { $this->arguments[] = 'DISTANCE'; $this->arguments[] = $distance; return $this; } /** * Specifies an inclusion (INCLUDE) or exclusion (EXCLUDE) of a custom dictionary named {dict}. * * @param string $dictionary * @param string $modifier * @param string ...$terms * @return $this */ public function terms(string $dictionary, string $modifier = 'INCLUDE', string ...$terms): self { if (!in_array(strtoupper($modifier), $this->termsEnum)) { $enumValues = implode(', ', array_values($this->termsEnum)); throw new InvalidArgumentException("Wrong modifier value given. Currently supports: {$enumValues}"); } array_push($this->arguments, 'TERMS', $this->termsEnum[strtolower($modifier)], $dictionary, ...$terms); return $this; } } PK\X]%$$4predis/src/Command/Argument/Search/DropArguments.phpnu[arguments[] = 'DD'; return $this; } /** * @return array */ public function toArray(): array { return $this->arguments; } } PK\X]?aa9predis/src/Command/Argument/Search/SynUpdateArguments.phpnu[ 'ASC', 'desc' => 'DESC', ]; /** * Loads document attributes from the source document. * * @param string ...$fields Could be just '*' to load all fields * @return $this */ public function load(string ...$fields): self { $arguments = func_get_args(); $this->arguments[] = 'LOAD'; if ($arguments[0] === '*') { $this->arguments[] = '*'; return $this; } $this->arguments[] = count($arguments); $this->arguments = array_merge($this->arguments, $arguments); return $this; } /** * Loads document attributes from the source document. * * @param string ...$properties * @return $this */ public function groupBy(string ...$properties): self { $arguments = func_get_args(); array_push($this->arguments, 'GROUPBY', count($arguments)); $this->arguments = array_merge($this->arguments, $arguments); return $this; } /** * Groups the results in the pipeline based on one or more properties. * * If you want to add alias property to your argument just add "true" value in arguments enumeration, * next value will be considered as alias to previous one. * * Example: 'argument', true, 'name' => 'argument' AS 'name' * * @param string $function * @param string|bool ...$argument * @return $this */ public function reduce(string $function, ...$argument): self { $arguments = func_get_args(); $functionValue = array_shift($arguments); $argumentsCounter = 0; for ($i = 0, $iMax = count($arguments); $i < $iMax; $i++) { if (true === $arguments[$i]) { $arguments[$i] = 'AS'; $i++; continue; } $argumentsCounter++; } array_push($this->arguments, 'REDUCE', $functionValue); $this->arguments = array_merge($this->arguments, [$argumentsCounter], $arguments); return $this; } /** * Sorts the pipeline up until the point of SORTBY, using a list of properties. * * @param int $max * @param string ...$properties Enumeration of properties, including sorting direction (ASC, DESC) * @return $this */ public function sortBy(int $max = 0, ...$properties): self { $arguments = func_get_args(); $maxValue = array_shift($arguments); $this->arguments[] = 'SORTBY'; $this->arguments = array_merge($this->arguments, [count($arguments)], $arguments); if ($maxValue !== 0) { array_push($this->arguments, 'MAX', $maxValue); } return $this; } /** * Applies a 1-to-1 transformation on one or more properties and either stores the result * as a new property down the pipeline or replaces any property using this transformation. * * @param string $expression * @param string $as * @return $this */ public function apply(string $expression, string $as = ''): self { array_push($this->arguments, 'APPLY', $expression); if ($as !== '') { array_push($this->arguments, 'AS', $as); } return $this; } /** * Scan part of the results with a quicker alternative than LIMIT. * * @param int $readSize * @param int $idleTime * @return $this */ public function withCursor(int $readSize = 0, int $idleTime = 0): self { $this->arguments[] = 'WITHCURSOR'; if ($readSize !== 0) { array_push($this->arguments, 'COUNT', $readSize); } if ($idleTime !== 0) { array_push($this->arguments, 'MAXIDLE', $idleTime); } return $this; } } PK\X],|.!.!6predis/src/Command/Argument/Search/SearchArguments.phpnu[ 'ASC', 'desc' => 'DESC', ]; /** * Returns the document ids and not the content. * * @return $this */ public function noContent(): self { $this->arguments[] = 'NOCONTENT'; return $this; } /** * Returns the value of the sorting key, right after the id and score and/or payload, if requested. * * @return $this */ public function withSortKeys(): self { $this->arguments[] = 'WITHSORTKEYS'; return $this; } /** * Limits results to those having numeric values ranging between min and max, * if numeric_attribute is defined as a numeric attribute in FT.CREATE. * Min and max follow ZRANGE syntax, and can be -inf, +inf, and use( for exclusive ranges. * Multiple numeric filters for different attributes are supported in one query. * * @param array ...$filter Should contain: numeric_field, min and max. Example: ['numeric_field', 1, 10] * @return $this */ public function searchFilter(array ...$filter): self { $arguments = func_get_args(); foreach ($arguments as $argument) { array_push($this->arguments, 'FILTER', ...$argument); } return $this; } /** * Filter the results to a given radius from lon and lat. Radius is given as a number and units. * * @param array ...$filter Should contain: geo_field, lon, lat, radius, unit. Example: ['geo_field', 34.1231, 35.1231, 300, km] * @return $this */ public function geoFilter(array ...$filter): self { $arguments = func_get_args(); foreach ($arguments as $argument) { array_push($this->arguments, 'GEOFILTER', ...$argument); } return $this; } /** * Limits the result to a given set of keys specified in the list. * * @param array $keys * @return $this */ public function inKeys(array $keys): self { $this->arguments[] = 'INKEYS'; $this->arguments[] = count($keys); $this->arguments = array_merge($this->arguments, $keys); return $this; } /** * Filters the results to those appearing only in specific attributes of the document, like title or URL. * * @param array $fields * @return $this */ public function inFields(array $fields): self { $this->arguments[] = 'INFIELDS'; $this->arguments[] = count($fields); $this->arguments = array_merge($this->arguments, $fields); return $this; } /** * Limits the attributes returned from the document. * Num is the number of attributes following the keyword. * If num is 0, it acts like NOCONTENT. * Identifier is either an attribute name (for hashes and JSON) or a JSON Path expression (for JSON). * Property is an optional name used in the result. If not provided, the identifier is used in the result. * * If you want to add alias property to your identifier just add "true" value in identifier enumeration, * next value will be considered as alias to previous one. * * Example: 'identifier', true, 'property' => 'identifier' AS 'property' * * @param int $count * @param string|bool ...$identifier * @return $this */ public function addReturn(int $count, ...$identifier): self { $arguments = func_get_args(); $this->arguments[] = 'RETURN'; for ($i = 1, $iMax = count($arguments); $i < $iMax; $i++) { if (true === $arguments[$i]) { $arguments[$i] = 'AS'; } } $this->arguments = array_merge($this->arguments, $arguments); return $this; } /** * Returns only the sections of the attribute that contain the matched text. * * @param array $fields * @param int $frags * @param int $len * @param string $separator * @return $this */ public function summarize(array $fields = [], int $frags = 0, int $len = 0, string $separator = ''): self { $this->arguments[] = 'SUMMARIZE'; if (!empty($fields)) { $this->arguments[] = 'FIELDS'; $this->arguments[] = count($fields); $this->arguments = array_merge($this->arguments, $fields); } if ($frags !== 0) { $this->arguments[] = 'FRAGS'; $this->arguments[] = $frags; } if ($len !== 0) { $this->arguments[] = 'LEN'; $this->arguments[] = $len; } if ($separator !== '') { $this->arguments[] = 'SEPARATOR'; $this->arguments[] = $separator; } return $this; } /** * Formats occurrences of matched text. * * @param array $fields * @param string $openTag * @param string $closeTag * @return $this */ public function highlight(array $fields = [], string $openTag = '', string $closeTag = ''): self { $this->arguments[] = 'HIGHLIGHT'; if (!empty($fields)) { $this->arguments[] = 'FIELDS'; $this->arguments[] = count($fields); $this->arguments = array_merge($this->arguments, $fields); } if ($openTag !== '' && $closeTag !== '') { array_push($this->arguments, 'TAGS', $openTag, $closeTag); } return $this; } /** * Allows a maximum of N intervening number of unmatched offsets between phrase terms. * In other words, the slop for exact phrases is 0. * * @param int $slop * @return $this */ public function slop(int $slop): self { $this->arguments[] = 'SLOP'; $this->arguments[] = $slop; return $this; } /** * Puts the query terms in the same order in the document as in the query, regardless of the offsets between them. * Typically used in conjunction with SLOP. * * @return $this */ public function inOrder(): self { $this->arguments[] = 'INORDER'; return $this; } /** * Uses a custom query expander instead of the stemmer. * * @param string $expander * @return $this */ public function expander(string $expander): self { $this->arguments[] = 'EXPANDER'; $this->arguments[] = $expander; return $this; } /** * Uses a custom scoring function you define. * * @param string $scorer * @return $this */ public function scorer(string $scorer): self { $this->arguments[] = 'SCORER'; $this->arguments[] = $scorer; return $this; } /** * Returns a textual description of how the scores were calculated. * Using this options requires the WITHSCORES option. * * @return $this */ public function explainScore(): self { $this->arguments[] = 'EXPLAINSCORE'; return $this; } /** * Orders the results by the value of this attribute. * This applies to both text and numeric attributes. * Attributes needed for SORTBY should be declared as SORTABLE in the index, in order to be available with very low latency. * Note that this adds memory overhead. * * @param string $sortAttribute * @param string $orderBy * @return $this */ public function sortBy(string $sortAttribute, string $orderBy = 'asc'): self { $this->arguments[] = 'SORTBY'; $this->arguments[] = $sortAttribute; if (in_array(strtoupper($orderBy), $this->sortingEnum)) { $this->arguments[] = $this->sortingEnum[strtolower($orderBy)]; } else { $enumValues = implode(', ', array_values($this->sortingEnum)); throw new InvalidArgumentException("Wrong order direction value given. Currently supports: {$enumValues}"); } return $this; } } PK\X]{ u6predis/src/Command/Argument/Search/SugAddArguments.phpnu[arguments[] = 'INCR'; return $this; } } PK\X]__7predis/src/Command/Argument/Search/ExplainArguments.phpnu[arguments, 'FILTER', ...$filterExpressions); return $this; } /** * Splits time series into groups, each group contains time series that share the same * value for the provided label name, then aggregates results in each group. * * @param string $label * @param string $reducer * @return $this */ public function groupBy(string $label, string $reducer): self { array_push($this->arguments, 'GROUPBY', $label, 'REDUCE', $reducer); return $this; } } PK\X]K.:predis/src/Command/Argument/TimeSeries/CommonArguments.phpnu[arguments, 'RETENTION', $retentionPeriod); return $this; } /** * Ignore samples with given time or value difference. * * @param int $maxTimeDiff Non-negative integer value in milliseconds * @param float $maxValDiff Non-negative float value * @return $this */ public function ignore(int $maxTimeDiff, float $maxValDiff): self { if ($maxTimeDiff < 0 || $maxValDiff < 0) { throw new UnexpectedValueException('Ignore does not accept negative values'); } array_push($this->arguments, 'IGNORE', $maxTimeDiff, $maxValDiff); return $this; } /** * Is initial allocation size, in bytes, for the data part of each new chunk. * * @param int $size * @return $this */ public function chunkSize(int $size): self { array_push($this->arguments, 'CHUNK_SIZE', $size); return $this; } /** * Is policy for handling insertion of multiple samples with identical timestamps. * * @param string $policy * @return $this */ public function duplicatePolicy(string $policy = self::POLICY_BLOCK): self { array_push($this->arguments, 'DUPLICATE_POLICY', $policy); return $this; } /** * Is set of label-value pairs that represent metadata labels of the key and serve as a secondary index. * * @param mixed ...$labelValuePair * @return $this */ public function labels(...$labelValuePair): self { array_push($this->arguments, 'LABELS', ...$labelValuePair); return $this; } /** * Specifies the series samples encoding format. * * @param string $encoding * @return $this */ public function encoding(string $encoding = self::ENCODING_COMPRESSED): self { array_push($this->arguments, 'ENCODING', $encoding); return $this; } /** * Is used when a time series is a compaction. * With LATEST, TS.GET reports the compacted value of the latest, possibly partial, bucket. * * @return $this */ public function latest(): self { $this->arguments[] = 'LATEST'; return $this; } /** * Includes in the reply all label-value pairs representing metadata labels of the time series. * * @return $this */ public function withLabels(): self { $this->arguments[] = 'WITHLABELS'; return $this; } /** * Returns a subset of the label-value pairs that represent metadata labels of the time series. * * @return $this */ public function selectedLabels(string ...$labels): self { array_push($this->arguments, 'SELECTED_LABELS', ...$labels); return $this; } /** * {@inheritDoc} */ public function toArray(): array { return $this->arguments; } } PK\X]arguments, 'TIMESTAMP', $timeStamp); return $this; } /** * Changes data storage from compressed (default) to uncompressed. * * @return $this */ public function uncompressed(): self { $this->arguments[] = 'UNCOMPRESSED'; return $this; } } PK\X]S``8predis/src/Command/Argument/TimeSeries/MGetArguments.phpnu[arguments, 'FILTER_BY_TS', ...$ts); return $this; } /** * Filters samples by minimum and maximum values. * * @param int $min * @param int $max * @return $this */ public function filterByValue(int $min, int $max): self { array_push($this->arguments, 'FILTER_BY_VALUE', $min, $max); return $this; } /** * Limits the number of returned samples. * * @param int $count * @return $this */ public function count(int $count): self { array_push($this->arguments, 'COUNT', $count); return $this; } /** * Aggregates samples into time buckets. * * @param string $aggregator * @param int $bucketDuration Is duration of each bucket, in milliseconds. * @param int $align It controls the time bucket timestamps by changing the reference timestamp on which a bucket is defined. * @param int $bucketTimestamp Controls how bucket timestamps are reported. * @param bool $empty Is a flag, which, when specified, reports aggregations also for empty buckets. * @return $this */ public function aggregation(string $aggregator, int $bucketDuration, int $align = 0, int $bucketTimestamp = 0, bool $empty = false): self { if ($align > 0) { array_push($this->arguments, 'ALIGN', $align); } array_push($this->arguments, 'AGGREGATION', $aggregator, $bucketDuration); if ($bucketTimestamp > 0) { array_push($this->arguments, 'BUCKETTIMESTAMP', $bucketTimestamp); } if (true === $empty) { $this->arguments[] = 'EMPTY'; } return $this; } } PK\X]&Mbb:predis/src/Command/Argument/TimeSeries/DecrByArguments.phpnu[arguments, 'ON_DUPLICATE', $policy); return $this; } } PK\X] _448predis/src/Command/Argument/TimeSeries/InfoArguments.phpnu[arguments[] = 'DEBUG'; return $this; } /** * {@inheritDoc} */ public function toArray(): array { return $this->arguments; } } PK\X]^3predis/src/Command/Argument/Geospatial/ByRadius.phpnu[radius = $radius; $this->setUnit($unit); } /** * {@inheritDoc} */ public function toArray(): array { return [self::KEYWORD, $this->radius, $this->unit]; } } PK\X]@س5predis/src/Command/Argument/Geospatial/AbstractBy.phpnu[unit = $unit; } } PK\X]SD335predis/src/Command/Argument/Geospatial/FromLonLat.phpnu[longitude = $longitude; $this->latitude = $latitude; } /** * {@inheritDoc} */ public function toArray(): array { return [self::KEYWORD, $this->longitude, $this->latitude]; } } PK\X]`6predis/src/Command/Argument/Geospatial/ByInterface.phpnu[width = $width; $this->height = $height; $this->setUnit($unit); } /** * {@inheritDoc} */ public function toArray(): array { return [self::KEYWORD, $this->width, $this->height, $this->unit]; } } PK\X]y5predis/src/Command/Argument/Geospatial/FromMember.phpnu[member = $member; } /** * {@inheritDoc} */ public function toArray(): array { return [self::KEYWORD, $this->member]; } } PK\X]G)  7predis/src/Command/Argument/Server/LimitOffsetCount.phpnu[offset = $offset; $this->count = $count; } /** * {@inheritDoc} */ public function toArray(): array { return [self::KEYWORD, $this->offset, $this->count]; } } PK\X]-m<<)predis/src/Command/Argument/Server/To.phpnu[host = $host; $this->port = $port; $this->isForce = $isForce; } /** * {@inheritDoc} */ public function toArray(): array { $arguments = [self::KEYWORD, $this->host, $this->port]; if ($this->isForce) { $arguments[] = self::FORCE_KEYWORD; } return $arguments; } } PK\X]ؓ5predis/src/Command/Argument/Server/LimitInterface.phpnu[prefix = $prefix; $prefixFirst = static::class . '::first'; $prefixFirstTwo = static::class . '::firstTwo'; $prefixAll = static::class . '::all'; $prefixInterleaved = static::class . '::interleaved'; $prefixSkipFirst = static::class . '::skipFirst'; $prefixSkipLast = static::class . '::skipLast'; $prefixSort = static::class . '::sort'; $prefixEvalKeys = static::class . '::evalKeys'; $prefixZsetStore = static::class . '::zsetStore'; $prefixMigrate = static::class . '::migrate'; $prefixGeoradius = static::class . '::georadius'; $this->commands = [ /* ---------------- Redis 1.2 ---------------- */ 'EXISTS' => $prefixAll, 'DEL' => $prefixAll, 'TYPE' => $prefixFirst, 'KEYS' => $prefixFirst, 'RENAME' => $prefixAll, 'RENAMENX' => $prefixAll, 'EXPIRE' => $prefixFirst, 'EXPIREAT' => $prefixFirst, 'TTL' => $prefixFirst, 'MOVE' => $prefixFirst, 'SORT' => $prefixSort, 'DUMP' => $prefixFirst, 'RESTORE' => $prefixFirst, 'SET' => $prefixFirst, 'SETNX' => $prefixFirst, 'MSET' => $prefixInterleaved, 'MSETNX' => $prefixInterleaved, 'GET' => $prefixFirst, 'MGET' => $prefixAll, 'GETSET' => $prefixFirst, 'INCR' => $prefixFirst, 'INCRBY' => $prefixFirst, 'DECR' => $prefixFirst, 'DECRBY' => $prefixFirst, 'RPUSH' => $prefixFirst, 'LPUSH' => $prefixFirst, 'LLEN' => $prefixFirst, 'LRANGE' => $prefixFirst, 'LTRIM' => $prefixFirst, 'LINDEX' => $prefixFirst, 'LSET' => $prefixFirst, 'LREM' => $prefixFirst, 'LPOP' => $prefixFirst, 'RPOP' => $prefixFirst, 'RPOPLPUSH' => $prefixAll, 'SADD' => $prefixFirst, 'SREM' => $prefixFirst, 'SPOP' => $prefixFirst, 'SMOVE' => $prefixSkipLast, 'SCARD' => $prefixFirst, 'SISMEMBER' => $prefixFirst, 'SINTER' => $prefixAll, 'SINTERSTORE' => $prefixAll, 'SUNION' => $prefixAll, 'SUNIONSTORE' => $prefixAll, 'SDIFF' => $prefixAll, 'SDIFFSTORE' => $prefixAll, 'SMEMBERS' => $prefixFirst, 'SMISMEMBER' => $prefixFirst, 'SRANDMEMBER' => $prefixFirst, 'ZADD' => $prefixFirst, 'ZINCRBY' => $prefixFirst, 'ZREM' => $prefixFirst, 'ZRANGE' => $prefixFirst, 'ZREVRANGE' => $prefixFirst, 'ZRANGEBYSCORE' => $prefixFirst, 'ZCARD' => $prefixFirst, 'ZSCORE' => $prefixFirst, 'ZREMRANGEBYSCORE' => $prefixFirst, /* ---------------- Redis 2.0 ---------------- */ 'SETEX' => $prefixFirst, 'APPEND' => $prefixFirst, 'SUBSTR' => $prefixFirst, 'BLPOP' => $prefixSkipLast, 'BRPOP' => $prefixSkipLast, 'ZUNIONSTORE' => $prefixZsetStore, 'ZINTERSTORE' => $prefixZsetStore, 'ZCOUNT' => $prefixFirst, 'ZRANK' => $prefixFirst, 'ZREVRANK' => $prefixFirst, 'ZREMRANGEBYRANK' => $prefixFirst, 'HSET' => $prefixFirst, 'HSETNX' => $prefixFirst, 'HMSET' => $prefixFirst, 'HINCRBY' => $prefixFirst, 'HGET' => $prefixFirst, 'HMGET' => $prefixFirst, 'HDEL' => $prefixFirst, 'HEXISTS' => $prefixFirst, 'HLEN' => $prefixFirst, 'HKEYS' => $prefixFirst, 'HVALS' => $prefixFirst, 'HGETALL' => $prefixFirst, 'SUBSCRIBE' => $prefixAll, 'UNSUBSCRIBE' => $prefixAll, 'PSUBSCRIBE' => $prefixAll, 'PUNSUBSCRIBE' => $prefixAll, 'PUBLISH' => $prefixFirst, /* ---------------- Redis 2.2 ---------------- */ 'PERSIST' => $prefixFirst, 'STRLEN' => $prefixFirst, 'SETRANGE' => $prefixFirst, 'GETRANGE' => $prefixFirst, 'SETBIT' => $prefixFirst, 'GETBIT' => $prefixFirst, 'RPUSHX' => $prefixFirst, 'LPUSHX' => $prefixFirst, 'LINSERT' => $prefixFirst, 'BRPOPLPUSH' => $prefixSkipLast, 'ZREVRANGEBYSCORE' => $prefixFirst, 'WATCH' => $prefixAll, /* ---------------- Redis 2.6 ---------------- */ 'PTTL' => $prefixFirst, 'PEXPIRE' => $prefixFirst, 'PEXPIREAT' => $prefixFirst, 'PSETEX' => $prefixFirst, 'INCRBYFLOAT' => $prefixFirst, 'BITOP' => $prefixSkipFirst, 'BITCOUNT' => $prefixFirst, 'HINCRBYFLOAT' => $prefixFirst, 'EVAL' => $prefixEvalKeys, 'EVALSHA' => $prefixEvalKeys, 'MIGRATE' => $prefixMigrate, /* ---------------- Redis 2.8 ---------------- */ 'SSCAN' => $prefixFirst, 'ZSCAN' => $prefixFirst, 'HSCAN' => $prefixFirst, 'PFADD' => $prefixFirst, 'PFCOUNT' => $prefixAll, 'PFMERGE' => $prefixAll, 'ZLEXCOUNT' => $prefixFirst, 'ZRANGEBYLEX' => $prefixFirst, 'ZREMRANGEBYLEX' => $prefixFirst, 'ZREVRANGEBYLEX' => $prefixFirst, 'BITPOS' => $prefixFirst, /* ---------------- Redis 3.2 ---------------- */ 'HSTRLEN' => $prefixFirst, 'BITFIELD' => $prefixFirst, 'GEOADD' => $prefixFirst, 'GEOHASH' => $prefixFirst, 'GEOPOS' => $prefixFirst, 'GEODIST' => $prefixFirst, 'GEORADIUS' => $prefixGeoradius, 'GEORADIUSBYMEMBER' => $prefixGeoradius, /* ---------------- Redis 5.0 ---------------- */ 'XADD' => $prefixFirst, 'XRANGE' => $prefixFirst, 'XREVRANGE' => $prefixFirst, 'XDEL' => $prefixFirst, 'XLEN' => $prefixFirst, 'XACK' => $prefixFirst, 'XTRIM' => $prefixFirst, 'ZPOPMIN' => $prefixFirst, 'ZPOPMAX' => $prefixFirst, /* ---------------- Redis 6.2 ---------------- */ 'GETDEL' => $prefixFirst, 'ZMSCORE' => $prefixFirst, 'LMOVE' => $prefixFirstTwo, 'BLMOVE' => $prefixFirstTwo, 'GEOSEARCH' => $prefixFirst, /* ---------------- Redis 7.0 ---------------- */ 'EXPIRETIME' => $prefixFirst, /* RedisJSON */ 'JSON.ARRAPPEND' => $prefixFirst, 'JSON.ARRINDEX' => $prefixFirst, 'JSON.ARRINSERT' => $prefixFirst, 'JSON.ARRLEN' => $prefixFirst, 'JSON.ARRPOP' => $prefixFirst, 'JSON.ARRTRIM' => $prefixFirst, 'JSON.CLEAR' => $prefixFirst, 'JSON.DEBUG MEMORY' => $prefixFirst, 'JSON.DEL' => $prefixFirst, 'JSON.FORGET' => $prefixFirst, 'JSON.GET' => $prefixFirst, 'JSON.MGET' => $prefixAll, 'JSON.NUMINCRBY' => $prefixFirst, 'JSON.OBJKEYS' => $prefixFirst, 'JSON.OBJLEN' => $prefixFirst, 'JSON.RESP' => $prefixFirst, 'JSON.SET' => $prefixFirst, 'JSON.STRAPPEND' => $prefixFirst, 'JSON.STRLEN' => $prefixFirst, 'JSON.TOGGLE' => $prefixFirst, 'JSON.TYPE' => $prefixFirst, /* RedisBloom */ 'BF.ADD' => $prefixFirst, 'BF.EXISTS' => $prefixFirst, 'BF.INFO' => $prefixFirst, 'BF.INSERT' => $prefixFirst, 'BF.LOADCHUNK' => $prefixFirst, 'BF.MADD' => $prefixFirst, 'BF.MEXISTS' => $prefixFirst, 'BF.RESERVE' => $prefixFirst, 'BF.SCANDUMP' => $prefixFirst, 'CF.ADD' => $prefixFirst, 'CF.ADDNX' => $prefixFirst, 'CF.COUNT' => $prefixFirst, 'CF.DEL' => $prefixFirst, 'CF.EXISTS' => $prefixFirst, 'CF.INFO' => $prefixFirst, 'CF.INSERT' => $prefixFirst, 'CF.INSERTNX' => $prefixFirst, 'CF.LOADCHUNK' => $prefixFirst, 'CF.MEXISTS' => $prefixFirst, 'CF.RESERVE' => $prefixFirst, 'CF.SCANDUMP' => $prefixFirst, 'CMS.INCRBY' => $prefixFirst, 'CMS.INFO' => $prefixFirst, 'CMS.INITBYDIM' => $prefixFirst, 'CMS.INITBYPROB' => $prefixFirst, 'CMS.QUERY' => $prefixFirst, 'TDIGEST.ADD' => $prefixFirst, 'TDIGEST.BYRANK' => $prefixFirst, 'TDIGEST.BYREVRANK' => $prefixFirst, 'TDIGEST.CDF' => $prefixFirst, 'TDIGEST.CREATE' => $prefixFirst, 'TDIGEST.INFO' => $prefixFirst, 'TDIGEST.MAX' => $prefixFirst, 'TDIGEST.MIN' => $prefixFirst, 'TDIGEST.QUANTILE' => $prefixFirst, 'TDIGEST.RANK' => $prefixFirst, 'TDIGEST.RESET' => $prefixFirst, 'TDIGEST.REVRANK' => $prefixFirst, 'TDIGEST.TRIMMED_MEAN' => $prefixFirst, 'TOPK.ADD' => $prefixFirst, 'TOPK.INCRBY' => $prefixFirst, 'TOPK.INFO' => $prefixFirst, 'TOPK.LIST' => $prefixFirst, 'TOPK.QUERY' => $prefixFirst, 'TOPK.RESERVE' => $prefixFirst, /* RediSearch */ 'FT.AGGREGATE' => $prefixFirst, 'FT.ALTER' => $prefixFirst, 'FT.CREATE' => $prefixFirst, 'FT.CURSOR DEL' => $prefixFirst, 'FT.CURSOR READ' => $prefixFirst, 'FT.DROPINDEX' => $prefixFirst, 'FT.EXPLAIN' => $prefixFirst, 'FT.INFO' => $prefixFirst, 'FT.PROFILE' => $prefixFirst, 'FT.SEARCH' => $prefixFirst, 'FT.SPELLCHECK' => $prefixFirst, 'FT.SYNDUMP' => $prefixFirst, 'FT.SYNUPDATE' => $prefixFirst, 'FT.TAGVALS' => $prefixFirst, /* Redis TimeSeries */ 'TS.ADD' => $prefixFirst, 'TS.ALTER' => $prefixFirst, 'TS.CREATE' => $prefixFirst, 'TS.DECRBY' => $prefixFirst, 'TS.DEL' => $prefixFirst, 'TS.GET' => $prefixFirst, 'TS.INCRBY' => $prefixFirst, 'TS.INFO' => $prefixFirst, 'TS.MGET' => $prefixFirst, 'TS.MRANGE' => $prefixFirst, 'TS.MREVRANGE' => $prefixFirst, 'TS.QUERYINDEX' => $prefixFirst, 'TS.RANGE' => $prefixFirst, 'TS.REVRANGE' => $prefixFirst, ]; } /** * Sets a prefix that is applied to all the keys. * * @param string $prefix Prefix for the keys. */ public function setPrefix($prefix) { $this->prefix = $prefix; } /** * Gets the current prefix. * * @return string */ public function getPrefix() { return $this->prefix; } /** * {@inheritdoc} */ public function process(CommandInterface $command) { if ($command instanceof PrefixableCommandInterface) { $command->prefixKeys($this->prefix); } elseif (isset($this->commands[$commandID = strtoupper($command->getId())])) { $this->commands[$commandID]($command, $this->prefix); } } /** * Sets an handler for the specified command ID. * * The callback signature must have 2 parameters of the following types: * * - Predis\Command\CommandInterface (command instance) * - String (prefix) * * When the callback argument is omitted or NULL, the previously * associated handler for the specified command ID is removed. * * @param string $commandID The ID of the command to be handled. * @param mixed $callback A valid callable object or NULL. * * @throws InvalidArgumentException */ public function setCommandHandler($commandID, $callback = null) { $commandID = strtoupper($commandID); if (!isset($callback)) { unset($this->commands[$commandID]); return; } if (!is_callable($callback)) { throw new InvalidArgumentException( 'Callback must be a valid callable object or NULL' ); } $this->commands[$commandID] = $callback; } /** * {@inheritdoc} */ public function __toString() { return $this->getPrefix(); } /** * Applies the specified prefix only the first argument. * * @param CommandInterface $command Command instance. * @param string $prefix Prefix string. */ public static function first(CommandInterface $command, $prefix) { if ($arguments = $command->getArguments()) { $arguments[0] = "$prefix{$arguments[0]}"; $command->setRawArguments($arguments); } } /** * Applies the specified prefix only to the first two arguments. * * @param CommandInterface $command Command instance. * @param string $prefix Prefix string. */ public static function firstTwo(CommandInterface $command, $prefix) { $arguments = $command->getArguments(); $length = min(count($arguments), 2); for ($i = 0; $i < $length; $i++) { $arguments[$i] = "$prefix{$arguments[$i]}"; } $command->setRawArguments($arguments); } /** * Applies the specified prefix to all the arguments. * * @param CommandInterface $command Command instance. * @param string $prefix Prefix string. */ public static function all(CommandInterface $command, $prefix) { if ($arguments = $command->getArguments()) { foreach ($arguments as &$key) { $key = "$prefix$key"; } $command->setRawArguments($arguments); } } /** * Applies the specified prefix only to even arguments in the list. * * @param CommandInterface $command Command instance. * @param string $prefix Prefix string. */ public static function interleaved(CommandInterface $command, $prefix) { if ($arguments = $command->getArguments()) { $length = count($arguments); for ($i = 0; $i < $length; $i += 2) { $arguments[$i] = "$prefix{$arguments[$i]}"; } $command->setRawArguments($arguments); } } /** * Applies the specified prefix to all the arguments but the first one. * * @param CommandInterface $command Command instance. * @param string $prefix Prefix string. */ public static function skipFirst(CommandInterface $command, $prefix) { if ($arguments = $command->getArguments()) { $length = count($arguments); for ($i = 1; $i < $length; ++$i) { $arguments[$i] = "$prefix{$arguments[$i]}"; } $command->setRawArguments($arguments); } } /** * Applies the specified prefix to all the arguments but the last one. * * @param CommandInterface $command Command instance. * @param string $prefix Prefix string. */ public static function skipLast(CommandInterface $command, $prefix) { if ($arguments = $command->getArguments()) { $length = count($arguments); for ($i = 0; $i < $length - 1; ++$i) { $arguments[$i] = "$prefix{$arguments[$i]}"; } $command->setRawArguments($arguments); } } /** * Applies the specified prefix to the keys of a SORT command. * * @param CommandInterface $command Command instance. * @param string $prefix Prefix string. */ public static function sort(CommandInterface $command, $prefix) { if ($arguments = $command->getArguments()) { $arguments[0] = "$prefix{$arguments[0]}"; if (($count = count($arguments)) > 1) { for ($i = 1; $i < $count; ++$i) { switch (strtoupper($arguments[$i])) { case 'BY': case 'STORE': $arguments[$i] = "$prefix{$arguments[++$i]}"; break; case 'GET': $value = $arguments[++$i]; if ($value !== '#') { $arguments[$i] = "$prefix$value"; } break; case 'LIMIT': $i += 2; break; } } } $command->setRawArguments($arguments); } } /** * Applies the specified prefix to the keys of an EVAL-based command. * * @param CommandInterface $command Command instance. * @param string $prefix Prefix string. */ public static function evalKeys(CommandInterface $command, $prefix) { if ($arguments = $command->getArguments()) { for ($i = 2; $i < $arguments[1] + 2; ++$i) { $arguments[$i] = "$prefix{$arguments[$i]}"; } $command->setRawArguments($arguments); } } /** * Applies the specified prefix to the keys of Z[INTERSECTION|UNION]STORE. * * @param CommandInterface $command Command instance. * @param string $prefix Prefix string. */ public static function zsetStore(CommandInterface $command, $prefix) { if ($arguments = $command->getArguments()) { $arguments[0] = "$prefix{$arguments[0]}"; $length = ((int) $arguments[1]) + 2; for ($i = 2; $i < $length; ++$i) { $arguments[$i] = "$prefix{$arguments[$i]}"; } $command->setRawArguments($arguments); } } /** * Applies the specified prefix to the key of a MIGRATE command. * * @param CommandInterface $command Command instance. * @param string $prefix Prefix string. */ public static function migrate(CommandInterface $command, $prefix) { if ($arguments = $command->getArguments()) { $arguments[2] = "$prefix{$arguments[2]}"; $command->setRawArguments($arguments); } } /** * Applies the specified prefix to the key of a GEORADIUS command. * * @param CommandInterface $command Command instance. * @param string $prefix Prefix string. */ public static function georadius(CommandInterface $command, $prefix) { if ($arguments = $command->getArguments()) { $arguments[0] = "$prefix{$arguments[0]}"; $startIndex = $command->getId() === 'GEORADIUS' ? 5 : 4; if (($count = count($arguments)) > $startIndex) { for ($i = $startIndex; $i < $count; ++$i) { switch (strtoupper($arguments[$i])) { case 'STORE': case 'STOREDIST': $arguments[$i] = "$prefix{$arguments[++$i]}"; break; } } } $command->setRawArguments($arguments); } } } PK\X]7i i /predis/src/Command/Processor/ProcessorChain.phpnu[add($processor); } } /** * {@inheritdoc} */ public function add(ProcessorInterface $processor) { $this->processors[] = $processor; } /** * {@inheritdoc} */ public function remove(ProcessorInterface $processor) { if (false !== $index = array_search($processor, $this->processors, true)) { unset($this[$index]); } } /** * {@inheritdoc} */ public function process(CommandInterface $command) { for ($i = 0; $i < $count = count($this->processors); ++$i) { $this->processors[$i]->process($command); } } /** * {@inheritdoc} */ public function getProcessors() { return $this->processors; } /** * Returns an iterator over the list of command processor in the chain. * * @return Traversable */ public function getIterator() { return new ArrayIterator($this->processors); } /** * Returns the number of command processors in the chain. * * @return int */ public function count() { return count($this->processors); } /** * @param int $index * @return bool */ #[ReturnTypeWillChange] public function offsetExists($index) { return isset($this->processors[$index]); } /** * @param int $index * @return ProcessorInterface */ #[ReturnTypeWillChange] public function offsetGet($index) { return $this->processors[$index]; } /** * @param int $index * @param ProcessorInterface $processor * @return void */ #[ReturnTypeWillChange] public function offsetSet($index, $processor) { if (!$processor instanceof ProcessorInterface) { throw new InvalidArgumentException( 'Processor chain accepts only instances of `Predis\Command\Processor\ProcessorInterface`' ); } $this->processors[$index] = $processor; } /** * @param int $index * @return void */ #[ReturnTypeWillChange] public function offsetUnset($index) { unset($this->processors[$index]); $this->processors = array_values($this->processors); } } PK\X]NcF $predis/src/Command/ScriptCommand.phpnu[getScript()); } /** * Specifies the number of arguments that should be considered as keys. * * The default behaviour for the base class is to return 0 to indicate that * all the elements of the arguments array should be considered as keys, but * subclasses can enforce a static number of keys. * * @return int */ protected function getKeysCount() { return 0; } /** * Returns the elements from the arguments that are identified as keys. * * @return array */ public function getKeys() { return array_slice($this->getArguments(), 2, $this->getKeysCount()); } /** * {@inheritdoc} */ public function setArguments(array $arguments) { if (($numkeys = $this->getKeysCount()) && $numkeys < 0) { $numkeys = count($arguments) + $numkeys; } $arguments = array_merge([$this->getScriptHash(), (int) $numkeys], $arguments); parent::setArguments($arguments); } /** * Returns arguments for EVAL command. * * @return array */ public function getEvalArguments() { $arguments = $this->getArguments(); $arguments[0] = $this->getScript(); return $arguments; } /** * Returns the equivalent EVAL command as a raw command instance. * * @return RawCommand */ public function getEvalCommand() { return new RawCommand('EVAL', $this->getEvalArguments()); } } PK\X]Cz?XX1predis/src/Command/PrefixableCommandInterface.phpnu[getCommandClass($commandID) === null) { return false; } } return true; } /** * Returns the FQCN of a class that represents the specified command ID. * * @codeCoverageIgnore * * @param string $commandID Command ID * * @return string|null */ public function getCommandClass(string $commandID): ?string { return $this->commands[strtoupper($commandID)] ?? null; } /** * {@inheritdoc} */ public function create(string $commandID, array $arguments = []): CommandInterface { if (!$commandClass = $this->getCommandClass($commandID)) { $commandID = strtoupper($commandID); throw new ClientException("Command `$commandID` is not a registered Redis command."); } $command = new $commandClass(); $command->setArguments($arguments); if (isset($this->processor)) { $this->processor->process($command); } return $command; } /** * Defines a command in the factory. * * Only classes implementing Predis\Command\CommandInterface are allowed to * handle a command. If the command specified by its ID is already handled * by the factory, the underlying command class is replaced by the new one. * * @param string $commandID Command ID * @param string $commandClass FQCN of a class implementing Predis\Command\CommandInterface * * @throws InvalidArgumentException */ public function define(string $commandID, string $commandClass): void { if (!is_a($commandClass, 'Predis\Command\CommandInterface', true)) { throw new InvalidArgumentException( "Class $commandClass must implement Predis\Command\CommandInterface" ); } $this->commands[strtoupper($commandID)] = $commandClass; } /** * Undefines a command in the factory. * * When the factory already has a class handler associated to the specified * command ID it is removed from the map of known commands. Nothing happens * when the command is not handled by the factory. * * @param string $commandID Command ID */ public function undefine(string $commandID): void { unset($this->commands[strtoupper($commandID)]); } /** * Sets a command processor for processing command arguments. * * Command processors are used to process and transform arguments of Redis * commands before their newly created instances are returned to the caller * of "create()". * * A NULL value can be used to effectively unset any processor if previously * set for the command factory. * * @param ProcessorInterface|null $processor Command processor or NULL value. */ public function setProcessor(?ProcessorInterface $processor): void { $this->processor = $processor; } /** * Returns the current command processor. * * @return ProcessorInterface|null */ public function getProcessor(): ?ProcessorInterface { return $this->processor; } } PK\X]i  predis/src/Command/Command.phpnu[arguments = $arguments; unset($this->slot); } /** * {@inheritdoc} */ public function setRawArguments(array $arguments) { $this->arguments = $arguments; unset($this->slot); } /** * {@inheritdoc} */ public function getArguments() { return $this->arguments; } /** * {@inheritdoc} */ public function getArgument($index) { if (isset($this->arguments[$index])) { return $this->arguments[$index]; } } /** * {@inheritdoc} */ public function setSlot($slot) { $this->slot = $slot; } /** * {@inheritdoc} */ public function getSlot() { return $this->slot ?? null; } /** * {@inheritdoc} */ public function parseResponse($data) { return $data; } /** * Normalizes the arguments array passed to a Redis command. * * @param array $arguments Arguments for a command. * * @return array */ public static function normalizeArguments(array $arguments) { if (count($arguments) === 1 && isset($arguments[0]) && is_array($arguments[0])) { return $arguments[0]; } return $arguments; } /** * Normalizes the arguments array passed to a variadic Redis command. * * @param array $arguments Arguments for a command. * * @return array */ public static function normalizeVariadic(array $arguments) { if (count($arguments) === 2 && is_array($arguments[1])) { return array_merge([$arguments[0]], $arguments[1]); } return $arguments; } /** * Remove all false values from arguments. * * @return void */ public function filterArguments(): void { $this->arguments = array_filter($this->arguments, static function ($argument) { return $argument !== false && $argument !== null; }); } } PK\X]ٞ))'predis/src/Command/CommandInterface.phpnu[commandID = strtoupper($commandID); $this->setArguments($arguments); } /** * Creates a new raw command using a variadic method. * * @param string $commandID Redis command ID * @param string ...$args Arguments list for the command * * @return CommandInterface */ public static function create($commandID, ...$args) { $arguments = func_get_args(); return new static(array_shift($arguments), $arguments); } /** * {@inheritdoc} */ public function getId() { return $this->commandID; } /** * {@inheritdoc} */ public function setArguments(array $arguments) { $this->arguments = $arguments; unset($this->slot); } /** * {@inheritdoc} */ public function setRawArguments(array $arguments) { $this->setArguments($arguments); } /** * {@inheritdoc} */ public function getArguments() { return $this->arguments; } /** * {@inheritdoc} */ public function getArgument($index) { if (isset($this->arguments[$index])) { return $this->arguments[$index]; } } /** * {@inheritdoc} */ public function setSlot($slot) { $this->slot = $slot; } /** * {@inheritdoc} */ public function getSlot() { return $this->slot ?? null; } /** * {@inheritdoc} */ public function parseResponse($data) { return $data; } } PK\X])@ @ #predis/src/Command/RedisFactory.phpnu[commands = [ 'ECHO' => 'Predis\Command\Redis\ECHO_', 'EVAL' => 'Predis\Command\Redis\EVAL_', 'OBJECT' => 'Predis\Command\Redis\OBJECT_', // Class name corresponds to PHP reserved word "function", added mapping to bypass restrictions 'FUNCTION' => FUNCTIONS::class, ]; } /** * {@inheritdoc} */ public function getCommandClass(string $commandID): ?string { $commandID = strtoupper($commandID); if (isset($this->commands[$commandID]) || array_key_exists($commandID, $this->commands)) { return $this->commands[$commandID]; } $commandClass = $this->resolve($commandID); if (null === $commandClass) { return null; } $this->commands[$commandID] = $commandClass; return $commandClass; } /** * {@inheritdoc} */ public function undefine(string $commandID): void { // NOTE: we explicitly associate `NULL` to the command ID in the map // instead of the parent's `unset()` because our subclass tries to load // a predefined class from the Predis\Command\Redis namespace when no // explicit mapping is defined, see RedisFactory::getCommandClass() for // details of the implementation of this mechanism. $this->commands[strtoupper($commandID)] = null; } /** * Resolves command object from given command ID. * * @param string $commandID Command ID of virtual method call * @return string|null FQDN of corresponding command object */ private function resolve(string $commandID): ?string { if (class_exists($commandClass = self::COMMANDS_NAMESPACE . '\\' . $commandID)) { return $commandClass; } $commandModule = $this->resolveCommandModuleByPrefix($commandID); if (null === $commandModule) { return null; } if (class_exists($commandClass = self::COMMANDS_NAMESPACE . '\\' . $commandModule . '\\' . $commandID)) { return $commandClass; } return null; } private function resolveCommandModuleByPrefix(string $commandID): ?string { foreach (ClientConfiguration::getModules() as $module) { if (preg_match("/^{$module['commandPrefix']}/", $commandID)) { return $module['name']; } } return null; } } PK\X]3 getHashGeneratorByDescription($options, $value); } elseif ($value instanceof Hash\HashGeneratorInterface) { return $value; } else { $class = get_class($this); throw new InvalidArgumentException("$class expects a valid hash generator"); } } /** * {@inheritdoc} */ public function getDefault(OptionsInterface $options) { return function_exists('phpiredis_utils_crc16') ? new Hash\PhpiredisCRC16() : new Hash\CRC16(); } } PK\X]j8q,R R +predis/src/Configuration/Option/Cluster.phpnu[getConnectionInitializerByString($options, $value); } if (is_callable($value)) { return $this->getConnectionInitializer($options, $value); } else { throw new InvalidArgumentException(sprintf( '%s expects either a string or a callable value, %s given', static::class, is_object($value) ? get_class($value) : gettype($value) )); } } /** * Returns a connection initializer from a descriptive name. * * @param OptionsInterface $options Client options * @param string $description Identifier of a replication backend (`predis`, `sentinel`) * * @return callable */ protected function getConnectionInitializerByString(OptionsInterface $options, string $description) { switch ($description) { case 'redis': case 'redis-cluster': return function ($parameters, $options, $option) { return new RedisCluster($options->connections, new RedisStrategy($options->crc16)); }; case 'predis': return $this->getDefaultConnectionInitializer(); default: throw new InvalidArgumentException(sprintf( '%s expects either `predis`, `redis` or `redis-cluster` as valid string values, `%s` given', static::class, $description )); } } /** * Returns the default connection initializer. * * @return callable */ protected function getDefaultConnectionInitializer() { return function ($parameters, $options, $option) { return new PredisCluster(); }; } /** * {@inheritdoc} */ public function getDefault(OptionsInterface $options) { return $this->getConnectionInitializer( $options, $this->getDefaultConnectionInitializer() ); } } PK\X] gxx*predis/src/Configuration/Option/Prefix.phpnu[createFactoryByArray($options, $value); } elseif (is_string($value)) { return $this->createFactoryByString($options, $value); } else { throw new InvalidArgumentException(sprintf( '%s expects a valid command factory', static::class )); } } /** * Creates a new default command factory from a named array. * * The factory instance is configured according to the supplied named array * mapping command IDs (passed as keys) to the FCQN of classes implementing * Predis\Command\CommandInterface. * * @param OptionsInterface $options Client options container * @param array $value Named array mapping command IDs to classes * * @return FactoryInterface */ protected function createFactoryByArray(OptionsInterface $options, array $value) { /** * @var FactoryInterface */ $commands = $this->getDefault($options); foreach ($value as $commandID => $commandClass) { if ($commandClass === null) { $commands->undefine($commandID); } else { $commands->define($commandID, $commandClass); } } return $commands; } /** * Creates a new command factory from a descriptive string. * * The factory instance is configured according to the supplied descriptive * string that identifies specific configurations of schemes and connection * classes. Supported configuration values are: * * - "predis" returns the default command factory used by Predis * - "raw" returns a command factory that creates only raw commands * - "default" is simply an alias of "predis" * * @param OptionsInterface $options Client options container * @param string $value Descriptive string identifying the desired configuration * * @return FactoryInterface */ protected function createFactoryByString(OptionsInterface $options, string $value) { switch (strtolower($value)) { case 'default': case 'predis': return $this->getDefault($options); case 'raw': return $this->createRawFactory($options); default: throw new InvalidArgumentException(sprintf( '%s does not recognize `%s` as a supported configuration string', static::class, $value )); } } /** * Creates a new raw command factory instance. * * @param OptionsInterface $options Client options container */ protected function createRawFactory(OptionsInterface $options): FactoryInterface { $commands = new RawFactory(); if (isset($options->prefix)) { throw new InvalidArgumentException(sprintf( '%s does not support key prefixing', RawFactory::class )); } return $commands; } /** * {@inheritdoc} */ public function getDefault(OptionsInterface $options) { $commands = new RedisFactory(); if (isset($options->prefix)) { $commands->setProcessor($options->prefix); } return $commands; } } PK\X]tō/predis/src/Configuration/Option/Connections.phpnu[createFactoryByArray($options, $value); } elseif (is_string($value)) { return $this->createFactoryByString($options, $value); } else { throw new InvalidArgumentException(sprintf( '%s expects a valid connection factory', static::class )); } } /** * Creates a new connection factory from a named array. * * The factory instance is configured according to the supplied named array * mapping URI schemes (passed as keys) to the FCQN of classes implementing * Predis\Connection\NodeConnectionInterface, or callable objects acting as * lazy initializers and returning new instances of classes implementing * Predis\Connection\NodeConnectionInterface. * * @param OptionsInterface $options Client options * @param array $value Named array mapping URI schemes to classes or callables * * @return FactoryInterface */ protected function createFactoryByArray(OptionsInterface $options, array $value) { /** * @var FactoryInterface */ $factory = $this->getDefault($options); foreach ($value as $scheme => $initializer) { $factory->define($scheme, $initializer); } return $factory; } /** * Creates a new connection factory from a descriptive string. * * The factory instance is configured according to the supplied descriptive * string that identifies specific configurations of schemes and connection * classes. Supported configuration values are: * * - "phpiredis-stream" maps tcp, redis, unix to PhpiredisStreamConnection * - "phpiredis-socket" maps tcp, redis, unix to PhpiredisSocketConnection * - "phpiredis" is an alias of "phpiredis-stream" * - "relay" maps tcp, redis, unix, tls, rediss to RelayConnection * * @param OptionsInterface $options Client options * @param string $value Descriptive string identifying the desired configuration * * @return FactoryInterface */ protected function createFactoryByString(OptionsInterface $options, string $value) { /** * @var FactoryInterface */ $factory = $this->getDefault($options); switch (strtolower($value)) { case 'phpiredis': case 'phpiredis-stream': $factory->define('tcp', PhpiredisStreamConnection::class); $factory->define('redis', PhpiredisStreamConnection::class); $factory->define('unix', PhpiredisStreamConnection::class); break; case 'phpiredis-socket': $factory->define('tcp', PhpiredisSocketConnection::class); $factory->define('redis', PhpiredisSocketConnection::class); $factory->define('unix', PhpiredisSocketConnection::class); break; case 'relay': $factory->define('tcp', RelayConnection::class); $factory->define('redis', RelayConnection::class); $factory->define('unix', RelayConnection::class); break; case 'default': return $factory; default: throw new InvalidArgumentException(sprintf( '%s does not recognize `%s` as a supported configuration string', static::class, $value )); } return $factory; } /** * {@inheritdoc} */ public function getDefault(OptionsInterface $options) { $factory = new Factory(); if ($options->defined('parameters')) { $factory->setDefaultParameters($options->parameters); } return $factory; } } PK\X]C ^^/predis/src/Configuration/Option/Replication.phpnu[getConnectionInitializerByString($options, $value); } if (is_callable($value)) { return $this->getConnectionInitializer($options, $value); } else { throw new InvalidArgumentException(sprintf( '%s expects either a string or a callable value, %s given', static::class, is_object($value) ? get_class($value) : gettype($value) )); } } /** * Returns a connection initializer (callable) from a descriptive string. * * Each connection initializer is specialized for the specified replication * backend so that all the necessary steps for the configuration of the new * aggregate connection are performed inside the initializer and the client * receives a ready-to-use connection. * * Supported configuration values are: * * - `predis` for unmanaged replication setups * - `redis-sentinel` for replication setups managed by redis-sentinel * - `sentinel` is an alias of `redis-sentinel` * * @param OptionsInterface $options Client options * @param string $description Identifier of a replication backend * * @return callable */ protected function getConnectionInitializerByString(OptionsInterface $options, string $description) { switch ($description) { case 'sentinel': case 'redis-sentinel': return function ($parameters, $options) { return new SentinelReplication($options->service, $parameters, $options->connections); }; case 'predis': return $this->getDefaultConnectionInitializer(); default: throw new InvalidArgumentException(sprintf( '%s expects either `predis`, `sentinel` or `redis-sentinel` as valid string values, `%s` given', static::class, $description )); } } /** * Returns the default connection initializer. * * @return callable */ protected function getDefaultConnectionInitializer() { return function ($parameters, $options) { $connection = new MasterSlaveReplication(); if ($options->autodiscovery) { $connection->setConnectionFactory($options->connections); $connection->setAutoDiscovery(true); } return $connection; }; } /** * {@inheritdoc} */ public static function aggregate(OptionsInterface $options, AggregateConnectionInterface $connection, array $nodes) { if (!$connection instanceof SentinelReplication) { parent::aggregate($options, $connection, $nodes); } } /** * {@inheritdoc} */ public function getDefault(OptionsInterface $options) { return $this->getConnectionInitializer( $options, $this->getDefaultConnectionInitializer() ); } } PK\X]3G-predis/src/Configuration/Option/Aggregate.phpnu[getConnectionInitializer($options, $value); } /** * Wraps a user-supplied callable used to create a new aggregate connection. * * When the original callable acting as a connection initializer is executed * by the client to create a new aggregate connection, it will receive the * following arguments: * * - $parameters (same as passed to Predis\Client::__construct()) * - $options (options container, Predis\Configuration\OptionsInterface) * - $option (current option, Predis\Configuration\OptionInterface) * * The original callable must return a valid aggregation connection instance * of type Predis\Connection\AggregateConnectionInterface, this is enforced * by the wrapper returned by this method and an exception is thrown when * invalid values are returned. * * @param OptionsInterface $options Client options * @param callable $callable Callable initializer * * @return callable * @throws InvalidArgumentException */ protected function getConnectionInitializer(OptionsInterface $options, callable $callable) { return function ($parameters = null, $autoaggregate = false) use ($callable, $options) { $connection = call_user_func_array($callable, [&$parameters, $options, $this]); if (!$connection instanceof AggregateConnectionInterface) { throw new InvalidArgumentException(sprintf( '%s expects the supplied callable to return an instance of %s, but %s was returned', static::class, AggregateConnectionInterface::class, is_object($connection) ? get_class($connection) : gettype($connection) )); } if ($parameters && $autoaggregate) { static::aggregate($options, $connection, $parameters); } return $connection; }; } /** * Adds single connections to an aggregate connection instance. * * @param OptionsInterface $options Client options * @param AggregateConnectionInterface $connection Target aggregate connection * @param array $nodes List of nodes to be added to the target aggregate connection */ public static function aggregate(OptionsInterface $options, AggregateConnectionInterface $connection, array $nodes) { $connections = $options->connections; foreach ($nodes as $node) { $connection->add($node instanceof NodeConnectionInterface ? $node : $connections->create($node)); } } /** * {@inheritdoc} */ public function getDefault(OptionsInterface $options) { return; } } PK\X]>+.predis/src/Configuration/Option/Exceptions.phpnu[ Option\Aggregate::class, 'cluster' => Option\Cluster::class, 'replication' => Option\Replication::class, 'connections' => Option\Connections::class, 'commands' => Option\Commands::class, 'exceptions' => Option\Exceptions::class, 'prefix' => Option\Prefix::class, 'crc16' => Option\CRC16::class, ]; /** @var array */ protected $options = []; /** @var array */ protected $input; /** * @param array|null $options Named array of client options */ public function __construct(?array $options = null) { $this->input = $options ?? []; } /** * {@inheritdoc} */ public function getDefault($option) { if (isset($this->handlers[$option])) { $handler = $this->handlers[$option]; $handler = new $handler(); return $handler->getDefault($this); } } /** * {@inheritdoc} */ public function defined($option) { return array_key_exists($option, $this->options) || array_key_exists($option, $this->input) ; } /** * {@inheritdoc} */ public function __isset($option) { return ( array_key_exists($option, $this->options) || array_key_exists($option, $this->input) ) && $this->__get($option) !== null; } /** * {@inheritdoc} */ public function __get($option) { if (isset($this->options[$option]) || array_key_exists($option, $this->options)) { return $this->options[$option]; } if (isset($this->input[$option]) || array_key_exists($option, $this->input)) { $value = $this->input[$option]; unset($this->input[$option]); if (isset($this->handlers[$option])) { $handler = $this->handlers[$option]; $handler = new $handler(); $value = $handler->filter($this, $value); } elseif (is_object($value) && method_exists($value, '__invoke')) { $value = $value($this); } return $this->options[$option] = $value; } if (isset($this->handlers[$option])) { return $this->options[$option] = $this->getDefault($option); } return; } } PK\X]S*predis/src/Response/Iterator/MultiBulk.phpnu[connection = $connection; $this->size = $size; $this->position = 0; $this->current = $size > 0 ? $this->getValue() : null; } /** * Handles the synchronization of the client with the Redis protocol when * the garbage collector kicks in (e.g. when the iterator goes out of the * scope of a foreach or it is unset). */ public function __destruct() { $this->drop(true); } /** * Drop queued elements that have not been read from the connection either * by consuming the rest of the multibulk response or quickly by closing the * underlying connection. * * @param bool $disconnect Consume the iterator or drop the connection. */ public function drop($disconnect = false) { if ($disconnect) { if ($this->valid()) { $this->position = $this->size; $this->connection->disconnect(); } } else { while ($this->valid()) { $this->next(); } } } /** * Reads the next item of the multibulk response from the connection. * * @return mixed */ protected function getValue() { return $this->connection->read(); } } PK\X]u /predis/src/Response/Iterator/MultiBulkTuple.phpnu[ $value pairs. */ class MultiBulkTuple extends MultiBulk implements OuterIterator { private $iterator; /** * @param MultiBulk $iterator Inner multibulk response iterator. */ public function __construct(MultiBulk $iterator) { $this->checkPreconditions($iterator); $this->size = count($iterator) / 2; $this->iterator = $iterator; $this->position = $iterator->getPosition(); $this->current = $this->size > 0 ? $this->getValue() : null; } /** * Checks for valid preconditions. * * @param MultiBulk $iterator Inner multibulk response iterator. * * @throws InvalidArgumentException * @throws UnexpectedValueException */ protected function checkPreconditions(MultiBulk $iterator) { if ($iterator->getPosition() !== 0) { throw new InvalidArgumentException( 'Cannot initialize a tuple iterator using an already initiated iterator.' ); } if (($size = count($iterator)) % 2 !== 0) { throw new UnexpectedValueException('Invalid response size for a tuple iterator.'); } } /** * @return MultiBulk */ #[ReturnTypeWillChange] public function getInnerIterator() { return $this->iterator; } /** * {@inheritdoc} */ public function __destruct() { $this->iterator->drop(true); } /** * {@inheritdoc} */ protected function getValue() { $k = $this->iterator->current(); $this->iterator->next(); $v = $this->iterator->current(); $this->iterator->next(); return [$k, $v]; } } PK\X]ތb 2predis/src/Response/Iterator/MultiBulkIterator.phpnu[current; } /** * @return int|null */ #[ReturnTypeWillChange] public function key() { return $this->position; } /** * @return void */ #[ReturnTypeWillChange] public function next() { if (++$this->position < $this->size) { $this->current = $this->getValue(); } } /** * @return bool */ #[ReturnTypeWillChange] public function valid() { return $this->position < $this->size; } /** * Returns the number of items comprising the whole multibulk response. * * This method should be used instead of iterator_count() to get the size of * the current multibulk response since the former consumes the iteration to * count the number of elements, but our iterators do not support rewinding. * * @return int */ #[ReturnTypeWillChange] public function count() { return $this->size; } /** * Returns the current position of the iterator. * * @return int */ public function getPosition() { return $this->position; } /** * {@inheritdoc} */ abstract protected function getValue(); } PK\X]򯁃'predis/src/Response/ServerException.phpnu[getMessage(), 2); return $errorType; } /** * Converts the exception to an instance of Predis\Response\Error. * * @return Error */ public function toErrorResponse() { return new Error($this->getMessage()); } } PK\X]@֟yy)predis/src/Response/ResponseInterface.phpnu[payload = $payload; } /** * Converts the response object to its string representation. * * @return string */ public function __toString() { return $this->payload; } /** * Returns the payload of status response. * * @return string */ public function getPayload() { return $this->payload; } /** * Returns an instance of a status response object. * * Common status responses such as OK or QUEUED are cached in order to lower * the global memory usage especially when using pipelines. * * @param string $payload Status response payload. * * @return self */ public static function get($payload) { switch ($payload) { case 'OK': case 'QUEUED': if (isset(self::$$payload)) { return self::$$payload; } return self::$$payload = new self($payload); default: return new self($payload); } } } PK\X]SSpredis/src/Response/Error.phpnu[message = $message; } /** * {@inheritdoc} */ public function getMessage() { return $this->message; } /** * {@inheritdoc} */ public function getErrorType() { [$errorType] = explode(' ', $this->getMessage(), 2); return $errorType; } /** * Converts the object to its string representation. * * @return string */ public function __toString() { return $this->getMessage(); } } PK\X]|B&predis/src/Response/ErrorInterface.phpnu[client = $client; if (isset($options['gc_maxlifetime'])) { $this->ttl = (int) $options['gc_maxlifetime']; } else { $this->ttl = ini_get('session.gc_maxlifetime'); } } /** * Registers this instance as the current session handler. */ public function register() { session_set_save_handler($this, true); } /** * @param string $save_path * @param string $session_id * @return bool */ #[ReturnTypeWillChange] public function open($save_path, $session_id) { // NOOP return true; } /** * @return bool */ #[ReturnTypeWillChange] public function close() { // NOOP return true; } /** * @param int $maxlifetime * @return bool */ #[ReturnTypeWillChange] public function gc($maxlifetime) { // NOOP return true; } /** * @param string $session_id * @return string */ #[ReturnTypeWillChange] public function read($session_id) { if ($data = $this->client->get($session_id)) { return $data; } return ''; } /** * @param string $session_id * @param string $session_data * @return bool */ #[ReturnTypeWillChange] public function write($session_id, $session_data) { $this->client->setex($session_id, $this->ttl, $session_data); return true; } /** * @param string $session_id * @return bool */ #[ReturnTypeWillChange] public function destroy($session_id) { $this->client->del($session_id); return true; } /** * Returns the underlying client instance. * * @return ClientInterface */ public function getClient() { return $this->client; } /** * Returns the session max lifetime value. * * @return int */ public function getMaxLifeTime() { return $this->ttl; } } PK\X]LG(predis/src/Replication/RoleException.phpnu[disallowed = $this->getDisallowedOperations(); $this->readonly = $this->getReadOnlyOperations(); $this->readonlySHA1 = []; } /** * Returns if the specified command will perform a read-only operation * on Redis or not. * * @param CommandInterface $command Command instance. * * @return bool * @throws NotSupportedException */ public function isReadOperation(CommandInterface $command) { if (!$this->loadBalancing) { return false; } if (isset($this->disallowed[$id = $command->getId()])) { throw new NotSupportedException( "The command '$id' is not allowed in replication mode." ); } if (isset($this->readonly[$id])) { if (true === $readonly = $this->readonly[$id]) { return true; } return call_user_func($readonly, $command); } if (($eval = $id === 'EVAL') || $id === 'EVALSHA') { $argument = $command->getArgument(0); $sha1 = $eval ? sha1(strval($argument)) : $argument; if (isset($this->readonlySHA1[$sha1])) { if (true === $readonly = $this->readonlySHA1[$sha1]) { return true; } return call_user_func($readonly, $command); } } return false; } /** * Returns if the specified command is not allowed for execution in a master * / slave replication context. * * @param CommandInterface $command Command instance. * * @return bool */ public function isDisallowedOperation(CommandInterface $command) { return isset($this->disallowed[$command->getId()]); } /** * Checks if BITFIELD performs a read-only operation by looking for certain * SET and INCRYBY modifiers in the arguments array of the command. * * @param CommandInterface $command Command instance. * * @return bool */ protected function isBitfieldReadOnly(CommandInterface $command) { $arguments = $command->getArguments(); $argc = count($arguments); if ($argc >= 2) { for ($i = 1; $i < $argc; ++$i) { $argument = strtoupper($arguments[$i]); if ($argument === 'SET' || $argument === 'INCRBY') { return false; } } } return true; } /** * Checks if a GEORADIUS command is a readable operation by parsing the * arguments array of the specified command instance. * * @param CommandInterface $command Command instance. * * @return bool */ protected function isGeoradiusReadOnly(CommandInterface $command) { $arguments = $command->getArguments(); $argc = count($arguments); $startIndex = $command->getId() === 'GEORADIUS' ? 5 : 4; if ($argc > $startIndex) { for ($i = $startIndex; $i < $argc; ++$i) { $argument = strtoupper($arguments[$i]); if ($argument === 'STORE' || $argument === 'STOREDIST') { return false; } } } return true; } /** * Marks a command as a read-only operation. * * When the behavior of a command can be decided only at runtime depending * on its arguments, a callable object can be provided to dynamically check * if the specified command performs a read or a write operation. * * @param string $commandID Command ID. * @param mixed $readonly A boolean value or a callable object. */ public function setCommandReadOnly($commandID, $readonly = true) { $commandID = strtoupper($commandID); if ($readonly) { $this->readonly[$commandID] = $readonly; } else { unset($this->readonly[$commandID]); } } /** * Marks a Lua script for EVAL and EVALSHA as a read-only operation. When * the behaviour of a script can be decided only at runtime depending on * its arguments, a callable object can be provided to dynamically check * if the passed instance of EVAL or EVALSHA performs write operations or * not. * * @param string $script Body of the Lua script. * @param mixed $readonly A boolean value or a callable object. */ public function setScriptReadOnly($script, $readonly = true) { $sha1 = sha1($script); if ($readonly) { $this->readonlySHA1[$sha1] = $readonly; } else { unset($this->readonlySHA1[$sha1]); } } /** * Returns the default list of disallowed commands. * * @return array */ protected function getDisallowedOperations() { return [ 'SHUTDOWN' => true, 'INFO' => true, 'DBSIZE' => true, 'LASTSAVE' => true, 'CONFIG' => true, 'MONITOR' => true, 'SLAVEOF' => true, 'SAVE' => true, 'BGSAVE' => true, 'BGREWRITEAOF' => true, 'SLOWLOG' => true, ]; } /** * Returns the default list of commands performing read-only operations. * * @return array */ protected function getReadOnlyOperations() { return [ 'EXISTS' => true, 'TYPE' => true, 'KEYS' => true, 'SCAN' => true, 'RANDOMKEY' => true, 'TTL' => true, 'GET' => true, 'MGET' => true, 'SUBSTR' => true, 'STRLEN' => true, 'GETRANGE' => true, 'GETBIT' => true, 'LLEN' => true, 'LRANGE' => true, 'LINDEX' => true, 'SCARD' => true, 'SISMEMBER' => true, 'SINTER' => true, 'SUNION' => true, 'SDIFF' => true, 'SMEMBERS' => true, 'SSCAN' => true, 'SRANDMEMBER' => true, 'ZRANGE' => true, 'ZREVRANGE' => true, 'ZRANGEBYSCORE' => true, 'ZREVRANGEBYSCORE' => true, 'ZCARD' => true, 'ZSCORE' => true, 'ZCOUNT' => true, 'ZRANK' => true, 'ZREVRANK' => true, 'ZSCAN' => true, 'ZLEXCOUNT' => true, 'ZRANGEBYLEX' => true, 'ZREVRANGEBYLEX' => true, 'HGET' => true, 'HMGET' => true, 'HEXISTS' => true, 'HLEN' => true, 'HKEYS' => true, 'HVALS' => true, 'HGETALL' => true, 'HSCAN' => true, 'HSTRLEN' => true, 'PING' => true, 'AUTH' => true, 'SELECT' => true, 'ECHO' => true, 'QUIT' => true, 'OBJECT' => true, 'BITCOUNT' => true, 'BITPOS' => true, 'TIME' => true, 'PFCOUNT' => true, 'BITFIELD' => [$this, 'isBitfieldReadOnly'], 'GEOHASH' => true, 'GEOPOS' => true, 'GEODIST' => true, 'GEORADIUS' => [$this, 'isGeoradiusReadOnly'], 'GEORADIUSBYMEMBER' => [$this, 'isGeoradiusReadOnly'], ]; } /** * Disables reads to slaves when using * a replication topology. * * @return self */ public function disableLoadBalancing(): self { $this->loadBalancing = false; return $this; } } PK\X]$1predis/src/Replication/MissingMasterException.phpnu[getParameters()}]" )); } if ($length === -1) { return; } $list = []; if ($length > 0) { $handlersCache = []; $reader = $connection->getProtocol()->getResponseReader(); for ($i = 0; $i < $length; ++$i) { $header = $connection->readLine(); $prefix = $header[0]; if (isset($handlersCache[$prefix])) { $handler = $handlersCache[$prefix]; } else { $handler = $reader->getHandler($prefix); $handlersCache[$prefix] = $handler; } $list[$i] = $handler->handle($connection, substr($header, 1)); } } return $list; } } PK\X]C4predis/src/Protocol/Text/Handler/IntegerResponse.phpnu[getParameters()}]" )); } return; } } PK\X] 5/@predis/src/Protocol/Text/Handler/StreamableMultiBulkResponse.phpnu[getParameters()}]" )); } return new MultiBulkIterator($connection, $length); } } PK\X]^~1predis/src/Protocol/Text/Handler/BulkResponse.phpnu[getParameters()}]" )); } if ($length >= 0) { return substr($connection->readBuffer($length + 2), 0, -2); } if ($length == -1) { return; } CommunicationException::handle(new ProtocolException( $connection, "Value '$payload' is not a valid length for a bulk response [{$connection->getParameters()}]" )); return; } } PK\X]iXX=predis/src/Protocol/Text/Handler/ResponseHandlerInterface.phpnu[handlers = $this->getDefaultHandlers(); } /** * Returns the default handlers for the supported type of responses. * * @return array */ protected function getDefaultHandlers() { return [ '+' => new Handler\StatusResponse(), '-' => new Handler\ErrorResponse(), ':' => new Handler\IntegerResponse(), '$' => new Handler\BulkResponse(), '*' => new Handler\MultiBulkResponse(), ]; } /** * Sets the handler for the specified prefix identifying the response type. * * @param string $prefix Identifier of the type of response. * @param Handler\ResponseHandlerInterface $handler Response handler. */ public function setHandler($prefix, Handler\ResponseHandlerInterface $handler) { $this->handlers[$prefix] = $handler; } /** * Returns the response handler associated to a certain type of response. * * @param string $prefix Identifier of the type of response. * * @return Handler\ResponseHandlerInterface */ public function getHandler($prefix) { if (isset($this->handlers[$prefix])) { return $this->handlers[$prefix]; } return; } /** * {@inheritdoc} */ public function read(CompositeConnectionInterface $connection) { $header = $connection->readLine(); if ($header === '') { $this->onProtocolError($connection, 'Unexpected empty response header'); } $prefix = $header[0]; if (!isset($this->handlers[$prefix])) { $this->onProtocolError($connection, "Unknown response prefix: '$prefix'"); } return $this->handlers[$prefix]->handle($connection, substr($header, 1)); } /** * Handles protocol errors generated while reading responses from a * connection. * * @param CompositeConnectionInterface $connection Redis connection that generated the error. * @param string $message Error message. */ protected function onProtocolError(CompositeConnectionInterface $connection, $message) { CommunicationException::handle( new ProtocolException($connection, "$message [{$connection->getParameters()}]") ); } } PK\X] 00.predis/src/Protocol/Text/RequestSerializer.phpnu[getId(); $arguments = $command->getArguments(); $cmdlen = strlen($commandID); $reqlen = count($arguments) + 1; $buffer = "*{$reqlen}\r\n\${$cmdlen}\r\n{$commandID}\r\n"; foreach ($arguments as $argument) { $arglen = strlen($argument); $buffer .= "\${$arglen}\r\n{$argument}\r\n"; } return $buffer; } } PK\X] 7predis/src/Protocol/Text/CompositeProtocolProcessor.phpnu[setRequestSerializer($serializer ?: new RequestSerializer()); $this->setResponseReader($reader ?: new ResponseReader()); } /** * {@inheritdoc} */ public function write(CompositeConnectionInterface $connection, CommandInterface $command) { $connection->writeBuffer($this->serializer->serialize($command)); } /** * {@inheritdoc} */ public function read(CompositeConnectionInterface $connection) { return $this->reader->read($connection); } /** * Sets the request serializer used by the protocol processor. * * @param RequestSerializerInterface $serializer Request serializer. */ public function setRequestSerializer(RequestSerializerInterface $serializer) { $this->serializer = $serializer; } /** * Returns the request serializer used by the protocol processor. * * @return RequestSerializerInterface */ public function getRequestSerializer() { return $this->serializer; } /** * Sets the response reader used by the protocol processor. * * @param ResponseReaderInterface $reader Response reader. */ public function setResponseReader(ResponseReaderInterface $reader) { $this->reader = $reader; } /** * Returns the Response reader used by the protocol processor. * * @return ResponseReaderInterface */ public function getResponseReader() { return $this->reader; } } PK\X]Ml .predis/src/Protocol/Text/ProtocolProcessor.phpnu[mbiterable = false; $this->serializer = new RequestSerializer(); } /** * {@inheritdoc} */ public function write(CompositeConnectionInterface $connection, CommandInterface $command) { $request = $this->serializer->serialize($command); $connection->writeBuffer($request); } /** * {@inheritdoc} */ public function read(CompositeConnectionInterface $connection) { $chunk = $connection->readLine(); $prefix = $chunk[0]; $payload = substr($chunk, 1); switch ($prefix) { case '+': return new StatusResponse($payload); case '$': $size = (int) $payload; if ($size === -1) { return; } return substr($connection->readBuffer($size + 2), 0, -2); case '*': $count = (int) $payload; if ($count === -1) { return; } if ($this->mbiterable) { return new MultiBulkIterator($connection, $count); } $multibulk = []; for ($i = 0; $i < $count; ++$i) { $multibulk[$i] = $this->read($connection); } return $multibulk; case ':': $integer = (int) $payload; return $integer == $payload ? $integer : $payload; case '-': return new ErrorResponse($payload); default: CommunicationException::handle(new ProtocolException( $connection, "Unknown response prefix: '$prefix' [{$connection->getParameters()}]" )); return; } } /** * Enables or disables returning multibulk responses as specialized PHP * iterators used to stream bulk elements of a multibulk response instead * returning a plain array. * * Streamable multibulk responses are not globally supported by the * abstractions built-in into Predis, such as transactions or pipelines. * Use them with care! * * @param bool $value Enable or disable streamable multibulk responses. */ public function useIterableMultibulk($value) { $this->mbiterable = (bool) $value; } } PK\X]lrr2predis/src/Protocol/RequestSerializerInterface.phpnu[getCommandFactory()->supports('multi', 'exec', 'discard')) { throw new ClientException( "'MULTI', 'EXEC' and 'DISCARD' are not supported by the current command factory." ); } parent::__construct($client); } /** * {@inheritdoc} */ protected function getConnection() { $connection = $this->getClient()->getConnection(); if (!$connection instanceof NodeConnectionInterface) { $class = __CLASS__; throw new ClientException("The class '$class' does not support aggregate connections."); } return $connection; } /** * {@inheritdoc} */ protected function executePipeline(ConnectionInterface $connection, SplQueue $commands) { $commandFactory = $this->getClient()->getCommandFactory(); $connection->executeCommand($commandFactory->create('multi')); foreach ($commands as $command) { $connection->writeRequest($command); } foreach ($commands as $command) { $response = $connection->readResponse($command); if ($response instanceof ErrorResponseInterface) { $connection->executeCommand($commandFactory->create('discard')); throw new ServerException($response->getMessage()); } } $executed = $connection->executeCommand($commandFactory->create('exec')); if (!isset($executed)) { throw new ClientException( 'The underlying transaction has been aborted by the server.' ); } if (count($executed) !== count($commands)) { $expected = count($commands); $received = count($executed); throw new ClientException( "Invalid number of responses [expected $expected, received $received]." ); } $responses = []; $sizeOfPipe = count($commands); $exceptions = $this->throwServerExceptions(); for ($i = 0; $i < $sizeOfPipe; ++$i) { $command = $commands->dequeue(); $response = $executed[$i]; if (!$response instanceof ResponseInterface) { $responses[] = $command->parseResponse($response); } elseif ($response instanceof ErrorResponseInterface && $exceptions) { $this->exception($connection, $response); } else { $responses[] = $response; } unset($executed[$i]); } return $responses; } } PK\X]i predis/src/Pipeline/Pipeline.phpnu[client = $client; $this->pipeline = new SplQueue(); } /** * Queues a command into the pipeline buffer. * * @param string $method Command ID. * @param array $arguments Arguments for the command. * * @return $this */ public function __call($method, $arguments) { $command = $this->client->createCommand($method, $arguments); $this->recordCommand($command); return $this; } /** * Queues a command instance into the pipeline buffer. * * @param CommandInterface $command Command to be queued in the buffer. */ protected function recordCommand(CommandInterface $command) { $this->pipeline->enqueue($command); } /** * Queues a command instance into the pipeline buffer. * * @param CommandInterface $command Command instance to be queued in the buffer. * * @return $this */ public function executeCommand(CommandInterface $command) { $this->recordCommand($command); return $this; } /** * Throws an exception on -ERR responses returned by Redis. * * @param ConnectionInterface $connection Redis connection that returned the error. * @param ErrorResponseInterface $response Instance of the error response. * * @throws ServerException */ protected function exception(ConnectionInterface $connection, ErrorResponseInterface $response) { $connection->disconnect(); $message = $response->getMessage(); throw new ServerException($message); } /** * Returns the underlying connection to be used by the pipeline. * * @return ConnectionInterface */ protected function getConnection() { $connection = $this->getClient()->getConnection(); if ($connection instanceof ReplicationInterface) { $connection->switchToMaster(); } return $connection; } /** * Implements the logic to flush the queued commands and read the responses * from the current connection. * * @param ConnectionInterface $connection Current connection instance. * @param SplQueue $commands Queued commands. * * @return array */ protected function executePipeline(ConnectionInterface $connection, SplQueue $commands) { foreach ($commands as $command) { $connection->writeRequest($command); } $responses = []; $exceptions = $this->throwServerExceptions(); while (!$commands->isEmpty()) { $command = $commands->dequeue(); $response = $connection->readResponse($command); if (!$response instanceof ResponseInterface) { $responses[] = $command->parseResponse($response); } elseif ($response instanceof ErrorResponseInterface && $exceptions) { $this->exception($connection, $response); } else { $responses[] = $response; } } return $responses; } /** * Flushes the buffer holding all of the commands queued so far. * * @param bool $send Specifies if the commands in the buffer should be sent to Redis. * * @return $this */ public function flushPipeline($send = true) { if ($send && !$this->pipeline->isEmpty()) { $responses = $this->executePipeline($this->getConnection(), $this->pipeline); $this->responses = array_merge($this->responses, $responses); } else { $this->pipeline = new SplQueue(); } return $this; } /** * Marks the running status of the pipeline. * * @param bool $bool Sets the running status of the pipeline. * * @throws ClientException */ private function setRunning($bool) { if ($bool && $this->running) { throw new ClientException('The current pipeline context is already being executed.'); } $this->running = $bool; } /** * Handles the actual execution of the whole pipeline. * * @param mixed $callable Optional callback for execution. * * @return array * @throws Exception * @throws InvalidArgumentException */ public function execute($callable = null) { if ($callable && !is_callable($callable)) { throw new InvalidArgumentException('The argument must be a callable object.'); } $exception = null; $this->setRunning(true); try { if ($callable) { call_user_func($callable, $this); } $this->flushPipeline(); } catch (Exception $exception) { // NOOP } $this->setRunning(false); if ($exception) { throw $exception; } return $this->responses; } /** * Returns if the pipeline should throw exceptions on server errors. * * @return bool */ protected function throwServerExceptions() { return (bool) $this->client->getOptions()->exceptions; } /** * Returns the underlying client instance used by the pipeline object. * * @return ClientInterface */ public function getClient() { return $this->client; } } PK\X]Yt҂%predis/src/Pipeline/RelayPipeline.phpnu[getClient(); $throw = $this->client->getOptions()->exceptions; try { $pipeline = $client->pipeline(); foreach ($commands as $command) { $name = $command->getId(); in_array($name, $connection->atypicalCommands) ? $pipeline->{$name}(...$command->getArguments()) : $pipeline->rawCommand($name, ...$command->getArguments()); } $responses = $pipeline->exec(); if (!is_array($responses)) { return $responses; } foreach ($responses as $key => $response) { if ($response instanceof RelayException) { if ($throw) { throw $response; } $responses[$key] = new Error($response->getMessage()); } } return $responses; } catch (RelayException $ex) { if ($client->getMode() !== $client::ATOMIC) { $client->discard(); } throw new ServerException($ex->getMessage(), $ex->getCode(), $ex); } } } PK\X],predis/src/Pipeline/ConnectionErrorProof.phpnu[getClient()->getConnection(); } /** * {@inheritdoc} */ protected function executePipeline(ConnectionInterface $connection, SplQueue $commands) { if ($connection instanceof NodeConnectionInterface) { return $this->executeSingleNode($connection, $commands); } elseif ($connection instanceof ClusterInterface) { return $this->executeCluster($connection, $commands); } else { $class = get_class($connection); throw new NotSupportedException("The connection class '$class' is not supported."); } } /** * {@inheritdoc} */ protected function executeSingleNode(NodeConnectionInterface $connection, SplQueue $commands) { $responses = []; $sizeOfPipe = count($commands); foreach ($commands as $command) { try { $connection->writeRequest($command); } catch (CommunicationException $exception) { return array_fill(0, $sizeOfPipe, $exception); } } for ($i = 0; $i < $sizeOfPipe; ++$i) { $command = $commands->dequeue(); try { $responses[$i] = $connection->readResponse($command); } catch (CommunicationException $exception) { $add = count($commands) - count($responses); $responses = array_merge($responses, array_fill(0, $add, $exception)); break; } } return $responses; } /** * {@inheritdoc} */ protected function executeCluster(ClusterInterface $connection, SplQueue $commands) { $responses = []; $sizeOfPipe = count($commands); $exceptions = []; foreach ($commands as $command) { $cmdConnection = $connection->getConnectionByCommand($command); if (isset($exceptions[spl_object_hash($cmdConnection)])) { continue; } try { $cmdConnection->writeRequest($command); } catch (CommunicationException $exception) { $exceptions[spl_object_hash($cmdConnection)] = $exception; } } for ($i = 0; $i < $sizeOfPipe; ++$i) { $command = $commands->dequeue(); $cmdConnection = $connection->getConnectionByCommand($command); $connectionHash = spl_object_hash($cmdConnection); if (isset($exceptions[$connectionHash])) { $responses[$i] = $exceptions[$connectionHash]; continue; } try { $responses[$i] = $cmdConnection->readResponse($command); } catch (CommunicationException $exception) { $responses[$i] = $exception; $exceptions[$connectionHash] = $exception; } } return $responses; } } PK\X]<<  %predis/src/Pipeline/FireAndForget.phpnu[isEmpty()) { $connection->writeRequest($commands->dequeue()); } $connection->disconnect(); return []; } } PK\X]ͶLtt#predis/src/Pipeline/RelayAtomic.phpnu[getClient(); $throw = $this->client->getOptions()->exceptions; try { $transaction = $client->multi(); foreach ($commands as $command) { $name = $command->getId(); in_array($name, $connection->atypicalCommands) ? $transaction->{$name}(...$command->getArguments()) : $transaction->rawCommand($name, ...$command->getArguments()); } $responses = $transaction->exec(); if (!is_array($responses)) { return $responses; } foreach ($responses as $key => $response) { if ($response instanceof RelayException) { if ($throw) { throw $response; } $responses[$key] = new Error($response->getMessage()); } } return $responses; } catch (RelayException $ex) { if ($client->getMode() !== $client::ATOMIC) { $client->discard(); } throw new ServerException($ex->getMessage(), $ex->getCode(), $ex); } } } PK\X]wpredis/src/Monitor/Consumer.phpnu[assertClient($client); $this->client = $client; $this->start(); } /** * Automatically stops the consumer when the garbage collector kicks in. */ public function __destruct() { $this->stop(); } /** * Checks if the passed client instance satisfies the required conditions * needed to initialize a monitor consumer. * * @param ClientInterface $client Client instance used by the consumer. * * @throws NotSupportedException */ private function assertClient(ClientInterface $client) { if ($client->getConnection() instanceof ClusterInterface) { throw new NotSupportedException( 'Cannot initialize a monitor consumer over cluster connections.' ); } if (!$client->getCommandFactory()->supports('MONITOR')) { throw new NotSupportedException("'MONITOR' is not supported by the current command factory."); } } /** * Initializes the consumer and sends the MONITOR command to the server. */ protected function start() { $this->client->executeCommand( $this->client->createCommand('MONITOR') ); $this->valid = true; } /** * Stops the consumer. Internally this is done by disconnecting from server * since there is no way to terminate the stream initialized by MONITOR. */ public function stop() { $this->client->disconnect(); $this->valid = false; } /** * @return void */ #[ReturnTypeWillChange] public function rewind() { // NOOP } /** * Returns the last message payload retrieved from the server. * * @return object */ #[ReturnTypeWillChange] public function current() { return $this->getValue(); } /** * @return int|null */ #[ReturnTypeWillChange] public function key() { return $this->position; } /** * @return void */ #[ReturnTypeWillChange] public function next() { ++$this->position; } /** * Checks if the the consumer is still in a valid state to continue. * * @return bool */ #[ReturnTypeWillChange] public function valid() { return $this->valid; } /** * Waits for a new message from the server generated by MONITOR and returns * it when available. * * @return object */ private function getValue() { $database = 0; $client = null; $event = $this->client->getConnection()->read(); $callback = function ($matches) use (&$database, &$client) { if (2 === $count = count($matches)) { // Redis <= 2.4 $database = (int) $matches[1]; } if (4 === $count) { // Redis >= 2.6 $database = (int) $matches[2]; $client = $matches[3]; } return ' '; }; $event = preg_replace_callback('/ \(db (\d+)\) | \[(\d+) (.*?)\] /', $callback, $event, 1); @[$timestamp, $command, $arguments] = explode(' ', $event, 3); return (object) [ 'timestamp' => (float) $timestamp, 'database' => $database, 'client' => $client, 'command' => substr($command, 1, -1), 'arguments' => $arguments, ]; } } PK\X] X]I]Ipredis/src/Client.phpnu[ */ class Client implements ClientInterface, IteratorAggregate { public const VERSION = '2.3.0'; /** @var OptionsInterface */ private $options; /** @var ConnectionInterface */ private $connection; /** @var Command\FactoryInterface */ private $commands; /** * @param mixed $parameters Connection parameters for one or more servers. * @param mixed $options Options to configure some behaviours of the client. */ public function __construct($parameters = null, $options = null) { $this->options = static::createOptions($options ?? new Options()); $this->connection = static::createConnection($this->options, $parameters ?? new Parameters()); $this->commands = $this->options->commands; } /** * Creates a new set of client options for the client. * * @param array|OptionsInterface $options Set of client options * * @return OptionsInterface * @throws InvalidArgumentException */ protected static function createOptions($options) { if (is_array($options)) { return new Options($options); } elseif ($options instanceof OptionsInterface) { return $options; } else { throw new InvalidArgumentException('Invalid type for client options'); } } /** * Creates single or aggregate connections from supplied arguments. * * This method accepts the following types to create a connection instance: * * - Array (dictionary: single connection, indexed: aggregate connections) * - String (URI for a single connection) * - Callable (connection initializer callback) * - Instance of Predis\Connection\ParametersInterface (used as-is) * - Instance of Predis\Connection\ConnectionInterface (returned as-is) * * When a callable is passed, it receives the original set of client options * and must return an instance of Predis\Connection\ConnectionInterface. * * Connections are created using the connection factory (in case of single * connections) or a specialized aggregate connection initializer (in case * of cluster and replication) retrieved from the supplied client options. * * @param OptionsInterface $options Client options container * @param mixed $parameters Connection parameters * * @return ConnectionInterface * @throws InvalidArgumentException */ protected static function createConnection(OptionsInterface $options, $parameters) { if ($parameters instanceof ConnectionInterface) { return $parameters; } if ($parameters instanceof ParametersInterface || is_string($parameters)) { return $options->connections->create($parameters); } if (is_array($parameters)) { if (!isset($parameters[0])) { return $options->connections->create($parameters); } elseif ($options->defined('cluster') && $initializer = $options->cluster) { return $initializer($parameters, true); } elseif ($options->defined('replication') && $initializer = $options->replication) { return $initializer($parameters, true); } elseif ($options->defined('aggregate') && $initializer = $options->aggregate) { return $initializer($parameters, false); } else { throw new InvalidArgumentException( 'Array of connection parameters requires `cluster`, `replication` or `aggregate` client option' ); } } if (is_callable($parameters)) { $connection = call_user_func($parameters, $options); if (!$connection instanceof ConnectionInterface) { throw new InvalidArgumentException('Callable parameters must return a valid connection'); } return $connection; } throw new InvalidArgumentException('Invalid type for connection parameters'); } /** * {@inheritdoc} */ public function getCommandFactory() { return $this->commands; } /** * {@inheritdoc} */ public function getOptions() { return $this->options; } /** * Creates a new client using a specific underlying connection. * * This method allows to create a new client instance by picking a specific * connection out of an aggregate one, with the same options of the original * client instance. * * The specified selector defines which logic to use to look for a suitable * connection by the specified value. Supported selectors are: * * - `id` * - `key` * - `slot` * - `command` * - `alias` * - `role` * * Internally the client relies on duck-typing and follows this convention: * * $selector string => getConnectionBy$selector($value) method * * This means that support for specific selectors may vary depending on the * actual logic implemented by connection classes and there is no interface * binding a connection class to implement any of these. * * @param string $selector Type of selector. * @param mixed $value Value to be used by the selector. * * @return ClientInterface */ public function getClientBy($selector, $value) { $selector = strtolower($selector); if (!in_array($selector, ['id', 'key', 'slot', 'role', 'alias', 'command'])) { throw new InvalidArgumentException("Invalid selector type: `$selector`"); } if (!method_exists($this->connection, $method = "getConnectionBy$selector")) { $class = get_class($this->connection); throw new InvalidArgumentException("Selecting connection by $selector is not supported by $class"); } if (!$connection = $this->connection->$method($value)) { throw new InvalidArgumentException("Cannot find a connection by $selector matching `$value`"); } return new static($connection, $this->getOptions()); } /** * Opens the underlying connection and connects to the server. */ public function connect() { $this->connection->connect(); } /** * Closes the underlying connection and disconnects from the server. */ public function disconnect() { $this->connection->disconnect(); } /** * Closes the underlying connection and disconnects from the server. * * This is the same as `Client::disconnect()` as it does not actually send * the `QUIT` command to Redis, but simply closes the connection. */ public function quit() { $this->disconnect(); } /** * Returns the current state of the underlying connection. * * @return bool */ public function isConnected() { return $this->connection->isConnected(); } /** * {@inheritdoc} */ public function getConnection() { return $this->connection; } /** * Applies the configured serializer and compression to given value. * * @param mixed $value * @return string */ public function pack($value) { return $this->connection instanceof RelayConnection ? $this->connection->pack($value) : $value; } /** * Deserializes and decompresses to given value. * * @param mixed $value * @return string */ public function unpack($value) { return $this->connection instanceof RelayConnection ? $this->connection->unpack($value) : $value; } /** * Executes a command without filtering its arguments, parsing the response, * applying any prefix to keys or throwing exceptions on Redis errors even * regardless of client options. * * It is possible to identify Redis error responses from normal responses * using the second optional argument which is populated by reference. * * @param array $arguments Command arguments as defined by the command signature. * @param bool $error Set to TRUE when Redis returned an error response. * * @return mixed */ public function executeRaw(array $arguments, &$error = null) { $error = false; $commandID = array_shift($arguments); $response = $this->connection->executeCommand( new RawCommand($commandID, $arguments) ); if ($response instanceof ResponseInterface) { if ($response instanceof ErrorResponseInterface) { $error = true; } return (string) $response; } return $response; } /** * {@inheritdoc} */ public function __call($commandID, $arguments) { return $this->executeCommand( $this->createCommand($commandID, $arguments) ); } /** * {@inheritdoc} */ public function createCommand($commandID, $arguments = []) { return $this->commands->create($commandID, $arguments); } /** * @param string $name * @return ContainerInterface */ public function __get(string $name) { return ContainerFactory::create($this, $name); } /** * @param string $name * @param mixed $value * @return mixed */ public function __set(string $name, $value) { throw new RuntimeException('Not allowed'); } /** * @param string $name * @return mixed */ public function __isset(string $name) { throw new RuntimeException('Not allowed'); } /** * {@inheritdoc} */ public function executeCommand(CommandInterface $command) { $response = $this->connection->executeCommand($command); if ($response instanceof ResponseInterface) { if ($response instanceof ErrorResponseInterface) { $response = $this->onErrorResponse($command, $response); } return $response; } return $command->parseResponse($response); } /** * Handles -ERR responses returned by Redis. * * @param CommandInterface $command Redis command that generated the error. * @param ErrorResponseInterface $response Instance of the error response. * * @return mixed * @throws ServerException */ protected function onErrorResponse(CommandInterface $command, ErrorResponseInterface $response) { if ($command instanceof ScriptCommand && $response->getErrorType() === 'NOSCRIPT') { $response = $this->executeCommand($command->getEvalCommand()); if (!$response instanceof ResponseInterface) { $response = $command->parseResponse($response); } return $response; } if ($this->options->exceptions) { throw new ServerException($response->getMessage()); } return $response; } /** * Executes the specified initializer method on `$this` by adjusting the * actual invocation depending on the arity (0, 1 or 2 arguments). This is * simply an utility method to create Redis contexts instances since they * follow a common initialization path. * * @param string $initializer Method name. * @param array $argv Arguments for the method. * * @return mixed */ private function sharedContextFactory($initializer, $argv = null) { switch (count($argv)) { case 0: return $this->$initializer(); case 1: return is_array($argv[0]) ? $this->$initializer($argv[0]) : $this->$initializer(null, $argv[0]); case 2: [$arg0, $arg1] = $argv; return $this->$initializer($arg0, $arg1); default: return $this->$initializer($this, $argv); } } /** * Creates a new pipeline context and returns it, or returns the results of * a pipeline executed inside the optionally provided callable object. * * @param mixed ...$arguments Array of options, a callable for execution, or both. * * @return Pipeline|array */ public function pipeline(...$arguments) { return $this->sharedContextFactory('createPipeline', func_get_args()); } /** * Actual pipeline context initializer method. * * @param array|null $options Options for the context. * @param mixed $callable Optional callable used to execute the context. * * @return Pipeline|array */ protected function createPipeline(?array $options = null, $callable = null) { if (isset($options['atomic']) && $options['atomic']) { $class = Atomic::class; } elseif (isset($options['fire-and-forget']) && $options['fire-and-forget']) { $class = FireAndForget::class; } else { $class = Pipeline::class; } if ($this->connection instanceof RelayConnection) { if (isset($options['atomic']) && $options['atomic']) { $class = RelayAtomic::class; } elseif (isset($options['fire-and-forget']) && $options['fire-and-forget']) { throw new NotSupportedException('The "relay" extension does not support fire-and-forget pipelines.'); } else { $class = RelayPipeline::class; } } /* * @var ClientContextInterface */ $pipeline = new $class($this); if (isset($callable)) { return $pipeline->execute($callable); } return $pipeline; } /** * Creates a new transaction context and returns it, or returns the results * of a transaction executed inside the optionally provided callable object. * * @param mixed ...$arguments Array of options, a callable for execution, or both. * * @return MultiExecTransaction|array */ public function transaction(...$arguments) { return $this->sharedContextFactory('createTransaction', func_get_args()); } /** * Actual transaction context initializer method. * * @param array|null $options Options for the context. * @param mixed $callable Optional callable used to execute the context. * * @return MultiExecTransaction|array */ protected function createTransaction(?array $options = null, $callable = null) { $transaction = new MultiExecTransaction($this, $options); if (isset($callable)) { return $transaction->execute($callable); } return $transaction; } /** * Creates a new publish/subscribe context and returns it, or starts its loop * inside the optionally provided callable object. * * @param mixed ...$arguments Array of options, a callable for execution, or both. * * @return PubSubConsumer|null */ public function pubSubLoop(...$arguments) { return $this->sharedContextFactory('createPubSub', func_get_args()); } /** * Actual publish/subscribe context initializer method. * * @param array|null $options Options for the context. * @param mixed $callable Optional callable used to execute the context. * * @return PubSubConsumer|null */ protected function createPubSub(?array $options = null, $callable = null) { if ($this->connection instanceof RelayConnection) { $pubsub = new RelayPubSubConsumer($this, $options); } else { $pubsub = new PubSubConsumer($this, $options); } if (!isset($callable)) { return $pubsub; } foreach ($pubsub as $message) { if (call_user_func($callable, $pubsub, $message) === false) { $pubsub->stop(); } } return null; } /** * Creates a new monitor consumer and returns it. * * @return MonitorConsumer */ public function monitor() { return new MonitorConsumer($this); } /** * @return Traversable */ #[ReturnTypeWillChange] public function getIterator() { $clients = []; $connection = $this->getConnection(); if (!$connection instanceof Traversable) { return new ArrayIterator([ (string) $connection => new static($connection, $this->getOptions()), ]); } foreach ($connection as $node) { $clients[(string) $node] = new static($node, $this->getOptions()); } return new ArrayIterator($clients); } } PK\X]nendSdS%predis/src/ClientContextInterface.phpnu[ [ ['name' => 'Json', 'commandPrefix' => 'JSON'], ['name' => 'BloomFilter', 'commandPrefix' => 'BF'], ['name' => 'CuckooFilter', 'commandPrefix' => 'CF'], ['name' => 'CountMinSketch', 'commandPrefix' => 'CMS'], ['name' => 'TDigest', 'commandPrefix' => 'TDIGEST'], ['name' => 'TopK', 'commandPrefix' => 'TOPK'], ['name' => 'Search', 'commandPrefix' => 'FT'], ['name' => 'TimeSeries', 'commandPrefix' => 'TS'], ], ]; /** * Returns available modules with configuration. * * @return array|string[][] */ public static function getModules(): array { return self::$config['modules']; } } PK\X]d2predis/src/PredisException.phpnu[ * @author Daniele Alessandri * @codeCoverageIgnore */ class Autoloader { private $directory; private $prefix; private $prefixLength; /** * @param string $baseDirectory Base directory where the source files are located. */ public function __construct($baseDirectory = __DIR__) { $this->directory = $baseDirectory; $this->prefix = __NAMESPACE__ . '\\'; $this->prefixLength = strlen($this->prefix); } /** * Registers the autoloader class with the PHP SPL autoloader. * * @param bool $prepend Prepend the autoloader on the stack instead of appending it. */ public static function register($prepend = false) { spl_autoload_register([new self(), 'autoload'], true, $prepend); } /** * Loads a class from a file using its fully qualified name. * * @param string $className Fully qualified name of a class. */ public function autoload($className) { if (0 === strpos($className, $this->prefix)) { $parts = explode('\\', substr($className, $this->prefixLength)); $filepath = $this->directory . DIRECTORY_SEPARATOR . implode(DIRECTORY_SEPARATOR, $parts) . '.php'; if (is_file($filepath)) { require $filepath; } } } } PK\X]DG $predis/src/NotSupportedException.phpnu[connection = $connection; } /** * Gets the connection that generated the exception. * * @return NodeConnectionInterface */ public function getConnection() { return $this->connection; } /** * Indicates if the receiver should reset the underlying connection. * * @return bool */ public function shouldResetConnection() { return true; } /** * Helper method to handle exceptions generated by a connection object. * * @param CommunicationException $exception Exception. * * @throws CommunicationException */ public static function handle(CommunicationException $exception) { if ($exception->shouldResetConnection()) { $connection = $exception->getConnection(); if ($connection->isConnected()) { $connection->disconnect(); } } throw $exception; } } PK\X]epredis/src/ClientException.phpnu[= 3.0). - Support for master-slave replication setups and [redis-sentinel](http://redis.io/topics/sentinel). - Transparent key prefixing of keys using a customizable prefix strategy. - Command pipelining on both single nodes and clusters (client-side sharding only). - Abstraction for Redis transactions (Redis >= 2.0) and CAS operations (Redis >= 2.2). - Abstraction for Lua scripting (Redis >= 2.6) and automatic switching between `EVALSHA` or `EVAL`. - Abstraction for `SCAN`, `SSCAN`, `ZSCAN` and `HSCAN` (Redis >= 2.8) based on PHP iterators. - Connections are established lazily by the client upon the first command and can be persisted. - Connections can be established via TCP/IP (also TLS/SSL-encrypted) or UNIX domain sockets. - Support for custom connection classes for providing different network or protocol backends. - Flexible system for defining custom commands and override the default ones. ## How to _install_ and use Predis ## This library can be found on [Packagist](http://packagist.org/packages/predis/predis) for an easier management of projects dependencies using [Composer](http://packagist.org/about-composer). Compressed archives of each release are [available on GitHub](https://github.com/predis/predis/releases). ```shell composer require predis/predis ``` ### Loading the library ### Predis relies on the autoloading features of PHP to load its files when needed and complies with the [PSR-4 standard](https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-4-autoloader.md). Autoloading is handled automatically when dependencies are managed through Composer, but it is also possible to leverage its own autoloader in projects or scripts lacking any autoload facility: ```php // Prepend a base path if Predis is not available in your "include_path". require 'Predis/Autoloader.php'; Predis\Autoloader::register(); ``` ### Connecting to Redis ### When creating a client instance without passing any connection parameter, Predis assumes `127.0.0.1` and `6379` as default host and port. The default timeout for the `connect()` operation is 5 seconds: ```php $client = new Predis\Client(); $client->set('foo', 'bar'); $value = $client->get('foo'); ``` Connection parameters can be supplied either in the form of URI strings or named arrays. The latter is the preferred way to supply parameters, but URI strings can be useful when parameters are read from non-structured or partially-structured sources: ```php // Parameters passed using a named array: $client = new Predis\Client([ 'scheme' => 'tcp', 'host' => '10.0.0.1', 'port' => 6379, ]); // Same set of parameters, passed using an URI string: $client = new Predis\Client('tcp://10.0.0.1:6379'); ``` Password protected servers can be accessed by adding `password` to the parameters set. When ACLs are enabled on Redis >= 6.0, both `username` and `password` are required for user authentication. It is also possible to connect to local instances of Redis using UNIX domain sockets, in this case the parameters must use the `unix` scheme and specify a path for the socket file: ```php $client = new Predis\Client(['scheme' => 'unix', 'path' => '/path/to/redis.sock']); $client = new Predis\Client('unix:/path/to/redis.sock'); ``` The client can leverage TLS/SSL encryption to connect to secured remote Redis instances without the need to configure an SSL proxy like stunnel. This can be useful when connecting to nodes running on various cloud hosting providers. Encryption can be enabled with using the `tls` scheme and an array of suitable [options](http://php.net/manual/context.ssl.php) passed via the `ssl` parameter: ```php // Named array of connection parameters: $client = new Predis\Client([ 'scheme' => 'tls', 'ssl' => ['cafile' => 'private.pem', 'verify_peer' => true], ]); // Same set of parameters, but using an URI string: $client = new Predis\Client('tls://127.0.0.1?ssl[cafile]=private.pem&ssl[verify_peer]=1'); ``` The connection schemes [`redis`](http://www.iana.org/assignments/uri-schemes/prov/redis) (alias of `tcp`) and [`rediss`](http://www.iana.org/assignments/uri-schemes/prov/rediss) (alias of `tls`) are also supported, with the difference that URI strings containing these schemes are parsed following the rules described on their respective IANA provisional registration documents. The actual list of supported connection parameters can vary depending on each connection backend so it is recommended to refer to their specific documentation or implementation for details. Predis can aggregate multiple connections when providing an array of connection parameters and the appropriate option to instruct the client about how to aggregate them (clustering, replication or a custom aggregation logic). Named arrays and URI strings can be mixed when providing configurations for each node: ```php $client = new Predis\Client([ 'tcp://10.0.0.1?alias=first-node', ['host' => '10.0.0.2', 'alias' => 'second-node'], ], [ 'cluster' => 'predis', ]); ``` See the [aggregate connections](#aggregate-connections) section of this document for more details. Connections to Redis are lazy meaning that the client connects to a server only if and when needed. While it is recommended to let the client do its own stuff under the hood, there may be times when it is still desired to have control of when the connection is opened or closed: this can easily be achieved by invoking `$client->connect()` and `$client->disconnect()`. Please note that the effect of these methods on aggregate connections may differ depending on each specific implementation. ### Client configuration ### Many aspects and behaviors of the client can be configured by passing specific client options to the second argument of `Predis\Client::__construct()`: ```php $client = new Predis\Client($parameters, ['prefix' => 'sample:']); ``` Options are managed using a mini DI-alike container and their values can be lazily initialized only when needed. The client options supported by default in Predis are: - `prefix`: prefix string applied to every key found in commands. - `exceptions`: whether the client should throw or return responses upon Redis errors. - `connections`: list of connection backends or a connection factory instance. - `cluster`: specifies a cluster backend (`predis`, `redis` or callable). - `replication`: specifies a replication backend (`predis`, `sentinel` or callable). - `aggregate`: configures the client with a custom aggregate connection (callable). - `parameters`: list of default connection parameters for aggregate connections. - `commands`: specifies a command factory instance to use through the library. Users can also provide custom options with values or callable objects (for lazy initialization) that are stored in the options container for later use through the library. ### Aggregate connections ### Aggregate connections are the foundation upon which Predis implements clustering and replication and they are used to group multiple connections to single Redis nodes and hide the specific logic needed to handle them properly depending on the context. Aggregate connections usually require an array of connection parameters along with the appropriate client option when creating a new client instance. #### Cluster #### Predis can be configured to work in clustering mode with a traditional client-side sharding approach to create a cluster of independent nodes and distribute the keyspace among them. This approach needs some sort of external health monitoring of nodes and requires the keyspace to be rebalanced manually when nodes are added or removed: ```php $parameters = ['tcp://10.0.0.1', 'tcp://10.0.0.2', 'tcp://10.0.0.3']; $options = ['cluster' => 'predis']; $client = new Predis\Client($parameters); ``` Along with Redis 3.0, a new supervised and coordinated type of clustering was introduced in the form of [redis-cluster](http://redis.io/topics/cluster-tutorial). This kind of approach uses a different algorithm to distribute the keyspaces, with Redis nodes coordinating themselves by communicating via a gossip protocol to handle health status, rebalancing, nodes discovery and request redirection. In order to connect to a cluster managed by redis-cluster, the client requires a list of its nodes (not necessarily complete since it will automatically discover new nodes if necessary) and the `cluster` client options set to `redis`: ```php $parameters = ['tcp://10.0.0.1', 'tcp://10.0.0.2', 'tcp://10.0.0.3']; $options = ['cluster' => 'redis']; $client = new Predis\Client($parameters, $options); ``` #### Replication #### The client can be configured to operate in a single master / multiple slaves setup to provide better service availability. When using replication, Predis recognizes read-only commands and sends them to a random slave in order to provide some sort of load-balancing and switches to the master as soon as it detects a command that performs any kind of operation that would end up modifying the keyspace or the value of a key. Instead of raising a connection error when a slave fails, the client attempts to fall back to a different slave among the ones provided in the configuration. The basic configuration needed to use the client in replication mode requires one Redis server to be identified as the master (this can be done via connection parameters by setting the `role` parameter to `master`) and one or more slaves (in this case setting `role` to `slave` for slaves is optional): ```php $parameters = ['tcp://10.0.0.1?role=master', 'tcp://10.0.0.2', 'tcp://10.0.0.3']; $options = ['replication' => 'predis']; $client = new Predis\Client($parameters, $options); ``` The above configuration has a static list of servers and relies entirely on the client's logic, but it is possible to rely on [`redis-sentinel`](http://redis.io/topics/sentinel) for a more robust HA environment with sentinel servers acting as a source of authority for clients for service discovery. The minimum configuration required by the client to work with redis-sentinel is a list of connection parameters pointing to a bunch of sentinel instances, the `replication` option set to `sentinel` and the `service` option set to the name of the service: ```php $sentinels = ['tcp://10.0.0.1', 'tcp://10.0.0.2', 'tcp://10.0.0.3']; $options = ['replication' => 'sentinel', 'service' => 'mymaster']; $client = new Predis\Client($sentinels, $options); ``` If the master and slave nodes are configured to require an authentication from clients, a password must be provided via the global `parameters` client option. This option can also be used to specify a different database index. The client options array would then look like this: ```php $options = [ 'replication' => 'sentinel', 'service' => 'mymaster', 'parameters' => [ 'password' => $secretpassword, 'database' => 10, ], ]; ``` While Predis is able to distinguish commands performing write and read-only operations, `EVAL` and `EVALSHA` represent a corner case in which the client switches to the master node because it cannot tell when a Lua script is safe to be executed on slaves. While this is indeed the default behavior, when certain Lua scripts do not perform write operations it is possible to provide an hint to tell the client to stick with slaves for their execution: ```php $parameters = ['tcp://10.0.0.1?role=master', 'tcp://10.0.0.2', 'tcp://10.0.0.3']; $options = ['replication' => function () { // Set scripts that won't trigger a switch from a slave to the master node. $strategy = new Predis\Replication\ReplicationStrategy(); $strategy->setScriptReadOnly($LUA_SCRIPT); return new Predis\Connection\Replication\MasterSlaveReplication($strategy); }]; $client = new Predis\Client($parameters, $options); $client->eval($LUA_SCRIPT, 0); // Sticks to slave using `eval`... $client->evalsha(sha1($LUA_SCRIPT), 0); // ... and `evalsha`, too. ``` The [`examples`](examples/) directory contains a few scripts that demonstrate how the client can be configured and used to leverage replication in both basic and complex scenarios. ### Command pipelines ### Pipelining can help with performances when many commands need to be sent to a server by reducing the latency introduced by network round-trip timings. Pipelining also works with aggregate connections. The client can execute the pipeline inside a callable block or return a pipeline instance with the ability to chain commands thanks to its fluent interface: ```php // Executes a pipeline inside the given callable block: $responses = $client->pipeline(function ($pipe) { for ($i = 0; $i < 1000; $i++) { $pipe->set("key:$i", str_pad($i, 4, '0', 0)); $pipe->get("key:$i"); } }); // Returns a pipeline that can be chained thanks to its fluent interface: $responses = $client->pipeline()->set('foo', 'bar')->get('foo')->execute(); ``` ### Transactions ### The client provides an abstraction for Redis transactions based on `MULTI` and `EXEC` with a similar interface to command pipelines: ```php // Executes a transaction inside the given callable block: $responses = $client->transaction(function ($tx) { $tx->set('foo', 'bar'); $tx->get('foo'); }); // Returns a transaction that can be chained thanks to its fluent interface: $responses = $client->transaction()->set('foo', 'bar')->get('foo')->execute(); ``` This abstraction can perform check-and-set operations thanks to `WATCH` and `UNWATCH` and provides automatic retries of transactions aborted by Redis when `WATCH`ed keys are touched. For an example of a transaction using CAS you can see [the following example](examples/transaction_using_cas.php). ### Adding new commands ### While we try to update Predis to stay up to date with all the commands available in Redis, you might prefer to stick with an old version of the library or provide a different way to filter arguments or parse responses for specific commands. To achieve that, Predis provides the ability to implement new command classes to define or override commands in the default command factory used by the client: ```php // Define a new command by extending Predis\Command\Command: class BrandNewRedisCommand extends Predis\Command\Command { public function getId() { return 'NEWCMD'; } } // Inject your command in the current command factory: $client = new Predis\Client($parameters, [ 'commands' => [ 'newcmd' => 'BrandNewRedisCommand', ], ]); $response = $client->newcmd(); ``` There is also a method to send raw commands without filtering their arguments or parsing responses. Users must provide the list of arguments for the command as an array, following the signatures as defined by the [Redis documentation for commands](http://redis.io/commands): ```php $response = $client->executeRaw(['SET', 'foo', 'bar']); ``` ### Script commands ### While it is possible to leverage [Lua scripting](http://redis.io/commands/eval) on Redis 2.6+ using directly [`EVAL`](http://redis.io/commands/eval) and [`EVALSHA`](http://redis.io/commands/evalsha), Predis offers script commands as an higher level abstraction built upon them to make things simple. Script commands can be registered in the command factory used by the client and are accessible as if they were plain Redis commands, but they define Lua scripts that get transmitted to the server for remote execution. Internally they use [`EVALSHA`](http://redis.io/commands/evalsha) by default and identify a script by its SHA1 hash to save bandwidth, but [`EVAL`](http://redis.io/commands/eval) is used as a fall back when needed: ```php // Define a new script command by extending Predis\Command\ScriptCommand: class ListPushRandomValue extends Predis\Command\ScriptCommand { public function getKeysCount() { return 1; } public function getScript() { return << [ 'lpushrand' => 'ListPushRandomValue', ], ]); $response = $client->lpushrand('random_values', $seed = mt_rand()); ``` ### Customizable connection backends ### Predis can use different connection backends to connect to Redis. The builtin Relay integration leverages the [Relay](https://github.com/cachewerk/relay) extension for PHP for major performance gains, by caching a partial replica of the Redis dataset in PHP shared runtime memory. ```php $client = new Predis\Client('tcp://127.0.0.1', [ 'connections' => 'relay', ]); ``` Developers can create their own connection classes to support whole new network backends, extend existing classes or provide completely different implementations. Connection classes must implement `Predis\Connection\NodeConnectionInterface` or extend `Predis\Connection\AbstractConnection`: ```php class MyConnectionClass implements Predis\Connection\NodeConnectionInterface { // Implementation goes here... } // Use MyConnectionClass to handle connections for the `tcp` scheme: $client = new Predis\Client('tcp://127.0.0.1', [ 'connections' => ['tcp' => 'MyConnectionClass'], ]); ``` For a more in-depth insight on how to create new connection backends you can refer to the actual implementation of the standard connection classes available in the `Predis\Connection` namespace. ## Development ## ### Reporting bugs and contributing code ### Contributions to Predis are highly appreciated either in the form of pull requests for new features, bug fixes, or just bug reports. We only ask you to adhere to issue and pull request templates. ### Test suite ### __ATTENTION__: Do not ever run the test suite shipped with Predis against instances of Redis running in production environments or containing data you are interested in! Predis has a comprehensive test suite covering every aspect of the library and that can optionally perform integration tests against a running instance of Redis (required >= 2.4.0 in order to verify the correct behavior of the implementation of each command. Integration tests for unsupported Redis commands are automatically skipped. If you do not have Redis up and running, integration tests can be disabled. See [the tests README](tests/README.md) for more details about testing this library. Predis uses GitHub Actions for continuous integration and the history for past and current builds can be found [on its actions page](https://github.com/predis/predis/actions). ### License ### The code for Predis is distributed under the terms of the MIT license (see [LICENSE](LICENSE)). [ico-license]: https://img.shields.io/github/license/predis/predis.svg?style=flat-square [ico-version-stable]: https://img.shields.io/github/v/tag/predis/predis?label=stable&style=flat-square [ico-version-dev]: https://img.shields.io/github/v/tag/predis/predis?include_prereleases&label=pre-release&style=flat-square [ico-downloads-monthly]: https://img.shields.io/packagist/dm/predis/predis.svg?style=flat-square [ico-build]: https://img.shields.io/github/actions/workflow/status/predis/predis/tests.yml?branch=main&style=flat-square [ico-coverage]: https://img.shields.io/coverallsCoverage/github/predis/predis?style=flat-square [link-releases]: https://github.com/predis/predis/releases [link-actions]: https://github.com/predis/predis/actions [link-downloads]: https://packagist.org/packages/predis/predis/stats [link-coverage]: https://coveralls.io/github/predis/predis PK\X]C"[""predis/composer.jsonnu[{ "name": "predis/predis", "type": "library", "description": "A flexible and feature-complete Redis client for PHP.", "keywords": ["nosql", "redis", "predis"], "homepage": "http://github.com/predis/predis", "license": "MIT", "support": { "issues": "https://github.com/predis/predis/issues" }, "authors": [ { "name": "Till Krüss", "homepage": "https://till.im", "role": "Maintainer" } ], "funding": [ { "type": "github", "url": "https://github.com/sponsors/tillkruss" } ], "require": { "php": "^7.2 || ^8.0" }, "require-dev": { "friendsofphp/php-cs-fixer": "^3.3", "phpstan/phpstan": "^1.9", "phpunit/phpunit": "^8.0 || ^9.4" }, "suggest": { "ext-relay": "Faster connection with in-memory caching (>=0.6.2)" }, "scripts": { "phpstan": "phpstan analyse", "style": "php-cs-fixer fix --diff --dry-run", "style:fix": "php-cs-fixer fix" }, "autoload": { "psr-4": { "Predis\\": "src/" } }, "config": { "sort-packages": true, "preferred-install": "dist" }, "minimum-stability": "dev", "prefer-stable": true } PK\X]j<||predis/LICENSEnu[MIT License Copyright (c) 2009-2020 Daniele Alessandri (original work) Copyright (c) 2021-2024 Till Krüss (modified work) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. PK)_]aD/ "src/Transaction/MultiExecState.phpnu[flags = 0; } /** * Sets the internal state flags. * * @param int $flags Set of flags */ public function set($flags) { $this->flags = $flags; } /** * Gets the internal state flags. * * @return int */ public function get() { return $this->flags; } /** * Sets one or more flags. * * @param int $flags Set of flags */ public function flag($flags) { $this->flags |= $flags; } /** * Resets one or more flags. * * @param int $flags Set of flags */ public function unflag($flags) { $this->flags &= ~$flags; } /** * Returns if the specified flag or set of flags is set. * * @param int $flags Flag * * @return bool */ public function check($flags) { return ($this->flags & $flags) === $flags; } /** * Resets the state of a transaction. */ public function reset() { $this->flags = 0; } /** * Returns the state of the RESET flag. * * @return bool */ public function isReset() { return $this->flags === 0; } /** * Returns the state of the INITIALIZED flag. * * @return bool */ public function isInitialized() { return $this->check(self::INITIALIZED); } /** * Returns the state of the INSIDEBLOCK flag. * * @return bool */ public function isExecuting() { return $this->check(self::INSIDEBLOCK); } /** * Returns the state of the CAS flag. * * @return bool */ public function isCAS() { return $this->check(self::CAS); } /** * Returns if WATCH is allowed in the current state. * * @return bool */ public function isWatchAllowed() { return $this->check(self::INITIALIZED) && !$this->check(self::CAS); } /** * Returns the state of the WATCH flag. * * @return bool */ public function isWatching() { return $this->check(self::WATCH); } /** * Returns the state of the DISCARDED flag. * * @return bool */ public function isDiscarded() { return $this->check(self::DISCARDED); } } PK)_]e ::-src/Transaction/AbortedMultiExecException.phpnu[transaction = $transaction; } /** * Returns the transaction that generated the exception. * * @return MultiExec */ public function getTransaction() { return $this->transaction; } } PK)_]>|6|6src/Transaction/MultiExec.phpnu[assertClient($client); $this->client = $client; $this->state = new MultiExecState(); $this->configure($client, $options ?: []); $this->reset(); } /** * Checks if the passed client instance satisfies the required conditions * needed to initialize the transaction object. * * @param ClientInterface $client Client instance used by the transaction object. * * @throws NotSupportedException */ private function assertClient(ClientInterface $client) { if ($client->getConnection() instanceof ClusterInterface) { throw new NotSupportedException( 'Cannot initialize a MULTI/EXEC transaction over cluster connections.' ); } if (!$client->getCommandFactory()->supports('MULTI', 'EXEC', 'DISCARD')) { throw new NotSupportedException( 'MULTI, EXEC and DISCARD are not supported by the current command factory.' ); } } /** * Configures the transaction using the provided options. * * @param ClientInterface $client Underlying client instance. * @param array $options Array of options for the transaction. **/ protected function configure(ClientInterface $client, array $options) { if (isset($options['exceptions'])) { $this->exceptions = (bool) $options['exceptions']; } else { $this->exceptions = $client->getOptions()->exceptions; } if (isset($options['cas'])) { $this->modeCAS = (bool) $options['cas']; } if (isset($options['watch']) && $keys = $options['watch']) { $this->watchKeys = $keys; } if (isset($options['retry'])) { $this->attempts = (int) $options['retry']; } } /** * Resets the state of the transaction. */ protected function reset() { $this->state->reset(); $this->commands = new SplQueue(); } /** * Initializes the transaction context. */ protected function initialize() { if ($this->state->isInitialized()) { return; } if ($this->modeCAS) { $this->state->flag(MultiExecState::CAS); } if ($this->watchKeys) { $this->watch($this->watchKeys); } $cas = $this->state->isCAS(); $discarded = $this->state->isDiscarded(); if (!$cas || ($cas && $discarded)) { $this->call('MULTI'); if ($discarded) { $this->state->unflag(MultiExecState::CAS); } } $this->state->unflag(MultiExecState::DISCARDED); $this->state->flag(MultiExecState::INITIALIZED); } /** * Dynamically invokes a Redis command with the specified arguments. * * @param string $method Command ID. * @param array $arguments Arguments for the command. * * @return mixed */ public function __call($method, $arguments) { return $this->executeCommand( $this->client->createCommand($method, $arguments) ); } /** * Executes a Redis command bypassing the transaction logic. * * @param string $commandID Command ID. * @param array $arguments Arguments for the command. * * @return mixed * @throws ServerException */ protected function call($commandID, array $arguments = []) { try { $response = $this->client->executeCommand( $this->client->createCommand($commandID, $arguments) ); } catch (ServerException $exception) { if (!$this->client->getConnection() instanceof RelayConnection) { throw $exception; } if (strcasecmp($commandID, 'EXEC') != 0) { throw $exception; } if (!strpos($exception->getMessage(), 'RELAY_ERR_REDIS')) { throw $exception; } return null; } if ($response instanceof ErrorResponseInterface) { throw new ServerException($response->getMessage()); } return $response; } /** * Executes the specified Redis command. * * @param CommandInterface $command Command instance. * * @return $this|mixed * @throws AbortedMultiExecException * @throws CommunicationException */ public function executeCommand(CommandInterface $command) { $this->initialize(); if ($this->state->isCAS()) { return $this->client->executeCommand($command); } $response = $this->client->getConnection()->executeCommand($command); if ($response instanceof StatusResponse && $response == 'QUEUED') { $this->commands->enqueue($command); } elseif ($response instanceof Relay) { $this->commands->enqueue($command); } elseif ($response instanceof ErrorResponseInterface) { throw new AbortedMultiExecException($this, $response->getMessage()); } else { $this->onProtocolError('The server did not return a +QUEUED status response.'); } return $this; } /** * Executes WATCH against one or more keys. * * @param string|array $keys One or more keys. * * @return mixed * @throws NotSupportedException * @throws ClientException */ public function watch($keys) { if (!$this->client->getCommandFactory()->supports('WATCH')) { throw new NotSupportedException('WATCH is not supported by the current command factory.'); } if ($this->state->isWatchAllowed()) { throw new ClientException('Sending WATCH after MULTI is not allowed.'); } $response = $this->call('WATCH', is_array($keys) ? $keys : [$keys]); $this->state->flag(MultiExecState::WATCH); return $response; } /** * Finalizes the transaction by executing MULTI on the server. * * @return MultiExec */ public function multi() { if ($this->state->check(MultiExecState::INITIALIZED | MultiExecState::CAS)) { $this->state->unflag(MultiExecState::CAS); $this->call('MULTI'); } else { $this->initialize(); } return $this; } /** * Executes UNWATCH. * * @return MultiExec * @throws NotSupportedException */ public function unwatch() { if (!$this->client->getCommandFactory()->supports('UNWATCH')) { throw new NotSupportedException( 'UNWATCH is not supported by the current command factory.' ); } $this->state->unflag(MultiExecState::WATCH); $this->__call('UNWATCH', []); return $this; } /** * Resets the transaction by UNWATCH-ing the keys that are being WATCHed and * DISCARD-ing pending commands that have been already sent to the server. * * @return MultiExec */ public function discard() { if ($this->state->isInitialized()) { $this->call($this->state->isCAS() ? 'UNWATCH' : 'DISCARD'); $this->reset(); $this->state->flag(MultiExecState::DISCARDED); } return $this; } /** * Executes the whole transaction. * * @return mixed */ public function exec() { return $this->execute(); } /** * Checks the state of the transaction before execution. * * @param mixed $callable Callback for execution. * * @throws InvalidArgumentException * @throws ClientException */ private function checkBeforeExecution($callable) { if ($this->state->isExecuting()) { throw new ClientException( 'Cannot invoke "execute" or "exec" inside an active transaction context.' ); } if ($callable) { if (!is_callable($callable)) { throw new InvalidArgumentException('The argument must be a callable object.'); } if (!$this->commands->isEmpty()) { $this->discard(); throw new ClientException( 'Cannot execute a transaction block after using fluent interface.' ); } } elseif ($this->attempts) { $this->discard(); throw new ClientException( 'Automatic retries are supported only when a callable block is provided.' ); } } /** * Handles the actual execution of the whole transaction. * * @param mixed $callable Optional callback for execution. * * @return array * @throws CommunicationException * @throws AbortedMultiExecException * @throws ServerException */ public function execute($callable = null) { $this->checkBeforeExecution($callable); $execResponse = null; $attempts = $this->attempts; do { if ($callable) { $this->executeTransactionBlock($callable); } if ($this->commands->isEmpty()) { if ($this->state->isWatching()) { $this->discard(); } return; } $execResponse = $this->call('EXEC'); // The additional `false` check is needed for Relay, // let's hope it won't break anything if ($execResponse === null || $execResponse === false) { if ($attempts === 0) { throw new AbortedMultiExecException( $this, 'The current transaction has been aborted by the server.' ); } $this->reset(); continue; } break; } while ($attempts-- > 0); $response = []; $commands = $this->commands; $size = count($execResponse); if ($size !== count($commands)) { $this->onProtocolError('EXEC returned an unexpected number of response items.'); } for ($i = 0; $i < $size; ++$i) { $cmdResponse = $execResponse[$i]; if ($this->exceptions && $cmdResponse instanceof ErrorResponseInterface) { throw new ServerException($cmdResponse->getMessage()); } if ($cmdResponse instanceof RelayException) { if ($this->exceptions) { throw new ServerException($cmdResponse->getMessage(), $cmdResponse->getCode(), $cmdResponse); } $commands->dequeue(); $response[$i] = new Error($cmdResponse->getMessage()); continue; } $response[$i] = $commands->dequeue()->parseResponse($cmdResponse); } return $response; } /** * Passes the current transaction object to a callable block for execution. * * @param mixed $callable Callback. * * @throws CommunicationException * @throws ServerException */ protected function executeTransactionBlock($callable) { $exception = null; $this->state->flag(MultiExecState::INSIDEBLOCK); try { call_user_func($callable, $this); } catch (CommunicationException $exception) { // NOOP } catch (ServerException $exception) { // NOOP } catch (Exception $exception) { $this->discard(); } $this->state->unflag(MultiExecState::INSIDEBLOCK); if ($exception) { throw $exception; } } /** * Helper method for protocol errors encountered inside the transaction. * * @param string $message Error message. */ private function onProtocolError($message) { // Since a MULTI/EXEC block cannot be initialized when using aggregate // connections we can safely assume that Predis\Client::getConnection() // will return a Predis\Connection\NodeConnectionInterface instance. CommunicationException::handle(new ProtocolException( $this->client->getConnection(), $message )); } } PK)_]Q#src/Collection/Iterator/ListKey.phpnu[requiredCommand($client, 'LRANGE'); if ((false === $count = filter_var($count, FILTER_VALIDATE_INT)) || $count < 0) { throw new InvalidArgumentException('The $count argument must be a positive integer.'); } $this->client = $client; $this->key = $key; $this->count = $count; $this->reset(); } /** * Ensures that the client instance supports the specified Redis command * required to fetch elements from the server to perform the iteration. * * @param ClientInterface $client Client connected to Redis. * @param string $commandID Command ID. * * @throws NotSupportedException */ protected function requiredCommand(ClientInterface $client, $commandID) { if (!$client->getCommandFactory()->supports($commandID)) { throw new NotSupportedException("'$commandID' is not supported by the current command factory."); } } /** * Resets the inner state of the iterator. */ protected function reset() { $this->valid = true; $this->fetchmore = true; $this->elements = []; $this->position = -1; $this->current = null; } /** * Fetches a new set of elements from the remote collection, effectively * advancing the iteration process. * * @return array */ protected function executeCommand() { return $this->client->lrange($this->key, $this->position + 1, $this->position + $this->count); } /** * Populates the local buffer of elements fetched from the server during the * iteration. */ protected function fetch() { $elements = $this->executeCommand(); if (count($elements) < $this->count) { $this->fetchmore = false; } $this->elements = $elements; } /** * Extracts next values for key() and current(). */ protected function extractNext() { ++$this->position; $this->current = array_shift($this->elements); } /** * @return void */ #[ReturnTypeWillChange] public function rewind() { $this->reset(); $this->next(); } /** * @return mixed */ #[ReturnTypeWillChange] public function current() { return $this->current; } /** * @return int|null */ #[ReturnTypeWillChange] public function key() { return $this->position; } /** * @return void */ #[ReturnTypeWillChange] public function next() { if (!$this->elements && $this->fetchmore) { $this->fetch(); } if ($this->elements) { $this->extractNext(); } else { $this->valid = false; } } /** * @return bool */ #[ReturnTypeWillChange] public function valid() { return $this->valid; } } PK)_]uT  (src/Collection/Iterator/SortedSetKey.phpnu[= 2.8) wrapped in a fully-rewindable PHP iterator. * * @see http://redis.io/commands/scan */ class SortedSetKey extends CursorBasedIterator { protected $key; /** * {@inheritdoc} */ public function __construct(ClientInterface $client, $key, $match = null, $count = null) { $this->requiredCommand($client, 'ZSCAN'); parent::__construct($client, $match, $count); $this->key = $key; } /** * {@inheritdoc} */ protected function executeCommand() { return $this->client->zscan($this->key, $this->cursor, $this->getScanOptions()); } /** * {@inheritdoc} */ protected function extractNext() { $this->position = key($this->elements); $this->current = current($this->elements); unset($this->elements[$this->position]); } } PK)_]lC$src/Collection/Iterator/Keyspace.phpnu[= 2.8) wrapped in a fully-rewindable PHP iterator. * * @see http://redis.io/commands/scan */ class Keyspace extends CursorBasedIterator { /** * {@inheritdoc} */ public function __construct(ClientInterface $client, $match = null, $count = null) { $this->requiredCommand($client, 'SCAN'); parent::__construct($client, $match, $count); } /** * {@inheritdoc} */ protected function executeCommand() { return $this->client->scan($this->cursor, $this->getScanOptions()); } } PK)_]oc"src/Collection/Iterator/SetKey.phpnu[= 2.8) wrapped in a fully-rewindable PHP iterator. * * @see http://redis.io/commands/scan */ class SetKey extends CursorBasedIterator { protected $key; /** * {@inheritdoc} */ public function __construct(ClientInterface $client, $key, $match = null, $count = null) { $this->requiredCommand($client, 'SSCAN'); parent::__construct($client, $match, $count); $this->key = $key; } /** * {@inheritdoc} */ protected function executeCommand() { return $this->client->sscan($this->key, $this->cursor, $this->getScanOptions()); } } PK)_]&t#src/Collection/Iterator/HashKey.phpnu[= 2.8) wrapped in a fully-rewindable PHP iterator. * * @see http://redis.io/commands/scan */ class HashKey extends CursorBasedIterator { protected $key; /** * {@inheritdoc} */ public function __construct(ClientInterface $client, $key, $match = null, $count = null) { $this->requiredCommand($client, 'HSCAN'); parent::__construct($client, $match, $count); $this->key = $key; } /** * {@inheritdoc} */ protected function executeCommand() { return $this->client->hscan($this->key, $this->cursor, $this->getScanOptions()); } /** * {@inheritdoc} */ protected function extractNext() { $this->position = key($this->elements); $this->current = current($this->elements); unset($this->elements[$this->position]); } } PK)_]- DD/src/Collection/Iterator/CursorBasedIterator.phpnu[client = $client; $this->match = $match; $this->count = $count; $this->reset(); } /** * Ensures that the client supports the specified Redis command required to * fetch elements from the server to perform the iteration. * * @param ClientInterface $client Client connected to Redis. * @param string $commandID Command ID. * * @throws NotSupportedException */ protected function requiredCommand(ClientInterface $client, $commandID) { if (!$client->getCommandFactory()->supports($commandID)) { throw new NotSupportedException("'$commandID' is not supported by the current command factory."); } } /** * Resets the inner state of the iterator. */ protected function reset() { $this->valid = true; $this->fetchmore = true; $this->elements = []; $this->cursor = 0; $this->position = -1; $this->current = null; } /** * Returns an array of options for the `SCAN` command. * * @return array */ protected function getScanOptions() { $options = []; if (strlen(strval($this->match)) > 0) { $options['MATCH'] = $this->match; } if ($this->count > 0) { $options['COUNT'] = $this->count; } return $options; } /** * Fetches a new set of elements from the remote collection, effectively * advancing the iteration process. * * @return array */ abstract protected function executeCommand(); /** * Populates the local buffer of elements fetched from the server during * the iteration. */ protected function fetch() { [$cursor, $elements] = $this->executeCommand(); if (!$cursor) { $this->fetchmore = false; } $this->cursor = $cursor; $this->elements = $elements; } /** * Extracts next values for key() and current(). */ protected function extractNext() { ++$this->position; $this->current = array_shift($this->elements); } /** * @return void */ #[ReturnTypeWillChange] public function rewind() { $this->reset(); $this->next(); } /** * @return mixed */ #[ReturnTypeWillChange] public function current() { return $this->current; } /** * @return int|null */ #[ReturnTypeWillChange] public function key() { return $this->position; } /** * @return void */ #[ReturnTypeWillChange] public function next() { tryFetch: if (!$this->elements && $this->fetchmore) { $this->fetch(); } if ($this->elements) { $this->extractNext(); } elseif ($this->cursor) { goto tryFetch; } else { $this->valid = false; } } /** * @return bool */ #[ReturnTypeWillChange] public function valid() { return $this->valid; } } PK)_]577src/PubSub/AbstractConsumer.phpnu[stop(true); } /** * Checks if the specified flag is valid based on the state of the consumer. * * @param int $value Flag. * * @return bool */ protected function isFlagSet($value) { return ($this->statusFlags & $value) === $value; } /** * Subscribes to the specified channels. * * @param string ...$channel One or more channel names. */ public function subscribe($channel /* , ... */) { $this->writeRequest(self::SUBSCRIBE, func_get_args()); $this->statusFlags |= self::STATUS_SUBSCRIBED; } /** * Unsubscribes from the specified channels. * * @param string ...$channel One or more channel names. */ public function unsubscribe(...$channel) { $this->writeRequest(self::UNSUBSCRIBE, func_get_args()); } /** * Subscribes to the specified channels using a pattern. * * @param string ...$pattern One or more channel name patterns. */ public function psubscribe(...$pattern) { $this->writeRequest(self::PSUBSCRIBE, func_get_args()); $this->statusFlags |= self::STATUS_PSUBSCRIBED; } /** * Unsubscribes from the specified channels using a pattern. * * @param string ...$pattern One or more channel name patterns. */ public function punsubscribe(...$pattern) { $this->writeRequest(self::PUNSUBSCRIBE, func_get_args()); } /** * PING the server with an optional payload that will be echoed as a * PONG message in the pub/sub loop. * * @param string $payload Optional PING payload. */ public function ping($payload = null) { $this->writeRequest('PING', [$payload]); } /** * Closes the context by unsubscribing from all the subscribed channels. The * context can be forcefully closed by dropping the underlying connection. * * @param bool $drop Indicates if the context should be closed by dropping the connection. * * @return bool Returns false when there are no pending messages. */ public function stop($drop = false) { if (!$this->valid()) { return false; } if ($drop) { $this->invalidate(); $this->disconnect(); } else { if ($this->isFlagSet(self::STATUS_SUBSCRIBED)) { $this->unsubscribe(); } if ($this->isFlagSet(self::STATUS_PSUBSCRIBED)) { $this->punsubscribe(); } } return !$drop; } /** * Closes the underlying connection when forcing a disconnection. */ abstract protected function disconnect(); /** * Writes a Redis command on the underlying connection. * * @param string $method Command ID. * @param array $arguments Arguments for the command. */ abstract protected function writeRequest($method, $arguments); /** * @return void */ #[ReturnTypeWillChange] public function rewind() { // NOOP } /** * Returns the last message payload retrieved from the server and generated * by one of the active subscriptions. * * @return array */ #[ReturnTypeWillChange] public function current() { return $this->getValue(); } /** * @return int|null */ #[ReturnTypeWillChange] public function key() { return $this->position; } /** * @return int|null */ #[ReturnTypeWillChange] public function next() { if ($this->valid()) { ++$this->position; } return $this->position; } /** * Checks if the the consumer is still in a valid state to continue. * * @return bool */ #[ReturnTypeWillChange] public function valid() { $isValid = $this->isFlagSet(self::STATUS_VALID); $subscriptionFlags = self::STATUS_SUBSCRIBED | self::STATUS_PSUBSCRIBED; $hasSubscriptions = ($this->statusFlags & $subscriptionFlags) > 0; return $isValid && $hasSubscriptions; } /** * Resets the state of the consumer. */ protected function invalidate() { $this->statusFlags = 0; // 0b0000; } /** * Waits for a new message from the server generated by one of the active * subscriptions and returns it when available. * * @return array */ abstract protected function getValue(); } PK)_]j~src/PubSub/DispatcherLoop.phpnu[callbacks = []; $this->pubsub = $pubsub; } /** * Checks if the passed argument is a valid callback. * * @param mixed $callable A callback. * * @throws InvalidArgumentException */ protected function assertCallback($callable) { if (!is_callable($callable)) { throw new InvalidArgumentException('The given argument must be a callable object.'); } } /** * Returns the underlying PUB / SUB context. * * @return Consumer */ public function getPubSubConsumer() { return $this->pubsub; } /** * Sets a callback that gets invoked upon new subscriptions. * * @param mixed $callable A callback. */ public function subscriptionCallback($callable = null) { if (isset($callable)) { $this->assertCallback($callable); } $this->subscriptionCallback = $callable; } /** * Sets a callback that gets invoked when a message is received on a * channel that does not have an associated callback. * * @param mixed $callable A callback. */ public function defaultCallback($callable = null) { if (isset($callable)) { $this->assertCallback($callable); } $this->subscriptionCallback = $callable; } /** * Binds a callback to a channel. * * @param string $channel Channel name. * @param callable $callback A callback. */ public function attachCallback($channel, $callback) { $callbackName = $this->getPrefixKeys() . $channel; $this->assertCallback($callback); $this->callbacks[$callbackName] = $callback; $this->pubsub->subscribe($channel); } /** * Stops listening to a channel and removes the associated callback. * * @param string $channel Redis channel. */ public function detachCallback($channel) { $callbackName = $this->getPrefixKeys() . $channel; if (isset($this->callbacks[$callbackName])) { unset($this->callbacks[$callbackName]); $this->pubsub->unsubscribe($channel); } } /** * Starts the dispatcher loop. */ public function run() { foreach ($this->pubsub as $message) { $kind = $message->kind; if ($kind !== Consumer::MESSAGE && $kind !== Consumer::PMESSAGE) { if (isset($this->subscriptionCallback)) { $callback = $this->subscriptionCallback; call_user_func($callback, $message, $this); } continue; } if (isset($this->callbacks[$message->channel])) { $callback = $this->callbacks[$message->channel]; call_user_func($callback, $message->payload, $this); } elseif (isset($this->defaultCallback)) { $callback = $this->defaultCallback; call_user_func($callback, $message, $this); } } } /** * Terminates the dispatcher loop. */ public function stop() { $this->pubsub->stop(); } /** * Return the prefix used for keys. * * @return string */ protected function getPrefixKeys() { $options = $this->pubsub->getClient()->getOptions(); if (isset($options->prefix)) { return $options->prefix->getPrefix(); } return ''; } } PK)_]U src/PubSub/RelayConsumer.phpnu[statusFlags |= self::STATUS_SUBSCRIBED; $command = $this->client->createCommand('subscribe', [ $channels, function ($relay, $channel, $message) use ($callback) { $callback((object) [ 'kind' => is_null($message) ? self::SUBSCRIBE : self::MESSAGE, 'channel' => $channel, 'payload' => $message, ], $relay); }, ]); $this->client->getConnection()->executeCommand($command); $this->invalidate(); } /** * Subscribes to the specified channels using a pattern. * * @param string ...$pattern One or more channel name patterns. * @param callable $callback The message callback. */ public function psubscribe(...$pattern) // @phpstan-ignore-line { $patterns = func_get_args(); $callback = array_pop($patterns); $this->statusFlags |= self::STATUS_PSUBSCRIBED; $command = $this->client->createCommand('psubscribe', [ $patterns, function ($relay, $pattern, $channel, $message) use ($callback) { $callback((object) [ 'kind' => is_null($message) ? self::PSUBSCRIBE : self::PMESSAGE, 'pattern' => $pattern, 'channel' => $channel, 'payload' => $message, ], $relay); }, ]); $this->client->getConnection()->executeCommand($command); $this->invalidate(); } /** * {@inheritDoc} */ protected function genericSubscribeInit($subscribeAction) { if (isset($this->options[$subscribeAction])) { throw new NotSupportedException('Relay does not support Pub/Sub constructor options.'); } } /** * {@inheritDoc} */ public function ping($payload = null) { throw new NotSupportedException('Relay does not support PING in Pub/Sub.'); } /** * {@inheritDoc} */ public function stop($drop = false) { return false; } /** * {@inheritDoc} */ public function __destruct() { // NOOP } } PK)_]k0src/PubSub/Consumer.phpnu[checkCapabilities($client); $this->options = $options ?: []; $this->client = $client; $this->genericSubscribeInit('subscribe'); $this->genericSubscribeInit('psubscribe'); } /** * Returns the underlying client instance used by the pub/sub iterator. * * @return ClientInterface */ public function getClient() { return $this->client; } /** * Checks if the client instance satisfies the required conditions needed to * initialize a PUB/SUB consumer. * * @param ClientInterface $client Client instance used by the consumer. * * @throws NotSupportedException */ protected function checkCapabilities(ClientInterface $client) { if ($client->getConnection() instanceof ClusterInterface) { throw new NotSupportedException( 'Cannot initialize a PUB/SUB consumer over cluster connections.' ); } $commands = ['publish', 'subscribe', 'unsubscribe', 'psubscribe', 'punsubscribe']; if (!$client->getCommandFactory()->supports(...$commands)) { throw new NotSupportedException( 'PUB/SUB commands are not supported by the current command factory.' ); } } /** * This method shares the logic to handle both SUBSCRIBE and PSUBSCRIBE. * * @param string $subscribeAction Type of subscription. */ protected function genericSubscribeInit($subscribeAction) { if (isset($this->options[$subscribeAction])) { $this->$subscribeAction($this->options[$subscribeAction]); } } /** * {@inheritdoc} */ protected function writeRequest($method, $arguments) { $this->client->getConnection()->writeRequest( $this->client->createCommand($method, Command::normalizeArguments($arguments) ) ); } /** * {@inheritdoc} */ protected function disconnect() { $this->client->disconnect(); } /** * {@inheritdoc} */ protected function getValue() { $response = $this->client->getConnection()->read(); switch ($response[0]) { case self::SUBSCRIBE: case self::UNSUBSCRIBE: case self::PSUBSCRIBE: case self::PUNSUBSCRIBE: if ($response[2] === 0) { $this->invalidate(); } // The missing break here is intentional as we must process // subscriptions and unsubscriptions as standard messages. // no break case self::MESSAGE: return (object) [ 'kind' => $response[0], 'channel' => $response[1], 'payload' => $response[2], ]; case self::PMESSAGE: return (object) [ 'kind' => $response[0], 'pattern' => $response[1], 'channel' => $response[2], 'payload' => $response[3], ]; case self::PONG: return (object) [ 'kind' => $response[0], 'payload' => $response[1], ]; default: throw new ClientException( "Unknown message type '{$response[0]}' received in the PUB/SUB context." ); } } } PK)_]c%!NN'src/Connection/Cluster/RedisCluster.phpnu[= 3.0.0). * * This connection backend offers smart support for redis-cluster by handling * automatic slots map (re)generation upon -MOVED or -ASK responses returned by * Redis when redirecting a client to a different node. * * The cluster can be pre-initialized using only a subset of the actual nodes in * the cluster, Predis will do the rest by adjusting the slots map and creating * the missing underlying connection instances on the fly. * * It is possible to pre-associate connections to a slots range with the "slots" * parameter in the form "$first-$last". This can greatly reduce runtime node * guessing and redirections. * * It is also possible to ask for the full and updated slots map directly to one * of the nodes and optionally enable such a behaviour upon -MOVED redirections. * Asking for the cluster configuration to Redis is actually done by issuing a * CLUSTER SLOTS command to a random node in the pool. */ class RedisCluster implements ClusterInterface, IteratorAggregate, Countable { private $useClusterSlots = true; private $pool = []; private $slots = []; private $slotmap; private $strategy; private $connections; private $retryLimit = 5; private $retryInterval = 10; /** * @param FactoryInterface $connections Optional connection factory. * @param StrategyInterface|null $strategy Optional cluster strategy. */ public function __construct( FactoryInterface $connections, ?StrategyInterface $strategy = null ) { $this->connections = $connections; $this->strategy = $strategy ?: new RedisClusterStrategy(); $this->slotmap = new SlotMap(); } /** * Sets the maximum number of retries for commands upon server failure. * * -1 = unlimited retry attempts * 0 = no retry attempts (fails immediately) * n = fail only after n retry attempts * * @param int $retry Number of retry attempts. */ public function setRetryLimit($retry) { $this->retryLimit = (int) $retry; } /** * Sets the initial retry interval (milliseconds). * * @param int $retryInterval Milliseconds between retries. */ public function setRetryInterval($retryInterval) { $this->retryInterval = (int) $retryInterval; } /** * Returns the retry interval (milliseconds). * * @return int Milliseconds between retries. */ public function getRetryInterval() { return (int) $this->retryInterval; } /** * {@inheritdoc} */ public function isConnected() { foreach ($this->pool as $connection) { if ($connection->isConnected()) { return true; } } return false; } /** * {@inheritdoc} */ public function connect() { if ($connection = $this->getRandomConnection()) { $connection->connect(); } } /** * {@inheritdoc} */ public function disconnect() { foreach ($this->pool as $connection) { $connection->disconnect(); } } /** * {@inheritdoc} */ public function add(NodeConnectionInterface $connection) { $this->pool[(string) $connection] = $connection; $this->slotmap->reset(); } /** * {@inheritdoc} */ public function remove(NodeConnectionInterface $connection) { if (false !== $id = array_search($connection, $this->pool, true)) { $this->slotmap->reset(); $this->slots = array_diff($this->slots, [$connection]); unset($this->pool[$id]); return true; } return false; } /** * Removes a connection instance by using its identifier. * * @param string $connectionID Connection identifier. * * @return bool True if the connection was in the pool. */ public function removeById($connectionID) { if (isset($this->pool[$connectionID])) { $this->slotmap->reset(); $this->slots = array_diff($this->slots, [$connectionID]); unset($this->pool[$connectionID]); return true; } return false; } /** * Generates the current slots map by guessing the cluster configuration out * of the connection parameters of the connections in the pool. * * Generation is based on the same algorithm used by Redis to generate the * cluster, so it is most effective when all of the connections supplied on * initialization have the "slots" parameter properly set accordingly to the * current cluster configuration. */ public function buildSlotMap() { $this->slotmap->reset(); foreach ($this->pool as $connectionID => $connection) { $parameters = $connection->getParameters(); if (!isset($parameters->slots)) { continue; } foreach (explode(',', $parameters->slots) as $slotRange) { $slots = explode('-', $slotRange, 2); if (!isset($slots[1])) { $slots[1] = $slots[0]; } $this->slotmap->setSlots($slots[0], $slots[1], $connectionID); } } } /** * Queries the specified node of the cluster to fetch the updated slots map. * * When the connection fails, this method tries to execute the same command * on a different connection picked at random from the pool of known nodes, * up until the retry limit is reached. * * @param NodeConnectionInterface $connection Connection to a node of the cluster. * * @return mixed */ private function queryClusterNodeForSlotMap(NodeConnectionInterface $connection) { $retries = 0; $retryAfter = $this->retryInterval; $command = RawCommand::create('CLUSTER', 'SLOTS'); while ($retries <= $this->retryLimit) { try { $response = $connection->executeCommand($command); break; } catch (ConnectionException $exception) { $connection = $exception->getConnection(); $connection->disconnect(); $this->remove($connection); if ($retries === $this->retryLimit) { throw $exception; } if (!$connection = $this->getRandomConnection()) { throw new ClientException('No connections left in the pool for `CLUSTER SLOTS`'); } usleep($retryAfter * 1000); $retryAfter *= 2; ++$retries; } } return $response; } /** * Generates an updated slots map fetching the cluster configuration using * the CLUSTER SLOTS command against the specified node or a random one from * the pool. * * @param NodeConnectionInterface|null $connection Optional connection instance. */ public function askSlotMap(?NodeConnectionInterface $connection = null) { if (!$connection && !$connection = $this->getRandomConnection()) { return; } $this->slotmap->reset(); $response = $this->queryClusterNodeForSlotMap($connection); foreach ($response as $slots) { // We only support master servers for now, so we ignore subsequent // elements in the $slots array identifying slaves. [$start, $end, $master] = $slots; if ($master[0] === '') { $this->slotmap->setSlots($start, $end, (string) $connection); } else { $this->slotmap->setSlots($start, $end, "{$master[0]}:{$master[1]}"); } } } /** * Guesses the correct node associated to a given slot using a precalculated * slots map, falling back to the same logic used by Redis to initialize a * cluster (best-effort). * * @param int $slot Slot index. * * @return string Connection ID. */ protected function guessNode($slot) { if (!$this->pool) { throw new ClientException('No connections available in the pool'); } if ($this->slotmap->isEmpty()) { $this->buildSlotMap(); } if ($node = $this->slotmap[$slot]) { return $node; } $count = count($this->pool); $index = min((int) ($slot / (int) (16384 / $count)), $count - 1); $nodes = array_keys($this->pool); return $nodes[$index]; } /** * Creates a new connection instance from the given connection ID. * * @param string $connectionID Identifier for the connection. * * @return NodeConnectionInterface */ protected function createConnection($connectionID) { $separator = strrpos($connectionID, ':'); return $this->connections->create([ 'host' => substr($connectionID, 0, $separator), 'port' => substr($connectionID, $separator + 1), ]); } /** * {@inheritdoc} */ public function getConnectionByCommand(CommandInterface $command) { $slot = $this->strategy->getSlot($command); if (!isset($slot)) { throw new NotSupportedException( "Cannot use '{$command->getId()}' with redis-cluster." ); } if (isset($this->slots[$slot])) { return $this->slots[$slot]; } else { return $this->getConnectionBySlot($slot); } } /** * Returns the connection currently associated to a given slot. * * @param int $slot Slot index. * * @return NodeConnectionInterface * @throws OutOfBoundsException */ public function getConnectionBySlot($slot) { if (!SlotMap::isValid($slot)) { throw new OutOfBoundsException("Invalid slot [$slot]."); } if (isset($this->slots[$slot])) { return $this->slots[$slot]; } $connectionID = $this->guessNode($slot); if (!$connection = $this->getConnectionById($connectionID)) { $connection = $this->createConnection($connectionID); $this->pool[$connectionID] = $connection; } return $this->slots[$slot] = $connection; } /** * {@inheritdoc} */ public function getConnectionById($connectionID) { return $this->pool[$connectionID] ?? null; } /** * Returns a random connection from the pool. * * @return NodeConnectionInterface|null */ protected function getRandomConnection() { if (!$this->pool) { return null; } return $this->pool[array_rand($this->pool)]; } /** * Permanently associates the connection instance to a new slot. * The connection is added to the connections pool if not yet included. * * @param NodeConnectionInterface $connection Connection instance. * @param int $slot Target slot index. */ protected function move(NodeConnectionInterface $connection, $slot) { $this->pool[(string) $connection] = $connection; $this->slots[(int) $slot] = $connection; $this->slotmap[(int) $slot] = $connection; } /** * Handles -ERR responses returned by Redis. * * @param CommandInterface $command Command that generated the -ERR response. * @param ErrorResponseInterface $error Redis error response object. * * @return mixed */ protected function onErrorResponse(CommandInterface $command, ErrorResponseInterface $error) { $details = explode(' ', $error->getMessage(), 2); switch ($details[0]) { case 'MOVED': return $this->onMovedResponse($command, $details[1]); case 'ASK': return $this->onAskResponse($command, $details[1]); default: return $error; } } /** * Handles -MOVED responses by executing again the command against the node * indicated by the Redis response. * * @param CommandInterface $command Command that generated the -MOVED response. * @param string $details Parameters of the -MOVED response. * * @return mixed */ protected function onMovedResponse(CommandInterface $command, $details) { [$slot, $connectionID] = explode(' ', $details, 2); // Handle connection ID in the form of "IP:port (details about exception)" // by trimming everything after first space (including the space) $startPositionOfExtraDetails = strpos($connectionID, ' '); if ($startPositionOfExtraDetails !== false) { $connectionID = substr($connectionID, 0, $startPositionOfExtraDetails); } if (!$connection = $this->getConnectionById($connectionID)) { $connection = $this->createConnection($connectionID); } if ($this->useClusterSlots) { $this->askSlotMap($connection); } $this->move($connection, $slot); return $this->executeCommand($command); } /** * Handles -ASK responses by executing again the command against the node * indicated by the Redis response. * * @param CommandInterface $command Command that generated the -ASK response. * @param string $details Parameters of the -ASK response. * * @return mixed */ protected function onAskResponse(CommandInterface $command, $details) { [$slot, $connectionID] = explode(' ', $details, 2); if (!$connection = $this->getConnectionById($connectionID)) { $connection = $this->createConnection($connectionID); } $connection->executeCommand(RawCommand::create('ASKING')); return $connection->executeCommand($command); } /** * Ensures that a command is executed one more time on connection failure. * * The connection to the node that generated the error is evicted from the * pool before trying to fetch an updated slots map from another node. If * the new slots map points to an unreachable server the client gives up and * throws the exception as the nodes participating in the cluster may still * have to agree that something changed in the configuration of the cluster. * * @param CommandInterface $command Command instance. * @param string $method Actual method. * * @return mixed */ private function retryCommandOnFailure(CommandInterface $command, $method) { $retries = 0; $retryAfter = $this->retryInterval; while ($retries <= $this->retryLimit) { try { $response = $this->getConnectionByCommand($command)->$method($command); if ($response instanceof ErrorResponse) { $message = $response->getMessage(); if (strpos($message, 'CLUSTERDOWN') !== false) { throw new ServerException($message); } } break; } catch (Throwable $exception) { usleep($retryAfter * 1000); $retryAfter *= 2; if ($exception instanceof ConnectionException) { $connection = $exception->getConnection(); if ($connection) { $connection->disconnect(); $this->remove($connection); } } if ($retries === $this->retryLimit) { throw $exception; } if ($this->useClusterSlots) { $this->askSlotMap(); } ++$retries; } } return $response; } /** * {@inheritdoc} */ public function writeRequest(CommandInterface $command) { $this->retryCommandOnFailure($command, __FUNCTION__); } /** * {@inheritdoc} */ public function readResponse(CommandInterface $command) { return $this->retryCommandOnFailure($command, __FUNCTION__); } /** * {@inheritdoc} */ public function executeCommand(CommandInterface $command) { $response = $this->retryCommandOnFailure($command, __FUNCTION__); if ($response instanceof ErrorResponseInterface) { return $this->onErrorResponse($command, $response); } return $response; } /** * @return int */ #[ReturnTypeWillChange] public function count() { return count($this->pool); } /** * @return Traversable */ #[ReturnTypeWillChange] public function getIterator() { if ($this->slotmap->isEmpty()) { $this->useClusterSlots ? $this->askSlotMap() : $this->buildSlotMap(); } $connections = []; foreach ($this->slotmap->getNodes() as $node) { if (!$connection = $this->getConnectionById($node)) { $this->add($connection = $this->createConnection($node)); } $connections[] = $connection; } return new ArrayIterator($connections); } /** * Returns the underlying slot map. * * @return SlotMap */ public function getSlotMap() { return $this->slotmap; } /** * Returns the underlying command hash strategy used to hash commands by * using keys found in their arguments. * * @return StrategyInterface */ public function getClusterStrategy() { return $this->strategy; } /** * Returns the underlying connection factory used to create new connection * instances to Redis nodes indicated by redis-cluster. * * @return FactoryInterface */ public function getConnectionFactory() { return $this->connections; } /** * Enables automatic fetching of the current slots map from one of the nodes * using the CLUSTER SLOTS command. This option is enabled by default as * asking the current slots map to Redis upon -MOVED responses may reduce * overhead by eliminating the trial-and-error nature of the node guessing * procedure, mostly when targeting many keys that would end up in a lot of * redirections. * * The slots map can still be manually fetched using the askSlotMap() * method whether or not this option is enabled. * * @param bool $value Enable or disable the use of CLUSTER SLOTS. */ public function useClusterSlots($value) { $this->useClusterSlots = (bool) $value; } } PK)_]+src/Connection/Cluster/ClusterInterface.phpnu[strategy = $strategy ?: new PredisStrategy(); $this->distributor = $this->strategy->getDistributor(); } /** * {@inheritdoc} */ public function isConnected() { foreach ($this->pool as $connection) { if ($connection->isConnected()) { return true; } } return false; } /** * {@inheritdoc} */ public function connect() { foreach ($this->pool as $connection) { $connection->connect(); } } /** * {@inheritdoc} */ public function disconnect() { foreach ($this->pool as $connection) { $connection->disconnect(); } } /** * {@inheritdoc} */ public function add(NodeConnectionInterface $connection) { $parameters = $connection->getParameters(); $this->pool[(string) $connection] = $connection; if (isset($parameters->alias)) { $this->aliases[$parameters->alias] = $connection; } $this->distributor->add($connection, $parameters->weight); } /** * {@inheritdoc} */ public function remove(NodeConnectionInterface $connection) { if (false !== $id = array_search($connection, $this->pool, true)) { unset($this->pool[$id]); $this->distributor->remove($connection); if ($this->aliases && $alias = $connection->getParameters()->alias) { unset($this->aliases[$alias]); } return true; } return false; } /** * {@inheritdoc} */ public function getConnectionByCommand(CommandInterface $command) { $slot = $this->strategy->getSlot($command); if (!isset($slot)) { throw new NotSupportedException( "Cannot use '{$command->getId()}' over clusters of connections." ); } return $this->distributor->getBySlot($slot); } /** * {@inheritdoc} */ public function getConnectionById($id) { return $this->pool[$id] ?? null; } /** * Returns a connection instance by its alias. * * @param string $alias Connection alias. * * @return NodeConnectionInterface|null */ public function getConnectionByAlias($alias) { return $this->aliases[$alias] ?? null; } /** * Retrieves a connection instance by slot. * * @param string $slot Slot name. * * @return NodeConnectionInterface|null */ public function getConnectionBySlot($slot) { return $this->distributor->getBySlot($slot); } /** * Retrieves a connection instance from the cluster using a key. * * @param string $key Key string. * * @return NodeConnectionInterface */ public function getConnectionByKey($key) { $hash = $this->strategy->getSlotByKey($key); return $this->distributor->getBySlot($hash); } /** * Returns the underlying command hash strategy used to hash commands by * using keys found in their arguments. * * @return StrategyInterface */ public function getClusterStrategy() { return $this->strategy; } /** * @return int */ #[ReturnTypeWillChange] public function count() { return count($this->pool); } /** * @return Traversable */ #[ReturnTypeWillChange] public function getIterator() { return new ArrayIterator($this->pool); } /** * {@inheritdoc} */ public function writeRequest(CommandInterface $command) { $this->getConnectionByCommand($command)->writeRequest($command); } /** * {@inheritdoc} */ public function readResponse(CommandInterface $command) { return $this->getConnectionByCommand($command)->readResponse($command); } /** * {@inheritdoc} */ public function executeCommand(CommandInterface $command) { return $this->getConnectionByCommand($command)->executeCommand($command); } } PK)_]i tRtR2src/Connection/Replication/SentinelReplication.phpnu[ * @author Ville Mattila */ class SentinelReplication implements ReplicationInterface { /** * @var NodeConnectionInterface */ protected $master; /** * @var NodeConnectionInterface[] */ protected $slaves = []; /** * @var NodeConnectionInterface[] */ protected $pool = []; /** * @var NodeConnectionInterface */ protected $current; /** * @var string */ protected $service; /** * @var ConnectionFactoryInterface */ protected $connectionFactory; /** * @var ReplicationStrategy */ protected $strategy; /** * @var NodeConnectionInterface[] */ protected $sentinels = []; /** * @var int */ protected $sentinelIndex = 0; /** * @var NodeConnectionInterface */ protected $sentinelConnection; /** * @var float */ protected $sentinelTimeout = 0.100; /** * Max number of automatic retries of commands upon server failure. * * -1 = unlimited retry attempts * 0 = no retry attempts (fails immediately) * n = fail only after n retry attempts * * @var int */ protected $retryLimit = 20; /** * Time to wait in milliseconds before fetching a new configuration from one * of the sentinel servers. * * @var int */ protected $retryWait = 1000; /** * Flag for automatic fetching of available sentinels. * * @var bool */ protected $updateSentinels = false; /** * @param string $service Name of the service for autodiscovery. * @param array $sentinels Sentinel servers connection parameters. * @param ConnectionFactoryInterface $connectionFactory Connection factory instance. * @param ReplicationStrategy|null $strategy Replication strategy instance. */ public function __construct( $service, array $sentinels, ConnectionFactoryInterface $connectionFactory, ?ReplicationStrategy $strategy = null ) { $this->sentinels = $sentinels; $this->service = $service; $this->connectionFactory = $connectionFactory; $this->strategy = $strategy ?: new ReplicationStrategy(); } /** * Sets a default timeout for connections to sentinels. * * When "timeout" is present in the connection parameters of sentinels, its * value overrides the default sentinel timeout. * * @param float $timeout Timeout value. */ public function setSentinelTimeout($timeout) { $this->sentinelTimeout = (float) $timeout; } /** * Sets the maximum number of retries for commands upon server failure. * * -1 = unlimited retry attempts * 0 = no retry attempts (fails immediately) * n = fail only after n retry attempts * * @param int $retry Number of retry attempts. */ public function setRetryLimit($retry) { $this->retryLimit = (int) $retry; } /** * Sets the time to wait (in milliseconds) before fetching a new configuration * from one of the sentinels. * * @param float $milliseconds Time to wait before the next attempt. */ public function setRetryWait($milliseconds) { $this->retryWait = (float) $milliseconds; } /** * Set automatic fetching of available sentinels. * * @param bool $update Enable or disable automatic updates. */ public function setUpdateSentinels($update) { $this->updateSentinels = (bool) $update; } /** * Resets the current connection. */ protected function reset() { $this->current = null; } /** * Wipes the current list of master and slaves nodes. */ protected function wipeServerList() { $this->reset(); $this->master = null; $this->slaves = []; $this->pool = []; } /** * {@inheritdoc} */ public function add(NodeConnectionInterface $connection) { $parameters = $connection->getParameters(); $role = $parameters->role; if ('master' === $role) { $this->master = $connection; } elseif ('sentinel' === $role) { $this->sentinels[] = $connection; // sentinels are not considered part of the pool. return; } else { // everything else is considered a slave. $this->slaves[] = $connection; } $this->pool[(string) $connection] = $connection; $this->reset(); } /** * {@inheritdoc} */ public function remove(NodeConnectionInterface $connection) { if ($connection === $this->master) { $this->master = null; } elseif (false !== $id = array_search($connection, $this->slaves, true)) { unset($this->slaves[$id]); } elseif (false !== $id = array_search($connection, $this->sentinels, true)) { unset($this->sentinels[$id]); return true; } else { return false; } unset($this->pool[(string) $connection]); $this->reset(); return true; } /** * Creates a new connection to a sentinel server. * * @return NodeConnectionInterface */ protected function createSentinelConnection($parameters) { if ($parameters instanceof NodeConnectionInterface) { return $parameters; } if (is_string($parameters)) { $parameters = Parameters::parse($parameters); } if (is_array($parameters)) { // NOTE: sentinels do not accept AUTH and SELECT commands so we must // explicitly set them to NULL to avoid problems when using default // parameters set via client options. Actually AUTH is supported for // sentinels starting with Redis 5 but we have to differentiate from // sentinels passwords and nodes passwords, this will be implemented // in a later release. $parameters['database'] = null; $parameters['username'] = null; // don't leak password from between configurations // https://github.com/predis/predis/pull/807/#discussion_r985764770 if (!isset($parameters['password'])) { $parameters['password'] = null; } if (!isset($parameters['timeout'])) { $parameters['timeout'] = $this->sentinelTimeout; } } return $this->connectionFactory->create($parameters); } /** * Returns the current sentinel connection. * * If there is no active sentinel connection, a new connection is created. * * @return NodeConnectionInterface */ public function getSentinelConnection() { if (!$this->sentinelConnection) { if ($this->sentinelIndex >= count($this->sentinels)) { $this->sentinelIndex = 0; throw new \Predis\ClientException('No sentinel server available for autodiscovery.'); } $sentinel = $this->sentinels[$this->sentinelIndex]; ++$this->sentinelIndex; $this->sentinelConnection = $this->createSentinelConnection($sentinel); } return $this->sentinelConnection; } /** * Fetches an updated list of sentinels from a sentinel. */ public function updateSentinels() { SENTINEL_QUERY: { $sentinel = $this->getSentinelConnection(); try { $payload = $sentinel->executeCommand( RawCommand::create('SENTINEL', 'sentinels', $this->service) ); $this->sentinels = []; $this->sentinelIndex = 0; // NOTE: sentinel server does not return itself, so we add it back. $this->sentinels[] = $sentinel->getParameters()->toArray(); foreach ($payload as $sentinel) { $this->sentinels[] = [ 'host' => $sentinel[3], 'port' => $sentinel[5], 'role' => 'sentinel', ]; } } catch (ConnectionException $exception) { $this->sentinelConnection = null; goto SENTINEL_QUERY; } } } /** * Fetches the details for the master and slave servers from a sentinel. */ public function querySentinel() { $this->wipeServerList(); $this->updateSentinels(); $this->getMaster(); $this->getSlaves(); } /** * Handles error responses returned by redis-sentinel. * * @param NodeConnectionInterface $sentinel Connection to a sentinel server. * @param ErrorResponseInterface $error Error response. */ private function handleSentinelErrorResponse(NodeConnectionInterface $sentinel, ErrorResponseInterface $error) { if ($error->getErrorType() === 'IDONTKNOW') { throw new ConnectionException($sentinel, $error->getMessage()); } else { throw new ServerException($error->getMessage()); } } /** * Fetches the details for the master server from a sentinel. * * @param NodeConnectionInterface $sentinel Connection to a sentinel server. * @param string $service Name of the service. * * @return array */ protected function querySentinelForMaster(NodeConnectionInterface $sentinel, $service) { $payload = $sentinel->executeCommand( RawCommand::create('SENTINEL', 'get-master-addr-by-name', $service) ); if ($payload === null) { throw new ServerException('ERR No such master with that name'); } if ($payload instanceof ErrorResponseInterface) { $this->handleSentinelErrorResponse($sentinel, $payload); } return [ 'host' => $payload[0], 'port' => $payload[1], 'role' => 'master', ]; } /** * Fetches the details for the slave servers from a sentinel. * * @param NodeConnectionInterface $sentinel Connection to a sentinel server. * @param string $service Name of the service. * * @return array */ protected function querySentinelForSlaves(NodeConnectionInterface $sentinel, $service) { $slaves = []; $payload = $sentinel->executeCommand( RawCommand::create('SENTINEL', 'slaves', $service) ); if ($payload instanceof ErrorResponseInterface) { $this->handleSentinelErrorResponse($sentinel, $payload); } foreach ($payload as $slave) { $flags = explode(',', $slave[9]); if (array_intersect($flags, ['s_down', 'o_down', 'disconnected'])) { continue; } // ensure `master-link-status` is ok if (isset($slave[31]) && $slave[31] === 'err') { continue; } $slaves[] = [ 'host' => $slave[3], 'port' => $slave[5], 'role' => 'slave', ]; } return $slaves; } /** * {@inheritdoc} */ public function getCurrent() { return $this->current; } /** * {@inheritdoc} */ public function getMaster() { if ($this->master) { return $this->master; } if ($this->updateSentinels) { $this->updateSentinels(); } SENTINEL_QUERY: { $sentinel = $this->getSentinelConnection(); try { $masterParameters = $this->querySentinelForMaster($sentinel, $this->service); $masterConnection = $this->connectionFactory->create($masterParameters); $this->add($masterConnection); } catch (ConnectionException $exception) { $this->sentinelConnection = null; goto SENTINEL_QUERY; } } return $masterConnection; } /** * {@inheritdoc} */ public function getSlaves() { if ($this->slaves) { return array_values($this->slaves); } if ($this->updateSentinels) { $this->updateSentinels(); } SENTINEL_QUERY: { $sentinel = $this->getSentinelConnection(); try { $slavesParameters = $this->querySentinelForSlaves($sentinel, $this->service); foreach ($slavesParameters as $slaveParameters) { $this->add($this->connectionFactory->create($slaveParameters)); } } catch (ConnectionException $exception) { $this->sentinelConnection = null; goto SENTINEL_QUERY; } } return array_values($this->slaves); } /** * Returns a random slave. * * @return NodeConnectionInterface|null */ protected function pickSlave() { $slaves = $this->getSlaves(); return $slaves ? $slaves[rand(1, count($slaves)) - 1] : null; } /** * Returns the connection instance in charge for the given command. * * @param CommandInterface $command Command instance. * * @return NodeConnectionInterface */ private function getConnectionInternal(CommandInterface $command) { if (!$this->current) { if ($this->strategy->isReadOperation($command) && $slave = $this->pickSlave()) { $this->current = $slave; } else { $this->current = $this->getMaster(); } return $this->current; } if ($this->current === $this->master) { return $this->current; } if (!$this->strategy->isReadOperation($command)) { $this->current = $this->getMaster(); } return $this->current; } /** * Asserts that the specified connection matches an expected role. * * @param NodeConnectionInterface $connection Connection to a redis server. * @param string $role Expected role of the server ("master", "slave" or "sentinel"). * * @throws RoleException|ConnectionException */ protected function assertConnectionRole(NodeConnectionInterface $connection, $role) { $role = strtolower($role); $actualRole = $connection->executeCommand(RawCommand::create('ROLE')); if ($actualRole instanceof Error) { throw new ConnectionException($connection, $actualRole->getMessage()); } if ($role !== $actualRole[0]) { throw new RoleException($connection, "Expected $role but got $actualRole[0] [$connection]"); } } /** * {@inheritdoc} */ public function getConnectionByCommand(CommandInterface $command) { $connection = $this->getConnectionInternal($command); if (!$connection->isConnected()) { // When we do not have any available slave in the pool we can expect // read-only operations to hit the master server. $expectedRole = $this->strategy->isReadOperation($command) && $this->slaves ? 'slave' : 'master'; $this->assertConnectionRole($connection, $expectedRole); } return $connection; } /** * {@inheritdoc} */ public function getConnectionById($id) { return $this->pool[$id] ?? null; } /** * Returns a connection by its role. * * @param string $role Connection role (`master`, `slave` or `sentinel`) * * @return NodeConnectionInterface|null */ public function getConnectionByRole($role) { if ($role === 'master') { return $this->getMaster(); } elseif ($role === 'slave') { return $this->pickSlave(); } elseif ($role === 'sentinel') { return $this->getSentinelConnection(); } else { return null; } } /** * Switches the internal connection in use by the backend. * * Sentinel connections are not considered as part of the pool, meaning that * trying to switch to a sentinel will throw an exception. * * @param NodeConnectionInterface $connection Connection instance in the pool. */ public function switchTo(NodeConnectionInterface $connection) { if ($connection && $connection === $this->current) { return; } if ($connection !== $this->master && !in_array($connection, $this->slaves, true)) { throw new InvalidArgumentException('Invalid connection or connection not found.'); } $connection->connect(); if ($this->current) { $this->current->disconnect(); } $this->current = $connection; } /** * {@inheritdoc} */ public function switchToMaster() { $connection = $this->getConnectionByRole('master'); $this->switchTo($connection); } /** * {@inheritdoc} */ public function switchToSlave() { $connection = $this->getConnectionByRole('slave'); $this->switchTo($connection); } /** * {@inheritdoc} */ public function isConnected() { return $this->current ? $this->current->isConnected() : false; } /** * {@inheritdoc} */ public function connect() { if (!$this->current) { if (!$this->current = $this->pickSlave()) { $this->current = $this->getMaster(); } } $this->current->connect(); } /** * {@inheritdoc} */ public function disconnect() { foreach ($this->pool as $connection) { $connection->disconnect(); } } /** * Retries the execution of a command upon server failure after asking a new * configuration to one of the sentinels. * * @param CommandInterface $command Command instance. * @param string $method Actual method. * * @return mixed */ private function retryCommandOnFailure(CommandInterface $command, $method) { $retries = 0; while ($retries <= $this->retryLimit) { try { $response = $this->getConnectionByCommand($command)->$method($command); break; } catch (CommunicationException $exception) { $this->wipeServerList(); $exception->getConnection()->disconnect(); if ($retries === $this->retryLimit) { throw $exception; } usleep($this->retryWait * 1000); ++$retries; } } return $response; } /** * {@inheritdoc} */ public function writeRequest(CommandInterface $command) { $this->retryCommandOnFailure($command, __FUNCTION__); } /** * {@inheritdoc} */ public function readResponse(CommandInterface $command) { return $this->retryCommandOnFailure($command, __FUNCTION__); } /** * {@inheritdoc} */ public function executeCommand(CommandInterface $command) { return $this->retryCommandOnFailure($command, __FUNCTION__); } /** * Returns the underlying replication strategy. * * @return ReplicationStrategy */ public function getReplicationStrategy() { return $this->strategy; } /** * {@inheritdoc} */ public function __sleep() { return [ 'master', 'slaves', 'pool', 'service', 'sentinels', 'connectionFactory', 'strategy', ]; } } PK)_]P(995src/Connection/Replication/MasterSlaveReplication.phpnu[strategy = $strategy ?: new ReplicationStrategy(); } /** * Configures the automatic discovery of the replication configuration on failure. * * @param bool $value Enable or disable auto discovery. */ public function setAutoDiscovery($value) { if (!$this->connectionFactory) { throw new ClientException('Automatic discovery requires a connection factory'); } $this->autoDiscovery = (bool) $value; } /** * Sets the connection factory used to create the connections by the auto * discovery procedure. * * @param FactoryInterface $connectionFactory Connection factory instance. */ public function setConnectionFactory(FactoryInterface $connectionFactory) { $this->connectionFactory = $connectionFactory; } /** * Resets the connection state. */ protected function reset() { $this->current = null; } /** * {@inheritdoc} */ public function add(NodeConnectionInterface $connection) { $parameters = $connection->getParameters(); if ('master' === $parameters->role) { $this->master = $connection; } else { // everything else is considered a slvave. $this->slaves[] = $connection; } if (isset($parameters->alias)) { $this->aliases[$parameters->alias] = $connection; } $this->pool[(string) $connection] = $connection; $this->reset(); } /** * {@inheritdoc} */ public function remove(NodeConnectionInterface $connection) { if ($connection === $this->master) { $this->master = null; } elseif (false !== $id = array_search($connection, $this->slaves, true)) { unset($this->slaves[$id]); } else { return false; } unset($this->pool[(string) $connection]); if ($this->aliases && $alias = $connection->getParameters()->alias) { unset($this->aliases[$alias]); } $this->reset(); return true; } /** * {@inheritdoc} */ public function getConnectionByCommand(CommandInterface $command) { if (!$this->current) { if ($this->strategy->isReadOperation($command) && $slave = $this->pickSlave()) { $this->current = $slave; } else { $this->current = $this->getMasterOrDie(); } return $this->current; } if ($this->current === $master = $this->getMasterOrDie()) { return $master; } if (!$this->strategy->isReadOperation($command) || !$this->slaves) { $this->current = $master; } return $this->current; } /** * {@inheritdoc} */ public function getConnectionById($id) { return $this->pool[$id] ?? null; } /** * Returns a connection instance by its alias. * * @param string $alias Connection alias. * * @return NodeConnectionInterface|null */ public function getConnectionByAlias($alias) { return $this->aliases[$alias] ?? null; } /** * Returns a connection by its role. * * @param string $role Connection role (`master` or `slave`) * * @return NodeConnectionInterface|null */ public function getConnectionByRole($role) { if ($role === 'master') { return $this->getMaster(); } elseif ($role === 'slave') { return $this->pickSlave(); } return null; } /** * Switches the internal connection in use by the backend. * * @param NodeConnectionInterface $connection Connection instance in the pool. */ public function switchTo(NodeConnectionInterface $connection) { if ($connection && $connection === $this->current) { return; } if ($connection !== $this->master && !in_array($connection, $this->slaves, true)) { throw new InvalidArgumentException('Invalid connection or connection not found.'); } $this->current = $connection; } /** * {@inheritdoc} */ public function switchToMaster() { if (!$connection = $this->getConnectionByRole('master')) { throw new InvalidArgumentException('Invalid connection or connection not found.'); } $this->switchTo($connection); } /** * {@inheritdoc} */ public function switchToSlave() { if (!$connection = $this->getConnectionByRole('slave')) { throw new InvalidArgumentException('Invalid connection or connection not found.'); } $this->switchTo($connection); } /** * {@inheritdoc} */ public function getCurrent() { return $this->current; } /** * {@inheritdoc} */ public function getMaster() { return $this->master; } /** * Returns the connection associated to the master server. * * @return NodeConnectionInterface */ private function getMasterOrDie() { if (!$connection = $this->getMaster()) { throw new MissingMasterException('No master server available for replication'); } return $connection; } /** * {@inheritdoc} */ public function getSlaves() { return $this->slaves; } /** * Returns the underlying replication strategy. * * @return ReplicationStrategy */ public function getReplicationStrategy() { return $this->strategy; } /** * Returns a random slave. * * @return NodeConnectionInterface|null */ protected function pickSlave() { if (!$this->slaves) { return null; } return $this->slaves[array_rand($this->slaves)]; } /** * {@inheritdoc} */ public function isConnected() { return $this->current ? $this->current->isConnected() : false; } /** * {@inheritdoc} */ public function connect() { if (!$this->current) { if (!$this->current = $this->pickSlave()) { if (!$this->current = $this->getMaster()) { throw new ClientException('No available connection for replication'); } } } $this->current->connect(); } /** * {@inheritdoc} */ public function disconnect() { foreach ($this->pool as $connection) { $connection->disconnect(); } } /** * Handles response from INFO. * * @param string $response * * @return array */ private function handleInfoResponse($response) { $info = []; foreach (preg_split('/\r?\n/', $response) as $row) { if (strpos($row, ':') === false) { continue; } [$k, $v] = explode(':', $row, 2); $info[$k] = $v; } return $info; } /** * Fetches the replication configuration from one of the servers. */ public function discover() { if (!$this->connectionFactory) { throw new ClientException('Discovery requires a connection factory'); } while (true) { try { if ($connection = $this->getMaster()) { $this->discoverFromMaster($connection, $this->connectionFactory); break; } elseif ($connection = $this->pickSlave()) { $this->discoverFromSlave($connection, $this->connectionFactory); break; } else { throw new ClientException('No connection available for discovery'); } } catch (ConnectionException $exception) { $this->remove($connection); } } } /** * Discovers the replication configuration by contacting the master node. * * @param NodeConnectionInterface $connection Connection to the master node. * @param FactoryInterface $connectionFactory Connection factory instance. */ protected function discoverFromMaster(NodeConnectionInterface $connection, FactoryInterface $connectionFactory) { $response = $connection->executeCommand(RawCommand::create('INFO', 'REPLICATION')); $replication = $this->handleInfoResponse($response); if ($replication['role'] !== 'master') { throw new ClientException("Role mismatch (expected master, got slave) [$connection]"); } $this->slaves = []; foreach ($replication as $k => $v) { $parameters = null; if (strpos($k, 'slave') === 0 && preg_match('/ip=(?P.*),port=(?P\d+)/', $v, $parameters)) { $slaveConnection = $connectionFactory->create([ 'host' => $parameters['host'], 'port' => $parameters['port'], 'role' => 'slave', ]); $this->add($slaveConnection); } } } /** * Discovers the replication configuration by contacting one of the slaves. * * @param NodeConnectionInterface $connection Connection to one of the slaves. * @param FactoryInterface $connectionFactory Connection factory instance. */ protected function discoverFromSlave(NodeConnectionInterface $connection, FactoryInterface $connectionFactory) { $response = $connection->executeCommand(RawCommand::create('INFO', 'REPLICATION')); $replication = $this->handleInfoResponse($response); if ($replication['role'] !== 'slave') { throw new ClientException("Role mismatch (expected slave, got master) [$connection]"); } $masterConnection = $connectionFactory->create([ 'host' => $replication['master_host'], 'port' => $replication['master_port'], 'role' => 'master', ]); $this->add($masterConnection); $this->discoverFromMaster($masterConnection, $connectionFactory); } /** * Retries the execution of a command upon slave failure. * * @param CommandInterface $command Command instance. * @param string $method Actual method. * * @return mixed */ private function retryCommandOnFailure(CommandInterface $command, $method) { while (true) { try { $connection = $this->getConnectionByCommand($command); $response = $connection->$method($command); if ($response instanceof ResponseErrorInterface && $response->getErrorType() === 'LOADING') { throw new ConnectionException($connection, "Redis is loading the dataset in memory [$connection]"); } break; } catch (ConnectionException $exception) { $connection = $exception->getConnection(); $connection->disconnect(); if ($connection === $this->master && !$this->autoDiscovery) { // Throw immediately when master connection is failing, even // when the command represents a read-only operation, unless // automatic discovery has been enabled. throw $exception; } else { // Otherwise remove the failing slave and attempt to execute // the command again on one of the remaining slaves... $this->remove($connection); } // ... that is, unless we have no more connections to use. if (!$this->slaves && !$this->master) { throw $exception; } elseif ($this->autoDiscovery) { $this->discover(); } } catch (MissingMasterException $exception) { if ($this->autoDiscovery) { $this->discover(); } else { throw $exception; } } } return $response; } /** * {@inheritdoc} */ public function writeRequest(CommandInterface $command) { $this->retryCommandOnFailure($command, __FUNCTION__); } /** * {@inheritdoc} */ public function readResponse(CommandInterface $command) { return $this->retryCommandOnFailure($command, __FUNCTION__); } /** * {@inheritdoc} */ public function executeCommand(CommandInterface $command) { return $this->retryCommandOnFailure($command, __FUNCTION__); } /** * {@inheritdoc} */ public function __sleep() { return ['master', 'slaves', 'pool', 'aliases', 'strategy']; } } PK)_]'o3src/Connection/Replication/ReplicationInterface.phpnu[parameters->persistent) && $this->parameters->persistent) { return; } $this->disconnect(); } /** * {@inheritdoc} */ protected function assertParameters(ParametersInterface $parameters) { switch ($parameters->scheme) { case 'tcp': case 'redis': case 'unix': case 'tls': case 'rediss': break; default: throw new InvalidArgumentException("Invalid scheme: '$parameters->scheme'."); } return $parameters; } /** * {@inheritdoc} */ protected function createResource() { switch ($this->parameters->scheme) { case 'tcp': case 'redis': return $this->tcpStreamInitializer($this->parameters); case 'unix': return $this->unixStreamInitializer($this->parameters); case 'tls': case 'rediss': return $this->tlsStreamInitializer($this->parameters); default: throw new InvalidArgumentException("Invalid scheme: '{$this->parameters->scheme}'."); } } /** * Creates a connected stream socket resource. * * @param ParametersInterface $parameters Connection parameters. * @param string $address Address for stream_socket_client(). * @param int $flags Flags for stream_socket_client(). * * @return resource */ protected function createStreamSocket(ParametersInterface $parameters, $address, $flags) { $timeout = (isset($parameters->timeout) ? (float) $parameters->timeout : 5.0); $context = stream_context_create(['socket' => ['tcp_nodelay' => (bool) $parameters->tcp_nodelay]]); if (!$resource = @stream_socket_client($address, $errno, $errstr, $timeout, $flags, $context)) { $this->onConnectionError(trim($errstr), $errno); } if (isset($parameters->read_write_timeout)) { $rwtimeout = (float) $parameters->read_write_timeout; $rwtimeout = $rwtimeout > 0 ? $rwtimeout : -1; $timeoutSeconds = floor($rwtimeout); $timeoutUSeconds = ($rwtimeout - $timeoutSeconds) * 1000000; stream_set_timeout($resource, $timeoutSeconds, $timeoutUSeconds); } return $resource; } /** * Initializes a TCP stream resource. * * @param ParametersInterface $parameters Initialization parameters for the connection. * * @return resource */ protected function tcpStreamInitializer(ParametersInterface $parameters) { if (!filter_var($parameters->host, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6)) { $address = "tcp://$parameters->host:$parameters->port"; } else { $address = "tcp://[$parameters->host]:$parameters->port"; } $flags = STREAM_CLIENT_CONNECT; if (isset($parameters->async_connect) && $parameters->async_connect) { $flags |= STREAM_CLIENT_ASYNC_CONNECT; } if (isset($parameters->persistent)) { if (false !== $persistent = filter_var($parameters->persistent, FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE)) { $flags |= STREAM_CLIENT_PERSISTENT; if ($persistent === null) { $address = "{$address}/{$parameters->persistent}"; } } } return $this->createStreamSocket($parameters, $address, $flags); } /** * Initializes a UNIX stream resource. * * @param ParametersInterface $parameters Initialization parameters for the connection. * * @return resource */ protected function unixStreamInitializer(ParametersInterface $parameters) { if (!isset($parameters->path)) { throw new InvalidArgumentException('Missing UNIX domain socket path.'); } $flags = STREAM_CLIENT_CONNECT; if (isset($parameters->persistent)) { if (false !== $persistent = filter_var($parameters->persistent, FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE)) { $flags |= STREAM_CLIENT_PERSISTENT; if ($persistent === null) { throw new InvalidArgumentException( 'Persistent connection IDs are not supported when using UNIX domain sockets.' ); } } } return $this->createStreamSocket($parameters, "unix://{$parameters->path}", $flags); } /** * Initializes a SSL-encrypted TCP stream resource. * * @param ParametersInterface $parameters Initialization parameters for the connection. * * @return resource */ protected function tlsStreamInitializer(ParametersInterface $parameters) { $resource = $this->tcpStreamInitializer($parameters); $metadata = stream_get_meta_data($resource); // Detect if crypto mode is already enabled for this stream (PHP >= 7.0.0). if (isset($metadata['crypto'])) { return $resource; } if (isset($parameters->ssl) && is_array($parameters->ssl)) { $options = $parameters->ssl; } else { $options = []; } if (!isset($options['crypto_type'])) { $options['crypto_type'] = STREAM_CRYPTO_METHOD_TLS_CLIENT; } if (!stream_context_set_option($resource, ['ssl' => $options])) { $this->onConnectionError('Error while setting SSL context options'); } if (!stream_socket_enable_crypto($resource, true, $options['crypto_type'])) { $this->onConnectionError('Error while switching to encrypted communication'); } return $resource; } /** * {@inheritdoc} */ public function connect() { if (parent::connect() && $this->initCommands) { foreach ($this->initCommands as $command) { $response = $this->executeCommand($command); if ($response instanceof ErrorResponseInterface && $command->getId() === 'CLIENT') { // Do nothing on CLIENT SETINFO command failure } elseif ($response instanceof ErrorResponseInterface) { $this->onConnectionError("`{$command->getId()}` failed: {$response->getMessage()}", 0); } } } } /** * {@inheritdoc} */ public function disconnect() { if ($this->isConnected()) { $resource = $this->getResource(); if (is_resource($resource)) { fclose($resource); } parent::disconnect(); } } /** * Performs a write operation over the stream of the buffer containing a * command serialized with the Redis wire protocol. * * @param string $buffer Representation of a command in the Redis wire protocol. */ protected function write($buffer) { $socket = $this->getResource(); while (($length = strlen($buffer)) > 0) { $written = is_resource($socket) ? @fwrite($socket, $buffer) : false; if ($length === $written) { return; } if ($written === false || $written === 0) { $this->onConnectionError('Error while writing bytes to the server.'); } $buffer = substr($buffer, $written); } } /** * {@inheritdoc} */ public function read() { $socket = $this->getResource(); $chunk = fgets($socket); if ($chunk === false || $chunk === '') { $this->onConnectionError('Error while reading line from the server.'); } $prefix = $chunk[0]; $payload = substr($chunk, 1, -2); switch ($prefix) { case '+': return StatusResponse::get($payload); case '$': $size = (int) $payload; if ($size === -1) { return; } $bulkData = ''; $bytesLeft = ($size += 2); do { $chunk = is_resource($socket) ? fread($socket, min($bytesLeft, 4096)) : false; if ($chunk === false || $chunk === '') { $this->onConnectionError('Error while reading bytes from the server.'); } $bulkData .= $chunk; $bytesLeft = $size - strlen($bulkData); } while ($bytesLeft > 0); return substr($bulkData, 0, -2); case '*': $count = (int) $payload; if ($count === -1) { return; } $multibulk = []; for ($i = 0; $i < $count; ++$i) { $multibulk[$i] = $this->read(); } return $multibulk; case ':': $integer = (int) $payload; return $integer == $payload ? $integer : $payload; case '-': return new ErrorResponse($payload); default: $this->onProtocolError("Unknown response prefix: '$prefix'."); return; } } /** * {@inheritdoc} */ public function writeRequest(CommandInterface $command) { $commandID = $command->getId(); $arguments = $command->getArguments(); $cmdlen = strlen($commandID); $reqlen = count($arguments) + 1; $buffer = "*{$reqlen}\r\n\${$cmdlen}\r\n{$commandID}\r\n"; foreach ($arguments as $argument) { $arglen = strlen(strval($argument)); $buffer .= "\${$arglen}\r\n{$argument}\r\n"; } $this->write($buffer); } } PK)_]!88,src/Connection/PhpiredisStreamConnection.phpnu[assertExtensions(); parent::__construct($parameters); $this->reader = $this->createReader(); } /** * {@inheritdoc} */ public function __destruct() { parent::__destruct(); phpiredis_reader_destroy($this->reader); } /** * {@inheritdoc} */ public function disconnect() { phpiredis_reader_reset($this->reader); parent::disconnect(); } /** * Checks if the phpiredis extension is loaded in PHP. */ private function assertExtensions() { if (!extension_loaded('phpiredis')) { throw new NotSupportedException( 'The "phpiredis" extension is required by this connection backend.' ); } } /** * {@inheritdoc} */ protected function assertParameters(ParametersInterface $parameters) { switch ($parameters->scheme) { case 'tcp': case 'redis': case 'unix': break; case 'tls': case 'rediss': throw new InvalidArgumentException('SSL encryption is not supported by this connection backend.'); default: throw new InvalidArgumentException("Invalid scheme: '$parameters->scheme'."); } return $parameters; } /** * {@inheritdoc} */ protected function createStreamSocket(ParametersInterface $parameters, $address, $flags) { $socket = null; $timeout = (isset($parameters->timeout) ? (float) $parameters->timeout : 5.0); $context = stream_context_create(['socket' => ['tcp_nodelay' => (bool) $parameters->tcp_nodelay]]); if (!$resource = @stream_socket_client($address, $errno, $errstr, $timeout, $flags, $context)) { $this->onConnectionError(trim($errstr), $errno); } if (isset($parameters->read_write_timeout) && function_exists('socket_import_stream')) { $rwtimeout = (float) $parameters->read_write_timeout; $rwtimeout = $rwtimeout > 0 ? $rwtimeout : -1; $timeout = [ 'sec' => $timeoutSeconds = floor($rwtimeout), 'usec' => ($rwtimeout - $timeoutSeconds) * 1000000, ]; $socket = $socket ?: socket_import_stream($resource); @socket_set_option($socket, SOL_SOCKET, SO_SNDTIMEO, $timeout); @socket_set_option($socket, SOL_SOCKET, SO_RCVTIMEO, $timeout); } if (isset($parameters->tcp_nodelay) && function_exists('socket_import_stream')) { $socket = $socket ?: socket_import_stream($resource); socket_set_option($socket, SOL_TCP, TCP_NODELAY, (int) $parameters->tcp_nodelay); } return $resource; } /** * Creates a new instance of the protocol reader resource. * * @return resource */ private function createReader() { $reader = phpiredis_reader_create(); phpiredis_reader_set_status_handler($reader, $this->getStatusHandler()); phpiredis_reader_set_error_handler($reader, $this->getErrorHandler()); return $reader; } /** * Returns the underlying protocol reader resource. * * @return resource */ protected function getReader() { return $this->reader; } /** * Returns the handler used by the protocol reader for inline responses. * * @return Closure */ protected function getStatusHandler() { static $statusHandler; if (!$statusHandler) { $statusHandler = function ($payload) { return StatusResponse::get($payload); }; } return $statusHandler; } /** * Returns the handler used by the protocol reader for error responses. * * @return Closure */ protected function getErrorHandler() { static $errorHandler; if (!$errorHandler) { $errorHandler = function ($errorMessage) { return new ErrorResponse($errorMessage); }; } return $errorHandler; } /** * {@inheritdoc} */ public function read() { $socket = $this->getResource(); $reader = $this->reader; while (PHPIREDIS_READER_STATE_INCOMPLETE === $state = phpiredis_reader_get_state($reader)) { $buffer = stream_socket_recvfrom($socket, 4096); if ($buffer === false || $buffer === '') { $this->onConnectionError('Error while reading bytes from the server.'); } phpiredis_reader_feed($reader, $buffer); } if ($state === PHPIREDIS_READER_STATE_COMPLETE) { return phpiredis_reader_get_reply($reader); } else { $this->onProtocolError(phpiredis_reader_get_error($reader)); return; } } /** * {@inheritdoc} */ public function writeRequest(CommandInterface $command) { $arguments = $command->getArguments(); array_unshift($arguments, $command->getId()); $this->write(phpiredis_format_command($arguments)); } /** * {@inheritdoc} */ public function __wakeup() { $this->assertExtensions(); $this->reader = $this->createReader(); } } PK)_]0&src/Connection/ConnectionException.phpnu[client->onFlushed($callback); } /** * Registers a new `invalidated` event listener. * * @param callable $callback * @param string|null $pattern * @return bool */ public function onInvalidated(?callable $callback, ?string $pattern = null) { return $this->client->onInvalidated($callback, $pattern); } /** * Dispatches all pending events. * * @return int|false */ public function dispatchEvents() { return $this->client->dispatchEvents(); } /** * Adds ignore pattern(s). Matching keys will not be cached in memory. * * @param string $pattern,... * @return int */ public function addIgnorePatterns(string ...$pattern) { return $this->client->addIgnorePatterns(...$pattern); } /** * Adds allow pattern(s). Only matching keys will be cached in memory. * * @param string $pattern,... * @return int */ public function addAllowPatterns(string ...$pattern) { return $this->client->addAllowPatterns(...$pattern); } /** * Returns the connection's endpoint identifier. * * @return string|false */ public function endpointId() { return $this->client->endpointId(); } /** * Returns a unique representation of the underlying socket connection identifier. * * @return string|false */ public function socketId() { return $this->client->socketId(); } /** * Returns information about the license. * * @return array */ public function license() { return $this->client->license(); } /** * Returns statistics about Relay. * * @return array> */ public function stats() { return $this->client->stats(); } /** * Returns the number of bytes allocated, or `0` in client-only mode. * * @return int */ public function maxMemory() { return $this->client->maxMemory(); } /** * Flushes Relay's in-memory cache of all databases. * When given an endpoint, only that connection will be flushed. * When given an endpoint and database index, only that database * for that connection will be flushed. * * @param ?string $endpointId * @param ?int $db * @return bool */ public function flushMemory(?string $endpointId = null, ?int $db = null) { return $this->client->flushMemory($endpointId, $db); } } PK)_]X:.:.,src/Connection/PhpiredisSocketConnection.phpnu[assertExtensions(); parent::__construct($parameters); $this->reader = $this->createReader(); } /** * Disconnects from the server and destroys the underlying resource and the * protocol reader resource when PHP's garbage collector kicks in. */ public function __destruct() { parent::__destruct(); phpiredis_reader_destroy($this->reader); } /** * Checks if the socket and phpiredis extensions are loaded in PHP. */ protected function assertExtensions() { if (!extension_loaded('sockets')) { throw new NotSupportedException( 'The "sockets" extension is required by this connection backend.' ); } if (!extension_loaded('phpiredis')) { throw new NotSupportedException( 'The "phpiredis" extension is required by this connection backend.' ); } } /** * {@inheritdoc} */ protected function assertParameters(ParametersInterface $parameters) { switch ($parameters->scheme) { case 'tcp': case 'redis': case 'unix': break; default: throw new InvalidArgumentException("Invalid scheme: '$parameters->scheme'."); } if (isset($parameters->persistent)) { throw new NotSupportedException( 'Persistent connections are not supported by this connection backend.' ); } return $parameters; } /** * Creates a new instance of the protocol reader resource. * * @return resource */ private function createReader() { $reader = phpiredis_reader_create(); phpiredis_reader_set_status_handler($reader, $this->getStatusHandler()); phpiredis_reader_set_error_handler($reader, $this->getErrorHandler()); return $reader; } /** * Returns the underlying protocol reader resource. * * @return resource */ protected function getReader() { return $this->reader; } /** * Returns the handler used by the protocol reader for inline responses. * * @return Closure */ protected function getStatusHandler() { static $statusHandler; if (!$statusHandler) { $statusHandler = function ($payload) { return StatusResponse::get($payload); }; } return $statusHandler; } /** * Returns the handler used by the protocol reader for error responses. * * @return Closure */ protected function getErrorHandler() { static $errorHandler; if (!$errorHandler) { $errorHandler = function ($errorMessage) { return new ErrorResponse($errorMessage); }; } return $errorHandler; } /** * Helper method used to throw exceptions on socket errors. */ private function emitSocketError() { $errno = socket_last_error(); $errstr = socket_strerror($errno); $this->disconnect(); $this->onConnectionError(trim($errstr), $errno); } /** * Gets the address of an host from connection parameters. * * @param ParametersInterface $parameters Parameters used to initialize the connection. * * @return string */ protected static function getAddress(ParametersInterface $parameters) { if (filter_var($host = $parameters->host, FILTER_VALIDATE_IP)) { return $host; } if ($host === $address = gethostbyname($host)) { return false; } return $address; } /** * {@inheritdoc} */ protected function createResource() { $parameters = $this->parameters; if ($parameters->scheme === 'unix') { $address = $parameters->path; $domain = AF_UNIX; $protocol = 0; } else { if (false === $address = self::getAddress($parameters)) { $this->onConnectionError("Cannot resolve the address of '$parameters->host'."); } $domain = filter_var($address, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6) ? AF_INET6 : AF_INET; $protocol = SOL_TCP; } if (false === $socket = @socket_create($domain, SOCK_STREAM, $protocol)) { $this->emitSocketError(); } $this->setSocketOptions($socket, $parameters); $this->connectWithTimeout($socket, $address, $parameters); return $socket; } /** * Sets options on the socket resource from the connection parameters. * * @param resource $socket Socket resource. * @param ParametersInterface $parameters Parameters used to initialize the connection. */ private function setSocketOptions($socket, ParametersInterface $parameters) { if ($parameters->scheme !== 'unix') { if (!socket_set_option($socket, SOL_TCP, TCP_NODELAY, 1)) { $this->emitSocketError(); } if (!socket_set_option($socket, SOL_SOCKET, SO_REUSEADDR, 1)) { $this->emitSocketError(); } } if (isset($parameters->read_write_timeout)) { $rwtimeout = (float) $parameters->read_write_timeout; $timeoutSec = floor($rwtimeout); $timeoutUsec = ($rwtimeout - $timeoutSec) * 1000000; $timeout = [ 'sec' => $timeoutSec, 'usec' => $timeoutUsec, ]; if (!socket_set_option($socket, SOL_SOCKET, SO_SNDTIMEO, $timeout)) { $this->emitSocketError(); } if (!socket_set_option($socket, SOL_SOCKET, SO_RCVTIMEO, $timeout)) { $this->emitSocketError(); } } } /** * Opens the actual connection to the server with a timeout. * * @param resource $socket Socket resource. * @param string $address IP address (DNS-resolved from hostname) * @param ParametersInterface $parameters Parameters used to initialize the connection. * * @return void */ private function connectWithTimeout($socket, $address, ParametersInterface $parameters) { socket_set_nonblock($socket); if (@socket_connect($socket, $address, (int) $parameters->port) === false) { $error = socket_last_error(); if ($error != SOCKET_EINPROGRESS && $error != SOCKET_EALREADY) { $this->emitSocketError(); } } socket_set_block($socket); $null = null; $selectable = [$socket]; $timeout = (isset($parameters->timeout) ? (float) $parameters->timeout : 5.0); $timeoutSecs = floor($timeout); $timeoutUSecs = ($timeout - $timeoutSecs) * 1000000; $selected = socket_select($selectable, $selectable, $null, $timeoutSecs, $timeoutUSecs); if ($selected === 2) { $this->onConnectionError('Connection refused.', SOCKET_ECONNREFUSED); } if ($selected === 0) { $this->onConnectionError('Connection timed out.', SOCKET_ETIMEDOUT); } if ($selected === false) { $this->emitSocketError(); } } /** * {@inheritdoc} */ public function connect() { if (parent::connect() && $this->initCommands) { foreach ($this->initCommands as $command) { $response = $this->executeCommand($command); if ($response instanceof ErrorResponseInterface) { $this->onConnectionError("`{$command->getId()}` failed: {$response->getMessage()}", 0); } } } } /** * {@inheritdoc} */ public function disconnect() { if ($this->isConnected()) { phpiredis_reader_reset($this->reader); socket_close($this->getResource()); parent::disconnect(); } } /** * {@inheritdoc} */ protected function write($buffer) { $socket = $this->getResource(); while (($length = strlen($buffer)) > 0) { $written = socket_write($socket, $buffer, $length); if ($length === $written) { return; } if ($written === false) { $this->onConnectionError('Error while writing bytes to the server.'); } $buffer = substr($buffer, $written); } } /** * {@inheritdoc} */ public function read() { $socket = $this->getResource(); $reader = $this->reader; while (PHPIREDIS_READER_STATE_INCOMPLETE === $state = phpiredis_reader_get_state($reader)) { if (@socket_recv($socket, $buffer, 4096, 0) === false || $buffer === '' || $buffer === null) { $this->emitSocketError(); } phpiredis_reader_feed($reader, $buffer); } if ($state === PHPIREDIS_READER_STATE_COMPLETE) { return phpiredis_reader_get_reply($reader); } else { $this->onProtocolError(phpiredis_reader_get_error($reader)); return; } } /** * {@inheritdoc} */ public function writeRequest(CommandInterface $command) { $arguments = $command->getArguments(); array_unshift($arguments, $command->getId()); $this->write(phpiredis_format_command($arguments)); } /** * {@inheritdoc} */ public function __wakeup() { $this->assertExtensions(); $this->reader = $this->createReader(); } } PK)_]fqЛ/src/Connection/CompositeConnectionInterface.phpnu[assertExtensions(); if ($parameters->scheme !== 'http') { throw new InvalidArgumentException("Invalid scheme: '{$parameters->scheme}'."); } $this->parameters = $parameters; $this->resource = $this->createCurl(); $this->reader = $this->createReader(); } /** * Frees the underlying cURL and protocol reader resources when the garbage * collector kicks in. */ public function __destruct() { curl_close($this->resource); phpiredis_reader_destroy($this->reader); } /** * Helper method used to throw on unsupported methods. * * @param string $method Name of the unsupported method. * * @throws NotSupportedException */ private function throwNotSupportedException($method) { $class = __CLASS__; throw new NotSupportedException("The method $class::$method() is not supported."); } /** * Checks if the cURL and phpiredis extensions are loaded in PHP. */ private function assertExtensions() { if (!extension_loaded('curl')) { throw new NotSupportedException( 'The "curl" extension is required by this connection backend.' ); } if (!extension_loaded('phpiredis')) { throw new NotSupportedException( 'The "phpiredis" extension is required by this connection backend.' ); } } /** * Initializes cURL. * * @return resource */ private function createCurl() { $parameters = $this->getParameters(); $timeout = (isset($parameters->timeout) ? (float) $parameters->timeout : 5.0) * 1000; if (filter_var($host = $parameters->host, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6)) { $host = "[$host]"; } $options = [ CURLOPT_FAILONERROR => true, CURLOPT_CONNECTTIMEOUT_MS => $timeout, CURLOPT_URL => "$parameters->scheme://$host:$parameters->port", CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_POST => true, CURLOPT_WRITEFUNCTION => [$this, 'feedReader'], ]; if (isset($parameters->user, $parameters->pass)) { $options[CURLOPT_USERPWD] = "{$parameters->user}:{$parameters->pass}"; } curl_setopt_array($resource = curl_init(), $options); return $resource; } /** * Initializes the phpiredis protocol reader. * * @return resource */ private function createReader() { $reader = phpiredis_reader_create(); phpiredis_reader_set_status_handler($reader, $this->getStatusHandler()); phpiredis_reader_set_error_handler($reader, $this->getErrorHandler()); return $reader; } /** * Returns the handler used by the protocol reader for inline responses. * * @return Closure */ protected function getStatusHandler() { static $statusHandler; if (!$statusHandler) { $statusHandler = function ($payload) { return StatusResponse::get($payload); }; } return $statusHandler; } /** * Returns the handler used by the protocol reader for error responses. * * @return Closure */ protected function getErrorHandler() { static $errorHandler; if (!$errorHandler) { $errorHandler = function ($errorMessage) { return new ErrorResponse($errorMessage); }; } return $errorHandler; } /** * Feeds the phpredis reader resource with the data read from the network. * * @param resource $resource Reader resource. * @param string $buffer Buffer of data read from a connection. * * @return int */ protected function feedReader($resource, $buffer) { phpiredis_reader_feed($this->reader, $buffer); return strlen($buffer); } /** * {@inheritdoc} */ public function connect() { // NOOP } /** * {@inheritdoc} */ public function disconnect() { // NOOP } /** * {@inheritdoc} */ public function isConnected() { return true; } /** * Checks if the specified command is supported by this connection class. * * @param CommandInterface $command Command instance. * * @return string * @throws NotSupportedException */ protected function getCommandId(CommandInterface $command) { switch ($commandID = $command->getId()) { case 'AUTH': case 'SELECT': case 'MULTI': case 'EXEC': case 'WATCH': case 'UNWATCH': case 'DISCARD': case 'MONITOR': throw new NotSupportedException("Command '$commandID' is not allowed by Webdis."); default: return $commandID; } } /** * {@inheritdoc} */ public function writeRequest(CommandInterface $command) { $this->throwNotSupportedException(__FUNCTION__); } /** * {@inheritdoc} */ public function readResponse(CommandInterface $command) { $this->throwNotSupportedException(__FUNCTION__); } /** * {@inheritdoc} */ public function executeCommand(CommandInterface $command) { $resource = $this->resource; $commandId = $this->getCommandId($command); if ($arguments = $command->getArguments()) { $arguments = implode('/', array_map('urlencode', $arguments)); $serializedCommand = "$commandId/$arguments.raw"; } else { $serializedCommand = "$commandId.raw"; } curl_setopt($resource, CURLOPT_POSTFIELDS, $serializedCommand); if (curl_exec($resource) === false) { $error = trim(curl_error($resource)); $errno = curl_errno($resource); throw new ConnectionException($this, "$error{$this->getParameters()}]", $errno); } if (phpiredis_reader_get_state($this->reader) !== PHPIREDIS_READER_STATE_COMPLETE) { throw new ProtocolException($this, phpiredis_reader_get_error($this->reader)); } return phpiredis_reader_get_reply($this->reader); } /** * {@inheritdoc} */ public function getResource() { return $this->resource; } /** * {@inheritdoc} */ public function getParameters() { return $this->parameters; } /** * {@inheritdoc} */ public function addConnectCommand(CommandInterface $command) { $this->throwNotSupportedException(__FUNCTION__); } /** * {@inheritdoc} */ public function read() { $this->throwNotSupportedException(__FUNCTION__); } /** * {@inheritdoc} */ public function __toString() { return "{$this->parameters->host}:{$this->parameters->port}"; } /** * {@inheritdoc} */ public function __sleep() { return ['parameters']; } /** * {@inheritdoc} */ public function __wakeup() { $this->assertExtensions(); $this->resource = $this->createCurl(); $this->reader = $this->createReader(); } } PK)_] j ,src/Connection/CompositeStreamConnection.phpnu[parameters = $this->assertParameters($parameters); $this->protocol = $protocol ?: new TextProtocolProcessor(); } /** * {@inheritdoc} */ public function getProtocol() { return $this->protocol; } /** * {@inheritdoc} */ public function writeBuffer($buffer) { $this->write($buffer); } /** * {@inheritdoc} */ public function readBuffer($length) { if ($length <= 0) { throw new InvalidArgumentException('Length parameter must be greater than 0.'); } $value = ''; $socket = $this->getResource(); do { $chunk = fread($socket, $length); if ($chunk === false || $chunk === '') { $this->onConnectionError('Error while reading bytes from the server.'); } $value .= $chunk; } while (($length -= strlen($chunk)) > 0); return $value; } /** * {@inheritdoc} */ public function readLine() { $value = ''; $socket = $this->getResource(); do { $chunk = fgets($socket); if ($chunk === false || $chunk === '') { $this->onConnectionError('Error while reading line from the server.'); } $value .= $chunk; } while (substr($value, -2) !== "\r\n"); return substr($value, 0, -2); } /** * {@inheritdoc} */ public function writeRequest(CommandInterface $command) { $this->protocol->write($this, $command); } /** * {@inheritdoc} */ public function read() { return $this->protocol->read($this); } /** * {@inheritdoc} */ public function __sleep() { return array_merge(parent::__sleep(), ['protocol']); } } PK)_]src/Connection/Factory.phpnu[ 'Predis\Connection\StreamConnection', 'unix' => 'Predis\Connection\StreamConnection', 'tls' => 'Predis\Connection\StreamConnection', 'redis' => 'Predis\Connection\StreamConnection', 'rediss' => 'Predis\Connection\StreamConnection', 'http' => 'Predis\Connection\WebdisConnection', ]; /** * Checks if the provided argument represents a valid connection class * implementing Predis\Connection\NodeConnectionInterface. Optionally, * callable objects are used for lazy initialization of connection objects. * * @param mixed $initializer FQN of a connection class or a callable for lazy initialization. * * @return mixed * @throws InvalidArgumentException */ protected function checkInitializer($initializer) { if (is_callable($initializer)) { return $initializer; } $class = new ReflectionClass($initializer); if (!$class->isSubclassOf('Predis\Connection\NodeConnectionInterface')) { throw new InvalidArgumentException( 'A connection initializer must be a valid connection class or a callable object.' ); } return $initializer; } /** * {@inheritdoc} */ public function define($scheme, $initializer) { $this->schemes[$scheme] = $this->checkInitializer($initializer); } /** * {@inheritdoc} */ public function undefine($scheme) { unset($this->schemes[$scheme]); } /** * {@inheritdoc} */ public function create($parameters) { if (!$parameters instanceof ParametersInterface) { $parameters = $this->createParameters($parameters); } $scheme = $parameters->scheme; if (!isset($this->schemes[$scheme])) { throw new InvalidArgumentException("Unknown connection scheme: '$scheme'."); } $initializer = $this->schemes[$scheme]; if (is_callable($initializer)) { $connection = call_user_func($initializer, $parameters, $this); } else { $connection = new $initializer($parameters); $this->prepareConnection($connection); } if (!$connection instanceof NodeConnectionInterface) { throw new UnexpectedValueException( 'Objects returned by connection initializers must implement ' . "'Predis\Connection\NodeConnectionInterface'." ); } return $connection; } /** * Assigns a default set of parameters applied to new connections. * * The set of parameters passed to create a new connection have precedence * over the default values set for the connection factory. * * @param array $parameters Set of connection parameters. */ public function setDefaultParameters(array $parameters) { $this->defaults = $parameters; } /** * Returns the default set of parameters applied to new connections. * * @return array */ public function getDefaultParameters() { return $this->defaults; } /** * Creates a connection parameters instance from the supplied argument. * * @param mixed $parameters Original connection parameters. * * @return ParametersInterface */ protected function createParameters($parameters) { if (is_string($parameters)) { $parameters = Parameters::parse($parameters); } else { $parameters = $parameters ?: []; } if ($this->defaults) { $parameters += $this->defaults; } return new Parameters($parameters); } /** * Prepares a connection instance after its initialization. * * @param NodeConnectionInterface $connection Connection instance. */ protected function prepareConnection(NodeConnectionInterface $connection) { $parameters = $connection->getParameters(); if (isset($parameters->password) && strlen($parameters->password)) { $cmdAuthArgs = isset($parameters->username) && strlen($parameters->username) ? [$parameters->username, $parameters->password] : [$parameters->password]; $connection->addConnectCommand( new RawCommand('AUTH', $cmdAuthArgs) ); } if (($parameters->client_info ?? false) && !$connection instanceof RelayConnection) { $connection->addConnectCommand( new RawCommand('CLIENT', ['SETINFO', 'LIB-NAME', 'predis']) ); $connection->addConnectCommand( new RawCommand('CLIENT', ['SETINFO', 'LIB-VER', Client::VERSION]) ); } if (isset($parameters->database) && strlen($parameters->database)) { $connection->addConnectCommand( new RawCommand('SELECT', [$parameters->database]) ); } } } PK)_]͑N""*src/Connection/NodeConnectionInterface.phpnu[assertExtensions(); $this->parameters = $this->assertParameters($parameters); $this->client = $this->createClient(); } /** * {@inheritdoc} */ public function isConnected() { return $this->client->isConnected(); } /** * {@inheritdoc} */ public function disconnect() { if ($this->client->isConnected()) { $this->client->close(); } } /** * Checks if the Relay extension is loaded in PHP. */ private function assertExtensions() { if (!extension_loaded('relay')) { throw new NotSupportedException( 'The "relay" extension is required by this connection backend.' ); } } /** * {@inheritdoc} */ protected function assertParameters(ParametersInterface $parameters) { if (!in_array($parameters->scheme, ['tcp', 'tls', 'unix', 'redis', 'rediss'])) { throw new InvalidArgumentException("Invalid scheme: '{$parameters->scheme}'."); } if (!in_array($parameters->serializer, [null, 'php', 'igbinary', 'msgpack', 'json'])) { throw new InvalidArgumentException("Invalid serializer: '{$parameters->serializer}'."); } if (!in_array($parameters->compression, [null, 'lzf', 'lz4', 'zstd'])) { throw new InvalidArgumentException("Invalid compression algorithm: '{$parameters->compression}'."); } return $parameters; } /** * Creates a new instance of the client. * * @return Relay */ private function createClient() { $client = new Relay(); // throw when errors occur and return `null` for non-existent keys $client->setOption(Relay::OPT_PHPREDIS_COMPATIBILITY, false); // use reply literals $client->setOption(Relay::OPT_REPLY_LITERAL, true); // disable Relay's command/connection retry $client->setOption(Relay::OPT_MAX_RETRIES, 0); // whether to use in-memory caching $client->setOption(Relay::OPT_USE_CACHE, $this->parameters->cache ?? true); // set data serializer $client->setOption(Relay::OPT_SERIALIZER, constant(sprintf( '%s::SERIALIZER_%s', Relay::class, strtoupper($this->parameters->serializer ?? 'none') ))); // set data compression algorithm $client->setOption(Relay::OPT_COMPRESSION, constant(sprintf( '%s::COMPRESSION_%s', Relay::class, strtoupper($this->parameters->compression ?? 'none') ))); return $client; } /** * Returns the underlying client. * * @return Relay */ public function getClient() { return $this->client; } /** * {@inheritdoc} */ public function getIdentifier() { try { return $this->client->endpointId(); } catch (RelayException $ex) { return parent::getIdentifier(); } } /** * {@inheritdoc} */ protected function createStreamSocket(ParametersInterface $parameters, $address, $flags) { $timeout = isset($parameters->timeout) ? (float) $parameters->timeout : 5.0; $retry_interval = 0; $read_timeout = 5.0; if (isset($parameters->read_write_timeout)) { $read_timeout = (float) $parameters->read_write_timeout; $read_timeout = $read_timeout > 0 ? $read_timeout : 0; } try { $this->client->connect( $parameters->path ?? $parameters->host, isset($parameters->path) ? 0 : $parameters->port, $timeout, null, $retry_interval, $read_timeout ); } catch (RelayException $ex) { $this->onConnectionError($ex->getMessage(), $ex->getCode()); } return $this->client; } /** * {@inheritdoc} */ public function executeCommand(CommandInterface $command) { if (!$this->client->isConnected()) { $this->getResource(); } try { $name = $command->getId(); // When using compression or a serializer, we'll need a dedicated // handler for `Predis\Command\RawCommand` calls, currently both // parameters are unsupported until a future Relay release return in_array($name, $this->atypicalCommands) ? $this->client->{$name}(...$command->getArguments()) : $this->client->rawCommand($name, ...$command->getArguments()); } catch (RelayException $ex) { $exception = $this->onCommandError($ex, $command); if ($exception instanceof ErrorResponseInterface) { return $exception; } throw $exception; } } /** * {@inheritdoc} */ public function onCommandError(RelayException $exception, CommandInterface $command) { $code = $exception->getCode(); $message = $exception->getMessage(); if (strpos($message, 'RELAY_ERR_IO') !== false) { return new ConnectionException($this, $message, $code, $exception); } if (strpos($message, 'RELAY_ERR_REDIS') !== false) { return new ServerException($message, $code, $exception); } if (strpos($message, 'RELAY_ERR_WRONGTYPE') !== false && strpos($message, "Got reply-type 'status'") !== false) { $message = 'Operation against a key holding the wrong kind of value'; } return new ClientException($message, $code, $exception); } /** * Applies the configured serializer and compression to given value. * * @param mixed $value * @return string */ public function pack($value) { return $this->client->_pack($value); } /** * Deserializes and decompresses to given value. * * @param mixed $value * @return string */ public function unpack($value) { return $this->client->_unpack($value); } /** * {@inheritdoc} */ public function writeRequest(CommandInterface $command) { throw new NotSupportedException('The "relay" extension does not support writing requests.'); } /** * {@inheritdoc} */ public function readResponse(CommandInterface $command) { throw new NotSupportedException('The "relay" extension does not support reading responses.'); } /** * {@inheritdoc} */ public function __destruct() { $this->disconnect(); } /** * {@inheritdoc} */ public function __wakeup() { $this->assertExtensions(); $this->client = $this->createClient(); } } PK)_]wD9osrc/Connection/Parameters.phpnu[ 'tcp', 'host' => '127.0.0.1', 'port' => 6379, ]; /** * Set of connection parameters already filtered * for NULL or 0-length string values. * * @var array */ protected $parameters; /** * @param array $parameters Named array of connection parameters. */ public function __construct(array $parameters = []) { $this->parameters = $this->filter($parameters + static::$defaults); } /** * Filters parameters removing entries with NULL or 0-length string values. * * @params array $parameters Array of parameters to be filtered * * @return array */ protected function filter(array $parameters) { return array_filter($parameters, function ($value) { return $value !== null && $value !== ''; }); } /** * Creates a new instance by supplying the initial parameters either in the * form of an URI string or a named array. * * @param array|string $parameters Set of connection parameters. * * @return Parameters */ public static function create($parameters) { if (is_string($parameters)) { $parameters = static::parse($parameters); } return new static($parameters ?: []); } /** * Parses an URI string returning an array of connection parameters. * * When using the "redis" and "rediss" schemes the URI is parsed according * to the rules defined by the provisional registration documents approved * by IANA. If the URI has a password in its "user-information" part or a * database number in the "path" part these values override the values of * "password" and "database" if they are present in the "query" part. * * @see http://www.iana.org/assignments/uri-schemes/prov/redis * @see http://www.iana.org/assignments/uri-schemes/prov/rediss * * @param string $uri URI string. * * @return array * @throws InvalidArgumentException */ public static function parse($uri) { if (stripos($uri, 'unix://') === 0) { // parse_url() can parse unix:/path/to/sock so we do not need the // unix:///path/to/sock hack, we will support it anyway until 2.0. $uri = str_ireplace('unix://', 'unix:', $uri); } if (!$parsed = parse_url($uri)) { throw new InvalidArgumentException("Invalid parameters URI: $uri"); } if ( isset($parsed['host']) && false !== strpos($parsed['host'], '[') && false !== strpos($parsed['host'], ']') ) { $parsed['host'] = substr($parsed['host'], 1, -1); } if (isset($parsed['query'])) { parse_str($parsed['query'], $queryarray); unset($parsed['query']); $parsed = array_merge($parsed, $queryarray); } if (stripos($uri, 'redis') === 0) { if (isset($parsed['user'])) { if (strlen($parsed['user'])) { $parsed['username'] = $parsed['user']; } unset($parsed['user']); } if (isset($parsed['pass'])) { if (strlen($parsed['pass'])) { $parsed['password'] = $parsed['pass']; } unset($parsed['pass']); } if (isset($parsed['path']) && preg_match('/^\/(\d+)(\/.*)?/', $parsed['path'], $path)) { $parsed['database'] = $path[1]; if (isset($path[2])) { $parsed['path'] = $path[2]; } else { unset($parsed['path']); } } } return $parsed; } /** * {@inheritdoc} */ public function toArray() { return $this->parameters; } /** * {@inheritdoc} */ public function __get($parameter) { if (isset($this->parameters[$parameter])) { return $this->parameters[$parameter]; } } /** * {@inheritdoc} */ public function __isset($parameter) { return isset($this->parameters[$parameter]); } /** * {@inheritdoc} */ public function __toString() { if ($this->scheme === 'unix') { return "$this->scheme:$this->path"; } if (filter_var($this->host, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6)) { return "$this->scheme://[$this->host]:$this->port"; } return "$this->scheme://$this->host:$this->port"; } /** * {@inheritdoc} */ public function __sleep() { return ['parameters']; } } PK)_]m %src/Connection/AbstractConnection.phpnu[parameters = $this->assertParameters($parameters); } /** * Disconnects from the server and destroys the underlying resource when * PHP's garbage collector kicks in. */ public function __destruct() { $this->disconnect(); } /** * Checks some of the parameters used to initialize the connection. * * @param ParametersInterface $parameters Initialization parameters for the connection. * * @return ParametersInterface * @throws InvalidArgumentException */ abstract protected function assertParameters(ParametersInterface $parameters); /** * Creates the underlying resource used to communicate with Redis. * * @return mixed */ abstract protected function createResource(); /** * {@inheritdoc} */ public function isConnected() { return isset($this->resource); } /** * {@inheritdoc} */ public function connect() { if (!$this->isConnected()) { $this->resource = $this->createResource(); return true; } return false; } /** * {@inheritdoc} */ public function disconnect() { unset($this->resource); } /** * {@inheritdoc} */ public function addConnectCommand(CommandInterface $command) { $this->initCommands[] = $command; } /** * {@inheritdoc} */ public function getInitCommands(): array { return $this->initCommands; } /** * {@inheritdoc} */ public function executeCommand(CommandInterface $command) { $this->writeRequest($command); return $this->readResponse($command); } /** * {@inheritdoc} */ public function readResponse(CommandInterface $command) { return $this->read(); } /** * Helper method to handle connection errors. * * @param string $message Error message. * @param int $code Error code. */ protected function onConnectionError($message, $code = 0) { CommunicationException::handle( new ConnectionException($this, "$message [{$this->getParameters()}]", $code) ); } /** * Helper method to handle protocol errors. * * @param string $message Error message. */ protected function onProtocolError($message) { CommunicationException::handle( new ProtocolException($this, "$message [{$this->getParameters()}]") ); } /** * {@inheritdoc} */ public function getResource() { if (isset($this->resource)) { return $this->resource; } $this->connect(); return $this->resource; } /** * {@inheritdoc} */ public function getParameters() { return $this->parameters; } /** * Gets an identifier for the connection. * * @return string */ protected function getIdentifier() { if ($this->parameters->scheme === 'unix') { return $this->parameters->path; } return "{$this->parameters->host}:{$this->parameters->port}"; } /** * {@inheritdoc} */ public function __toString() { if (!isset($this->cachedId)) { $this->cachedId = $this->getIdentifier(); } return $this->cachedId; } /** * {@inheritdoc} */ public function __sleep() { return ['parameters', 'initCommands']; } } PK)_]G.$$/src/Connection/AggregateConnectionInterface.phpnu[> 8) ^ ord($value[$i])]) & 0xFFFF; } return $crc; } } PK)_]nx#src/Cluster/Hash/PhpiredisCRC16.phpnu[ */ class HashRing implements DistributorInterface, HashGeneratorInterface { public const DEFAULT_REPLICAS = 128; public const DEFAULT_WEIGHT = 100; private $ring; private $ringKeys; private $ringKeysCount; private $replicas; private $nodeHashCallback; private $nodes = []; /** * @param int $replicas Number of replicas in the ring. * @param mixed $nodeHashCallback Callback returning a string used to calculate the hash of nodes. */ public function __construct($replicas = self::DEFAULT_REPLICAS, $nodeHashCallback = null) { $this->replicas = $replicas; $this->nodeHashCallback = $nodeHashCallback; } /** * Adds a node to the ring with an optional weight. * * @param mixed $node Node object. * @param int $weight Weight for the node. */ public function add($node, $weight = null) { // In case of collisions in the hashes of the nodes, the node added // last wins, thus the order in which nodes are added is significant. $this->nodes[] = [ 'object' => $node, 'weight' => (int) $weight ?: $this::DEFAULT_WEIGHT, ]; $this->reset(); } /** * {@inheritdoc} */ public function remove($node) { // A node is removed by resetting the ring so that it's recreated from // scratch, in order to reassign possible hashes with collisions to the // right node according to the order in which they were added in the // first place. for ($i = 0; $i < count($this->nodes); ++$i) { if ($this->nodes[$i]['object'] === $node) { array_splice($this->nodes, $i, 1); $this->reset(); break; } } } /** * Resets the distributor. */ private function reset() { unset( $this->ring, $this->ringKeys, $this->ringKeysCount ); } /** * Returns the initialization status of the distributor. * * @return bool */ private function isInitialized() { return isset($this->ringKeys); } /** * Calculates the total weight of all the nodes in the distributor. * * @return int */ private function computeTotalWeight() { $totalWeight = 0; foreach ($this->nodes as $node) { $totalWeight += $node['weight']; } return $totalWeight; } /** * Initializes the distributor. */ private function initialize() { if ($this->isInitialized()) { return; } if (!$this->nodes) { throw new EmptyRingException('Cannot initialize an empty hashring.'); } $this->ring = []; $totalWeight = $this->computeTotalWeight(); $nodesCount = count($this->nodes); foreach ($this->nodes as $node) { $weightRatio = $node['weight'] / $totalWeight; $this->addNodeToRing($this->ring, $node, $nodesCount, $this->replicas, $weightRatio); } ksort($this->ring, SORT_NUMERIC); $this->ringKeys = array_keys($this->ring); $this->ringKeysCount = count($this->ringKeys); } /** * Implements the logic needed to add a node to the hashring. * * @param array $ring Source hashring. * @param mixed $node Node object to be added. * @param int $totalNodes Total number of nodes. * @param int $replicas Number of replicas in the ring. * @param float $weightRatio Weight ratio for the node. */ protected function addNodeToRing(&$ring, $node, $totalNodes, $replicas, $weightRatio) { $nodeObject = $node['object']; $nodeHash = $this->getNodeHash($nodeObject); $replicas = (int) round($weightRatio * $totalNodes * $replicas); for ($i = 0; $i < $replicas; ++$i) { $key = $this->hash("$nodeHash:$i"); $ring[$key] = $nodeObject; } } /** * {@inheritdoc} */ protected function getNodeHash($nodeObject) { if (!isset($this->nodeHashCallback)) { return (string) $nodeObject; } return call_user_func($this->nodeHashCallback, $nodeObject); } /** * {@inheritdoc} */ public function hash($value) { return crc32($value); } /** * {@inheritdoc} */ public function getByHash($hash) { return $this->ring[$this->getSlot($hash)]; } /** * {@inheritdoc} */ public function getBySlot($slot) { $this->initialize(); if (isset($this->ring[$slot])) { return $this->ring[$slot]; } } /** * {@inheritdoc} */ public function getSlot($hash) { $this->initialize(); $ringKeys = $this->ringKeys; $upper = $this->ringKeysCount - 1; $lower = 0; while ($lower <= $upper) { $index = ($lower + $upper) >> 1; $item = $ringKeys[$index]; if ($item > $hash) { $upper = $index - 1; } elseif ($item < $hash) { $lower = $index + 1; } else { return $item; } } return $ringKeys[$this->wrapAroundStrategy($upper, $lower, $this->ringKeysCount)]; } /** * {@inheritdoc} */ public function get($value) { $hash = $this->hash($value); return $this->getByHash($hash); } /** * Implements a strategy to deal with wrap-around errors during binary searches. * * @param int $upper * @param int $lower * @param int $ringKeysCount * * @return int */ protected function wrapAroundStrategy($upper, $lower, $ringKeysCount) { // Binary search for the last item in ringkeys with a value less or // equal to the key. If no such item exists, return the last item. return $upper >= 0 ? $upper : $ringKeysCount - 1; } /** * {@inheritdoc} */ public function getHashGenerator() { return $this; } } PK)_];$$0src/Cluster/Distributor/DistributorInterface.phpnu[ */ class KetamaRing extends HashRing { public const DEFAULT_REPLICAS = 160; /** * @param mixed $nodeHashCallback Callback returning a string used to calculate the hash of nodes. */ public function __construct($nodeHashCallback = null) { parent::__construct($this::DEFAULT_REPLICAS, $nodeHashCallback); } /** * {@inheritdoc} */ protected function addNodeToRing(&$ring, $node, $totalNodes, $replicas, $weightRatio) { $nodeObject = $node['object']; $nodeHash = $this->getNodeHash($nodeObject); $replicas = (int) floor($weightRatio * $totalNodes * ($replicas / 4)); for ($i = 0; $i < $replicas; ++$i) { $unpackedDigest = unpack('V4', md5("$nodeHash-$i", true)); foreach ($unpackedDigest as $key) { $ring[$key] = $nodeObject; } } } /** * {@inheritdoc} */ public function hash($value) { $hash = unpack('V', md5($value, true)); return $hash[1]; } /** * {@inheritdoc} */ protected function wrapAroundStrategy($upper, $lower, $ringKeysCount) { // Binary search for the first item in ringkeys with a value greater // or equal to the key. If no such item exists, return the first item. return $lower < $ringKeysCount ? $lower : 0; } } PK)_].src/Cluster/Distributor/EmptyRingException.phpnu[distributor = $distributor ?: new HashRing(); } /** * {@inheritdoc} */ public function getSlotByKey($key) { $key = $this->extractKeyTag($key); $hash = $this->distributor->hash($key); return $this->distributor->getSlot($hash); } /** * {@inheritdoc} */ protected function checkSameSlotForKeys(array $keys) { if (!$count = count($keys)) { return false; } $currentKey = $this->extractKeyTag($keys[0]); for ($i = 1; $i < $count; ++$i) { $nextKey = $this->extractKeyTag($keys[$i]); if ($currentKey !== $nextKey) { return false; } $currentKey = $nextKey; } return true; } /** * {@inheritdoc} */ public function getDistributor() { return $this->distributor; } } PK)_]/^ = =src/Cluster/ClusterStrategy.phpnu[commands = $this->getDefaultCommands(); } /** * Returns the default map of supported commands with their handlers. * * @return array */ protected function getDefaultCommands() { $getKeyFromFirstArgument = [$this, 'getKeyFromFirstArgument']; $getKeyFromAllArguments = [$this, 'getKeyFromAllArguments']; return [ /* commands operating on the key space */ 'EXISTS' => $getKeyFromAllArguments, 'DEL' => $getKeyFromAllArguments, 'TYPE' => $getKeyFromFirstArgument, 'EXPIRE' => $getKeyFromFirstArgument, 'EXPIREAT' => $getKeyFromFirstArgument, 'PERSIST' => $getKeyFromFirstArgument, 'PEXPIRE' => $getKeyFromFirstArgument, 'PEXPIREAT' => $getKeyFromFirstArgument, 'TTL' => $getKeyFromFirstArgument, 'PTTL' => $getKeyFromFirstArgument, 'SORT' => [$this, 'getKeyFromSortCommand'], 'DUMP' => $getKeyFromFirstArgument, 'RESTORE' => $getKeyFromFirstArgument, 'FLUSHDB' => [$this, 'getFakeKey'], /* commands operating on string values */ 'APPEND' => $getKeyFromFirstArgument, 'DECR' => $getKeyFromFirstArgument, 'DECRBY' => $getKeyFromFirstArgument, 'GET' => $getKeyFromFirstArgument, 'GETBIT' => $getKeyFromFirstArgument, 'MGET' => $getKeyFromAllArguments, 'SET' => $getKeyFromFirstArgument, 'GETRANGE' => $getKeyFromFirstArgument, 'GETSET' => $getKeyFromFirstArgument, 'INCR' => $getKeyFromFirstArgument, 'INCRBY' => $getKeyFromFirstArgument, 'INCRBYFLOAT' => $getKeyFromFirstArgument, 'SETBIT' => $getKeyFromFirstArgument, 'SETEX' => $getKeyFromFirstArgument, 'MSET' => [$this, 'getKeyFromInterleavedArguments'], 'MSETNX' => [$this, 'getKeyFromInterleavedArguments'], 'SETNX' => $getKeyFromFirstArgument, 'SETRANGE' => $getKeyFromFirstArgument, 'STRLEN' => $getKeyFromFirstArgument, 'SUBSTR' => $getKeyFromFirstArgument, 'BITOP' => [$this, 'getKeyFromBitOp'], 'BITCOUNT' => $getKeyFromFirstArgument, 'BITFIELD' => $getKeyFromFirstArgument, /* commands operating on lists */ 'LINSERT' => $getKeyFromFirstArgument, 'LINDEX' => $getKeyFromFirstArgument, 'LLEN' => $getKeyFromFirstArgument, 'LPOP' => $getKeyFromFirstArgument, 'RPOP' => $getKeyFromFirstArgument, 'RPOPLPUSH' => $getKeyFromAllArguments, 'BLPOP' => [$this, 'getKeyFromBlockingListCommands'], 'BRPOP' => [$this, 'getKeyFromBlockingListCommands'], 'BRPOPLPUSH' => [$this, 'getKeyFromBlockingListCommands'], 'LPUSH' => $getKeyFromFirstArgument, 'LPUSHX' => $getKeyFromFirstArgument, 'RPUSH' => $getKeyFromFirstArgument, 'RPUSHX' => $getKeyFromFirstArgument, 'LRANGE' => $getKeyFromFirstArgument, 'LREM' => $getKeyFromFirstArgument, 'LSET' => $getKeyFromFirstArgument, 'LTRIM' => $getKeyFromFirstArgument, /* commands operating on sets */ 'SADD' => $getKeyFromFirstArgument, 'SCARD' => $getKeyFromFirstArgument, 'SDIFF' => $getKeyFromAllArguments, 'SDIFFSTORE' => $getKeyFromAllArguments, 'SINTER' => $getKeyFromAllArguments, 'SINTERSTORE' => $getKeyFromAllArguments, 'SUNION' => $getKeyFromAllArguments, 'SUNIONSTORE' => $getKeyFromAllArguments, 'SISMEMBER' => $getKeyFromFirstArgument, 'SMEMBERS' => $getKeyFromFirstArgument, 'SSCAN' => $getKeyFromFirstArgument, 'SPOP' => $getKeyFromFirstArgument, 'SRANDMEMBER' => $getKeyFromFirstArgument, 'SREM' => $getKeyFromFirstArgument, /* commands operating on sorted sets */ 'ZADD' => $getKeyFromFirstArgument, 'ZCARD' => $getKeyFromFirstArgument, 'ZCOUNT' => $getKeyFromFirstArgument, 'ZINCRBY' => $getKeyFromFirstArgument, 'ZINTERSTORE' => [$this, 'getKeyFromZsetAggregationCommands'], 'ZRANGE' => $getKeyFromFirstArgument, 'ZRANGEBYSCORE' => $getKeyFromFirstArgument, 'ZRANK' => $getKeyFromFirstArgument, 'ZREM' => $getKeyFromFirstArgument, 'ZREMRANGEBYRANK' => $getKeyFromFirstArgument, 'ZREMRANGEBYSCORE' => $getKeyFromFirstArgument, 'ZREVRANGE' => $getKeyFromFirstArgument, 'ZREVRANGEBYSCORE' => $getKeyFromFirstArgument, 'ZREVRANK' => $getKeyFromFirstArgument, 'ZSCORE' => $getKeyFromFirstArgument, 'ZUNIONSTORE' => [$this, 'getKeyFromZsetAggregationCommands'], 'ZSCAN' => $getKeyFromFirstArgument, 'ZLEXCOUNT' => $getKeyFromFirstArgument, 'ZRANGEBYLEX' => $getKeyFromFirstArgument, 'ZREMRANGEBYLEX' => $getKeyFromFirstArgument, 'ZREVRANGEBYLEX' => $getKeyFromFirstArgument, /* commands operating on hashes */ 'HDEL' => $getKeyFromFirstArgument, 'HEXISTS' => $getKeyFromFirstArgument, 'HGET' => $getKeyFromFirstArgument, 'HGETALL' => $getKeyFromFirstArgument, 'HMGET' => $getKeyFromFirstArgument, 'HMSET' => $getKeyFromFirstArgument, 'HINCRBY' => $getKeyFromFirstArgument, 'HINCRBYFLOAT' => $getKeyFromFirstArgument, 'HKEYS' => $getKeyFromFirstArgument, 'HLEN' => $getKeyFromFirstArgument, 'HSET' => $getKeyFromFirstArgument, 'HSETNX' => $getKeyFromFirstArgument, 'HVALS' => $getKeyFromFirstArgument, 'HSCAN' => $getKeyFromFirstArgument, 'HSTRLEN' => $getKeyFromFirstArgument, /* commands operating on HyperLogLog */ 'PFADD' => $getKeyFromFirstArgument, 'PFCOUNT' => $getKeyFromAllArguments, 'PFMERGE' => $getKeyFromAllArguments, /* scripting */ 'EVAL' => [$this, 'getKeyFromScriptingCommands'], 'EVALSHA' => [$this, 'getKeyFromScriptingCommands'], /* server */ 'INFO' => [$this, 'getFakeKey'], /* commands performing geospatial operations */ 'GEOADD' => $getKeyFromFirstArgument, 'GEOHASH' => $getKeyFromFirstArgument, 'GEOPOS' => $getKeyFromFirstArgument, 'GEODIST' => $getKeyFromFirstArgument, 'GEORADIUS' => [$this, 'getKeyFromGeoradiusCommands'], 'GEORADIUSBYMEMBER' => [$this, 'getKeyFromGeoradiusCommands'], /* cluster */ 'CLUSTER' => [$this, 'getFakeKey'], ]; } /** * Returns the list of IDs for the supported commands. * * @return array */ public function getSupportedCommands() { return array_keys($this->commands); } /** * Sets an handler for the specified command ID. * * The signature of the callback must have a single parameter of type * Predis\Command\CommandInterface. * * When the callback argument is omitted or NULL, the previously associated * handler for the specified command ID is removed. * * @param string $commandID Command ID. * @param mixed $callback A valid callable object, or NULL to unset the handler. * * @throws InvalidArgumentException */ public function setCommandHandler($commandID, $callback = null) { $commandID = strtoupper($commandID); if (!isset($callback)) { unset($this->commands[$commandID]); return; } if (!is_callable($callback)) { throw new InvalidArgumentException( 'The argument must be a callable object or NULL.' ); } $this->commands[$commandID] = $callback; } /** * Get fake key for commands with no key argument. * * @return string */ protected function getFakeKey(): string { return 'key'; } /** * Extracts the key from the first argument of a command instance. * * @param CommandInterface $command Command instance. * * @return string */ protected function getKeyFromFirstArgument(CommandInterface $command) { return $command->getArgument(0); } /** * Extracts the key from a command with multiple keys only when all keys in * the arguments array produce the same hash. * * @param CommandInterface $command Command instance. * * @return string|null */ protected function getKeyFromAllArguments(CommandInterface $command) { $arguments = $command->getArguments(); if (!$this->checkSameSlotForKeys($arguments)) { return null; } return $arguments[0]; } /** * Extracts the key from a command with multiple keys only when all keys in * the arguments array produce the same hash. * * @param CommandInterface $command Command instance. * * @return string|null */ protected function getKeyFromInterleavedArguments(CommandInterface $command) { $arguments = $command->getArguments(); $keys = []; for ($i = 0; $i < count($arguments); $i += 2) { $keys[] = $arguments[$i]; } if (!$this->checkSameSlotForKeys($keys)) { return null; } return $arguments[0]; } /** * Extracts the key from SORT command. * * @param CommandInterface $command Command instance. * * @return string|null */ protected function getKeyFromSortCommand(CommandInterface $command) { $arguments = $command->getArguments(); $firstKey = $arguments[0]; if (1 === $argc = count($arguments)) { return $firstKey; } $keys = [$firstKey]; for ($i = 1; $i < $argc; ++$i) { if (strtoupper($arguments[$i]) === 'STORE') { $keys[] = $arguments[++$i]; } } if (!$this->checkSameSlotForKeys($keys)) { return null; } return $firstKey; } /** * Extracts the key from BLPOP and BRPOP commands. * * @param CommandInterface $command Command instance. * * @return string|null */ protected function getKeyFromBlockingListCommands(CommandInterface $command) { $arguments = $command->getArguments(); if (!$this->checkSameSlotForKeys(array_slice($arguments, 0, count($arguments) - 1))) { return null; } return $arguments[0]; } /** * Extracts the key from BITOP command. * * @param CommandInterface $command Command instance. * * @return string|null */ protected function getKeyFromBitOp(CommandInterface $command) { $arguments = $command->getArguments(); if (!$this->checkSameSlotForKeys(array_slice($arguments, 1, count($arguments)))) { return null; } return $arguments[1]; } /** * Extracts the key from GEORADIUS and GEORADIUSBYMEMBER commands. * * @param CommandInterface $command Command instance. * * @return string|null */ protected function getKeyFromGeoradiusCommands(CommandInterface $command) { $arguments = $command->getArguments(); $argc = count($arguments); $startIndex = $command->getId() === 'GEORADIUS' ? 5 : 4; if ($argc > $startIndex) { $keys = [$arguments[0]]; for ($i = $startIndex; $i < $argc; ++$i) { $argument = strtoupper($arguments[$i]); if ($argument === 'STORE' || $argument === 'STOREDIST') { $keys[] = $arguments[++$i]; } } if (!$this->checkSameSlotForKeys($keys)) { return null; } } return $arguments[0]; } /** * Extracts the key from ZINTERSTORE and ZUNIONSTORE commands. * * @param CommandInterface $command Command instance. * * @return string|null */ protected function getKeyFromZsetAggregationCommands(CommandInterface $command) { $arguments = $command->getArguments(); $keys = array_merge([$arguments[0]], array_slice($arguments, 2, $arguments[1])); if (!$this->checkSameSlotForKeys($keys)) { return null; } return $arguments[0]; } /** * Extracts the key from EVAL and EVALSHA commands. * * @param CommandInterface $command Command instance. * * @return string|null */ protected function getKeyFromScriptingCommands(CommandInterface $command) { $keys = $command instanceof ScriptCommand ? $command->getKeys() : array_slice($args = $command->getArguments(), 2, $args[1]); if (!$keys || !$this->checkSameSlotForKeys($keys)) { return null; } return $keys[0]; } /** * {@inheritdoc} */ public function getSlot(CommandInterface $command) { $slot = $command->getSlot(); if (!isset($slot) && isset($this->commands[$cmdID = $command->getId()])) { $key = call_user_func($this->commands[$cmdID], $command); if (isset($key)) { $slot = $this->getSlotByKey($key); $command->setSlot($slot); } } return $slot; } /** * Checks if the specified array of keys will generate the same hash. * * @param array $keys Array of keys. * * @return bool */ protected function checkSameSlotForKeys(array $keys) { if (!$count = count($keys)) { return false; } $currentSlot = $this->getSlotByKey($keys[0]); for ($i = 1; $i < $count; ++$i) { $nextSlot = $this->getSlotByKey($keys[$i]); if ($currentSlot !== $nextSlot) { return false; } $currentSlot = $nextSlot; } return true; } /** * Returns only the hashable part of a key (delimited by "{...}"), or the * whole key if a key tag is not found in the string. * * @param string $key A key. * * @return string */ protected function extractKeyTag($key) { if (false !== $start = strpos($key, '{')) { if (false !== ($end = strpos($key, '}', $start)) && $end !== ++$start) { $key = substr($key, $start, $end - $start); } } return $key; } } PK)_])=  src/Cluster/SlotMap.phpnu[= 0x0000 && $slot <= 0x3FFF; } /** * Checks if the given slot range is valid. * * @param int $first Initial slot of the range. * @param int $last Last slot of the range. * * @return bool */ public static function isValidRange($first, $last) { return $first >= 0x0000 && $first <= 0x3FFF && $last >= 0x0000 && $last <= 0x3FFF && $first <= $last; } /** * Resets the slot map. */ public function reset() { $this->slots = []; } /** * Checks if the slot map is empty. * * @return bool */ public function isEmpty() { return empty($this->slots); } /** * Returns the current slot map as a dictionary of $slot => $node. * * The order of the slots in the dictionary is not guaranteed. * * @return array */ public function toArray() { return $this->slots; } /** * Returns the list of unique nodes in the slot map. * * @return array */ public function getNodes() { return array_keys(array_flip($this->slots)); } /** * Assigns the specified slot range to a node. * * @param int $first Initial slot of the range. * @param int $last Last slot of the range. * @param NodeConnectionInterface|string $connection ID or connection instance. * * @throws OutOfBoundsException */ public function setSlots($first, $last, $connection) { if (!static::isValidRange($first, $last)) { throw new OutOfBoundsException("Invalid slot range $first-$last for `$connection`"); } $this->slots += array_fill($first, $last - $first + 1, (string) $connection); } /** * Returns the specified slot range. * * @param int $first Initial slot of the range. * @param int $last Last slot of the range. * * @return array */ public function getSlots($first, $last) { if (!static::isValidRange($first, $last)) { throw new OutOfBoundsException("Invalid slot range $first-$last"); } return array_intersect_key($this->slots, array_fill($first, $last - $first + 1, null)); } /** * Checks if the specified slot is assigned. * * @param int $slot Slot index. * * @return bool */ #[ReturnTypeWillChange] public function offsetExists($slot) { return isset($this->slots[$slot]); } /** * Returns the node assigned to the specified slot. * * @param int $slot Slot index. * * @return string|null */ #[ReturnTypeWillChange] public function offsetGet($slot) { return $this->slots[$slot] ?? null; } /** * Assigns the specified slot to a node. * * @param int $slot Slot index. * @param NodeConnectionInterface|string $connection ID or connection instance. * * @return void */ #[ReturnTypeWillChange] public function offsetSet($slot, $connection) { if (!static::isValid($slot)) { throw new OutOfBoundsException("Invalid slot $slot for `$connection`"); } $this->slots[(int) $slot] = (string) $connection; } /** * Returns the node assigned to the specified slot. * * @param int $slot Slot index. * * @return void */ #[ReturnTypeWillChange] public function offsetUnset($slot) { unset($this->slots[$slot]); } /** * Returns the current number of assigned slots. * * @return int */ #[ReturnTypeWillChange] public function count() { return count($this->slots); } /** * Returns an iterator over the slot map. * * @return Traversable */ #[ReturnTypeWillChange] public function getIterator() { return new ArrayIterator($this->slots); } } PK)_]/jsrc/Cluster/RedisStrategy.phpnu[hashGenerator = $hashGenerator ?: new CRC16(); } /** * {@inheritdoc} */ public function getSlotByKey($key) { $key = $this->extractKeyTag($key); return $this->hashGenerator->hash($key) & 0x3FFF; } /** * {@inheritdoc} */ public function getDistributor() { $class = get_class($this); throw new NotSupportedException("$class does not provide an external distributor"); } } PK)_].-  !src/Cluster/StrategyInterface.phpnu[gDDBsrc/Command/Strategy/ContainerCommands/Functions/StatsStrategy.phpnu[separator = $separator; } /** * {@inheritDoc} */ public function resolve(string $commandId, string $subcommandId): SubcommandStrategyInterface { $subcommandStrategyClass = ucwords($subcommandId) . 'Strategy'; $commandDirectoryName = ucwords($commandId); if (!is_null($this->separator)) { $subcommandStrategyClass = str_replace($this->separator, '', $subcommandStrategyClass); $commandDirectoryName = str_replace($this->separator, '', $commandDirectoryName); } if (class_exists( $containerCommandClass = self::CONTAINER_COMMANDS_NAMESPACE . '\\' . $commandDirectoryName . '\\' . $subcommandStrategyClass )) { return new $containerCommandClass(); } throw new InvalidArgumentException('Non-existing container command given'); } } PK)_]TF"src/Command/Traits/To/ServerTo.phpnu[= $argumentsLength) { parent::setArguments($arguments); return; } /** @var To|null $toArgument */ $toArgument = $arguments[static::$toArgumentPositionOffset]; if (null === $toArgument) { array_splice($arguments, static::$toArgumentPositionOffset, 1, [false]); parent::setArguments($arguments); return; } $argumentsBefore = array_slice($arguments, 0, static::$toArgumentPositionOffset); $argumentsAfter = array_slice($arguments, static::$toArgumentPositionOffset + 1); parent::setArguments(array_merge( $argumentsBefore, $toArgument->toArray(), $argumentsAfter )); } } PK)_]g66#src/Command/Traits/From/GeoFrom.phpnu[getFromArgumentPositionOffset($arguments); if (null === $argumentPositionOffset) { throw new InvalidArgumentException('Invalid FROM argument value given'); } $fromArgumentObject = $arguments[$argumentPositionOffset]; $argumentsBefore = array_slice($arguments, 0, $argumentPositionOffset); $argumentsAfter = array_slice($arguments, $argumentPositionOffset + 1); parent::setArguments(array_merge( $argumentsBefore, $fromArgumentObject->toArray(), $argumentsAfter )); } private function getFromArgumentPositionOffset(array $arguments): ?int { foreach ($arguments as $i => $value) { if ($value instanceof FromInterface) { return $i; } } return null; } } PK)_].C+src/Command/Traits/Expire/ExpireOptions.phpnu[ 'NX', 'xx' => 'XX', 'gt' => 'GT', 'lt' => 'LT', ]; public function setArguments(array $arguments) { $value = array_pop($arguments); if (null === $value) { parent::setArguments($arguments); return; } if (in_array(strtoupper($value), self::$argumentEnum, true)) { $arguments[] = self::$argumentEnum[strtolower($value)]; } else { $arguments[] = $value; } parent::setArguments($arguments); } } PK)_]X(src/Command/Traits/Limit/LimitObject.phpnu[getLimitArgumentPositionOffset($arguments); if (null === $argumentPositionOffset) { parent::setArguments($arguments); return; } $limitObject = $arguments[$argumentPositionOffset]; $argumentsBefore = array_slice($arguments, 0, $argumentPositionOffset); $argumentsAfter = array_slice($arguments, $argumentPositionOffset + 1); parent::setArguments(array_merge( $argumentsBefore, $limitObject->toArray(), $argumentsAfter )); } private function getLimitArgumentPositionOffset(array $arguments): ?int { foreach ($arguments as $i => $value) { if ($value instanceof LimitInterface) { return $i; } } return null; } } PK)_]"src/Command/Traits/Limit/Limit.phpnu[= $argumentsLength || false === $arguments[static::$limitArgumentPositionOffset] ) { parent::setArguments($argumentsBefore); return; } $argument = $arguments[static::$limitArgumentPositionOffset]; $argumentsAfter = array_slice($arguments, static::$limitArgumentPositionOffset + 1); if (true === $argument) { parent::setArguments(array_merge($argumentsBefore, [self::$limitModifier], $argumentsAfter)); return; } if (!is_int($argument)) { throw new UnexpectedValueException('Wrong limit argument type'); } parent::setArguments(array_merge($argumentsBefore, [self::$limitModifier], [$argument], $argumentsAfter)); } } PK)_]=src/Command/Traits/Get/Get.phpnu[= $argumentsLength) { parent::setArguments($arguments); return; } if (!is_array($arguments[static::$getArgumentPositionOffset])) { throw new UnexpectedValueException('Wrong get argument type'); } $patterns = []; foreach ($arguments[static::$getArgumentPositionOffset] as $pattern) { $patterns[] = self::$getModifier; $patterns[] = $pattern; } $argumentsBeforeKeys = array_slice($arguments, 0, static::$getArgumentPositionOffset); $argumentsAfterKeys = array_slice($arguments, static::$getArgumentPositionOffset + 1); parent::setArguments(array_merge($argumentsBeforeKeys, $patterns, $argumentsAfterKeys)); } } PK)_]:@X$src/Command/Traits/With/WithDist.phpnu[= $argumentsLength || false === $arguments[static::$withDistArgumentPositionOffset] ) { parent::setArguments($arguments); return; } $argument = $arguments[static::$withDistArgumentPositionOffset]; if (true === $argument) { $argument = 'WITHDIST'; } else { throw new UnexpectedValueException('Wrong WITHDIST argument type'); } $argumentsBefore = array_slice($arguments, 0, static::$withDistArgumentPositionOffset); $argumentsAfter = array_slice($arguments, static::$withDistArgumentPositionOffset + 1); parent::setArguments(array_merge($argumentsBefore, [$argument], $argumentsAfter)); } } PK)_]r!%src/Command/Traits/With/WithCoord.phpnu[= $argumentsLength || false === $arguments[static::$withCoordArgumentPositionOffset] ) { parent::setArguments($arguments); return; } $argument = $arguments[static::$withCoordArgumentPositionOffset]; if (true === $argument) { $argument = 'WITHCOORD'; } else { throw new UnexpectedValueException('Wrong WITHCOORD argument type'); } $argumentsBefore = array_slice($arguments, 0, static::$withCoordArgumentPositionOffset); $argumentsAfter = array_slice($arguments, static::$withCoordArgumentPositionOffset + 1); parent::setArguments(array_merge($argumentsBefore, [$argument], $argumentsAfter)); } } PK)_]ޝz&src/Command/Traits/With/WithValues.phpnu[= $argumentsLength || false === $arguments[static::$withHashArgumentPositionOffset] ) { parent::setArguments($arguments); return; } $argument = $arguments[static::$withHashArgumentPositionOffset]; if (true === $argument) { $argument = 'WITHHASH'; } else { throw new UnexpectedValueException('Wrong WITHHASH argument type'); } $argumentsBefore = array_slice($arguments, 0, static::$withHashArgumentPositionOffset); $argumentsAfter = array_slice($arguments, static::$withHashArgumentPositionOffset + 1); parent::setArguments(array_merge($argumentsBefore, [$argument], $argumentsAfter)); } } PK)_]*܅&src/Command/Traits/With/WithScores.phpnu[isWithScoreModifier()) { $result = []; for ($i = 0, $iMax = count($data); $i < $iMax; ++$i) { if (is_array($data[$i])) { $result[$data[$i][0]] = $data[$i][1]; // Relay } elseif (array_key_exists($i + 1, $data)) { $result[$data[$i]] = $data[++$i]; } } return $result; } return $data; } } PK)_]T(src/Command/Traits/Json/NxXxArgument.phpnu[ 'NX', 'xx' => 'XX', ]; public function setArguments(array $arguments) { $argumentsLength = count($arguments); if (static::$nxXxArgumentPositionOffset >= $argumentsLength) { parent::setArguments($arguments); return; } if (null === $arguments[static::$nxXxArgumentPositionOffset]) { array_splice($arguments, static::$nxXxArgumentPositionOffset, 1, [false]); parent::setArguments($arguments); return; } $argument = $arguments[static::$nxXxArgumentPositionOffset]; if (!in_array(strtoupper($argument), self::$argumentEnum, true)) { $enumValues = implode(', ', array_keys(self::$argumentEnum)); throw new UnexpectedValueException("Argument accepts only: {$enumValues} values"); } $argumentsBefore = array_slice($arguments, 0, static::$nxXxArgumentPositionOffset); $argumentsAfter = array_slice($arguments, static::$nxXxArgumentPositionOffset + 1); parent::setArguments(array_merge( $argumentsBefore, [self::$argumentEnum[strtolower($argument)]], $argumentsAfter )); } } PK)_]EgDȰ!src/Command/Traits/Json/Space.phpnu[= $argumentsLength) { parent::setArguments($arguments); return; } if ($arguments[static::$spaceArgumentPositionOffset] === '') { array_splice($arguments, static::$spaceArgumentPositionOffset, 1, [false]); parent::setArguments($arguments); return; } $argument = $arguments[static::$spaceArgumentPositionOffset]; if (!is_string($argument)) { throw new UnexpectedValueException('Space argument value should be a string'); } $argumentsBefore = array_slice($arguments, 0, static::$spaceArgumentPositionOffset); $argumentsAfter = array_slice($arguments, static::$spaceArgumentPositionOffset + 1); parent::setArguments(array_merge( $argumentsBefore, [self::$spaceModifier], [$argument], $argumentsAfter )); } } PK)_]p!#src/Command/Traits/Json/Newline.phpnu[= $argumentsLength) { parent::setArguments($arguments); return; } if ($arguments[static::$newlineArgumentPositionOffset] === '') { array_splice($arguments, static::$newlineArgumentPositionOffset, 1, [false]); parent::setArguments($arguments); return; } $argument = $arguments[static::$newlineArgumentPositionOffset]; if (!is_string($argument)) { throw new UnexpectedValueException('Newline argument value should be a string'); } $argumentsBefore = array_slice($arguments, 0, static::$newlineArgumentPositionOffset); $argumentsAfter = array_slice($arguments, static::$newlineArgumentPositionOffset + 1); parent::setArguments(array_merge( $argumentsBefore, [self::$newlineModifier], [$argument], $argumentsAfter )); } } PK)_]/5"src/Command/Traits/Json/Indent.phpnu[= $argumentsLength) { parent::setArguments($arguments); return; } if ($arguments[static::$indentArgumentPositionOffset] === '') { array_splice($arguments, static::$indentArgumentPositionOffset, 1, [false]); parent::setArguments($arguments); return; } $argument = $arguments[static::$indentArgumentPositionOffset]; if (!is_string($argument)) { throw new UnexpectedValueException('Indent argument value should be a string'); } $argumentsBefore = array_slice($arguments, 0, static::$indentArgumentPositionOffset); $argumentsAfter = array_slice($arguments, static::$indentArgumentPositionOffset + 1); parent::setArguments(array_merge( $argumentsBefore, [self::$indentModifier], [$argument], $argumentsAfter )); } } PK)_] $$src/Command/Traits/By/GeoBy.phpnu[getByArgumentPositionOffset($arguments); if (null === $argumentPositionOffset) { throw new InvalidArgumentException('Invalid BY argument value given'); } $byArgumentObject = $arguments[$argumentPositionOffset]; $argumentsBefore = array_slice($arguments, 0, $argumentPositionOffset); $argumentsAfter = array_slice($arguments, $argumentPositionOffset + 1); parent::setArguments(array_merge( $argumentsBefore, $byArgumentObject->toArray(), $argumentsAfter )); } private function getByArgumentPositionOffset(array $arguments): ?int { foreach ($arguments as $i => $value) { if ($value instanceof ByInterface) { return $i; } } return null; } } PK)_]99&src/Command/Traits/By/ByLexByScore.phpnu[ 'BYLEX', 'byscore' => 'BYSCORE', ]; public function setArguments(array $arguments) { $argument = $arguments[static::$byLexByScoreArgumentPositionOffset]; if (false === $argument) { parent::setArguments($arguments); return; } if (is_string($argument) && in_array(strtoupper($argument), self::$argumentsEnum)) { $argument = self::$argumentsEnum[$argument]; } else { throw new UnexpectedValueException('By argument accepts only "bylex" and "byscore" values'); } $argumentsBefore = array_slice($arguments, 0, static::$byLexByScoreArgumentPositionOffset); $argumentsAfter = array_slice($arguments, static::$byLexByScoreArgumentPositionOffset + 1); parent::setArguments(array_merge($argumentsBefore, [$argument], $argumentsAfter)); } } PK)_]Pq44$src/Command/Traits/By/ByArgument.phpnu[= $argumentsLength || null === $arguments[static::$byArgumentPositionOffset]) { parent::setArguments($arguments); return; } $argument = $arguments[static::$byArgumentPositionOffset]; $argumentsBefore = array_slice($arguments, 0, static::$byArgumentPositionOffset); $argumentsAfter = array_slice($arguments, static::$byArgumentPositionOffset + 1); parent::setArguments(array_merge($argumentsBefore, [$this->byModifier, $argument], $argumentsAfter)); } } PK)_]OO.src/Command/Traits/BloomFilters/BucketSize.phpnu[= $argumentsLength) { parent::setArguments($arguments); return; } if ($arguments[static::$bucketSizeArgumentPositionOffset] === -1) { array_splice($arguments, static::$bucketSizeArgumentPositionOffset, 1, [false]); parent::setArguments($arguments); return; } if ($arguments[static::$bucketSizeArgumentPositionOffset] < 1) { throw new UnexpectedValueException('Wrong bucket size argument value or position offset'); } $argument = $arguments[static::$bucketSizeArgumentPositionOffset]; $argumentsBefore = array_slice($arguments, 0, static::$bucketSizeArgumentPositionOffset); $argumentsAfter = array_slice($arguments, static::$bucketSizeArgumentPositionOffset + 1); parent::setArguments(array_merge( $argumentsBefore, [self::$bucketSizeModifier], [$argument], $argumentsAfter )); } } PK)_]BFT  -src/Command/Traits/BloomFilters/Expansion.phpnu[= $argumentsLength) { parent::setArguments($arguments); return; } if ($arguments[static::$expansionArgumentPositionOffset] === -1) { array_splice($arguments, static::$expansionArgumentPositionOffset, 1, [false]); parent::setArguments($arguments); return; } if ($arguments[static::$expansionArgumentPositionOffset] < 1) { throw new UnexpectedValueException('Wrong expansion argument value or position offset'); } $argument = $arguments[static::$expansionArgumentPositionOffset]; $argumentsBefore = array_slice($arguments, 0, static::$expansionArgumentPositionOffset); $argumentsAfter = array_slice($arguments, static::$expansionArgumentPositionOffset + 1); parent::setArguments(array_merge( $argumentsBefore, [self::$expansionModifier], [$argument], $argumentsAfter )); } } PK)_]Xss1src/Command/Traits/BloomFilters/MaxIterations.phpnu[= $argumentsLength) { parent::setArguments($arguments); return; } if ($arguments[static::$maxIterationsArgumentPositionOffset] === -1) { array_splice($arguments, static::$maxIterationsArgumentPositionOffset, 1, [false]); parent::setArguments($arguments); return; } if ($arguments[static::$maxIterationsArgumentPositionOffset] < 1) { throw new UnexpectedValueException('Wrong max iterations argument value or position offset'); } $argument = $arguments[static::$maxIterationsArgumentPositionOffset]; $argumentsBefore = array_slice($arguments, 0, static::$maxIterationsArgumentPositionOffset); $argumentsAfter = array_slice($arguments, static::$maxIterationsArgumentPositionOffset + 1); parent::setArguments(array_merge( $argumentsBefore, [self::$maxIterationsModifier], [$argument], $argumentsAfter )); } } PK)_];)src/Command/Traits/BloomFilters/Error.phpnu[= $argumentsLength) { parent::setArguments($arguments); return; } if ($arguments[static::$errorArgumentPositionOffset] === -1) { array_splice($arguments, static::$errorArgumentPositionOffset, 1, [false]); parent::setArguments($arguments); return; } if ($arguments[static::$errorArgumentPositionOffset] < 0) { throw new UnexpectedValueException('Wrong error argument value or position offset'); } $argument = $arguments[static::$errorArgumentPositionOffset]; $argumentsBefore = array_slice($arguments, 0, static::$errorArgumentPositionOffset); $argumentsAfter = array_slice($arguments, static::$errorArgumentPositionOffset + 1); parent::setArguments(array_merge( $argumentsBefore, [self::$errorModifier], [$argument], $argumentsAfter )); } } PK)_]TJWW)src/Command/Traits/BloomFilters/Items.phpnu[= $argumentsLength) { parent::setArguments($arguments); return; } $argument = $arguments[static::$itemsArgumentPositionOffset]; $argumentsBefore = array_slice($arguments, 0, static::$itemsArgumentPositionOffset); $argumentsAfter = array_slice($arguments, static::$itemsArgumentPositionOffset + 1); parent::setArguments(array_merge( $argumentsBefore, [self::$itemsModifier], [$argument], $argumentsAfter )); } } PK)_]4,src/Command/Traits/BloomFilters/NoCreate.phpnu[= $argumentsLength || false === $arguments[static::$noCreateArgumentPositionOffset] ) { parent::setArguments($arguments); return; } $argument = $arguments[static::$noCreateArgumentPositionOffset]; if (true === $argument) { $argument = 'NOCREATE'; } else { throw new UnexpectedValueException('Wrong NOCREATE argument type'); } $argumentsBefore = array_slice($arguments, 0, static::$noCreateArgumentPositionOffset); $argumentsAfter = array_slice($arguments, static::$noCreateArgumentPositionOffset + 1); parent::setArguments(array_merge($argumentsBefore, [$argument], $argumentsAfter)); } } PK)_] 66,src/Command/Traits/BloomFilters/Capacity.phpnu[= $argumentsLength) { parent::setArguments($arguments); return; } if ($arguments[static::$capacityArgumentPositionOffset] === -1) { array_splice($arguments, static::$capacityArgumentPositionOffset, 1, [false]); parent::setArguments($arguments); return; } if ($arguments[static::$capacityArgumentPositionOffset] < 1) { throw new UnexpectedValueException('Wrong capacity argument value or position offset'); } $argument = $arguments[static::$capacityArgumentPositionOffset]; $argumentsBefore = array_slice($arguments, 0, static::$capacityArgumentPositionOffset); $argumentsAfter = array_slice($arguments, static::$capacityArgumentPositionOffset + 1); parent::setArguments(array_merge( $argumentsBefore, [self::$capacityModifier], [$argument], $argumentsAfter )); } } PK)_]tsrc/Command/Traits/Sorting.phpnu[ 'ASC', 'desc' => 'DESC', ]; public function setArguments(array $arguments) { $argumentsLength = count($arguments); if (static::$sortArgumentPositionOffset >= $argumentsLength) { parent::setArguments($arguments); return; } $argument = $arguments[static::$sortArgumentPositionOffset]; if (null === $argument) { array_splice($arguments, static::$sortArgumentPositionOffset, 1, [false]); parent::setArguments($arguments); return; } if (!in_array(strtoupper($argument), self::$sortingEnum, true)) { $enumValues = implode(', ', array_keys(self::$sortingEnum)); throw new UnexpectedValueException("Sorting argument accepts only: {$enumValues} values"); } $argumentsBefore = array_slice($arguments, 0, static::$sortArgumentPositionOffset); $argumentsAfter = array_slice($arguments, static::$sortArgumentPositionOffset + 1); parent::setArguments(array_merge( $argumentsBefore, [self::$sortingEnum[$argument]], $argumentsAfter )); } } PK)_]  %src/Command/Traits/MinMaxModifier.phpnu[ 'MIN', 'max' => 'MAX', ]; public function resolveModifier(int $offset, array &$arguments): void { if ($offset >= count($arguments)) { $arguments[$offset] = $this->modifierEnum['min']; return; } if (!is_string($arguments[$offset]) || !array_key_exists($arguments[$offset], $this->modifierEnum)) { throw new UnexpectedValueException('Wrong type of modifier given'); } $arguments[$offset] = $this->modifierEnum[$arguments[$offset]]; } } PK)_]ٕQQsrc/Command/Traits/BitByte.phpnu[ 'BIT', 'byte' => 'BYTE', ]; public function setArguments(array $arguments) { $value = array_pop($arguments); if (null === $value) { parent::setArguments($arguments); return; } if (in_array(strtoupper($value), self::$argumentEnum, true)) { $arguments[] = self::$argumentEnum[$value]; } else { $arguments[] = $value; } parent::setArguments($arguments); } } PK)_]Rꌿsrc/Command/Traits/Count.phpnu[= $argumentsLength) { parent::setArguments($arguments); return; } if ($arguments[static::$countArgumentPositionOffset] === -1) { array_splice($arguments, static::$countArgumentPositionOffset, 1, [false]); parent::setArguments($arguments); return; } if ($arguments[static::$countArgumentPositionOffset] < 1) { throw new UnexpectedValueException('Wrong count argument value or position offset'); } $countArgument = $arguments[static::$countArgumentPositionOffset]; $argumentsBefore = array_slice($arguments, 0, static::$countArgumentPositionOffset); $argumentsAfter = array_slice($arguments, static::$countArgumentPositionOffset + 2); if (!$any) { $argumentsAfter = array_slice($arguments, static::$countArgumentPositionOffset + 1); parent::setArguments(array_merge( $argumentsBefore, [$this->countModifier], [$countArgument], $argumentsAfter )); return; } parent::setArguments(array_merge( $argumentsBefore, [$this->countModifier], [$countArgument], [$this->anyModifier], $argumentsAfter )); } } PK)_]< src/Command/Traits/Storedist.phpnu[= $argumentsLength || false === $arguments[static::$storeDistArgumentPositionOffset] ) { parent::setArguments($arguments); return; } $argument = $arguments[static::$storeDistArgumentPositionOffset]; if (true === $argument) { $argument = 'STOREDIST'; } else { throw new UnexpectedValueException('Wrong STOREDIST argument type'); } $argumentsBefore = array_slice($arguments, 0, static::$storeDistArgumentPositionOffset); $argumentsAfter = array_slice($arguments, static::$storeDistArgumentPositionOffset + 1); parent::setArguments(array_merge($argumentsBefore, [$argument], $argumentsAfter)); } } PK)_]f55src/Command/Traits/Rev.phpnu[= $argumentsLength) { parent::setArguments($arguments); return; } if (!is_numeric($arguments[static::$dbArgumentPositionOffset])) { throw new UnexpectedValueException('DB argument should be a valid numeric value'); } if ($arguments[static::$dbArgumentPositionOffset] < 0) { array_splice($arguments, static::$dbArgumentPositionOffset, 1); parent::setArguments($arguments); return; } $argument = $arguments[static::$dbArgumentPositionOffset]; $argumentsBefore = array_slice($arguments, 0, static::$dbArgumentPositionOffset); $argumentsAfter = array_slice($arguments, static::$dbArgumentPositionOffset + 1); parent::setArguments(array_merge( $argumentsBefore, [$this->dbModifier], [$argument], $argumentsAfter )); } } PK)_]]iVllsrc/Command/Traits/Keys.phpnu[ $argumentsLength || !is_array($arguments[static::$keysArgumentPositionOffset]) ) { throw new UnexpectedValueException('Wrong keys argument type or position offset'); } $keysArgument = $arguments[static::$keysArgumentPositionOffset]; $argumentsBeforeKeys = array_slice($arguments, 0, static::$keysArgumentPositionOffset); $argumentsAfterKeys = array_slice($arguments, static::$keysArgumentPositionOffset + 1); if ($withNumkeys) { $numkeys = count($keysArgument); parent::setArguments(array_merge($argumentsBeforeKeys, [$numkeys], $keysArgument, $argumentsAfterKeys)); return; } parent::setArguments(array_merge($argumentsBeforeKeys, $keysArgument, $argumentsAfterKeys)); } } PK)_]}]src/Command/Traits/Replace.phpnu[= $argumentsLength) { parent::setArguments($arguments); return; } if (!is_array($arguments[static::$weightsArgumentPositionOffset])) { throw new UnexpectedValueException('Wrong weights argument type'); } $weightsArray = $arguments[static::$weightsArgumentPositionOffset]; if (empty($weightsArray)) { unset($arguments[static::$weightsArgumentPositionOffset]); parent::setArguments($arguments); return; } $argumentsBefore = array_slice($arguments, 0, static::$weightsArgumentPositionOffset); $argumentsAfter = array_slice($arguments, static::$weightsArgumentPositionOffset + 1); parent::setArguments(array_merge( $argumentsBefore, [self::$weightsModifier], $weightsArray, $argumentsAfter )); } } PK)_]3QQ src/Command/Traits/LeftRight.phpnu[ 'LEFT', 'right' => 'RIGHT', ]; public function setArguments(array $arguments) { $argumentsLength = count($arguments); if (static::$leftRightArgumentPositionOffset >= $argumentsLength) { $arguments[] = 'LEFT'; parent::setArguments($arguments); return; } $argument = $arguments[static::$leftRightArgumentPositionOffset]; if (is_string($argument) && in_array(strtoupper($argument), self::$leftRightEnum, true)) { $argument = self::$leftRightEnum[$argument]; } else { $enumValues = implode(', ', array_keys(self::$leftRightEnum)); throw new UnexpectedValueException("Left/Right argument accepts only: {$enumValues} values"); } $argumentsBefore = array_slice($arguments, 0, static::$leftRightArgumentPositionOffset); $argumentsAfter = array_slice($arguments, static::$leftRightArgumentPositionOffset + 1); parent::setArguments(array_merge( $argumentsBefore, [$argument], $argumentsAfter )); } } PK)_]|  src/Command/Traits/Aggregate.phpnu[ 'MIN', 'max' => 'MAX', 'sum' => 'SUM', ]; /** * @var string */ private static $aggregateModifier = 'AGGREGATE'; public function setArguments(array $arguments) { $argumentsLength = count($arguments); if (static::$aggregateArgumentPositionOffset >= $argumentsLength) { parent::setArguments($arguments); return; } $argument = $arguments[static::$aggregateArgumentPositionOffset]; if (is_string($argument) && in_array(strtoupper($argument), self::$aggregateValuesEnum)) { $argument = self::$aggregateValuesEnum[$argument]; } else { $enumValues = implode(', ', array_keys(self::$aggregateValuesEnum)); throw new UnexpectedValueException("Aggregate argument accepts only: {$enumValues} values"); } $argumentsBefore = array_slice($arguments, 0, static::$aggregateArgumentPositionOffset); $argumentsAfter = array_slice($arguments, static::$aggregateArgumentPositionOffset + 1); parent::setArguments(array_merge( $argumentsBefore, [self::$aggregateModifier], [$argument], $argumentsAfter )); } } PK)_]|vsrc/Command/Traits/Timeout.phpnu[= $argumentsLength) { parent::setArguments($arguments); return; } if ($arguments[static::$timeoutArgumentPositionOffset] === -1) { array_splice($arguments, static::$timeoutArgumentPositionOffset, 1, [false]); parent::setArguments($arguments); return; } if ($arguments[static::$timeoutArgumentPositionOffset] < 1) { throw new UnexpectedValueException('Wrong timeout argument value or position offset'); } $argument = $arguments[static::$timeoutArgumentPositionOffset]; $argumentsBefore = array_slice($arguments, 0, static::$timeoutArgumentPositionOffset); $argumentsAfter = array_slice($arguments, static::$timeoutArgumentPositionOffset + 1); parent::setArguments(array_merge( $argumentsBefore, [self::$timeoutModifier], [$argument], $argumentsAfter )); } } PK)_]h WWsrc/Command/Redis/LMPOP.phpnu[setCount($arguments); $arguments = $this->getArguments(); $this->setLeftRight($arguments); $arguments = $this->getArguments(); $this->setKeys($arguments); $this->filterArguments(); } public function parseResponse($data) { if (null === $data) { return null; } return [$data[0] => $data[1]]; } } PK)_]޳'src/Command/Redis/GEORADIUSBYMEMBER.phpnu[setSorting($arguments); $arguments = $this->getArguments(); $this->setGetArgument($arguments); $arguments = $this->getArguments(); $this->setLimit($arguments); $arguments = $this->getArguments(); $this->setBy($arguments); $this->filterArguments(); } } PK)_]o#src/Command/Redis/MULTI.phpnu[ true]; $lastType = 'array'; } if ($lastType === 'array') { $options = $this->prepareOptions(array_pop($arguments)); $arguments = array_merge($arguments, $options); } } parent::setArguments($arguments); } /** * Returns a list of options and modifiers compatible with Redis. * * @param array $options List of options. * * @return array */ protected function prepareOptions($options) { $opts = array_change_key_case($options, CASE_UPPER); $finalizedOpts = []; if (!empty($opts['WITHSCORES'])) { $finalizedOpts[] = 'WITHSCORES'; } return $finalizedOpts; } /** * Checks for the presence of the WITHSCORES modifier. * * @return bool */ protected function withScores() { $arguments = $this->getArguments(); if (count($arguments) < 4) { return false; } return strtoupper($arguments[3]) === 'WITHSCORES'; } /** * {@inheritdoc} */ public function parseResponse($data) { if ($this->withScores()) { $result = []; for ($i = 0; $i < count($data); ++$i) { if (is_array($data[$i])) { $result[$data[$i][0]] = $data[$i][1]; // Relay } else { $result[$data[$i]] = $data[++$i]; } } return $result; } return $data; } } PK)_]tPTTsrc/Command/Redis/GEOHASH.phpnu[toArray(); } parent::setArguments(array_merge( [$index, $query], $commandArguments )); } } PK)_]M88&src/Command/Redis/Search/FTTAGVALS.phpnu[toArray(); } $terms = array_slice($arguments, 3); parent::setArguments(array_merge( [$index, $synonymGroupId], $commandArguments, $terms )); } } PK)_]w(o~~%src/Command/Redis/Search/FTCREATE.phpnu[toArray() : []; $schema = array_reduce($schema, static function (array $carry, FieldInterface $field) { return array_merge($carry, $field->toArray()); }, []); array_unshift($schema, 'SCHEMA'); parent::setArguments(array_merge( [$index], $commandArguments, $schema )); } } PK)_]&,,&src/Command/Redis/Search/FTPROFILE.phpnu[toArray() )); } } PK)_] 0`'src/Command/Redis/Search/FTALIASADD.phpnu[toArray() : []; parent::setArguments(array_merge( [$index, $query], $commandArguments )); } } PK)_]}}%src/Command/Redis/Search/FTSUGADD.phpnu[toArray() : []; parent::setArguments(array_merge( [$key, $string, $score], $commandArguments )); } } PK)_]Y#(src/Command/Redis/Search/FTAGGREGATE.phpnu[toArray() : []; parent::setArguments(array_merge( [$index, $query], $commandArguments )); } } PK)_]c55%src/Command/Redis/Search/FTSUGLEN.phpnu[toArray() : []; parent::setArguments(array_merge( [$key, $prefix], $commandArguments )); } } PK)_]e%%src/Command/Redis/Search/FTCURSOR.phpnu[toArray() : []; parent::setArguments(array_merge( [$subcommand, $index, $cursorId], $commandArguments )); } } PK)_]z<""'src/Command/Redis/Search/FTALIASDEL.phpnu[toArray(); } parent::setArguments(array_merge( [$index, $query], $commandArguments )); } } PK)_]bv$src/Command/Redis/Search/FTALTER.phpnu[toArray() : []; $schema = array_reduce($schema, static function (array $carry, FieldInterface $field) { return array_merge($carry, $field->toArray()); }, []); array_unshift($schema, 'SCHEMA', 'ADD'); parent::setArguments(array_merge( [$index], $commandArguments, $schema )); } } PK)_]T&&&src/Command/Redis/Search/FTSYNDUMP.phpnu[toArray(); } parent::setArguments(array_merge( [$index], $commandArguments )); } } PK)_]xr&src/Command/Redis/Search/FTDICTADD.phpnu[src/Command/Redis/GET.phpnu[setByLexByScoreArgument($arguments); $arguments = $this->getArguments(); $this->setReversedArgument($arguments); $arguments = $this->getArguments(); $this->setLimitArguments($arguments); $this->filterArguments(); } } PK)_],Un::src/Command/Redis/HEXPIRE.phpnu[flagsEnum, true)) { $processedArguments[] = strtoupper($arguments[3]); } else { throw new UnexpectedValueException('Unsupported flag value'); } } if (array_key_exists(2, $arguments) && null !== $arguments[2]) { array_push($processedArguments, 'FIELDS', count($arguments[2])); $processedArguments = array_merge($processedArguments, $arguments[2]); } parent::setArguments($processedArguments); } } PK)_]Jsrc/Command/Redis/QUIT.phpnu[toArray() : []; parent::setArguments(array_merge( [$key], $commandArguments )); } } PK)_]xxWW&src/Command/Redis/TimeSeries/TSGET.phpnu[toArray() : []; parent::setArguments(array_merge( [$key], $commandArguments )); } } PK)_]7>>-src/Command/Redis/TimeSeries/TSQUERYINDEX.phpnu[toArray() : []; parent::setArguments(array_merge( [$key], $commandArguments )); } } PK)_]j]''-src/Command/Redis/TimeSeries/TSDELETERULE.phpnu[toArray() : []; parent::setArguments(array_merge( [$key, $fromTimestamp, $toTimestamp], $commandArguments )); } } PK)_]` )src/Command/Redis/TimeSeries/TSINCRBY.phpnu[toArray() : []; parent::setArguments(array_merge( [$key, $value], $commandArguments )); } } PK)_]>)src/Command/Redis/TimeSeries/TSDECRBY.phpnu[toArray() : []; parent::setArguments(array_merge( [$key, $value], $commandArguments )); } } PK)_]]]&src/Command/Redis/TimeSeries/TSADD.phpnu[toArray() : []; parent::setArguments(array_merge( [$key, $timestamp, $value], $commandArguments )); } } PK)_]nY66)src/Command/Redis/TimeSeries/TSCREATE.phpnu[toArray() : []; parent::setArguments(array_merge( [$key], $commandArguments )); } } PK)_]toArray(); array_push($processedArguments, 'FILTER', ...$arguments); parent::setArguments(array_merge( $commandArguments, $processedArguments )); } } PK)_]e+src/Command/Redis/TimeSeries/TSREVRANGE.phpnu[toArray(); parent::setArguments(array_merge( [$fromTimestamp, $toTimestamp], $commandArguments )); } } PK)_]z_  src/Command/Redis/EXISTS.phpnu[wsrc/Command/Redis/SSCAN.phpnu[prepareOptions(array_pop($arguments)); $arguments = array_merge($arguments, $options); } parent::setArguments($arguments); } /** * Returns a list of options and modifiers compatible with Redis. * * @param array $options List of options. * * @return array */ protected function prepareOptions($options) { $options = array_change_key_case($options, CASE_UPPER); $normalized = []; if (!empty($options['MATCH'])) { $normalized[] = 'MATCH'; $normalized[] = $options['MATCH']; } if (!empty($options['COUNT'])) { $normalized[] = 'COUNT'; $normalized[] = $options['COUNT']; } return $normalized; } } PK)_]rsrc/Command/Redis/DUMP.phpnu[ $score) { $arguments[] = $score; $arguments[] = $member; } } parent::setArguments($arguments); } } PK)_]D!src/Command/Redis/ZUNIONSTORE.phpnu[setAggregate($arguments); $arguments = $this->getArguments(); $this->setWeights($arguments); $arguments = $this->getArguments(); $this->setKeys($arguments); } } PK)_]tsrc/Command/Redis/BITOP.phpnu[ $entry) { $log[$index] = [ 'id' => $entry[0], 'timestamp' => $entry[1], 'duration' => $entry[2], 'command' => $entry[3], ]; } return $log; } return $data; } } PK)_];2\\src/Command/Redis/HGETALL.phpnu[parseNewResponseFormat($lines); } else { return $this->parseOldResponseFormat($lines); } } /** * {@inheritdoc} */ public function parseNewResponseFormat($lines) { $info = []; $current = null; foreach ($lines as $row) { if ($row === '') { continue; } if (preg_match('/^# (\w+)$/', $row, $matches)) { $info[$matches[1]] = []; $current = &$info[$matches[1]]; continue; } [$k, $v] = $this->parseRow($row); $current[$k] = $v; } return $info; } /** * {@inheritdoc} */ public function parseOldResponseFormat($lines) { $info = []; foreach ($lines as $row) { if (strpos($row, ':') === false) { continue; } [$k, $v] = $this->parseRow($row); $info[$k] = $v; } return $info; } /** * Parses a single row of the response and returns the key-value pair. * * @param string $row Single row of the response. * * @return array */ protected function parseRow($row) { if (preg_match('/^module:name/', $row)) { return $this->parseModuleRow($row); } [$k, $v] = explode(':', $row, 2); if (preg_match('/^db\d+$/', $k)) { $v = $this->parseDatabaseStats($v); } return [$k, $v]; } /** * Extracts the statistics of each logical DB from the string buffer. * * @param string $str Response buffer. * * @return array */ protected function parseDatabaseStats($str) { $db = []; foreach (explode(',', $str) as $dbvar) { [$dbvk, $dbvv] = explode('=', $dbvar); $db[trim($dbvk)] = $dbvv; } return $db; } /** * Parsing module rows because of different format. * * @param string $row * @return array */ protected function parseModuleRow(string $row): array { [$moduleKeyword, $moduleData] = explode(':', $row); $explodedData = explode(',', $moduleData); $parsedData = []; foreach ($explodedData as $moduleDataRow) { [$k, $v] = explode('=', $moduleDataRow); if ($k === 'name') { $parsedData[0] = $v; continue; } $parsedData[1][$k] = $v; } return $parsedData; } } PK)_]t7src/Command/Redis/EVAL_RO.phpnu[ 1) { $result = []; for ($i = 0, $iMax = count($data); $i < $iMax; ++$i) { if (array_key_exists($i + 1, $data)) { $result[(string) $data[$i]] = $data[++$i]; } } return $result; } return $data; } } PK)_]! 44-src/Command/Redis/CountMinSketch/CMSMERGE.phpnu[getArguments(), CASE_UPPER); switch (strtoupper($args[0])) { case 'LIST': return $this->parseClientList($data); case 'KILL': case 'GETNAME': case 'SETNAME': default: return $data; } // @codeCoverageIgnore } /** * Parses the response to CLIENT LIST and returns a structured list. * * @param string $data Response buffer. * * @return array */ protected function parseClientList($data) { $clients = []; foreach (explode("\n", $data, -1) as $clientData) { $client = []; foreach (explode(' ', $clientData) as $kv) { @[$k, $v] = explode('=', $kv); $client[$k] = $v; } $clients[] = $client; } return $clients; } } PK)_]R<< src/Command/Redis/SMISMEMBER.phpnu[setDB($arguments); $arguments = $this->getArguments(); $this->setReplace($arguments); } } PK)_]~b3 src/Command/Redis/LASTSAVE.phpnu[ $value) { if ($index < 2) { continue; } if (false === $value || null === $value) { unset($arguments[$index]); } } parent::setArguments($arguments); } } PK)_]-Ksrc/Command/Redis/ZPOPMAX.phpnu[getArgument(0); } } PK)_]'v  src/Command/Redis/RENAME.phpnu[filterArguments(); } public function parseResponse($data) { if ($this->isWithCountModifier()) { $result = []; for ($i = 0, $iMax = count($data); $i < $iMax; ++$i) { if (array_key_exists($i + 1, $data)) { $result[(string) $data[$i]] = $data[++$i]; } } return $result; } return $data; } /** * Checks for the presence of the WITHCOUNT modifier. * * @return bool */ private function isWithCountModifier(): bool { $arguments = $this->getArguments(); $lastArgument = (!empty($arguments)) ? $arguments[count($arguments) - 1] : null; return is_string($lastArgument) && strtoupper($lastArgument) === 'WITHCOUNT'; } } PK)_]k9VV$src/Command/Redis/TopK/TOPKQUERY.phpnu[getArguments(); for ($i = 3; $i < count($arguments); ++$i) { switch (strtoupper($arguments[$i])) { case 'WITHSCORES': return true; case 'LIMIT': $i += 2; break; } } return false; } } PK)_]2src/Command/Redis/PEXPIREAT.phpnu[setLimit($arguments); $arguments = $this->getArguments(); $this->setKeys($arguments); } } PK)_] src/Command/Redis/ZMPOP.phpnu[setCount($arguments); $arguments = $this->getArguments(); $this->resolveModifier(static::$modifierArgumentPositionOffset, $arguments); $this->setKeys($arguments); $arguments = $this->getArguments(); parent::setArguments($arguments); } public function parseResponse($data) { $key = array_shift($data); if (null === $key) { return [$key]; } $data = $data[0]; $parsedData = []; for ($i = 0, $iMax = count($data); $i < $iMax; $i++) { for ($j = 0, $jMax = count($data[$i]); $j < $jMax; ++$j) { if ($data[$i][$j + 1] ?? false) { $parsedData[$data[$i][$j]] = $data[$i][++$j]; } } } return array_combine([$key], [$parsedData]); } } PK)_]#&>!src/Command/Redis/PEXPIRETIME.phpnu[setKeys($arguments, false); } public function parseResponse($data) { $key = array_shift($data); if (null === $key) { return [$key]; } return array_combine([$key], [[$data[0] => $data[1]]]); } } PK)_]5'src/Command/Redis/INCR.phpnu[setTimeout($arguments); $arguments = $this->getArguments(); $this->setTo($arguments); $this->filterArguments(); } } PK)_]ԫUbsrc/Command/Redis/ZINCRBY.phpnu[getArgument(0))) { case 'numsub': return self::processNumsub($data); default: return $data; } } /** * Returns the processed response to PUBSUB NUMSUB. * * @param array $channels List of channels * * @return array */ protected static function processNumsub(array $channels) { $processed = []; $count = count($channels); for ($i = 0; $i < $count; ++$i) { $processed[$channels[$i]] = $channels[++$i]; } return $processed; } } PK)_]&src/Command/Redis/HPEXPIRE.phpnu[b(src/Command/Redis/TDigest/TDIGESTMAX.phpnu[getArgument(0); $argument = is_null($argument) ? null : strtolower($argument); switch ($argument) { case 'masters': case 'slaves': return self::processMastersOrSlaves($data); default: return $data; } } /** * Returns a processed response to SENTINEL MASTERS or SENTINEL SLAVES. * * @param array $servers List of Redis servers. * * @return array */ protected static function processMastersOrSlaves(array $servers) { foreach ($servers as $idx => $node) { $processed = []; $count = count($node); for ($i = 0; $i < $count; ++$i) { $processed[$node[$i]] = $node[++$i]; } $servers[$idx] = $processed; } return $servers; } } PK)_]ьsrc/Command/Redis/HINCRBY.phpnu[setStoreDist($arguments); $arguments = $this->getArguments(); $this->setCount($arguments, $arguments[6] ?? false); $arguments = $this->getArguments(); $this->setSorting($arguments); $arguments = $this->getArguments(); $this->setFrom($arguments); $arguments = $this->getArguments(); $this->setBy($arguments); $this->filterArguments(); } } PK)_]K@$  src/Command/Redis/LINDEX.phpnu[ 2) { for ($i = 2, $iMax = count($arguments); $i < $iMax; $i++) { $processedArguments[] = $arguments[$i]; } } parent::setArguments($processedArguments); } } PK)_]esrc/Command/Redis/MOVE.phpnu[setLimit($arguments); $arguments = $this->getArguments(); $this->setKeys($arguments); } } PK)_]a~src/Command/Redis/XADD.phpnu[ $val) { $args[] = $key; $args[] = $val; } } parent::setArguments($args); } } PK)_]P P src/Command/Redis/GEOSEARCH.phpnu[setSorting($arguments); $arguments = $this->getArguments(); $this->setWithCoord($arguments); $arguments = $this->getArguments(); $this->setWithDist($arguments); $arguments = $this->getArguments(); $this->setWithHash($arguments); $arguments = $this->getArguments(); $this->setCount($arguments, $arguments[5] ?? false); $arguments = $this->getArguments(); $this->setFrom($arguments); $arguments = $this->getArguments(); $this->setBy($arguments); $this->filterArguments(); } public function parseResponse($data) { $parsedData = []; $itemKey = ''; foreach ($data as $item) { if (!is_array($item)) { $parsedData[] = $item; continue; } foreach ($item as $key => $itemRow) { if ($key === 0) { $itemKey = $itemRow; continue; } if (is_string($itemRow)) { $parsedData[$itemKey]['dist'] = round((float) $itemRow, 5); } elseif (is_int($itemRow)) { $parsedData[$itemKey]['hash'] = $itemRow; } else { $parsedData[$itemKey]['lng'] = round($itemRow[0], 5); $parsedData[$itemKey]['lat'] = round($itemRow[1], 5); } } } return $parsedData; } } PK)_]I  src/Command/Redis/DBSIZE.phpnu[ 'EX', 'px' => 'PX', 'exat' => 'EXAT', 'pxat' => 'PXAT', 'persist' => 'PERSIST', ]; public function getId() { return 'GETEX'; } public function setArguments(array $arguments) { if (!array_key_exists(1, $arguments) || $arguments[1] === '') { parent::setArguments([$arguments[0]]); return; } if (!in_array(strtoupper($arguments[1]), self::$modifierEnum)) { $enumValues = implode(', ', array_keys(self::$modifierEnum)); throw new UnexpectedValueException("Modifier argument accepts only: {$enumValues} values"); } if ($arguments[1] === 'persist') { parent::setArguments([$arguments[0], self::$modifierEnum[$arguments[1]]]); return; } $arguments[1] = self::$modifierEnum[$arguments[1]]; if (!array_key_exists(2, $arguments)) { throw new UnexpectedValueException('You should provide value for current modifier'); } parent::setArguments($arguments); } } PK)_]src/Command/Redis/RPOPLPUSH.phpnu[setExpansion($arguments); $arguments = $this->getArguments(); $this->setMaxIterations($arguments); $arguments = $this->getArguments(); $this->setBucketSize($arguments); $this->filterArguments(); } } PK)_]4_+src/Command/Redis/CuckooFilter/CFINSERT.phpnu[setNoCreate($arguments); $arguments = $this->getArguments(); $this->setItems($arguments); $arguments = $this->getArguments(); $this->setCapacity($arguments); $this->filterArguments(); } } PK)_]ڠ`)src/Command/Redis/CuckooFilter/CFINFO.phpnu[ 1) { $result = []; for ($i = 0, $iMax = count($data); $i < $iMax; ++$i) { if (array_key_exists($i + 1, $data)) { $result[(string) $data[$i]] = $data[++$i]; } } return $result; } return $data; } } PK)_],ic33+src/Command/Redis/CuckooFilter/CFEXISTS.phpnu[prepareOptions(array_pop($arguments)); $arguments = array_merge($arguments, $options); } parent::setArguments($arguments); } /** * Returns a list of options and modifiers compatible with Redis. * * @param array $options List of options. * * @return array */ protected function prepareOptions($options) { $options = array_change_key_case($options, CASE_UPPER); $normalized = []; if (!empty($options['MATCH'])) { $normalized[] = 'MATCH'; $normalized[] = $options['MATCH']; } if (!empty($options['COUNT'])) { $normalized[] = 'COUNT'; $normalized[] = $options['COUNT']; } return $normalized; } } PK)_]u&src/Command/Redis/ZREVRANGEBYSCORE.phpnu[setExpansion($arguments); $this->filterArguments(); } } PK)_]R_4,src/Command/Redis/BloomFilter/BFSCANDUMP.phpnu[ 'CAPACITY', 'size' => 'SIZE', 'filters' => 'FILTERS', 'items' => 'ITEMS', 'expansion' => 'EXPANSION', ]; public function getId() { return 'BF.INFO'; } public function setArguments(array $arguments) { if (isset($arguments[1])) { $modifier = array_pop($arguments); if ($modifier === '') { parent::setArguments($arguments); return; } if (!in_array(strtoupper($modifier), $this->modifierEnum)) { $enumValues = implode(', ', array_keys($this->modifierEnum)); throw new UnexpectedValueException("Argument accepts only: {$enumValues} values"); } $arguments[] = $this->modifierEnum[strtolower($modifier)]; } parent::setArguments($arguments); } public function parseResponse($data) { if (count($data) > 1) { $result = []; for ($i = 0, $iMax = count($data); $i < $iMax; ++$i) { if (array_key_exists($i + 1, $data)) { $result[(string) $data[$i]] = $data[++$i]; } } return $result; } return $data; } } PK)_]wACC*src/Command/Redis/BloomFilter/BFEXISTS.phpnu[setNoCreate($arguments); $arguments = $this->getArguments(); if (array_key_exists(5, $arguments) && $arguments[5]) { $arguments[5] = 'NONSCALING'; } $this->setItems($arguments); $arguments = $this->getArguments(); $this->setExpansion($arguments); $arguments = $this->getArguments(); $this->setErrorRate($arguments); $arguments = $this->getArguments(); $this->setCapacity($arguments); $this->filterArguments(); } } PK)_]7t/src/Command/Redis/Container/Search/FTCURSOR.phpnu[client = $client; } /** * {@inheritDoc} */ public function __call(string $subcommandID, array $arguments) { array_unshift($arguments, strtoupper($subcommandID)); return $this->client->executeCommand( $this->client->createCommand($this->getContainerCommandId(), $arguments) ); } abstract public function getContainerCommandId(): string; } PK)_]ЯYa a 0src/Command/Redis/Container/ContainerFactory.phpnu[ FunctionContainer::class, ]; /** * Creates container command. * * @param ClientInterface $client * @param string $containerCommandID * @return ContainerInterface */ public static function create(ClientInterface $client, string $containerCommandID): ContainerInterface { $containerCommandID = strtoupper($containerCommandID); $commandModule = self::resolveCommandModuleByPrefix($containerCommandID); if (null !== $commandModule) { if (class_exists($containerClass = self::CONTAINER_NAMESPACE . '\\' . $commandModule . '\\' . $containerCommandID)) { return new $containerClass($client); } throw new UnexpectedValueException('Given module container command is not supported.'); } if (class_exists($containerClass = self::CONTAINER_NAMESPACE . '\\' . $containerCommandID)) { return new $containerClass($client); } if (array_key_exists($containerCommandID, self::$specialMappings)) { $containerClass = self::$specialMappings[$containerCommandID]; return new $containerClass($client); } throw new UnexpectedValueException('Given container command is not supported.'); } /** * @param string $commandID * @return string|null */ private static function resolveCommandModuleByPrefix(string $commandID): ?string { $modules = ClientConfiguration::getModules(); foreach ($modules as $module) { if (preg_match("/^{$module['commandPrefix']}/", $commandID)) { return $module['name']; } } return null; } } PK)_]=lQmzz'src/Command/Redis/Container/CLUSTER.phpnu[ $value) { $modifier = strtoupper($modifier); if ($modifier === 'COPY' && $value == true) { $arguments[] = $modifier; } if ($modifier === 'REPLACE' && $value == true) { $arguments[] = $modifier; } } } parent::setArguments($arguments); } } PK)_]\R src/Command/Redis/HRANDFIELD.phpnu[strategyResolver = new SubcommandStrategyResolver(); } public function getId() { return 'FUNCTION'; } public function setArguments(array $arguments) { $strategy = $this->strategyResolver->resolve('functions', strtolower($arguments[0])); $arguments = $strategy->processArguments($arguments); parent::setArguments($arguments); $this->filterArguments(); } } PK)_]UU#src/Command/Redis/Json/JSONMSET.phpnu[setSpace($arguments); $arguments = $this->getArguments(); $this->setNewline($arguments); $arguments = $this->getArguments(); $this->setIndent($arguments); $this->filterArguments(); } } PK)_]ɸBB$src/Command/Redis/Json/JSONCLEAR.phpnu[setSubcommand($arguments); $this->filterArguments(); } } PK)_]b#src/Command/Redis/Json/JSONMGET.phpnu[>(src/Command/Redis/Json/JSONNUMINCRBY.phpnu[>(src/Command/Redis/Json/JSONSTRAPPEND.phpnu[X"src/Command/Redis/HINCRBYFLOAT.phpnu[prepareOptions(array_pop($arguments)); $arguments = array_merge($arguments, $options); } $this->arguments = $arguments; parent::setArguments($arguments); } /** * Returns a list of options and modifiers compatible with Redis. * * @param array $options List of options. * * @return array */ protected function prepareOptions($options) { $options = array_change_key_case($options, CASE_UPPER); $normalized = []; if (!empty($options['MATCH'])) { $normalized[] = 'MATCH'; $normalized[] = $options['MATCH']; } if (!empty($options['COUNT'])) { $normalized[] = 'COUNT'; $normalized[] = $options['COUNT']; } if (!empty($options['NOVALUES']) && true === $options['NOVALUES']) { $normalized[] = 'NOVALUES'; } return $normalized; } /** * {@inheritdoc} */ public function parseResponse($data) { if (!in_array('NOVALUES', $this->arguments, true)) { if (is_array($data)) { $fields = $data[1]; $result = []; for ($i = 0; $i < count($fields); ++$i) { $result[$fields[$i]] = $fields[++$i]; } $data[1] = $result; } } return $data; } } PK)_]B  src/Command/Redis/SUBSTR.phpnu[filterArguments(); } public function parseResponse($data) { if (is_array($data)) { if ($data !== array_values($data)) { return $data; // Relay } return [$data[0] => $data[1], $data[2] => $data[3]]; } return $data; } } PK)_]3P!src/Command/Redis/SRANDMEMBER.phpnu[ $v) { $flattenedKVs[] = $k; $flattenedKVs[] = $v; } $arguments = $flattenedKVs; } parent::setArguments($arguments); } } PK)_]src/Command/Redis/EXPIREAT.phpnu[setKeys($arguments); $arguments = $this->getArguments(); $this->setWithScore($arguments); } } PK)_] !src/Command/Redis/UNSUBSCRIBE.phpnu[getArgument(0)); } } PK)_]rSpMMsrc/Command/Redis/ZSCAN.phpnu[prepareOptions(array_pop($arguments)); $arguments = array_merge($arguments, $options); } parent::setArguments($arguments); } /** * Returns a list of options and modifiers compatible with Redis. * * @param array $options List of options. * * @return array */ protected function prepareOptions($options) { $options = array_change_key_case($options, CASE_UPPER); $normalized = []; if (!empty($options['MATCH'])) { $normalized[] = 'MATCH'; $normalized[] = $options['MATCH']; } if (!empty($options['COUNT'])) { $normalized[] = 'COUNT'; $normalized[] = $options['COUNT']; } return $normalized; } /** * {@inheritdoc} */ public function parseResponse($data) { if (is_array($data)) { $members = $data[1]; $result = []; for ($i = 0; $i < count($members); ++$i) { $result[$members[$i]] = (float) $members[++$i]; } $data[1] = $result; } return $data; } } PK)_];src/Command/Redis/GETRANGE.phpnu[ $v) { $flattenedKVs[] = $k; $flattenedKVs[] = $v; } $arguments = $flattenedKVs; } parent::setArguments($arguments); } } PK)_]G  src/Command/Redis/SELECT.phpnu[src/Command/Redis/PFADD.phpnu[setCommonOptions('VECTOR', $fieldName, $alias); array_push($this->fieldArguments, $algorithm, count($attributeNameValueDictionary)); $this->fieldArguments = array_merge($this->fieldArguments, $attributeNameValueDictionary); } /** * {@inheritDoc} */ public function toArray(): array { return $this->fieldArguments; } } PK)_]:src/Command/Argument/Search/SchemaFields/GeoShapeField.phpnu[fieldArguments[] = $identifier; if ($alias !== '') { $this->fieldArguments[] = 'AS'; $this->fieldArguments[] = $alias; } $this->fieldArguments[] = 'GEOSHAPE'; if (null !== $coordSystem) { $this->fieldArguments[] = $coordSystem; } if ($sortable === self::SORTABLE) { $this->fieldArguments[] = 'SORTABLE'; } elseif ($sortable === self::SORTABLE_UNF) { $this->fieldArguments[] = 'SORTABLE'; $this->fieldArguments[] = 'UNF'; } if ($noIndex) { $this->fieldArguments[] = 'NOINDEX'; } } } PK)_]/q__5src/Command/Argument/Search/SchemaFields/TagField.phpnu[setCommonOptions('TAG', $identifier, $alias, $sortable, $noIndex, $allowsMissing); if ($separator !== ',') { $this->fieldArguments[] = 'SEPARATOR'; $this->fieldArguments[] = $separator; } if ($caseSensitive) { $this->fieldArguments[] = 'CASESENSITIVE'; } if ($allowsEmpty) { $this->fieldArguments[] = 'INDEXEMPTY'; } } } PK)_]K ;src/Command/Argument/Search/SchemaFields/FieldInterface.phpnu[fieldArguments[] = $identifier; if ($alias !== '') { $this->fieldArguments[] = 'AS'; $this->fieldArguments[] = $alias; } $this->fieldArguments[] = $fieldType; if ($sortable === self::SORTABLE) { $this->fieldArguments[] = 'SORTABLE'; } elseif ($sortable === self::SORTABLE_UNF) { $this->fieldArguments[] = 'SORTABLE'; $this->fieldArguments[] = 'UNF'; } if ($noIndex) { $this->fieldArguments[] = 'NOINDEX'; } if ($allowsMissing) { $this->fieldArguments[] = 'INDEXMISSING'; } } /** * {@inheritDoc} */ public function toArray(): array { return $this->fieldArguments; } } PK)_]52N]]5src/Command/Argument/Search/SchemaFields/GeoField.phpnu[setCommonOptions('GEO', $identifier, $alias, $sortable, $noIndex, $allowsMissing); } } PK)_]`L6src/Command/Argument/Search/SchemaFields/TextField.phpnu[setCommonOptions('TEXT', $identifier, $alias, $sortable, $noIndex, $allowsMissing); if ($noStem) { $this->fieldArguments[] = 'NOSTEM'; } if ($phonetic !== '') { $this->fieldArguments[] = 'PHONETIC'; $this->fieldArguments[] = $phonetic; } if ($weight !== 1) { $this->fieldArguments[] = 'WEIGHT'; $this->fieldArguments[] = $weight; } if ($withSuffixTrie) { $this->fieldArguments[] = 'WITHSUFFIXTRIE'; } if ($allowsEmpty) { $this->fieldArguments[] = 'INDEXEMPTY'; } } } PK)_]4qee9src/Command/Argument/Search/SchemaFields/NumericField.phpnu[setCommonOptions('NUMERIC', $identifier, $alias, $sortable, $noIndex, $allowsMissing); } } PK)_]6cc/src/Command/Argument/Search/SugGetArguments.phpnu[arguments[] = 'FUZZY'; return $this; } /** * Limits the results to a maximum of num (default: 5). * * @param int $num * @return $this */ public function max(int $num): self { array_push($this->arguments, 'MAX', $num); return $this; } } PK)_]/bb/src/Command/Argument/Search/CreateArguments.phpnu[ 'HASH', 'json' => 'JSON', ]; /** * Specify data type for given index. To index JSON you must have the RedisJSON module to be installed. * * @param string $modifier * @return $this */ public function on(string $modifier = 'HASH'): self { if (in_array(strtoupper($modifier), $this->supportedDataTypesEnum)) { $this->arguments[] = 'ON'; $this->arguments[] = $this->supportedDataTypesEnum[strtolower($modifier)]; return $this; } $enumValues = implode(', ', array_values($this->supportedDataTypesEnum)); throw new InvalidArgumentException("Wrong modifier value given. Currently supports: {$enumValues}"); } /** * Adds one or more prefixes into index. * * @param array $prefixes * @return $this */ public function prefix(array $prefixes): self { $this->arguments[] = 'PREFIX'; $this->arguments[] = count($prefixes); $this->arguments = array_merge($this->arguments, $prefixes); return $this; } /** * Document attribute set as document language. * * @param string $languageAttribute * @return $this */ public function languageField(string $languageAttribute): self { $this->arguments[] = 'LANGUAGE_FIELD'; $this->arguments[] = $languageAttribute; return $this; } /** * Default score for documents in the index. * * @param float $defaultScore * @return $this */ public function score(float $defaultScore = 1.0): self { $this->arguments[] = 'SCORE'; $this->arguments[] = $defaultScore; return $this; } /** * Document attribute that used as the document rank based on the user ranking. * * @param string $scoreAttribute * @return $this */ public function scoreField(string $scoreAttribute): self { $this->arguments[] = 'SCORE_FIELD'; $this->arguments[] = $scoreAttribute; return $this; } /** * Forces RediSearch to encode indexes as if there were more than 32 text attributes. * * @return $this */ public function maxTextFields(): self { $this->arguments[] = 'MAXTEXTFIELDS'; return $this; } /** * Does not store term offsets for documents. * * @return $this */ public function noOffsets(): self { $this->arguments[] = 'NOOFFSETS'; return $this; } /** * Creates a lightweight temporary index that expires after a specified period of inactivity, in seconds. * * @param int $seconds * @return $this */ public function temporary(int $seconds): self { $this->arguments[] = 'TEMPORARY'; $this->arguments[] = $seconds; return $this; } /** * Conserves storage space and memory by disabling highlighting support. * * @return $this */ public function noHl(): self { $this->arguments[] = 'NOHL'; return $this; } /** * Does not store attribute bits for each term. * * @return $this */ public function noFields(): self { $this->arguments[] = 'NOFIELDS'; return $this; } /** * Avoids saving the term frequencies in the index. * * @return $this */ public function noFreqs(): self { $this->arguments[] = 'NOFREQS'; return $this; } /** * Sets the index with a custom stopword list, to be ignored during indexing and search time. * * @param array $stopWords * @return $this */ public function stopWords(array $stopWords): self { $this->arguments[] = 'STOPWORDS'; $this->arguments[] = count($stopWords); $this->arguments = array_merge($this->arguments, $stopWords); return $this; } } PK)_]19/src/Command/Argument/Search/CursorArguments.phpnu[arguments, 'COUNT', $readSize); return $this; } /** * {@inheritDoc} */ public function toArray(): array { return $this->arguments; } } PK)_]}W/src/Command/Argument/Search/CommonArguments.phpnu[arguments[] = 'LANGUAGE'; $this->arguments[] = $defaultLanguage; return $this; } /** * Selects the dialect version under which to execute the query. * If not specified, the query will execute under the default dialect version * set during module initial loading or via FT.CONFIG SET command. * * @param string $dialect * @return $this */ public function dialect(string $dialect): self { $this->arguments[] = 'DIALECT'; $this->arguments[] = $dialect; return $this; } /** * If set, does not scan and index. * * @return $this */ public function skipInitialScan(): self { $this->arguments[] = 'SKIPINITIALSCAN'; return $this; } /** * Adds an arbitrary, binary safe payload that is exposed to custom scoring functions. * * @param string $payload * @return $this */ public function payload(string $payload): self { $this->arguments[] = 'PAYLOAD'; $this->arguments[] = $payload; return $this; } /** * Also returns the relative internal score of each document. * * @return $this */ public function withScores(): self { $this->arguments[] = 'WITHSCORES'; return $this; } /** * Retrieves optional document payloads. * * @return $this */ public function withPayloads(): self { $this->arguments[] = 'WITHPAYLOADS'; return $this; } /** * Does not try to use stemming for query expansion but searches the query terms verbatim. * * @return $this */ public function verbatim(): self { $this->arguments[] = 'VERBATIM'; return $this; } /** * Overrides the timeout parameter of the module. * * @param int $timeout * @return $this */ public function timeout(int $timeout): self { $this->arguments[] = 'TIMEOUT'; $this->arguments[] = $timeout; return $this; } /** * Adds an arbitrary, binary safe payload that is exposed to custom scoring functions. * * @param int $offset * @param int $num * @return $this */ public function limit(int $offset, int $num): self { array_push($this->arguments, 'LIMIT', $offset, $num); return $this; } /** * Adds filter expression into index. * * @param string $filter * @return $this */ public function filter(string $filter): self { $this->arguments[] = 'FILTER'; $this->arguments[] = $filter; return $this; } /** * Defines one or more value parameters. Each parameter has a name and a value. * * Example: ['name1', 'value1', 'name2', 'value2'...] * * @param array $nameValuesDictionary * @return $this */ public function params(array $nameValuesDictionary): self { $this->arguments[] = 'PARAMS'; $this->arguments[] = count($nameValuesDictionary); $this->arguments = array_merge($this->arguments, $nameValuesDictionary); return $this; } /** * {@inheritDoc} */ public function toArray(): array { return $this->arguments; } } PK)_]1F0src/Command/Argument/Search/ProfileArguments.phpnu[arguments[] = 'SEARCH'; return $this; } /** * Adds aggregate context. * * @return $this */ public function aggregate(): self { $this->arguments[] = 'AGGREGATE'; return $this; } /** * Removes details of reader iterator. * * @return $this */ public function limited(): self { $this->arguments[] = 'LIMITED'; return $this; } /** * Is query string, as if sent to FT.SEARCH. * * @param string $query * @return $this */ public function query(string $query): self { $this->arguments[] = 'QUERY'; $this->arguments[] = $query; return $this; } /** * {@inheritDoc} */ public function toArray(): array { return $this->arguments; } } PK)_]%""3src/Command/Argument/Search/SpellcheckArguments.phpnu[ 'INCLUDE', 'exclude' => 'EXCLUDE', ]; /** * Is maximum Levenshtein distance for spelling suggestions (default: 1, max: 4). * * @return $this */ public function distance(int $distance): self { $this->arguments[] = 'DISTANCE'; $this->arguments[] = $distance; return $this; } /** * Specifies an inclusion (INCLUDE) or exclusion (EXCLUDE) of a custom dictionary named {dict}. * * @param string $dictionary * @param string $modifier * @param string ...$terms * @return $this */ public function terms(string $dictionary, string $modifier = 'INCLUDE', string ...$terms): self { if (!in_array(strtoupper($modifier), $this->termsEnum)) { $enumValues = implode(', ', array_values($this->termsEnum)); throw new InvalidArgumentException("Wrong modifier value given. Currently supports: {$enumValues}"); } array_push($this->arguments, 'TERMS', $this->termsEnum[strtolower($modifier)], $dictionary, ...$terms); return $this; } } PK)_]%$$-src/Command/Argument/Search/DropArguments.phpnu[arguments[] = 'DD'; return $this; } /** * @return array */ public function toArray(): array { return $this->arguments; } } PK)_]?aa2src/Command/Argument/Search/SynUpdateArguments.phpnu[ 'ASC', 'desc' => 'DESC', ]; /** * Loads document attributes from the source document. * * @param string ...$fields Could be just '*' to load all fields * @return $this */ public function load(string ...$fields): self { $arguments = func_get_args(); $this->arguments[] = 'LOAD'; if ($arguments[0] === '*') { $this->arguments[] = '*'; return $this; } $this->arguments[] = count($arguments); $this->arguments = array_merge($this->arguments, $arguments); return $this; } /** * Loads document attributes from the source document. * * @param string ...$properties * @return $this */ public function groupBy(string ...$properties): self { $arguments = func_get_args(); array_push($this->arguments, 'GROUPBY', count($arguments)); $this->arguments = array_merge($this->arguments, $arguments); return $this; } /** * Groups the results in the pipeline based on one or more properties. * * If you want to add alias property to your argument just add "true" value in arguments enumeration, * next value will be considered as alias to previous one. * * Example: 'argument', true, 'name' => 'argument' AS 'name' * * @param string $function * @param string|bool ...$argument * @return $this */ public function reduce(string $function, ...$argument): self { $arguments = func_get_args(); $functionValue = array_shift($arguments); $argumentsCounter = 0; for ($i = 0, $iMax = count($arguments); $i < $iMax; $i++) { if (true === $arguments[$i]) { $arguments[$i] = 'AS'; $i++; continue; } $argumentsCounter++; } array_push($this->arguments, 'REDUCE', $functionValue); $this->arguments = array_merge($this->arguments, [$argumentsCounter], $arguments); return $this; } /** * Sorts the pipeline up until the point of SORTBY, using a list of properties. * * @param int $max * @param string ...$properties Enumeration of properties, including sorting direction (ASC, DESC) * @return $this */ public function sortBy(int $max = 0, ...$properties): self { $arguments = func_get_args(); $maxValue = array_shift($arguments); $this->arguments[] = 'SORTBY'; $this->arguments = array_merge($this->arguments, [count($arguments)], $arguments); if ($maxValue !== 0) { array_push($this->arguments, 'MAX', $maxValue); } return $this; } /** * Applies a 1-to-1 transformation on one or more properties and either stores the result * as a new property down the pipeline or replaces any property using this transformation. * * @param string $expression * @param string $as * @return $this */ public function apply(string $expression, string $as = ''): self { array_push($this->arguments, 'APPLY', $expression); if ($as !== '') { array_push($this->arguments, 'AS', $as); } return $this; } /** * Scan part of the results with a quicker alternative than LIMIT. * * @param int $readSize * @param int $idleTime * @return $this */ public function withCursor(int $readSize = 0, int $idleTime = 0): self { $this->arguments[] = 'WITHCURSOR'; if ($readSize !== 0) { array_push($this->arguments, 'COUNT', $readSize); } if ($idleTime !== 0) { array_push($this->arguments, 'MAXIDLE', $idleTime); } return $this; } } PK)_],|.!.!/src/Command/Argument/Search/SearchArguments.phpnu[ 'ASC', 'desc' => 'DESC', ]; /** * Returns the document ids and not the content. * * @return $this */ public function noContent(): self { $this->arguments[] = 'NOCONTENT'; return $this; } /** * Returns the value of the sorting key, right after the id and score and/or payload, if requested. * * @return $this */ public function withSortKeys(): self { $this->arguments[] = 'WITHSORTKEYS'; return $this; } /** * Limits results to those having numeric values ranging between min and max, * if numeric_attribute is defined as a numeric attribute in FT.CREATE. * Min and max follow ZRANGE syntax, and can be -inf, +inf, and use( for exclusive ranges. * Multiple numeric filters for different attributes are supported in one query. * * @param array ...$filter Should contain: numeric_field, min and max. Example: ['numeric_field', 1, 10] * @return $this */ public function searchFilter(array ...$filter): self { $arguments = func_get_args(); foreach ($arguments as $argument) { array_push($this->arguments, 'FILTER', ...$argument); } return $this; } /** * Filter the results to a given radius from lon and lat. Radius is given as a number and units. * * @param array ...$filter Should contain: geo_field, lon, lat, radius, unit. Example: ['geo_field', 34.1231, 35.1231, 300, km] * @return $this */ public function geoFilter(array ...$filter): self { $arguments = func_get_args(); foreach ($arguments as $argument) { array_push($this->arguments, 'GEOFILTER', ...$argument); } return $this; } /** * Limits the result to a given set of keys specified in the list. * * @param array $keys * @return $this */ public function inKeys(array $keys): self { $this->arguments[] = 'INKEYS'; $this->arguments[] = count($keys); $this->arguments = array_merge($this->arguments, $keys); return $this; } /** * Filters the results to those appearing only in specific attributes of the document, like title or URL. * * @param array $fields * @return $this */ public function inFields(array $fields): self { $this->arguments[] = 'INFIELDS'; $this->arguments[] = count($fields); $this->arguments = array_merge($this->arguments, $fields); return $this; } /** * Limits the attributes returned from the document. * Num is the number of attributes following the keyword. * If num is 0, it acts like NOCONTENT. * Identifier is either an attribute name (for hashes and JSON) or a JSON Path expression (for JSON). * Property is an optional name used in the result. If not provided, the identifier is used in the result. * * If you want to add alias property to your identifier just add "true" value in identifier enumeration, * next value will be considered as alias to previous one. * * Example: 'identifier', true, 'property' => 'identifier' AS 'property' * * @param int $count * @param string|bool ...$identifier * @return $this */ public function addReturn(int $count, ...$identifier): self { $arguments = func_get_args(); $this->arguments[] = 'RETURN'; for ($i = 1, $iMax = count($arguments); $i < $iMax; $i++) { if (true === $arguments[$i]) { $arguments[$i] = 'AS'; } } $this->arguments = array_merge($this->arguments, $arguments); return $this; } /** * Returns only the sections of the attribute that contain the matched text. * * @param array $fields * @param int $frags * @param int $len * @param string $separator * @return $this */ public function summarize(array $fields = [], int $frags = 0, int $len = 0, string $separator = ''): self { $this->arguments[] = 'SUMMARIZE'; if (!empty($fields)) { $this->arguments[] = 'FIELDS'; $this->arguments[] = count($fields); $this->arguments = array_merge($this->arguments, $fields); } if ($frags !== 0) { $this->arguments[] = 'FRAGS'; $this->arguments[] = $frags; } if ($len !== 0) { $this->arguments[] = 'LEN'; $this->arguments[] = $len; } if ($separator !== '') { $this->arguments[] = 'SEPARATOR'; $this->arguments[] = $separator; } return $this; } /** * Formats occurrences of matched text. * * @param array $fields * @param string $openTag * @param string $closeTag * @return $this */ public function highlight(array $fields = [], string $openTag = '', string $closeTag = ''): self { $this->arguments[] = 'HIGHLIGHT'; if (!empty($fields)) { $this->arguments[] = 'FIELDS'; $this->arguments[] = count($fields); $this->arguments = array_merge($this->arguments, $fields); } if ($openTag !== '' && $closeTag !== '') { array_push($this->arguments, 'TAGS', $openTag, $closeTag); } return $this; } /** * Allows a maximum of N intervening number of unmatched offsets between phrase terms. * In other words, the slop for exact phrases is 0. * * @param int $slop * @return $this */ public function slop(int $slop): self { $this->arguments[] = 'SLOP'; $this->arguments[] = $slop; return $this; } /** * Puts the query terms in the same order in the document as in the query, regardless of the offsets between them. * Typically used in conjunction with SLOP. * * @return $this */ public function inOrder(): self { $this->arguments[] = 'INORDER'; return $this; } /** * Uses a custom query expander instead of the stemmer. * * @param string $expander * @return $this */ public function expander(string $expander): self { $this->arguments[] = 'EXPANDER'; $this->arguments[] = $expander; return $this; } /** * Uses a custom scoring function you define. * * @param string $scorer * @return $this */ public function scorer(string $scorer): self { $this->arguments[] = 'SCORER'; $this->arguments[] = $scorer; return $this; } /** * Returns a textual description of how the scores were calculated. * Using this options requires the WITHSCORES option. * * @return $this */ public function explainScore(): self { $this->arguments[] = 'EXPLAINSCORE'; return $this; } /** * Orders the results by the value of this attribute. * This applies to both text and numeric attributes. * Attributes needed for SORTBY should be declared as SORTABLE in the index, in order to be available with very low latency. * Note that this adds memory overhead. * * @param string $sortAttribute * @param string $orderBy * @return $this */ public function sortBy(string $sortAttribute, string $orderBy = 'asc'): self { $this->arguments[] = 'SORTBY'; $this->arguments[] = $sortAttribute; if (in_array(strtoupper($orderBy), $this->sortingEnum)) { $this->arguments[] = $this->sortingEnum[strtolower($orderBy)]; } else { $enumValues = implode(', ', array_values($this->sortingEnum)); throw new InvalidArgumentException("Wrong order direction value given. Currently supports: {$enumValues}"); } return $this; } } PK)_]{ u/src/Command/Argument/Search/SugAddArguments.phpnu[arguments[] = 'INCR'; return $this; } } PK)_]__0src/Command/Argument/Search/ExplainArguments.phpnu[arguments, 'FILTER', ...$filterExpressions); return $this; } /** * Splits time series into groups, each group contains time series that share the same * value for the provided label name, then aggregates results in each group. * * @param string $label * @param string $reducer * @return $this */ public function groupBy(string $label, string $reducer): self { array_push($this->arguments, 'GROUPBY', $label, 'REDUCE', $reducer); return $this; } } PK)_]K.3src/Command/Argument/TimeSeries/CommonArguments.phpnu[arguments, 'RETENTION', $retentionPeriod); return $this; } /** * Ignore samples with given time or value difference. * * @param int $maxTimeDiff Non-negative integer value in milliseconds * @param float $maxValDiff Non-negative float value * @return $this */ public function ignore(int $maxTimeDiff, float $maxValDiff): self { if ($maxTimeDiff < 0 || $maxValDiff < 0) { throw new UnexpectedValueException('Ignore does not accept negative values'); } array_push($this->arguments, 'IGNORE', $maxTimeDiff, $maxValDiff); return $this; } /** * Is initial allocation size, in bytes, for the data part of each new chunk. * * @param int $size * @return $this */ public function chunkSize(int $size): self { array_push($this->arguments, 'CHUNK_SIZE', $size); return $this; } /** * Is policy for handling insertion of multiple samples with identical timestamps. * * @param string $policy * @return $this */ public function duplicatePolicy(string $policy = self::POLICY_BLOCK): self { array_push($this->arguments, 'DUPLICATE_POLICY', $policy); return $this; } /** * Is set of label-value pairs that represent metadata labels of the key and serve as a secondary index. * * @param mixed ...$labelValuePair * @return $this */ public function labels(...$labelValuePair): self { array_push($this->arguments, 'LABELS', ...$labelValuePair); return $this; } /** * Specifies the series samples encoding format. * * @param string $encoding * @return $this */ public function encoding(string $encoding = self::ENCODING_COMPRESSED): self { array_push($this->arguments, 'ENCODING', $encoding); return $this; } /** * Is used when a time series is a compaction. * With LATEST, TS.GET reports the compacted value of the latest, possibly partial, bucket. * * @return $this */ public function latest(): self { $this->arguments[] = 'LATEST'; return $this; } /** * Includes in the reply all label-value pairs representing metadata labels of the time series. * * @return $this */ public function withLabels(): self { $this->arguments[] = 'WITHLABELS'; return $this; } /** * Returns a subset of the label-value pairs that represent metadata labels of the time series. * * @return $this */ public function selectedLabels(string ...$labels): self { array_push($this->arguments, 'SELECTED_LABELS', ...$labels); return $this; } /** * {@inheritDoc} */ public function toArray(): array { return $this->arguments; } } PK)_]arguments, 'TIMESTAMP', $timeStamp); return $this; } /** * Changes data storage from compressed (default) to uncompressed. * * @return $this */ public function uncompressed(): self { $this->arguments[] = 'UNCOMPRESSED'; return $this; } } PK)_]S``1src/Command/Argument/TimeSeries/MGetArguments.phpnu[arguments, 'FILTER_BY_TS', ...$ts); return $this; } /** * Filters samples by minimum and maximum values. * * @param int $min * @param int $max * @return $this */ public function filterByValue(int $min, int $max): self { array_push($this->arguments, 'FILTER_BY_VALUE', $min, $max); return $this; } /** * Limits the number of returned samples. * * @param int $count * @return $this */ public function count(int $count): self { array_push($this->arguments, 'COUNT', $count); return $this; } /** * Aggregates samples into time buckets. * * @param string $aggregator * @param int $bucketDuration Is duration of each bucket, in milliseconds. * @param int $align It controls the time bucket timestamps by changing the reference timestamp on which a bucket is defined. * @param int $bucketTimestamp Controls how bucket timestamps are reported. * @param bool $empty Is a flag, which, when specified, reports aggregations also for empty buckets. * @return $this */ public function aggregation(string $aggregator, int $bucketDuration, int $align = 0, int $bucketTimestamp = 0, bool $empty = false): self { if ($align > 0) { array_push($this->arguments, 'ALIGN', $align); } array_push($this->arguments, 'AGGREGATION', $aggregator, $bucketDuration); if ($bucketTimestamp > 0) { array_push($this->arguments, 'BUCKETTIMESTAMP', $bucketTimestamp); } if (true === $empty) { $this->arguments[] = 'EMPTY'; } return $this; } } PK)_]&Mbb3src/Command/Argument/TimeSeries/DecrByArguments.phpnu[arguments, 'ON_DUPLICATE', $policy); return $this; } } PK)_] _441src/Command/Argument/TimeSeries/InfoArguments.phpnu[arguments[] = 'DEBUG'; return $this; } /** * {@inheritDoc} */ public function toArray(): array { return $this->arguments; } } PK)_]^,src/Command/Argument/Geospatial/ByRadius.phpnu[radius = $radius; $this->setUnit($unit); } /** * {@inheritDoc} */ public function toArray(): array { return [self::KEYWORD, $this->radius, $this->unit]; } } PK)_]@س.src/Command/Argument/Geospatial/AbstractBy.phpnu[unit = $unit; } } PK)_]SD33.src/Command/Argument/Geospatial/FromLonLat.phpnu[longitude = $longitude; $this->latitude = $latitude; } /** * {@inheritDoc} */ public function toArray(): array { return [self::KEYWORD, $this->longitude, $this->latitude]; } } PK)_]`/src/Command/Argument/Geospatial/ByInterface.phpnu[width = $width; $this->height = $height; $this->setUnit($unit); } /** * {@inheritDoc} */ public function toArray(): array { return [self::KEYWORD, $this->width, $this->height, $this->unit]; } } PK)_]y.src/Command/Argument/Geospatial/FromMember.phpnu[member = $member; } /** * {@inheritDoc} */ public function toArray(): array { return [self::KEYWORD, $this->member]; } } PK)_]G)  0src/Command/Argument/Server/LimitOffsetCount.phpnu[offset = $offset; $this->count = $count; } /** * {@inheritDoc} */ public function toArray(): array { return [self::KEYWORD, $this->offset, $this->count]; } } PK)_]-m<<"src/Command/Argument/Server/To.phpnu[host = $host; $this->port = $port; $this->isForce = $isForce; } /** * {@inheritDoc} */ public function toArray(): array { $arguments = [self::KEYWORD, $this->host, $this->port]; if ($this->isForce) { $arguments[] = self::FORCE_KEYWORD; } return $arguments; } } PK)_]ؓ.src/Command/Argument/Server/LimitInterface.phpnu[prefix = $prefix; $prefixFirst = static::class . '::first'; $prefixFirstTwo = static::class . '::firstTwo'; $prefixAll = static::class . '::all'; $prefixInterleaved = static::class . '::interleaved'; $prefixSkipFirst = static::class . '::skipFirst'; $prefixSkipLast = static::class . '::skipLast'; $prefixSort = static::class . '::sort'; $prefixEvalKeys = static::class . '::evalKeys'; $prefixZsetStore = static::class . '::zsetStore'; $prefixMigrate = static::class . '::migrate'; $prefixGeoradius = static::class . '::georadius'; $this->commands = [ /* ---------------- Redis 1.2 ---------------- */ 'EXISTS' => $prefixAll, 'DEL' => $prefixAll, 'TYPE' => $prefixFirst, 'KEYS' => $prefixFirst, 'RENAME' => $prefixAll, 'RENAMENX' => $prefixAll, 'EXPIRE' => $prefixFirst, 'EXPIREAT' => $prefixFirst, 'TTL' => $prefixFirst, 'MOVE' => $prefixFirst, 'SORT' => $prefixSort, 'DUMP' => $prefixFirst, 'RESTORE' => $prefixFirst, 'SET' => $prefixFirst, 'SETNX' => $prefixFirst, 'MSET' => $prefixInterleaved, 'MSETNX' => $prefixInterleaved, 'GET' => $prefixFirst, 'MGET' => $prefixAll, 'GETSET' => $prefixFirst, 'INCR' => $prefixFirst, 'INCRBY' => $prefixFirst, 'DECR' => $prefixFirst, 'DECRBY' => $prefixFirst, 'RPUSH' => $prefixFirst, 'LPUSH' => $prefixFirst, 'LLEN' => $prefixFirst, 'LRANGE' => $prefixFirst, 'LTRIM' => $prefixFirst, 'LINDEX' => $prefixFirst, 'LSET' => $prefixFirst, 'LREM' => $prefixFirst, 'LPOP' => $prefixFirst, 'RPOP' => $prefixFirst, 'RPOPLPUSH' => $prefixAll, 'SADD' => $prefixFirst, 'SREM' => $prefixFirst, 'SPOP' => $prefixFirst, 'SMOVE' => $prefixSkipLast, 'SCARD' => $prefixFirst, 'SISMEMBER' => $prefixFirst, 'SINTER' => $prefixAll, 'SINTERSTORE' => $prefixAll, 'SUNION' => $prefixAll, 'SUNIONSTORE' => $prefixAll, 'SDIFF' => $prefixAll, 'SDIFFSTORE' => $prefixAll, 'SMEMBERS' => $prefixFirst, 'SMISMEMBER' => $prefixFirst, 'SRANDMEMBER' => $prefixFirst, 'ZADD' => $prefixFirst, 'ZINCRBY' => $prefixFirst, 'ZREM' => $prefixFirst, 'ZRANGE' => $prefixFirst, 'ZREVRANGE' => $prefixFirst, 'ZRANGEBYSCORE' => $prefixFirst, 'ZCARD' => $prefixFirst, 'ZSCORE' => $prefixFirst, 'ZREMRANGEBYSCORE' => $prefixFirst, /* ---------------- Redis 2.0 ---------------- */ 'SETEX' => $prefixFirst, 'APPEND' => $prefixFirst, 'SUBSTR' => $prefixFirst, 'BLPOP' => $prefixSkipLast, 'BRPOP' => $prefixSkipLast, 'ZUNIONSTORE' => $prefixZsetStore, 'ZINTERSTORE' => $prefixZsetStore, 'ZCOUNT' => $prefixFirst, 'ZRANK' => $prefixFirst, 'ZREVRANK' => $prefixFirst, 'ZREMRANGEBYRANK' => $prefixFirst, 'HSET' => $prefixFirst, 'HSETNX' => $prefixFirst, 'HMSET' => $prefixFirst, 'HINCRBY' => $prefixFirst, 'HGET' => $prefixFirst, 'HMGET' => $prefixFirst, 'HDEL' => $prefixFirst, 'HEXISTS' => $prefixFirst, 'HLEN' => $prefixFirst, 'HKEYS' => $prefixFirst, 'HVALS' => $prefixFirst, 'HGETALL' => $prefixFirst, 'SUBSCRIBE' => $prefixAll, 'UNSUBSCRIBE' => $prefixAll, 'PSUBSCRIBE' => $prefixAll, 'PUNSUBSCRIBE' => $prefixAll, 'PUBLISH' => $prefixFirst, /* ---------------- Redis 2.2 ---------------- */ 'PERSIST' => $prefixFirst, 'STRLEN' => $prefixFirst, 'SETRANGE' => $prefixFirst, 'GETRANGE' => $prefixFirst, 'SETBIT' => $prefixFirst, 'GETBIT' => $prefixFirst, 'RPUSHX' => $prefixFirst, 'LPUSHX' => $prefixFirst, 'LINSERT' => $prefixFirst, 'BRPOPLPUSH' => $prefixSkipLast, 'ZREVRANGEBYSCORE' => $prefixFirst, 'WATCH' => $prefixAll, /* ---------------- Redis 2.6 ---------------- */ 'PTTL' => $prefixFirst, 'PEXPIRE' => $prefixFirst, 'PEXPIREAT' => $prefixFirst, 'PSETEX' => $prefixFirst, 'INCRBYFLOAT' => $prefixFirst, 'BITOP' => $prefixSkipFirst, 'BITCOUNT' => $prefixFirst, 'HINCRBYFLOAT' => $prefixFirst, 'EVAL' => $prefixEvalKeys, 'EVALSHA' => $prefixEvalKeys, 'MIGRATE' => $prefixMigrate, /* ---------------- Redis 2.8 ---------------- */ 'SSCAN' => $prefixFirst, 'ZSCAN' => $prefixFirst, 'HSCAN' => $prefixFirst, 'PFADD' => $prefixFirst, 'PFCOUNT' => $prefixAll, 'PFMERGE' => $prefixAll, 'ZLEXCOUNT' => $prefixFirst, 'ZRANGEBYLEX' => $prefixFirst, 'ZREMRANGEBYLEX' => $prefixFirst, 'ZREVRANGEBYLEX' => $prefixFirst, 'BITPOS' => $prefixFirst, /* ---------------- Redis 3.2 ---------------- */ 'HSTRLEN' => $prefixFirst, 'BITFIELD' => $prefixFirst, 'GEOADD' => $prefixFirst, 'GEOHASH' => $prefixFirst, 'GEOPOS' => $prefixFirst, 'GEODIST' => $prefixFirst, 'GEORADIUS' => $prefixGeoradius, 'GEORADIUSBYMEMBER' => $prefixGeoradius, /* ---------------- Redis 5.0 ---------------- */ 'XADD' => $prefixFirst, 'XRANGE' => $prefixFirst, 'XREVRANGE' => $prefixFirst, 'XDEL' => $prefixFirst, 'XLEN' => $prefixFirst, 'XACK' => $prefixFirst, 'XTRIM' => $prefixFirst, 'ZPOPMIN' => $prefixFirst, 'ZPOPMAX' => $prefixFirst, /* ---------------- Redis 6.2 ---------------- */ 'GETDEL' => $prefixFirst, 'ZMSCORE' => $prefixFirst, 'LMOVE' => $prefixFirstTwo, 'BLMOVE' => $prefixFirstTwo, 'GEOSEARCH' => $prefixFirst, /* ---------------- Redis 7.0 ---------------- */ 'EXPIRETIME' => $prefixFirst, /* RedisJSON */ 'JSON.ARRAPPEND' => $prefixFirst, 'JSON.ARRINDEX' => $prefixFirst, 'JSON.ARRINSERT' => $prefixFirst, 'JSON.ARRLEN' => $prefixFirst, 'JSON.ARRPOP' => $prefixFirst, 'JSON.ARRTRIM' => $prefixFirst, 'JSON.CLEAR' => $prefixFirst, 'JSON.DEBUG MEMORY' => $prefixFirst, 'JSON.DEL' => $prefixFirst, 'JSON.FORGET' => $prefixFirst, 'JSON.GET' => $prefixFirst, 'JSON.MGET' => $prefixAll, 'JSON.NUMINCRBY' => $prefixFirst, 'JSON.OBJKEYS' => $prefixFirst, 'JSON.OBJLEN' => $prefixFirst, 'JSON.RESP' => $prefixFirst, 'JSON.SET' => $prefixFirst, 'JSON.STRAPPEND' => $prefixFirst, 'JSON.STRLEN' => $prefixFirst, 'JSON.TOGGLE' => $prefixFirst, 'JSON.TYPE' => $prefixFirst, /* RedisBloom */ 'BF.ADD' => $prefixFirst, 'BF.EXISTS' => $prefixFirst, 'BF.INFO' => $prefixFirst, 'BF.INSERT' => $prefixFirst, 'BF.LOADCHUNK' => $prefixFirst, 'BF.MADD' => $prefixFirst, 'BF.MEXISTS' => $prefixFirst, 'BF.RESERVE' => $prefixFirst, 'BF.SCANDUMP' => $prefixFirst, 'CF.ADD' => $prefixFirst, 'CF.ADDNX' => $prefixFirst, 'CF.COUNT' => $prefixFirst, 'CF.DEL' => $prefixFirst, 'CF.EXISTS' => $prefixFirst, 'CF.INFO' => $prefixFirst, 'CF.INSERT' => $prefixFirst, 'CF.INSERTNX' => $prefixFirst, 'CF.LOADCHUNK' => $prefixFirst, 'CF.MEXISTS' => $prefixFirst, 'CF.RESERVE' => $prefixFirst, 'CF.SCANDUMP' => $prefixFirst, 'CMS.INCRBY' => $prefixFirst, 'CMS.INFO' => $prefixFirst, 'CMS.INITBYDIM' => $prefixFirst, 'CMS.INITBYPROB' => $prefixFirst, 'CMS.QUERY' => $prefixFirst, 'TDIGEST.ADD' => $prefixFirst, 'TDIGEST.BYRANK' => $prefixFirst, 'TDIGEST.BYREVRANK' => $prefixFirst, 'TDIGEST.CDF' => $prefixFirst, 'TDIGEST.CREATE' => $prefixFirst, 'TDIGEST.INFO' => $prefixFirst, 'TDIGEST.MAX' => $prefixFirst, 'TDIGEST.MIN' => $prefixFirst, 'TDIGEST.QUANTILE' => $prefixFirst, 'TDIGEST.RANK' => $prefixFirst, 'TDIGEST.RESET' => $prefixFirst, 'TDIGEST.REVRANK' => $prefixFirst, 'TDIGEST.TRIMMED_MEAN' => $prefixFirst, 'TOPK.ADD' => $prefixFirst, 'TOPK.INCRBY' => $prefixFirst, 'TOPK.INFO' => $prefixFirst, 'TOPK.LIST' => $prefixFirst, 'TOPK.QUERY' => $prefixFirst, 'TOPK.RESERVE' => $prefixFirst, /* RediSearch */ 'FT.AGGREGATE' => $prefixFirst, 'FT.ALTER' => $prefixFirst, 'FT.CREATE' => $prefixFirst, 'FT.CURSOR DEL' => $prefixFirst, 'FT.CURSOR READ' => $prefixFirst, 'FT.DROPINDEX' => $prefixFirst, 'FT.EXPLAIN' => $prefixFirst, 'FT.INFO' => $prefixFirst, 'FT.PROFILE' => $prefixFirst, 'FT.SEARCH' => $prefixFirst, 'FT.SPELLCHECK' => $prefixFirst, 'FT.SYNDUMP' => $prefixFirst, 'FT.SYNUPDATE' => $prefixFirst, 'FT.TAGVALS' => $prefixFirst, /* Redis TimeSeries */ 'TS.ADD' => $prefixFirst, 'TS.ALTER' => $prefixFirst, 'TS.CREATE' => $prefixFirst, 'TS.DECRBY' => $prefixFirst, 'TS.DEL' => $prefixFirst, 'TS.GET' => $prefixFirst, 'TS.INCRBY' => $prefixFirst, 'TS.INFO' => $prefixFirst, 'TS.MGET' => $prefixFirst, 'TS.MRANGE' => $prefixFirst, 'TS.MREVRANGE' => $prefixFirst, 'TS.QUERYINDEX' => $prefixFirst, 'TS.RANGE' => $prefixFirst, 'TS.REVRANGE' => $prefixFirst, ]; } /** * Sets a prefix that is applied to all the keys. * * @param string $prefix Prefix for the keys. */ public function setPrefix($prefix) { $this->prefix = $prefix; } /** * Gets the current prefix. * * @return string */ public function getPrefix() { return $this->prefix; } /** * {@inheritdoc} */ public function process(CommandInterface $command) { if ($command instanceof PrefixableCommandInterface) { $command->prefixKeys($this->prefix); } elseif (isset($this->commands[$commandID = strtoupper($command->getId())])) { $this->commands[$commandID]($command, $this->prefix); } } /** * Sets an handler for the specified command ID. * * The callback signature must have 2 parameters of the following types: * * - Predis\Command\CommandInterface (command instance) * - String (prefix) * * When the callback argument is omitted or NULL, the previously * associated handler for the specified command ID is removed. * * @param string $commandID The ID of the command to be handled. * @param mixed $callback A valid callable object or NULL. * * @throws InvalidArgumentException */ public function setCommandHandler($commandID, $callback = null) { $commandID = strtoupper($commandID); if (!isset($callback)) { unset($this->commands[$commandID]); return; } if (!is_callable($callback)) { throw new InvalidArgumentException( 'Callback must be a valid callable object or NULL' ); } $this->commands[$commandID] = $callback; } /** * {@inheritdoc} */ public function __toString() { return $this->getPrefix(); } /** * Applies the specified prefix only the first argument. * * @param CommandInterface $command Command instance. * @param string $prefix Prefix string. */ public static function first(CommandInterface $command, $prefix) { if ($arguments = $command->getArguments()) { $arguments[0] = "$prefix{$arguments[0]}"; $command->setRawArguments($arguments); } } /** * Applies the specified prefix only to the first two arguments. * * @param CommandInterface $command Command instance. * @param string $prefix Prefix string. */ public static function firstTwo(CommandInterface $command, $prefix) { $arguments = $command->getArguments(); $length = min(count($arguments), 2); for ($i = 0; $i < $length; $i++) { $arguments[$i] = "$prefix{$arguments[$i]}"; } $command->setRawArguments($arguments); } /** * Applies the specified prefix to all the arguments. * * @param CommandInterface $command Command instance. * @param string $prefix Prefix string. */ public static function all(CommandInterface $command, $prefix) { if ($arguments = $command->getArguments()) { foreach ($arguments as &$key) { $key = "$prefix$key"; } $command->setRawArguments($arguments); } } /** * Applies the specified prefix only to even arguments in the list. * * @param CommandInterface $command Command instance. * @param string $prefix Prefix string. */ public static function interleaved(CommandInterface $command, $prefix) { if ($arguments = $command->getArguments()) { $length = count($arguments); for ($i = 0; $i < $length; $i += 2) { $arguments[$i] = "$prefix{$arguments[$i]}"; } $command->setRawArguments($arguments); } } /** * Applies the specified prefix to all the arguments but the first one. * * @param CommandInterface $command Command instance. * @param string $prefix Prefix string. */ public static function skipFirst(CommandInterface $command, $prefix) { if ($arguments = $command->getArguments()) { $length = count($arguments); for ($i = 1; $i < $length; ++$i) { $arguments[$i] = "$prefix{$arguments[$i]}"; } $command->setRawArguments($arguments); } } /** * Applies the specified prefix to all the arguments but the last one. * * @param CommandInterface $command Command instance. * @param string $prefix Prefix string. */ public static function skipLast(CommandInterface $command, $prefix) { if ($arguments = $command->getArguments()) { $length = count($arguments); for ($i = 0; $i < $length - 1; ++$i) { $arguments[$i] = "$prefix{$arguments[$i]}"; } $command->setRawArguments($arguments); } } /** * Applies the specified prefix to the keys of a SORT command. * * @param CommandInterface $command Command instance. * @param string $prefix Prefix string. */ public static function sort(CommandInterface $command, $prefix) { if ($arguments = $command->getArguments()) { $arguments[0] = "$prefix{$arguments[0]}"; if (($count = count($arguments)) > 1) { for ($i = 1; $i < $count; ++$i) { switch (strtoupper($arguments[$i])) { case 'BY': case 'STORE': $arguments[$i] = "$prefix{$arguments[++$i]}"; break; case 'GET': $value = $arguments[++$i]; if ($value !== '#') { $arguments[$i] = "$prefix$value"; } break; case 'LIMIT': $i += 2; break; } } } $command->setRawArguments($arguments); } } /** * Applies the specified prefix to the keys of an EVAL-based command. * * @param CommandInterface $command Command instance. * @param string $prefix Prefix string. */ public static function evalKeys(CommandInterface $command, $prefix) { if ($arguments = $command->getArguments()) { for ($i = 2; $i < $arguments[1] + 2; ++$i) { $arguments[$i] = "$prefix{$arguments[$i]}"; } $command->setRawArguments($arguments); } } /** * Applies the specified prefix to the keys of Z[INTERSECTION|UNION]STORE. * * @param CommandInterface $command Command instance. * @param string $prefix Prefix string. */ public static function zsetStore(CommandInterface $command, $prefix) { if ($arguments = $command->getArguments()) { $arguments[0] = "$prefix{$arguments[0]}"; $length = ((int) $arguments[1]) + 2; for ($i = 2; $i < $length; ++$i) { $arguments[$i] = "$prefix{$arguments[$i]}"; } $command->setRawArguments($arguments); } } /** * Applies the specified prefix to the key of a MIGRATE command. * * @param CommandInterface $command Command instance. * @param string $prefix Prefix string. */ public static function migrate(CommandInterface $command, $prefix) { if ($arguments = $command->getArguments()) { $arguments[2] = "$prefix{$arguments[2]}"; $command->setRawArguments($arguments); } } /** * Applies the specified prefix to the key of a GEORADIUS command. * * @param CommandInterface $command Command instance. * @param string $prefix Prefix string. */ public static function georadius(CommandInterface $command, $prefix) { if ($arguments = $command->getArguments()) { $arguments[0] = "$prefix{$arguments[0]}"; $startIndex = $command->getId() === 'GEORADIUS' ? 5 : 4; if (($count = count($arguments)) > $startIndex) { for ($i = $startIndex; $i < $count; ++$i) { switch (strtoupper($arguments[$i])) { case 'STORE': case 'STOREDIST': $arguments[$i] = "$prefix{$arguments[++$i]}"; break; } } } $command->setRawArguments($arguments); } } } PK)_]7i i (src/Command/Processor/ProcessorChain.phpnu[add($processor); } } /** * {@inheritdoc} */ public function add(ProcessorInterface $processor) { $this->processors[] = $processor; } /** * {@inheritdoc} */ public function remove(ProcessorInterface $processor) { if (false !== $index = array_search($processor, $this->processors, true)) { unset($this[$index]); } } /** * {@inheritdoc} */ public function process(CommandInterface $command) { for ($i = 0; $i < $count = count($this->processors); ++$i) { $this->processors[$i]->process($command); } } /** * {@inheritdoc} */ public function getProcessors() { return $this->processors; } /** * Returns an iterator over the list of command processor in the chain. * * @return Traversable */ public function getIterator() { return new ArrayIterator($this->processors); } /** * Returns the number of command processors in the chain. * * @return int */ public function count() { return count($this->processors); } /** * @param int $index * @return bool */ #[ReturnTypeWillChange] public function offsetExists($index) { return isset($this->processors[$index]); } /** * @param int $index * @return ProcessorInterface */ #[ReturnTypeWillChange] public function offsetGet($index) { return $this->processors[$index]; } /** * @param int $index * @param ProcessorInterface $processor * @return void */ #[ReturnTypeWillChange] public function offsetSet($index, $processor) { if (!$processor instanceof ProcessorInterface) { throw new InvalidArgumentException( 'Processor chain accepts only instances of `Predis\Command\Processor\ProcessorInterface`' ); } $this->processors[$index] = $processor; } /** * @param int $index * @return void */ #[ReturnTypeWillChange] public function offsetUnset($index) { unset($this->processors[$index]); $this->processors = array_values($this->processors); } } PK)_]NcF src/Command/ScriptCommand.phpnu[getScript()); } /** * Specifies the number of arguments that should be considered as keys. * * The default behaviour for the base class is to return 0 to indicate that * all the elements of the arguments array should be considered as keys, but * subclasses can enforce a static number of keys. * * @return int */ protected function getKeysCount() { return 0; } /** * Returns the elements from the arguments that are identified as keys. * * @return array */ public function getKeys() { return array_slice($this->getArguments(), 2, $this->getKeysCount()); } /** * {@inheritdoc} */ public function setArguments(array $arguments) { if (($numkeys = $this->getKeysCount()) && $numkeys < 0) { $numkeys = count($arguments) + $numkeys; } $arguments = array_merge([$this->getScriptHash(), (int) $numkeys], $arguments); parent::setArguments($arguments); } /** * Returns arguments for EVAL command. * * @return array */ public function getEvalArguments() { $arguments = $this->getArguments(); $arguments[0] = $this->getScript(); return $arguments; } /** * Returns the equivalent EVAL command as a raw command instance. * * @return RawCommand */ public function getEvalCommand() { return new RawCommand('EVAL', $this->getEvalArguments()); } } PK)_]Cz?XX*src/Command/PrefixableCommandInterface.phpnu[getCommandClass($commandID) === null) { return false; } } return true; } /** * Returns the FQCN of a class that represents the specified command ID. * * @codeCoverageIgnore * * @param string $commandID Command ID * * @return string|null */ public function getCommandClass(string $commandID): ?string { return $this->commands[strtoupper($commandID)] ?? null; } /** * {@inheritdoc} */ public function create(string $commandID, array $arguments = []): CommandInterface { if (!$commandClass = $this->getCommandClass($commandID)) { $commandID = strtoupper($commandID); throw new ClientException("Command `$commandID` is not a registered Redis command."); } $command = new $commandClass(); $command->setArguments($arguments); if (isset($this->processor)) { $this->processor->process($command); } return $command; } /** * Defines a command in the factory. * * Only classes implementing Predis\Command\CommandInterface are allowed to * handle a command. If the command specified by its ID is already handled * by the factory, the underlying command class is replaced by the new one. * * @param string $commandID Command ID * @param string $commandClass FQCN of a class implementing Predis\Command\CommandInterface * * @throws InvalidArgumentException */ public function define(string $commandID, string $commandClass): void { if (!is_a($commandClass, 'Predis\Command\CommandInterface', true)) { throw new InvalidArgumentException( "Class $commandClass must implement Predis\Command\CommandInterface" ); } $this->commands[strtoupper($commandID)] = $commandClass; } /** * Undefines a command in the factory. * * When the factory already has a class handler associated to the specified * command ID it is removed from the map of known commands. Nothing happens * when the command is not handled by the factory. * * @param string $commandID Command ID */ public function undefine(string $commandID): void { unset($this->commands[strtoupper($commandID)]); } /** * Sets a command processor for processing command arguments. * * Command processors are used to process and transform arguments of Redis * commands before their newly created instances are returned to the caller * of "create()". * * A NULL value can be used to effectively unset any processor if previously * set for the command factory. * * @param ProcessorInterface|null $processor Command processor or NULL value. */ public function setProcessor(?ProcessorInterface $processor): void { $this->processor = $processor; } /** * Returns the current command processor. * * @return ProcessorInterface|null */ public function getProcessor(): ?ProcessorInterface { return $this->processor; } } PK)_]i  src/Command/Command.phpnu[arguments = $arguments; unset($this->slot); } /** * {@inheritdoc} */ public function setRawArguments(array $arguments) { $this->arguments = $arguments; unset($this->slot); } /** * {@inheritdoc} */ public function getArguments() { return $this->arguments; } /** * {@inheritdoc} */ public function getArgument($index) { if (isset($this->arguments[$index])) { return $this->arguments[$index]; } } /** * {@inheritdoc} */ public function setSlot($slot) { $this->slot = $slot; } /** * {@inheritdoc} */ public function getSlot() { return $this->slot ?? null; } /** * {@inheritdoc} */ public function parseResponse($data) { return $data; } /** * Normalizes the arguments array passed to a Redis command. * * @param array $arguments Arguments for a command. * * @return array */ public static function normalizeArguments(array $arguments) { if (count($arguments) === 1 && isset($arguments[0]) && is_array($arguments[0])) { return $arguments[0]; } return $arguments; } /** * Normalizes the arguments array passed to a variadic Redis command. * * @param array $arguments Arguments for a command. * * @return array */ public static function normalizeVariadic(array $arguments) { if (count($arguments) === 2 && is_array($arguments[1])) { return array_merge([$arguments[0]], $arguments[1]); } return $arguments; } /** * Remove all false values from arguments. * * @return void */ public function filterArguments(): void { $this->arguments = array_filter($this->arguments, static function ($argument) { return $argument !== false && $argument !== null; }); } } PK)_]ٞ)) src/Command/CommandInterface.phpnu[commandID = strtoupper($commandID); $this->setArguments($arguments); } /** * Creates a new raw command using a variadic method. * * @param string $commandID Redis command ID * @param string ...$args Arguments list for the command * * @return CommandInterface */ public static function create($commandID, ...$args) { $arguments = func_get_args(); return new static(array_shift($arguments), $arguments); } /** * {@inheritdoc} */ public function getId() { return $this->commandID; } /** * {@inheritdoc} */ public function setArguments(array $arguments) { $this->arguments = $arguments; unset($this->slot); } /** * {@inheritdoc} */ public function setRawArguments(array $arguments) { $this->setArguments($arguments); } /** * {@inheritdoc} */ public function getArguments() { return $this->arguments; } /** * {@inheritdoc} */ public function getArgument($index) { if (isset($this->arguments[$index])) { return $this->arguments[$index]; } } /** * {@inheritdoc} */ public function setSlot($slot) { $this->slot = $slot; } /** * {@inheritdoc} */ public function getSlot() { return $this->slot ?? null; } /** * {@inheritdoc} */ public function parseResponse($data) { return $data; } } PK)_])@ @ src/Command/RedisFactory.phpnu[commands = [ 'ECHO' => 'Predis\Command\Redis\ECHO_', 'EVAL' => 'Predis\Command\Redis\EVAL_', 'OBJECT' => 'Predis\Command\Redis\OBJECT_', // Class name corresponds to PHP reserved word "function", added mapping to bypass restrictions 'FUNCTION' => FUNCTIONS::class, ]; } /** * {@inheritdoc} */ public function getCommandClass(string $commandID): ?string { $commandID = strtoupper($commandID); if (isset($this->commands[$commandID]) || array_key_exists($commandID, $this->commands)) { return $this->commands[$commandID]; } $commandClass = $this->resolve($commandID); if (null === $commandClass) { return null; } $this->commands[$commandID] = $commandClass; return $commandClass; } /** * {@inheritdoc} */ public function undefine(string $commandID): void { // NOTE: we explicitly associate `NULL` to the command ID in the map // instead of the parent's `unset()` because our subclass tries to load // a predefined class from the Predis\Command\Redis namespace when no // explicit mapping is defined, see RedisFactory::getCommandClass() for // details of the implementation of this mechanism. $this->commands[strtoupper($commandID)] = null; } /** * Resolves command object from given command ID. * * @param string $commandID Command ID of virtual method call * @return string|null FQDN of corresponding command object */ private function resolve(string $commandID): ?string { if (class_exists($commandClass = self::COMMANDS_NAMESPACE . '\\' . $commandID)) { return $commandClass; } $commandModule = $this->resolveCommandModuleByPrefix($commandID); if (null === $commandModule) { return null; } if (class_exists($commandClass = self::COMMANDS_NAMESPACE . '\\' . $commandModule . '\\' . $commandID)) { return $commandClass; } return null; } private function resolveCommandModuleByPrefix(string $commandID): ?string { foreach (ClientConfiguration::getModules() as $module) { if (preg_match("/^{$module['commandPrefix']}/", $commandID)) { return $module['name']; } } return null; } } PK)_]3 getHashGeneratorByDescription($options, $value); } elseif ($value instanceof Hash\HashGeneratorInterface) { return $value; } else { $class = get_class($this); throw new InvalidArgumentException("$class expects a valid hash generator"); } } /** * {@inheritdoc} */ public function getDefault(OptionsInterface $options) { return function_exists('phpiredis_utils_crc16') ? new Hash\PhpiredisCRC16() : new Hash\CRC16(); } } PK)_]j8q,R R $src/Configuration/Option/Cluster.phpnu[getConnectionInitializerByString($options, $value); } if (is_callable($value)) { return $this->getConnectionInitializer($options, $value); } else { throw new InvalidArgumentException(sprintf( '%s expects either a string or a callable value, %s given', static::class, is_object($value) ? get_class($value) : gettype($value) )); } } /** * Returns a connection initializer from a descriptive name. * * @param OptionsInterface $options Client options * @param string $description Identifier of a replication backend (`predis`, `sentinel`) * * @return callable */ protected function getConnectionInitializerByString(OptionsInterface $options, string $description) { switch ($description) { case 'redis': case 'redis-cluster': return function ($parameters, $options, $option) { return new RedisCluster($options->connections, new RedisStrategy($options->crc16)); }; case 'predis': return $this->getDefaultConnectionInitializer(); default: throw new InvalidArgumentException(sprintf( '%s expects either `predis`, `redis` or `redis-cluster` as valid string values, `%s` given', static::class, $description )); } } /** * Returns the default connection initializer. * * @return callable */ protected function getDefaultConnectionInitializer() { return function ($parameters, $options, $option) { return new PredisCluster(); }; } /** * {@inheritdoc} */ public function getDefault(OptionsInterface $options) { return $this->getConnectionInitializer( $options, $this->getDefaultConnectionInitializer() ); } } PK)_] gxx#src/Configuration/Option/Prefix.phpnu[createFactoryByArray($options, $value); } elseif (is_string($value)) { return $this->createFactoryByString($options, $value); } else { throw new InvalidArgumentException(sprintf( '%s expects a valid command factory', static::class )); } } /** * Creates a new default command factory from a named array. * * The factory instance is configured according to the supplied named array * mapping command IDs (passed as keys) to the FCQN of classes implementing * Predis\Command\CommandInterface. * * @param OptionsInterface $options Client options container * @param array $value Named array mapping command IDs to classes * * @return FactoryInterface */ protected function createFactoryByArray(OptionsInterface $options, array $value) { /** * @var FactoryInterface */ $commands = $this->getDefault($options); foreach ($value as $commandID => $commandClass) { if ($commandClass === null) { $commands->undefine($commandID); } else { $commands->define($commandID, $commandClass); } } return $commands; } /** * Creates a new command factory from a descriptive string. * * The factory instance is configured according to the supplied descriptive * string that identifies specific configurations of schemes and connection * classes. Supported configuration values are: * * - "predis" returns the default command factory used by Predis * - "raw" returns a command factory that creates only raw commands * - "default" is simply an alias of "predis" * * @param OptionsInterface $options Client options container * @param string $value Descriptive string identifying the desired configuration * * @return FactoryInterface */ protected function createFactoryByString(OptionsInterface $options, string $value) { switch (strtolower($value)) { case 'default': case 'predis': return $this->getDefault($options); case 'raw': return $this->createRawFactory($options); default: throw new InvalidArgumentException(sprintf( '%s does not recognize `%s` as a supported configuration string', static::class, $value )); } } /** * Creates a new raw command factory instance. * * @param OptionsInterface $options Client options container */ protected function createRawFactory(OptionsInterface $options): FactoryInterface { $commands = new RawFactory(); if (isset($options->prefix)) { throw new InvalidArgumentException(sprintf( '%s does not support key prefixing', RawFactory::class )); } return $commands; } /** * {@inheritdoc} */ public function getDefault(OptionsInterface $options) { $commands = new RedisFactory(); if (isset($options->prefix)) { $commands->setProcessor($options->prefix); } return $commands; } } PK)_]tō(src/Configuration/Option/Connections.phpnu[createFactoryByArray($options, $value); } elseif (is_string($value)) { return $this->createFactoryByString($options, $value); } else { throw new InvalidArgumentException(sprintf( '%s expects a valid connection factory', static::class )); } } /** * Creates a new connection factory from a named array. * * The factory instance is configured according to the supplied named array * mapping URI schemes (passed as keys) to the FCQN of classes implementing * Predis\Connection\NodeConnectionInterface, or callable objects acting as * lazy initializers and returning new instances of classes implementing * Predis\Connection\NodeConnectionInterface. * * @param OptionsInterface $options Client options * @param array $value Named array mapping URI schemes to classes or callables * * @return FactoryInterface */ protected function createFactoryByArray(OptionsInterface $options, array $value) { /** * @var FactoryInterface */ $factory = $this->getDefault($options); foreach ($value as $scheme => $initializer) { $factory->define($scheme, $initializer); } return $factory; } /** * Creates a new connection factory from a descriptive string. * * The factory instance is configured according to the supplied descriptive * string that identifies specific configurations of schemes and connection * classes. Supported configuration values are: * * - "phpiredis-stream" maps tcp, redis, unix to PhpiredisStreamConnection * - "phpiredis-socket" maps tcp, redis, unix to PhpiredisSocketConnection * - "phpiredis" is an alias of "phpiredis-stream" * - "relay" maps tcp, redis, unix, tls, rediss to RelayConnection * * @param OptionsInterface $options Client options * @param string $value Descriptive string identifying the desired configuration * * @return FactoryInterface */ protected function createFactoryByString(OptionsInterface $options, string $value) { /** * @var FactoryInterface */ $factory = $this->getDefault($options); switch (strtolower($value)) { case 'phpiredis': case 'phpiredis-stream': $factory->define('tcp', PhpiredisStreamConnection::class); $factory->define('redis', PhpiredisStreamConnection::class); $factory->define('unix', PhpiredisStreamConnection::class); break; case 'phpiredis-socket': $factory->define('tcp', PhpiredisSocketConnection::class); $factory->define('redis', PhpiredisSocketConnection::class); $factory->define('unix', PhpiredisSocketConnection::class); break; case 'relay': $factory->define('tcp', RelayConnection::class); $factory->define('redis', RelayConnection::class); $factory->define('unix', RelayConnection::class); break; case 'default': return $factory; default: throw new InvalidArgumentException(sprintf( '%s does not recognize `%s` as a supported configuration string', static::class, $value )); } return $factory; } /** * {@inheritdoc} */ public function getDefault(OptionsInterface $options) { $factory = new Factory(); if ($options->defined('parameters')) { $factory->setDefaultParameters($options->parameters); } return $factory; } } PK)_]C ^^(src/Configuration/Option/Replication.phpnu[getConnectionInitializerByString($options, $value); } if (is_callable($value)) { return $this->getConnectionInitializer($options, $value); } else { throw new InvalidArgumentException(sprintf( '%s expects either a string or a callable value, %s given', static::class, is_object($value) ? get_class($value) : gettype($value) )); } } /** * Returns a connection initializer (callable) from a descriptive string. * * Each connection initializer is specialized for the specified replication * backend so that all the necessary steps for the configuration of the new * aggregate connection are performed inside the initializer and the client * receives a ready-to-use connection. * * Supported configuration values are: * * - `predis` for unmanaged replication setups * - `redis-sentinel` for replication setups managed by redis-sentinel * - `sentinel` is an alias of `redis-sentinel` * * @param OptionsInterface $options Client options * @param string $description Identifier of a replication backend * * @return callable */ protected function getConnectionInitializerByString(OptionsInterface $options, string $description) { switch ($description) { case 'sentinel': case 'redis-sentinel': return function ($parameters, $options) { return new SentinelReplication($options->service, $parameters, $options->connections); }; case 'predis': return $this->getDefaultConnectionInitializer(); default: throw new InvalidArgumentException(sprintf( '%s expects either `predis`, `sentinel` or `redis-sentinel` as valid string values, `%s` given', static::class, $description )); } } /** * Returns the default connection initializer. * * @return callable */ protected function getDefaultConnectionInitializer() { return function ($parameters, $options) { $connection = new MasterSlaveReplication(); if ($options->autodiscovery) { $connection->setConnectionFactory($options->connections); $connection->setAutoDiscovery(true); } return $connection; }; } /** * {@inheritdoc} */ public static function aggregate(OptionsInterface $options, AggregateConnectionInterface $connection, array $nodes) { if (!$connection instanceof SentinelReplication) { parent::aggregate($options, $connection, $nodes); } } /** * {@inheritdoc} */ public function getDefault(OptionsInterface $options) { return $this->getConnectionInitializer( $options, $this->getDefaultConnectionInitializer() ); } } PK)_]3G&src/Configuration/Option/Aggregate.phpnu[getConnectionInitializer($options, $value); } /** * Wraps a user-supplied callable used to create a new aggregate connection. * * When the original callable acting as a connection initializer is executed * by the client to create a new aggregate connection, it will receive the * following arguments: * * - $parameters (same as passed to Predis\Client::__construct()) * - $options (options container, Predis\Configuration\OptionsInterface) * - $option (current option, Predis\Configuration\OptionInterface) * * The original callable must return a valid aggregation connection instance * of type Predis\Connection\AggregateConnectionInterface, this is enforced * by the wrapper returned by this method and an exception is thrown when * invalid values are returned. * * @param OptionsInterface $options Client options * @param callable $callable Callable initializer * * @return callable * @throws InvalidArgumentException */ protected function getConnectionInitializer(OptionsInterface $options, callable $callable) { return function ($parameters = null, $autoaggregate = false) use ($callable, $options) { $connection = call_user_func_array($callable, [&$parameters, $options, $this]); if (!$connection instanceof AggregateConnectionInterface) { throw new InvalidArgumentException(sprintf( '%s expects the supplied callable to return an instance of %s, but %s was returned', static::class, AggregateConnectionInterface::class, is_object($connection) ? get_class($connection) : gettype($connection) )); } if ($parameters && $autoaggregate) { static::aggregate($options, $connection, $parameters); } return $connection; }; } /** * Adds single connections to an aggregate connection instance. * * @param OptionsInterface $options Client options * @param AggregateConnectionInterface $connection Target aggregate connection * @param array $nodes List of nodes to be added to the target aggregate connection */ public static function aggregate(OptionsInterface $options, AggregateConnectionInterface $connection, array $nodes) { $connections = $options->connections; foreach ($nodes as $node) { $connection->add($node instanceof NodeConnectionInterface ? $node : $connections->create($node)); } } /** * {@inheritdoc} */ public function getDefault(OptionsInterface $options) { return; } } PK)_]>+'src/Configuration/Option/Exceptions.phpnu[ Option\Aggregate::class, 'cluster' => Option\Cluster::class, 'replication' => Option\Replication::class, 'connections' => Option\Connections::class, 'commands' => Option\Commands::class, 'exceptions' => Option\Exceptions::class, 'prefix' => Option\Prefix::class, 'crc16' => Option\CRC16::class, ]; /** @var array */ protected $options = []; /** @var array */ protected $input; /** * @param array|null $options Named array of client options */ public function __construct(?array $options = null) { $this->input = $options ?? []; } /** * {@inheritdoc} */ public function getDefault($option) { if (isset($this->handlers[$option])) { $handler = $this->handlers[$option]; $handler = new $handler(); return $handler->getDefault($this); } } /** * {@inheritdoc} */ public function defined($option) { return array_key_exists($option, $this->options) || array_key_exists($option, $this->input) ; } /** * {@inheritdoc} */ public function __isset($option) { return ( array_key_exists($option, $this->options) || array_key_exists($option, $this->input) ) && $this->__get($option) !== null; } /** * {@inheritdoc} */ public function __get($option) { if (isset($this->options[$option]) || array_key_exists($option, $this->options)) { return $this->options[$option]; } if (isset($this->input[$option]) || array_key_exists($option, $this->input)) { $value = $this->input[$option]; unset($this->input[$option]); if (isset($this->handlers[$option])) { $handler = $this->handlers[$option]; $handler = new $handler(); $value = $handler->filter($this, $value); } elseif (is_object($value) && method_exists($value, '__invoke')) { $value = $value($this); } return $this->options[$option] = $value; } if (isset($this->handlers[$option])) { return $this->options[$option] = $this->getDefault($option); } return; } } PK)_]S#src/Response/Iterator/MultiBulk.phpnu[connection = $connection; $this->size = $size; $this->position = 0; $this->current = $size > 0 ? $this->getValue() : null; } /** * Handles the synchronization of the client with the Redis protocol when * the garbage collector kicks in (e.g. when the iterator goes out of the * scope of a foreach or it is unset). */ public function __destruct() { $this->drop(true); } /** * Drop queued elements that have not been read from the connection either * by consuming the rest of the multibulk response or quickly by closing the * underlying connection. * * @param bool $disconnect Consume the iterator or drop the connection. */ public function drop($disconnect = false) { if ($disconnect) { if ($this->valid()) { $this->position = $this->size; $this->connection->disconnect(); } } else { while ($this->valid()) { $this->next(); } } } /** * Reads the next item of the multibulk response from the connection. * * @return mixed */ protected function getValue() { return $this->connection->read(); } } PK)_]u (src/Response/Iterator/MultiBulkTuple.phpnu[ $value pairs. */ class MultiBulkTuple extends MultiBulk implements OuterIterator { private $iterator; /** * @param MultiBulk $iterator Inner multibulk response iterator. */ public function __construct(MultiBulk $iterator) { $this->checkPreconditions($iterator); $this->size = count($iterator) / 2; $this->iterator = $iterator; $this->position = $iterator->getPosition(); $this->current = $this->size > 0 ? $this->getValue() : null; } /** * Checks for valid preconditions. * * @param MultiBulk $iterator Inner multibulk response iterator. * * @throws InvalidArgumentException * @throws UnexpectedValueException */ protected function checkPreconditions(MultiBulk $iterator) { if ($iterator->getPosition() !== 0) { throw new InvalidArgumentException( 'Cannot initialize a tuple iterator using an already initiated iterator.' ); } if (($size = count($iterator)) % 2 !== 0) { throw new UnexpectedValueException('Invalid response size for a tuple iterator.'); } } /** * @return MultiBulk */ #[ReturnTypeWillChange] public function getInnerIterator() { return $this->iterator; } /** * {@inheritdoc} */ public function __destruct() { $this->iterator->drop(true); } /** * {@inheritdoc} */ protected function getValue() { $k = $this->iterator->current(); $this->iterator->next(); $v = $this->iterator->current(); $this->iterator->next(); return [$k, $v]; } } PK)_]ތb +src/Response/Iterator/MultiBulkIterator.phpnu[current; } /** * @return int|null */ #[ReturnTypeWillChange] public function key() { return $this->position; } /** * @return void */ #[ReturnTypeWillChange] public function next() { if (++$this->position < $this->size) { $this->current = $this->getValue(); } } /** * @return bool */ #[ReturnTypeWillChange] public function valid() { return $this->position < $this->size; } /** * Returns the number of items comprising the whole multibulk response. * * This method should be used instead of iterator_count() to get the size of * the current multibulk response since the former consumes the iteration to * count the number of elements, but our iterators do not support rewinding. * * @return int */ #[ReturnTypeWillChange] public function count() { return $this->size; } /** * Returns the current position of the iterator. * * @return int */ public function getPosition() { return $this->position; } /** * {@inheritdoc} */ abstract protected function getValue(); } PK)_]򯁃 src/Response/ServerException.phpnu[getMessage(), 2); return $errorType; } /** * Converts the exception to an instance of Predis\Response\Error. * * @return Error */ public function toErrorResponse() { return new Error($this->getMessage()); } } PK)_]@֟yy"src/Response/ResponseInterface.phpnu[payload = $payload; } /** * Converts the response object to its string representation. * * @return string */ public function __toString() { return $this->payload; } /** * Returns the payload of status response. * * @return string */ public function getPayload() { return $this->payload; } /** * Returns an instance of a status response object. * * Common status responses such as OK or QUEUED are cached in order to lower * the global memory usage especially when using pipelines. * * @param string $payload Status response payload. * * @return self */ public static function get($payload) { switch ($payload) { case 'OK': case 'QUEUED': if (isset(self::$$payload)) { return self::$$payload; } return self::$$payload = new self($payload); default: return new self($payload); } } } PK)_]SSsrc/Response/Error.phpnu[message = $message; } /** * {@inheritdoc} */ public function getMessage() { return $this->message; } /** * {@inheritdoc} */ public function getErrorType() { [$errorType] = explode(' ', $this->getMessage(), 2); return $errorType; } /** * Converts the object to its string representation. * * @return string */ public function __toString() { return $this->getMessage(); } } PK)_]|Bsrc/Response/ErrorInterface.phpnu[client = $client; if (isset($options['gc_maxlifetime'])) { $this->ttl = (int) $options['gc_maxlifetime']; } else { $this->ttl = ini_get('session.gc_maxlifetime'); } } /** * Registers this instance as the current session handler. */ public function register() { session_set_save_handler($this, true); } /** * @param string $save_path * @param string $session_id * @return bool */ #[ReturnTypeWillChange] public function open($save_path, $session_id) { // NOOP return true; } /** * @return bool */ #[ReturnTypeWillChange] public function close() { // NOOP return true; } /** * @param int $maxlifetime * @return bool */ #[ReturnTypeWillChange] public function gc($maxlifetime) { // NOOP return true; } /** * @param string $session_id * @return string */ #[ReturnTypeWillChange] public function read($session_id) { if ($data = $this->client->get($session_id)) { return $data; } return ''; } /** * @param string $session_id * @param string $session_data * @return bool */ #[ReturnTypeWillChange] public function write($session_id, $session_data) { $this->client->setex($session_id, $this->ttl, $session_data); return true; } /** * @param string $session_id * @return bool */ #[ReturnTypeWillChange] public function destroy($session_id) { $this->client->del($session_id); return true; } /** * Returns the underlying client instance. * * @return ClientInterface */ public function getClient() { return $this->client; } /** * Returns the session max lifetime value. * * @return int */ public function getMaxLifeTime() { return $this->ttl; } } PK)_]LG!src/Replication/RoleException.phpnu[disallowed = $this->getDisallowedOperations(); $this->readonly = $this->getReadOnlyOperations(); $this->readonlySHA1 = []; } /** * Returns if the specified command will perform a read-only operation * on Redis or not. * * @param CommandInterface $command Command instance. * * @return bool * @throws NotSupportedException */ public function isReadOperation(CommandInterface $command) { if (!$this->loadBalancing) { return false; } if (isset($this->disallowed[$id = $command->getId()])) { throw new NotSupportedException( "The command '$id' is not allowed in replication mode." ); } if (isset($this->readonly[$id])) { if (true === $readonly = $this->readonly[$id]) { return true; } return call_user_func($readonly, $command); } if (($eval = $id === 'EVAL') || $id === 'EVALSHA') { $argument = $command->getArgument(0); $sha1 = $eval ? sha1(strval($argument)) : $argument; if (isset($this->readonlySHA1[$sha1])) { if (true === $readonly = $this->readonlySHA1[$sha1]) { return true; } return call_user_func($readonly, $command); } } return false; } /** * Returns if the specified command is not allowed for execution in a master * / slave replication context. * * @param CommandInterface $command Command instance. * * @return bool */ public function isDisallowedOperation(CommandInterface $command) { return isset($this->disallowed[$command->getId()]); } /** * Checks if BITFIELD performs a read-only operation by looking for certain * SET and INCRYBY modifiers in the arguments array of the command. * * @param CommandInterface $command Command instance. * * @return bool */ protected function isBitfieldReadOnly(CommandInterface $command) { $arguments = $command->getArguments(); $argc = count($arguments); if ($argc >= 2) { for ($i = 1; $i < $argc; ++$i) { $argument = strtoupper($arguments[$i]); if ($argument === 'SET' || $argument === 'INCRBY') { return false; } } } return true; } /** * Checks if a GEORADIUS command is a readable operation by parsing the * arguments array of the specified command instance. * * @param CommandInterface $command Command instance. * * @return bool */ protected function isGeoradiusReadOnly(CommandInterface $command) { $arguments = $command->getArguments(); $argc = count($arguments); $startIndex = $command->getId() === 'GEORADIUS' ? 5 : 4; if ($argc > $startIndex) { for ($i = $startIndex; $i < $argc; ++$i) { $argument = strtoupper($arguments[$i]); if ($argument === 'STORE' || $argument === 'STOREDIST') { return false; } } } return true; } /** * Marks a command as a read-only operation. * * When the behavior of a command can be decided only at runtime depending * on its arguments, a callable object can be provided to dynamically check * if the specified command performs a read or a write operation. * * @param string $commandID Command ID. * @param mixed $readonly A boolean value or a callable object. */ public function setCommandReadOnly($commandID, $readonly = true) { $commandID = strtoupper($commandID); if ($readonly) { $this->readonly[$commandID] = $readonly; } else { unset($this->readonly[$commandID]); } } /** * Marks a Lua script for EVAL and EVALSHA as a read-only operation. When * the behaviour of a script can be decided only at runtime depending on * its arguments, a callable object can be provided to dynamically check * if the passed instance of EVAL or EVALSHA performs write operations or * not. * * @param string $script Body of the Lua script. * @param mixed $readonly A boolean value or a callable object. */ public function setScriptReadOnly($script, $readonly = true) { $sha1 = sha1($script); if ($readonly) { $this->readonlySHA1[$sha1] = $readonly; } else { unset($this->readonlySHA1[$sha1]); } } /** * Returns the default list of disallowed commands. * * @return array */ protected function getDisallowedOperations() { return [ 'SHUTDOWN' => true, 'INFO' => true, 'DBSIZE' => true, 'LASTSAVE' => true, 'CONFIG' => true, 'MONITOR' => true, 'SLAVEOF' => true, 'SAVE' => true, 'BGSAVE' => true, 'BGREWRITEAOF' => true, 'SLOWLOG' => true, ]; } /** * Returns the default list of commands performing read-only operations. * * @return array */ protected function getReadOnlyOperations() { return [ 'EXISTS' => true, 'TYPE' => true, 'KEYS' => true, 'SCAN' => true, 'RANDOMKEY' => true, 'TTL' => true, 'GET' => true, 'MGET' => true, 'SUBSTR' => true, 'STRLEN' => true, 'GETRANGE' => true, 'GETBIT' => true, 'LLEN' => true, 'LRANGE' => true, 'LINDEX' => true, 'SCARD' => true, 'SISMEMBER' => true, 'SINTER' => true, 'SUNION' => true, 'SDIFF' => true, 'SMEMBERS' => true, 'SSCAN' => true, 'SRANDMEMBER' => true, 'ZRANGE' => true, 'ZREVRANGE' => true, 'ZRANGEBYSCORE' => true, 'ZREVRANGEBYSCORE' => true, 'ZCARD' => true, 'ZSCORE' => true, 'ZCOUNT' => true, 'ZRANK' => true, 'ZREVRANK' => true, 'ZSCAN' => true, 'ZLEXCOUNT' => true, 'ZRANGEBYLEX' => true, 'ZREVRANGEBYLEX' => true, 'HGET' => true, 'HMGET' => true, 'HEXISTS' => true, 'HLEN' => true, 'HKEYS' => true, 'HVALS' => true, 'HGETALL' => true, 'HSCAN' => true, 'HSTRLEN' => true, 'PING' => true, 'AUTH' => true, 'SELECT' => true, 'ECHO' => true, 'QUIT' => true, 'OBJECT' => true, 'BITCOUNT' => true, 'BITPOS' => true, 'TIME' => true, 'PFCOUNT' => true, 'BITFIELD' => [$this, 'isBitfieldReadOnly'], 'GEOHASH' => true, 'GEOPOS' => true, 'GEODIST' => true, 'GEORADIUS' => [$this, 'isGeoradiusReadOnly'], 'GEORADIUSBYMEMBER' => [$this, 'isGeoradiusReadOnly'], ]; } /** * Disables reads to slaves when using * a replication topology. * * @return self */ public function disableLoadBalancing(): self { $this->loadBalancing = false; return $this; } } PK)_]$*src/Replication/MissingMasterException.phpnu[getParameters()}]" )); } if ($length === -1) { return; } $list = []; if ($length > 0) { $handlersCache = []; $reader = $connection->getProtocol()->getResponseReader(); for ($i = 0; $i < $length; ++$i) { $header = $connection->readLine(); $prefix = $header[0]; if (isset($handlersCache[$prefix])) { $handler = $handlersCache[$prefix]; } else { $handler = $reader->getHandler($prefix); $handlersCache[$prefix] = $handler; } $list[$i] = $handler->handle($connection, substr($header, 1)); } } return $list; } } PK)_]C-src/Protocol/Text/Handler/IntegerResponse.phpnu[getParameters()}]" )); } return; } } PK)_] 5/9src/Protocol/Text/Handler/StreamableMultiBulkResponse.phpnu[getParameters()}]" )); } return new MultiBulkIterator($connection, $length); } } PK)_]^~*src/Protocol/Text/Handler/BulkResponse.phpnu[getParameters()}]" )); } if ($length >= 0) { return substr($connection->readBuffer($length + 2), 0, -2); } if ($length == -1) { return; } CommunicationException::handle(new ProtocolException( $connection, "Value '$payload' is not a valid length for a bulk response [{$connection->getParameters()}]" )); return; } } PK)_]iXX6src/Protocol/Text/Handler/ResponseHandlerInterface.phpnu[handlers = $this->getDefaultHandlers(); } /** * Returns the default handlers for the supported type of responses. * * @return array */ protected function getDefaultHandlers() { return [ '+' => new Handler\StatusResponse(), '-' => new Handler\ErrorResponse(), ':' => new Handler\IntegerResponse(), '$' => new Handler\BulkResponse(), '*' => new Handler\MultiBulkResponse(), ]; } /** * Sets the handler for the specified prefix identifying the response type. * * @param string $prefix Identifier of the type of response. * @param Handler\ResponseHandlerInterface $handler Response handler. */ public function setHandler($prefix, Handler\ResponseHandlerInterface $handler) { $this->handlers[$prefix] = $handler; } /** * Returns the response handler associated to a certain type of response. * * @param string $prefix Identifier of the type of response. * * @return Handler\ResponseHandlerInterface */ public function getHandler($prefix) { if (isset($this->handlers[$prefix])) { return $this->handlers[$prefix]; } return; } /** * {@inheritdoc} */ public function read(CompositeConnectionInterface $connection) { $header = $connection->readLine(); if ($header === '') { $this->onProtocolError($connection, 'Unexpected empty response header'); } $prefix = $header[0]; if (!isset($this->handlers[$prefix])) { $this->onProtocolError($connection, "Unknown response prefix: '$prefix'"); } return $this->handlers[$prefix]->handle($connection, substr($header, 1)); } /** * Handles protocol errors generated while reading responses from a * connection. * * @param CompositeConnectionInterface $connection Redis connection that generated the error. * @param string $message Error message. */ protected function onProtocolError(CompositeConnectionInterface $connection, $message) { CommunicationException::handle( new ProtocolException($connection, "$message [{$connection->getParameters()}]") ); } } PK)_] 00'src/Protocol/Text/RequestSerializer.phpnu[getId(); $arguments = $command->getArguments(); $cmdlen = strlen($commandID); $reqlen = count($arguments) + 1; $buffer = "*{$reqlen}\r\n\${$cmdlen}\r\n{$commandID}\r\n"; foreach ($arguments as $argument) { $arglen = strlen($argument); $buffer .= "\${$arglen}\r\n{$argument}\r\n"; } return $buffer; } } PK)_] 0src/Protocol/Text/CompositeProtocolProcessor.phpnu[setRequestSerializer($serializer ?: new RequestSerializer()); $this->setResponseReader($reader ?: new ResponseReader()); } /** * {@inheritdoc} */ public function write(CompositeConnectionInterface $connection, CommandInterface $command) { $connection->writeBuffer($this->serializer->serialize($command)); } /** * {@inheritdoc} */ public function read(CompositeConnectionInterface $connection) { return $this->reader->read($connection); } /** * Sets the request serializer used by the protocol processor. * * @param RequestSerializerInterface $serializer Request serializer. */ public function setRequestSerializer(RequestSerializerInterface $serializer) { $this->serializer = $serializer; } /** * Returns the request serializer used by the protocol processor. * * @return RequestSerializerInterface */ public function getRequestSerializer() { return $this->serializer; } /** * Sets the response reader used by the protocol processor. * * @param ResponseReaderInterface $reader Response reader. */ public function setResponseReader(ResponseReaderInterface $reader) { $this->reader = $reader; } /** * Returns the Response reader used by the protocol processor. * * @return ResponseReaderInterface */ public function getResponseReader() { return $this->reader; } } PK)_]Ml 'src/Protocol/Text/ProtocolProcessor.phpnu[mbiterable = false; $this->serializer = new RequestSerializer(); } /** * {@inheritdoc} */ public function write(CompositeConnectionInterface $connection, CommandInterface $command) { $request = $this->serializer->serialize($command); $connection->writeBuffer($request); } /** * {@inheritdoc} */ public function read(CompositeConnectionInterface $connection) { $chunk = $connection->readLine(); $prefix = $chunk[0]; $payload = substr($chunk, 1); switch ($prefix) { case '+': return new StatusResponse($payload); case '$': $size = (int) $payload; if ($size === -1) { return; } return substr($connection->readBuffer($size + 2), 0, -2); case '*': $count = (int) $payload; if ($count === -1) { return; } if ($this->mbiterable) { return new MultiBulkIterator($connection, $count); } $multibulk = []; for ($i = 0; $i < $count; ++$i) { $multibulk[$i] = $this->read($connection); } return $multibulk; case ':': $integer = (int) $payload; return $integer == $payload ? $integer : $payload; case '-': return new ErrorResponse($payload); default: CommunicationException::handle(new ProtocolException( $connection, "Unknown response prefix: '$prefix' [{$connection->getParameters()}]" )); return; } } /** * Enables or disables returning multibulk responses as specialized PHP * iterators used to stream bulk elements of a multibulk response instead * returning a plain array. * * Streamable multibulk responses are not globally supported by the * abstractions built-in into Predis, such as transactions or pipelines. * Use them with care! * * @param bool $value Enable or disable streamable multibulk responses. */ public function useIterableMultibulk($value) { $this->mbiterable = (bool) $value; } } PK)_]lrr+src/Protocol/RequestSerializerInterface.phpnu[getCommandFactory()->supports('multi', 'exec', 'discard')) { throw new ClientException( "'MULTI', 'EXEC' and 'DISCARD' are not supported by the current command factory." ); } parent::__construct($client); } /** * {@inheritdoc} */ protected function getConnection() { $connection = $this->getClient()->getConnection(); if (!$connection instanceof NodeConnectionInterface) { $class = __CLASS__; throw new ClientException("The class '$class' does not support aggregate connections."); } return $connection; } /** * {@inheritdoc} */ protected function executePipeline(ConnectionInterface $connection, SplQueue $commands) { $commandFactory = $this->getClient()->getCommandFactory(); $connection->executeCommand($commandFactory->create('multi')); foreach ($commands as $command) { $connection->writeRequest($command); } foreach ($commands as $command) { $response = $connection->readResponse($command); if ($response instanceof ErrorResponseInterface) { $connection->executeCommand($commandFactory->create('discard')); throw new ServerException($response->getMessage()); } } $executed = $connection->executeCommand($commandFactory->create('exec')); if (!isset($executed)) { throw new ClientException( 'The underlying transaction has been aborted by the server.' ); } if (count($executed) !== count($commands)) { $expected = count($commands); $received = count($executed); throw new ClientException( "Invalid number of responses [expected $expected, received $received]." ); } $responses = []; $sizeOfPipe = count($commands); $exceptions = $this->throwServerExceptions(); for ($i = 0; $i < $sizeOfPipe; ++$i) { $command = $commands->dequeue(); $response = $executed[$i]; if (!$response instanceof ResponseInterface) { $responses[] = $command->parseResponse($response); } elseif ($response instanceof ErrorResponseInterface && $exceptions) { $this->exception($connection, $response); } else { $responses[] = $response; } unset($executed[$i]); } return $responses; } } PK)_]isrc/Pipeline/Pipeline.phpnu[client = $client; $this->pipeline = new SplQueue(); } /** * Queues a command into the pipeline buffer. * * @param string $method Command ID. * @param array $arguments Arguments for the command. * * @return $this */ public function __call($method, $arguments) { $command = $this->client->createCommand($method, $arguments); $this->recordCommand($command); return $this; } /** * Queues a command instance into the pipeline buffer. * * @param CommandInterface $command Command to be queued in the buffer. */ protected function recordCommand(CommandInterface $command) { $this->pipeline->enqueue($command); } /** * Queues a command instance into the pipeline buffer. * * @param CommandInterface $command Command instance to be queued in the buffer. * * @return $this */ public function executeCommand(CommandInterface $command) { $this->recordCommand($command); return $this; } /** * Throws an exception on -ERR responses returned by Redis. * * @param ConnectionInterface $connection Redis connection that returned the error. * @param ErrorResponseInterface $response Instance of the error response. * * @throws ServerException */ protected function exception(ConnectionInterface $connection, ErrorResponseInterface $response) { $connection->disconnect(); $message = $response->getMessage(); throw new ServerException($message); } /** * Returns the underlying connection to be used by the pipeline. * * @return ConnectionInterface */ protected function getConnection() { $connection = $this->getClient()->getConnection(); if ($connection instanceof ReplicationInterface) { $connection->switchToMaster(); } return $connection; } /** * Implements the logic to flush the queued commands and read the responses * from the current connection. * * @param ConnectionInterface $connection Current connection instance. * @param SplQueue $commands Queued commands. * * @return array */ protected function executePipeline(ConnectionInterface $connection, SplQueue $commands) { foreach ($commands as $command) { $connection->writeRequest($command); } $responses = []; $exceptions = $this->throwServerExceptions(); while (!$commands->isEmpty()) { $command = $commands->dequeue(); $response = $connection->readResponse($command); if (!$response instanceof ResponseInterface) { $responses[] = $command->parseResponse($response); } elseif ($response instanceof ErrorResponseInterface && $exceptions) { $this->exception($connection, $response); } else { $responses[] = $response; } } return $responses; } /** * Flushes the buffer holding all of the commands queued so far. * * @param bool $send Specifies if the commands in the buffer should be sent to Redis. * * @return $this */ public function flushPipeline($send = true) { if ($send && !$this->pipeline->isEmpty()) { $responses = $this->executePipeline($this->getConnection(), $this->pipeline); $this->responses = array_merge($this->responses, $responses); } else { $this->pipeline = new SplQueue(); } return $this; } /** * Marks the running status of the pipeline. * * @param bool $bool Sets the running status of the pipeline. * * @throws ClientException */ private function setRunning($bool) { if ($bool && $this->running) { throw new ClientException('The current pipeline context is already being executed.'); } $this->running = $bool; } /** * Handles the actual execution of the whole pipeline. * * @param mixed $callable Optional callback for execution. * * @return array * @throws Exception * @throws InvalidArgumentException */ public function execute($callable = null) { if ($callable && !is_callable($callable)) { throw new InvalidArgumentException('The argument must be a callable object.'); } $exception = null; $this->setRunning(true); try { if ($callable) { call_user_func($callable, $this); } $this->flushPipeline(); } catch (Exception $exception) { // NOOP } $this->setRunning(false); if ($exception) { throw $exception; } return $this->responses; } /** * Returns if the pipeline should throw exceptions on server errors. * * @return bool */ protected function throwServerExceptions() { return (bool) $this->client->getOptions()->exceptions; } /** * Returns the underlying client instance used by the pipeline object. * * @return ClientInterface */ public function getClient() { return $this->client; } } PK)_]Yt҂src/Pipeline/RelayPipeline.phpnu[getClient(); $throw = $this->client->getOptions()->exceptions; try { $pipeline = $client->pipeline(); foreach ($commands as $command) { $name = $command->getId(); in_array($name, $connection->atypicalCommands) ? $pipeline->{$name}(...$command->getArguments()) : $pipeline->rawCommand($name, ...$command->getArguments()); } $responses = $pipeline->exec(); if (!is_array($responses)) { return $responses; } foreach ($responses as $key => $response) { if ($response instanceof RelayException) { if ($throw) { throw $response; } $responses[$key] = new Error($response->getMessage()); } } return $responses; } catch (RelayException $ex) { if ($client->getMode() !== $client::ATOMIC) { $client->discard(); } throw new ServerException($ex->getMessage(), $ex->getCode(), $ex); } } } PK)_]%src/Pipeline/ConnectionErrorProof.phpnu[getClient()->getConnection(); } /** * {@inheritdoc} */ protected function executePipeline(ConnectionInterface $connection, SplQueue $commands) { if ($connection instanceof NodeConnectionInterface) { return $this->executeSingleNode($connection, $commands); } elseif ($connection instanceof ClusterInterface) { return $this->executeCluster($connection, $commands); } else { $class = get_class($connection); throw new NotSupportedException("The connection class '$class' is not supported."); } } /** * {@inheritdoc} */ protected function executeSingleNode(NodeConnectionInterface $connection, SplQueue $commands) { $responses = []; $sizeOfPipe = count($commands); foreach ($commands as $command) { try { $connection->writeRequest($command); } catch (CommunicationException $exception) { return array_fill(0, $sizeOfPipe, $exception); } } for ($i = 0; $i < $sizeOfPipe; ++$i) { $command = $commands->dequeue(); try { $responses[$i] = $connection->readResponse($command); } catch (CommunicationException $exception) { $add = count($commands) - count($responses); $responses = array_merge($responses, array_fill(0, $add, $exception)); break; } } return $responses; } /** * {@inheritdoc} */ protected function executeCluster(ClusterInterface $connection, SplQueue $commands) { $responses = []; $sizeOfPipe = count($commands); $exceptions = []; foreach ($commands as $command) { $cmdConnection = $connection->getConnectionByCommand($command); if (isset($exceptions[spl_object_hash($cmdConnection)])) { continue; } try { $cmdConnection->writeRequest($command); } catch (CommunicationException $exception) { $exceptions[spl_object_hash($cmdConnection)] = $exception; } } for ($i = 0; $i < $sizeOfPipe; ++$i) { $command = $commands->dequeue(); $cmdConnection = $connection->getConnectionByCommand($command); $connectionHash = spl_object_hash($cmdConnection); if (isset($exceptions[$connectionHash])) { $responses[$i] = $exceptions[$connectionHash]; continue; } try { $responses[$i] = $cmdConnection->readResponse($command); } catch (CommunicationException $exception) { $responses[$i] = $exception; $exceptions[$connectionHash] = $exception; } } return $responses; } } PK)_]<<  src/Pipeline/FireAndForget.phpnu[isEmpty()) { $connection->writeRequest($commands->dequeue()); } $connection->disconnect(); return []; } } PK)_]ͶLttsrc/Pipeline/RelayAtomic.phpnu[getClient(); $throw = $this->client->getOptions()->exceptions; try { $transaction = $client->multi(); foreach ($commands as $command) { $name = $command->getId(); in_array($name, $connection->atypicalCommands) ? $transaction->{$name}(...$command->getArguments()) : $transaction->rawCommand($name, ...$command->getArguments()); } $responses = $transaction->exec(); if (!is_array($responses)) { return $responses; } foreach ($responses as $key => $response) { if ($response instanceof RelayException) { if ($throw) { throw $response; } $responses[$key] = new Error($response->getMessage()); } } return $responses; } catch (RelayException $ex) { if ($client->getMode() !== $client::ATOMIC) { $client->discard(); } throw new ServerException($ex->getMessage(), $ex->getCode(), $ex); } } } PK)_]wsrc/Monitor/Consumer.phpnu[assertClient($client); $this->client = $client; $this->start(); } /** * Automatically stops the consumer when the garbage collector kicks in. */ public function __destruct() { $this->stop(); } /** * Checks if the passed client instance satisfies the required conditions * needed to initialize a monitor consumer. * * @param ClientInterface $client Client instance used by the consumer. * * @throws NotSupportedException */ private function assertClient(ClientInterface $client) { if ($client->getConnection() instanceof ClusterInterface) { throw new NotSupportedException( 'Cannot initialize a monitor consumer over cluster connections.' ); } if (!$client->getCommandFactory()->supports('MONITOR')) { throw new NotSupportedException("'MONITOR' is not supported by the current command factory."); } } /** * Initializes the consumer and sends the MONITOR command to the server. */ protected function start() { $this->client->executeCommand( $this->client->createCommand('MONITOR') ); $this->valid = true; } /** * Stops the consumer. Internally this is done by disconnecting from server * since there is no way to terminate the stream initialized by MONITOR. */ public function stop() { $this->client->disconnect(); $this->valid = false; } /** * @return void */ #[ReturnTypeWillChange] public function rewind() { // NOOP } /** * Returns the last message payload retrieved from the server. * * @return object */ #[ReturnTypeWillChange] public function current() { return $this->getValue(); } /** * @return int|null */ #[ReturnTypeWillChange] public function key() { return $this->position; } /** * @return void */ #[ReturnTypeWillChange] public function next() { ++$this->position; } /** * Checks if the the consumer is still in a valid state to continue. * * @return bool */ #[ReturnTypeWillChange] public function valid() { return $this->valid; } /** * Waits for a new message from the server generated by MONITOR and returns * it when available. * * @return object */ private function getValue() { $database = 0; $client = null; $event = $this->client->getConnection()->read(); $callback = function ($matches) use (&$database, &$client) { if (2 === $count = count($matches)) { // Redis <= 2.4 $database = (int) $matches[1]; } if (4 === $count) { // Redis >= 2.6 $database = (int) $matches[2]; $client = $matches[3]; } return ' '; }; $event = preg_replace_callback('/ \(db (\d+)\) | \[(\d+) (.*?)\] /', $callback, $event, 1); @[$timestamp, $command, $arguments] = explode(' ', $event, 3); return (object) [ 'timestamp' => (float) $timestamp, 'database' => $database, 'client' => $client, 'command' => substr($command, 1, -1), 'arguments' => $arguments, ]; } } PK)_] X]I]Isrc/Client.phpnu[ */ class Client implements ClientInterface, IteratorAggregate { public const VERSION = '2.3.0'; /** @var OptionsInterface */ private $options; /** @var ConnectionInterface */ private $connection; /** @var Command\FactoryInterface */ private $commands; /** * @param mixed $parameters Connection parameters for one or more servers. * @param mixed $options Options to configure some behaviours of the client. */ public function __construct($parameters = null, $options = null) { $this->options = static::createOptions($options ?? new Options()); $this->connection = static::createConnection($this->options, $parameters ?? new Parameters()); $this->commands = $this->options->commands; } /** * Creates a new set of client options for the client. * * @param array|OptionsInterface $options Set of client options * * @return OptionsInterface * @throws InvalidArgumentException */ protected static function createOptions($options) { if (is_array($options)) { return new Options($options); } elseif ($options instanceof OptionsInterface) { return $options; } else { throw new InvalidArgumentException('Invalid type for client options'); } } /** * Creates single or aggregate connections from supplied arguments. * * This method accepts the following types to create a connection instance: * * - Array (dictionary: single connection, indexed: aggregate connections) * - String (URI for a single connection) * - Callable (connection initializer callback) * - Instance of Predis\Connection\ParametersInterface (used as-is) * - Instance of Predis\Connection\ConnectionInterface (returned as-is) * * When a callable is passed, it receives the original set of client options * and must return an instance of Predis\Connection\ConnectionInterface. * * Connections are created using the connection factory (in case of single * connections) or a specialized aggregate connection initializer (in case * of cluster and replication) retrieved from the supplied client options. * * @param OptionsInterface $options Client options container * @param mixed $parameters Connection parameters * * @return ConnectionInterface * @throws InvalidArgumentException */ protected static function createConnection(OptionsInterface $options, $parameters) { if ($parameters instanceof ConnectionInterface) { return $parameters; } if ($parameters instanceof ParametersInterface || is_string($parameters)) { return $options->connections->create($parameters); } if (is_array($parameters)) { if (!isset($parameters[0])) { return $options->connections->create($parameters); } elseif ($options->defined('cluster') && $initializer = $options->cluster) { return $initializer($parameters, true); } elseif ($options->defined('replication') && $initializer = $options->replication) { return $initializer($parameters, true); } elseif ($options->defined('aggregate') && $initializer = $options->aggregate) { return $initializer($parameters, false); } else { throw new InvalidArgumentException( 'Array of connection parameters requires `cluster`, `replication` or `aggregate` client option' ); } } if (is_callable($parameters)) { $connection = call_user_func($parameters, $options); if (!$connection instanceof ConnectionInterface) { throw new InvalidArgumentException('Callable parameters must return a valid connection'); } return $connection; } throw new InvalidArgumentException('Invalid type for connection parameters'); } /** * {@inheritdoc} */ public function getCommandFactory() { return $this->commands; } /** * {@inheritdoc} */ public function getOptions() { return $this->options; } /** * Creates a new client using a specific underlying connection. * * This method allows to create a new client instance by picking a specific * connection out of an aggregate one, with the same options of the original * client instance. * * The specified selector defines which logic to use to look for a suitable * connection by the specified value. Supported selectors are: * * - `id` * - `key` * - `slot` * - `command` * - `alias` * - `role` * * Internally the client relies on duck-typing and follows this convention: * * $selector string => getConnectionBy$selector($value) method * * This means that support for specific selectors may vary depending on the * actual logic implemented by connection classes and there is no interface * binding a connection class to implement any of these. * * @param string $selector Type of selector. * @param mixed $value Value to be used by the selector. * * @return ClientInterface */ public function getClientBy($selector, $value) { $selector = strtolower($selector); if (!in_array($selector, ['id', 'key', 'slot', 'role', 'alias', 'command'])) { throw new InvalidArgumentException("Invalid selector type: `$selector`"); } if (!method_exists($this->connection, $method = "getConnectionBy$selector")) { $class = get_class($this->connection); throw new InvalidArgumentException("Selecting connection by $selector is not supported by $class"); } if (!$connection = $this->connection->$method($value)) { throw new InvalidArgumentException("Cannot find a connection by $selector matching `$value`"); } return new static($connection, $this->getOptions()); } /** * Opens the underlying connection and connects to the server. */ public function connect() { $this->connection->connect(); } /** * Closes the underlying connection and disconnects from the server. */ public function disconnect() { $this->connection->disconnect(); } /** * Closes the underlying connection and disconnects from the server. * * This is the same as `Client::disconnect()` as it does not actually send * the `QUIT` command to Redis, but simply closes the connection. */ public function quit() { $this->disconnect(); } /** * Returns the current state of the underlying connection. * * @return bool */ public function isConnected() { return $this->connection->isConnected(); } /** * {@inheritdoc} */ public function getConnection() { return $this->connection; } /** * Applies the configured serializer and compression to given value. * * @param mixed $value * @return string */ public function pack($value) { return $this->connection instanceof RelayConnection ? $this->connection->pack($value) : $value; } /** * Deserializes and decompresses to given value. * * @param mixed $value * @return string */ public function unpack($value) { return $this->connection instanceof RelayConnection ? $this->connection->unpack($value) : $value; } /** * Executes a command without filtering its arguments, parsing the response, * applying any prefix to keys or throwing exceptions on Redis errors even * regardless of client options. * * It is possible to identify Redis error responses from normal responses * using the second optional argument which is populated by reference. * * @param array $arguments Command arguments as defined by the command signature. * @param bool $error Set to TRUE when Redis returned an error response. * * @return mixed */ public function executeRaw(array $arguments, &$error = null) { $error = false; $commandID = array_shift($arguments); $response = $this->connection->executeCommand( new RawCommand($commandID, $arguments) ); if ($response instanceof ResponseInterface) { if ($response instanceof ErrorResponseInterface) { $error = true; } return (string) $response; } return $response; } /** * {@inheritdoc} */ public function __call($commandID, $arguments) { return $this->executeCommand( $this->createCommand($commandID, $arguments) ); } /** * {@inheritdoc} */ public function createCommand($commandID, $arguments = []) { return $this->commands->create($commandID, $arguments); } /** * @param string $name * @return ContainerInterface */ public function __get(string $name) { return ContainerFactory::create($this, $name); } /** * @param string $name * @param mixed $value * @return mixed */ public function __set(string $name, $value) { throw new RuntimeException('Not allowed'); } /** * @param string $name * @return mixed */ public function __isset(string $name) { throw new RuntimeException('Not allowed'); } /** * {@inheritdoc} */ public function executeCommand(CommandInterface $command) { $response = $this->connection->executeCommand($command); if ($response instanceof ResponseInterface) { if ($response instanceof ErrorResponseInterface) { $response = $this->onErrorResponse($command, $response); } return $response; } return $command->parseResponse($response); } /** * Handles -ERR responses returned by Redis. * * @param CommandInterface $command Redis command that generated the error. * @param ErrorResponseInterface $response Instance of the error response. * * @return mixed * @throws ServerException */ protected function onErrorResponse(CommandInterface $command, ErrorResponseInterface $response) { if ($command instanceof ScriptCommand && $response->getErrorType() === 'NOSCRIPT') { $response = $this->executeCommand($command->getEvalCommand()); if (!$response instanceof ResponseInterface) { $response = $command->parseResponse($response); } return $response; } if ($this->options->exceptions) { throw new ServerException($response->getMessage()); } return $response; } /** * Executes the specified initializer method on `$this` by adjusting the * actual invocation depending on the arity (0, 1 or 2 arguments). This is * simply an utility method to create Redis contexts instances since they * follow a common initialization path. * * @param string $initializer Method name. * @param array $argv Arguments for the method. * * @return mixed */ private function sharedContextFactory($initializer, $argv = null) { switch (count($argv)) { case 0: return $this->$initializer(); case 1: return is_array($argv[0]) ? $this->$initializer($argv[0]) : $this->$initializer(null, $argv[0]); case 2: [$arg0, $arg1] = $argv; return $this->$initializer($arg0, $arg1); default: return $this->$initializer($this, $argv); } } /** * Creates a new pipeline context and returns it, or returns the results of * a pipeline executed inside the optionally provided callable object. * * @param mixed ...$arguments Array of options, a callable for execution, or both. * * @return Pipeline|array */ public function pipeline(...$arguments) { return $this->sharedContextFactory('createPipeline', func_get_args()); } /** * Actual pipeline context initializer method. * * @param array|null $options Options for the context. * @param mixed $callable Optional callable used to execute the context. * * @return Pipeline|array */ protected function createPipeline(?array $options = null, $callable = null) { if (isset($options['atomic']) && $options['atomic']) { $class = Atomic::class; } elseif (isset($options['fire-and-forget']) && $options['fire-and-forget']) { $class = FireAndForget::class; } else { $class = Pipeline::class; } if ($this->connection instanceof RelayConnection) { if (isset($options['atomic']) && $options['atomic']) { $class = RelayAtomic::class; } elseif (isset($options['fire-and-forget']) && $options['fire-and-forget']) { throw new NotSupportedException('The "relay" extension does not support fire-and-forget pipelines.'); } else { $class = RelayPipeline::class; } } /* * @var ClientContextInterface */ $pipeline = new $class($this); if (isset($callable)) { return $pipeline->execute($callable); } return $pipeline; } /** * Creates a new transaction context and returns it, or returns the results * of a transaction executed inside the optionally provided callable object. * * @param mixed ...$arguments Array of options, a callable for execution, or both. * * @return MultiExecTransaction|array */ public function transaction(...$arguments) { return $this->sharedContextFactory('createTransaction', func_get_args()); } /** * Actual transaction context initializer method. * * @param array|null $options Options for the context. * @param mixed $callable Optional callable used to execute the context. * * @return MultiExecTransaction|array */ protected function createTransaction(?array $options = null, $callable = null) { $transaction = new MultiExecTransaction($this, $options); if (isset($callable)) { return $transaction->execute($callable); } return $transaction; } /** * Creates a new publish/subscribe context and returns it, or starts its loop * inside the optionally provided callable object. * * @param mixed ...$arguments Array of options, a callable for execution, or both. * * @return PubSubConsumer|null */ public function pubSubLoop(...$arguments) { return $this->sharedContextFactory('createPubSub', func_get_args()); } /** * Actual publish/subscribe context initializer method. * * @param array|null $options Options for the context. * @param mixed $callable Optional callable used to execute the context. * * @return PubSubConsumer|null */ protected function createPubSub(?array $options = null, $callable = null) { if ($this->connection instanceof RelayConnection) { $pubsub = new RelayPubSubConsumer($this, $options); } else { $pubsub = new PubSubConsumer($this, $options); } if (!isset($callable)) { return $pubsub; } foreach ($pubsub as $message) { if (call_user_func($callable, $pubsub, $message) === false) { $pubsub->stop(); } } return null; } /** * Creates a new monitor consumer and returns it. * * @return MonitorConsumer */ public function monitor() { return new MonitorConsumer($this); } /** * @return Traversable */ #[ReturnTypeWillChange] public function getIterator() { $clients = []; $connection = $this->getConnection(); if (!$connection instanceof Traversable) { return new ArrayIterator([ (string) $connection => new static($connection, $this->getOptions()), ]); } foreach ($connection as $node) { $clients[(string) $node] = new static($node, $this->getOptions()); } return new ArrayIterator($clients); } } PK)_]nendSdSsrc/ClientContextInterface.phpnu[ [ ['name' => 'Json', 'commandPrefix' => 'JSON'], ['name' => 'BloomFilter', 'commandPrefix' => 'BF'], ['name' => 'CuckooFilter', 'commandPrefix' => 'CF'], ['name' => 'CountMinSketch', 'commandPrefix' => 'CMS'], ['name' => 'TDigest', 'commandPrefix' => 'TDIGEST'], ['name' => 'TopK', 'commandPrefix' => 'TOPK'], ['name' => 'Search', 'commandPrefix' => 'FT'], ['name' => 'TimeSeries', 'commandPrefix' => 'TS'], ], ]; /** * Returns available modules with configuration. * * @return array|string[][] */ public static function getModules(): array { return self::$config['modules']; } } PK)_]d2src/PredisException.phpnu[ * @author Daniele Alessandri * @codeCoverageIgnore */ class Autoloader { private $directory; private $prefix; private $prefixLength; /** * @param string $baseDirectory Base directory where the source files are located. */ public function __construct($baseDirectory = __DIR__) { $this->directory = $baseDirectory; $this->prefix = __NAMESPACE__ . '\\'; $this->prefixLength = strlen($this->prefix); } /** * Registers the autoloader class with the PHP SPL autoloader. * * @param bool $prepend Prepend the autoloader on the stack instead of appending it. */ public static function register($prepend = false) { spl_autoload_register([new self(), 'autoload'], true, $prepend); } /** * Loads a class from a file using its fully qualified name. * * @param string $className Fully qualified name of a class. */ public function autoload($className) { if (0 === strpos($className, $this->prefix)) { $parts = explode('\\', substr($className, $this->prefixLength)); $filepath = $this->directory . DIRECTORY_SEPARATOR . implode(DIRECTORY_SEPARATOR, $parts) . '.php'; if (is_file($filepath)) { require $filepath; } } } } PK)_]DG src/NotSupportedException.phpnu[connection = $connection; } /** * Gets the connection that generated the exception. * * @return NodeConnectionInterface */ public function getConnection() { return $this->connection; } /** * Indicates if the receiver should reset the underlying connection. * * @return bool */ public function shouldResetConnection() { return true; } /** * Helper method to handle exceptions generated by a connection object. * * @param CommunicationException $exception Exception. * * @throws CommunicationException */ public static function handle(CommunicationException $exception) { if ($exception->shouldResetConnection()) { $connection = $exception->getConnection(); if ($connection->isConnected()) { $connection->disconnect(); } } throw $exception; } } PK)_]esrc/ClientException.phpnu[= 3.0). - Support for master-slave replication setups and [redis-sentinel](http://redis.io/topics/sentinel). - Transparent key prefixing of keys using a customizable prefix strategy. - Command pipelining on both single nodes and clusters (client-side sharding only). - Abstraction for Redis transactions (Redis >= 2.0) and CAS operations (Redis >= 2.2). - Abstraction for Lua scripting (Redis >= 2.6) and automatic switching between `EVALSHA` or `EVAL`. - Abstraction for `SCAN`, `SSCAN`, `ZSCAN` and `HSCAN` (Redis >= 2.8) based on PHP iterators. - Connections are established lazily by the client upon the first command and can be persisted. - Connections can be established via TCP/IP (also TLS/SSL-encrypted) or UNIX domain sockets. - Support for custom connection classes for providing different network or protocol backends. - Flexible system for defining custom commands and override the default ones. ## How to _install_ and use Predis ## This library can be found on [Packagist](http://packagist.org/packages/predis/predis) for an easier management of projects dependencies using [Composer](http://packagist.org/about-composer). Compressed archives of each release are [available on GitHub](https://github.com/predis/predis/releases). ```shell composer require predis/predis ``` ### Loading the library ### Predis relies on the autoloading features of PHP to load its files when needed and complies with the [PSR-4 standard](https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-4-autoloader.md). Autoloading is handled automatically when dependencies are managed through Composer, but it is also possible to leverage its own autoloader in projects or scripts lacking any autoload facility: ```php // Prepend a base path if Predis is not available in your "include_path". require 'Predis/Autoloader.php'; Predis\Autoloader::register(); ``` ### Connecting to Redis ### When creating a client instance without passing any connection parameter, Predis assumes `127.0.0.1` and `6379` as default host and port. The default timeout for the `connect()` operation is 5 seconds: ```php $client = new Predis\Client(); $client->set('foo', 'bar'); $value = $client->get('foo'); ``` Connection parameters can be supplied either in the form of URI strings or named arrays. The latter is the preferred way to supply parameters, but URI strings can be useful when parameters are read from non-structured or partially-structured sources: ```php // Parameters passed using a named array: $client = new Predis\Client([ 'scheme' => 'tcp', 'host' => '10.0.0.1', 'port' => 6379, ]); // Same set of parameters, passed using an URI string: $client = new Predis\Client('tcp://10.0.0.1:6379'); ``` Password protected servers can be accessed by adding `password` to the parameters set. When ACLs are enabled on Redis >= 6.0, both `username` and `password` are required for user authentication. It is also possible to connect to local instances of Redis using UNIX domain sockets, in this case the parameters must use the `unix` scheme and specify a path for the socket file: ```php $client = new Predis\Client(['scheme' => 'unix', 'path' => '/path/to/redis.sock']); $client = new Predis\Client('unix:/path/to/redis.sock'); ``` The client can leverage TLS/SSL encryption to connect to secured remote Redis instances without the need to configure an SSL proxy like stunnel. This can be useful when connecting to nodes running on various cloud hosting providers. Encryption can be enabled with using the `tls` scheme and an array of suitable [options](http://php.net/manual/context.ssl.php) passed via the `ssl` parameter: ```php // Named array of connection parameters: $client = new Predis\Client([ 'scheme' => 'tls', 'ssl' => ['cafile' => 'private.pem', 'verify_peer' => true], ]); // Same set of parameters, but using an URI string: $client = new Predis\Client('tls://127.0.0.1?ssl[cafile]=private.pem&ssl[verify_peer]=1'); ``` The connection schemes [`redis`](http://www.iana.org/assignments/uri-schemes/prov/redis) (alias of `tcp`) and [`rediss`](http://www.iana.org/assignments/uri-schemes/prov/rediss) (alias of `tls`) are also supported, with the difference that URI strings containing these schemes are parsed following the rules described on their respective IANA provisional registration documents. The actual list of supported connection parameters can vary depending on each connection backend so it is recommended to refer to their specific documentation or implementation for details. Predis can aggregate multiple connections when providing an array of connection parameters and the appropriate option to instruct the client about how to aggregate them (clustering, replication or a custom aggregation logic). Named arrays and URI strings can be mixed when providing configurations for each node: ```php $client = new Predis\Client([ 'tcp://10.0.0.1?alias=first-node', ['host' => '10.0.0.2', 'alias' => 'second-node'], ], [ 'cluster' => 'predis', ]); ``` See the [aggregate connections](#aggregate-connections) section of this document for more details. Connections to Redis are lazy meaning that the client connects to a server only if and when needed. While it is recommended to let the client do its own stuff under the hood, there may be times when it is still desired to have control of when the connection is opened or closed: this can easily be achieved by invoking `$client->connect()` and `$client->disconnect()`. Please note that the effect of these methods on aggregate connections may differ depending on each specific implementation. ### Client configuration ### Many aspects and behaviors of the client can be configured by passing specific client options to the second argument of `Predis\Client::__construct()`: ```php $client = new Predis\Client($parameters, ['prefix' => 'sample:']); ``` Options are managed using a mini DI-alike container and their values can be lazily initialized only when needed. The client options supported by default in Predis are: - `prefix`: prefix string applied to every key found in commands. - `exceptions`: whether the client should throw or return responses upon Redis errors. - `connections`: list of connection backends or a connection factory instance. - `cluster`: specifies a cluster backend (`predis`, `redis` or callable). - `replication`: specifies a replication backend (`predis`, `sentinel` or callable). - `aggregate`: configures the client with a custom aggregate connection (callable). - `parameters`: list of default connection parameters for aggregate connections. - `commands`: specifies a command factory instance to use through the library. Users can also provide custom options with values or callable objects (for lazy initialization) that are stored in the options container for later use through the library. ### Aggregate connections ### Aggregate connections are the foundation upon which Predis implements clustering and replication and they are used to group multiple connections to single Redis nodes and hide the specific logic needed to handle them properly depending on the context. Aggregate connections usually require an array of connection parameters along with the appropriate client option when creating a new client instance. #### Cluster #### Predis can be configured to work in clustering mode with a traditional client-side sharding approach to create a cluster of independent nodes and distribute the keyspace among them. This approach needs some sort of external health monitoring of nodes and requires the keyspace to be rebalanced manually when nodes are added or removed: ```php $parameters = ['tcp://10.0.0.1', 'tcp://10.0.0.2', 'tcp://10.0.0.3']; $options = ['cluster' => 'predis']; $client = new Predis\Client($parameters); ``` Along with Redis 3.0, a new supervised and coordinated type of clustering was introduced in the form of [redis-cluster](http://redis.io/topics/cluster-tutorial). This kind of approach uses a different algorithm to distribute the keyspaces, with Redis nodes coordinating themselves by communicating via a gossip protocol to handle health status, rebalancing, nodes discovery and request redirection. In order to connect to a cluster managed by redis-cluster, the client requires a list of its nodes (not necessarily complete since it will automatically discover new nodes if necessary) and the `cluster` client options set to `redis`: ```php $parameters = ['tcp://10.0.0.1', 'tcp://10.0.0.2', 'tcp://10.0.0.3']; $options = ['cluster' => 'redis']; $client = new Predis\Client($parameters, $options); ``` #### Replication #### The client can be configured to operate in a single master / multiple slaves setup to provide better service availability. When using replication, Predis recognizes read-only commands and sends them to a random slave in order to provide some sort of load-balancing and switches to the master as soon as it detects a command that performs any kind of operation that would end up modifying the keyspace or the value of a key. Instead of raising a connection error when a slave fails, the client attempts to fall back to a different slave among the ones provided in the configuration. The basic configuration needed to use the client in replication mode requires one Redis server to be identified as the master (this can be done via connection parameters by setting the `role` parameter to `master`) and one or more slaves (in this case setting `role` to `slave` for slaves is optional): ```php $parameters = ['tcp://10.0.0.1?role=master', 'tcp://10.0.0.2', 'tcp://10.0.0.3']; $options = ['replication' => 'predis']; $client = new Predis\Client($parameters, $options); ``` The above configuration has a static list of servers and relies entirely on the client's logic, but it is possible to rely on [`redis-sentinel`](http://redis.io/topics/sentinel) for a more robust HA environment with sentinel servers acting as a source of authority for clients for service discovery. The minimum configuration required by the client to work with redis-sentinel is a list of connection parameters pointing to a bunch of sentinel instances, the `replication` option set to `sentinel` and the `service` option set to the name of the service: ```php $sentinels = ['tcp://10.0.0.1', 'tcp://10.0.0.2', 'tcp://10.0.0.3']; $options = ['replication' => 'sentinel', 'service' => 'mymaster']; $client = new Predis\Client($sentinels, $options); ``` If the master and slave nodes are configured to require an authentication from clients, a password must be provided via the global `parameters` client option. This option can also be used to specify a different database index. The client options array would then look like this: ```php $options = [ 'replication' => 'sentinel', 'service' => 'mymaster', 'parameters' => [ 'password' => $secretpassword, 'database' => 10, ], ]; ``` While Predis is able to distinguish commands performing write and read-only operations, `EVAL` and `EVALSHA` represent a corner case in which the client switches to the master node because it cannot tell when a Lua script is safe to be executed on slaves. While this is indeed the default behavior, when certain Lua scripts do not perform write operations it is possible to provide an hint to tell the client to stick with slaves for their execution: ```php $parameters = ['tcp://10.0.0.1?role=master', 'tcp://10.0.0.2', 'tcp://10.0.0.3']; $options = ['replication' => function () { // Set scripts that won't trigger a switch from a slave to the master node. $strategy = new Predis\Replication\ReplicationStrategy(); $strategy->setScriptReadOnly($LUA_SCRIPT); return new Predis\Connection\Replication\MasterSlaveReplication($strategy); }]; $client = new Predis\Client($parameters, $options); $client->eval($LUA_SCRIPT, 0); // Sticks to slave using `eval`... $client->evalsha(sha1($LUA_SCRIPT), 0); // ... and `evalsha`, too. ``` The [`examples`](examples/) directory contains a few scripts that demonstrate how the client can be configured and used to leverage replication in both basic and complex scenarios. ### Command pipelines ### Pipelining can help with performances when many commands need to be sent to a server by reducing the latency introduced by network round-trip timings. Pipelining also works with aggregate connections. The client can execute the pipeline inside a callable block or return a pipeline instance with the ability to chain commands thanks to its fluent interface: ```php // Executes a pipeline inside the given callable block: $responses = $client->pipeline(function ($pipe) { for ($i = 0; $i < 1000; $i++) { $pipe->set("key:$i", str_pad($i, 4, '0', 0)); $pipe->get("key:$i"); } }); // Returns a pipeline that can be chained thanks to its fluent interface: $responses = $client->pipeline()->set('foo', 'bar')->get('foo')->execute(); ``` ### Transactions ### The client provides an abstraction for Redis transactions based on `MULTI` and `EXEC` with a similar interface to command pipelines: ```php // Executes a transaction inside the given callable block: $responses = $client->transaction(function ($tx) { $tx->set('foo', 'bar'); $tx->get('foo'); }); // Returns a transaction that can be chained thanks to its fluent interface: $responses = $client->transaction()->set('foo', 'bar')->get('foo')->execute(); ``` This abstraction can perform check-and-set operations thanks to `WATCH` and `UNWATCH` and provides automatic retries of transactions aborted by Redis when `WATCH`ed keys are touched. For an example of a transaction using CAS you can see [the following example](examples/transaction_using_cas.php). ### Adding new commands ### While we try to update Predis to stay up to date with all the commands available in Redis, you might prefer to stick with an old version of the library or provide a different way to filter arguments or parse responses for specific commands. To achieve that, Predis provides the ability to implement new command classes to define or override commands in the default command factory used by the client: ```php // Define a new command by extending Predis\Command\Command: class BrandNewRedisCommand extends Predis\Command\Command { public function getId() { return 'NEWCMD'; } } // Inject your command in the current command factory: $client = new Predis\Client($parameters, [ 'commands' => [ 'newcmd' => 'BrandNewRedisCommand', ], ]); $response = $client->newcmd(); ``` There is also a method to send raw commands without filtering their arguments or parsing responses. Users must provide the list of arguments for the command as an array, following the signatures as defined by the [Redis documentation for commands](http://redis.io/commands): ```php $response = $client->executeRaw(['SET', 'foo', 'bar']); ``` ### Script commands ### While it is possible to leverage [Lua scripting](http://redis.io/commands/eval) on Redis 2.6+ using directly [`EVAL`](http://redis.io/commands/eval) and [`EVALSHA`](http://redis.io/commands/evalsha), Predis offers script commands as an higher level abstraction built upon them to make things simple. Script commands can be registered in the command factory used by the client and are accessible as if they were plain Redis commands, but they define Lua scripts that get transmitted to the server for remote execution. Internally they use [`EVALSHA`](http://redis.io/commands/evalsha) by default and identify a script by its SHA1 hash to save bandwidth, but [`EVAL`](http://redis.io/commands/eval) is used as a fall back when needed: ```php // Define a new script command by extending Predis\Command\ScriptCommand: class ListPushRandomValue extends Predis\Command\ScriptCommand { public function getKeysCount() { return 1; } public function getScript() { return << [ 'lpushrand' => 'ListPushRandomValue', ], ]); $response = $client->lpushrand('random_values', $seed = mt_rand()); ``` ### Customizable connection backends ### Predis can use different connection backends to connect to Redis. The builtin Relay integration leverages the [Relay](https://github.com/cachewerk/relay) extension for PHP for major performance gains, by caching a partial replica of the Redis dataset in PHP shared runtime memory. ```php $client = new Predis\Client('tcp://127.0.0.1', [ 'connections' => 'relay', ]); ``` Developers can create their own connection classes to support whole new network backends, extend existing classes or provide completely different implementations. Connection classes must implement `Predis\Connection\NodeConnectionInterface` or extend `Predis\Connection\AbstractConnection`: ```php class MyConnectionClass implements Predis\Connection\NodeConnectionInterface { // Implementation goes here... } // Use MyConnectionClass to handle connections for the `tcp` scheme: $client = new Predis\Client('tcp://127.0.0.1', [ 'connections' => ['tcp' => 'MyConnectionClass'], ]); ``` For a more in-depth insight on how to create new connection backends you can refer to the actual implementation of the standard connection classes available in the `Predis\Connection` namespace. ## Development ## ### Reporting bugs and contributing code ### Contributions to Predis are highly appreciated either in the form of pull requests for new features, bug fixes, or just bug reports. We only ask you to adhere to issue and pull request templates. ### Test suite ### __ATTENTION__: Do not ever run the test suite shipped with Predis against instances of Redis running in production environments or containing data you are interested in! Predis has a comprehensive test suite covering every aspect of the library and that can optionally perform integration tests against a running instance of Redis (required >= 2.4.0 in order to verify the correct behavior of the implementation of each command. Integration tests for unsupported Redis commands are automatically skipped. If you do not have Redis up and running, integration tests can be disabled. See [the tests README](tests/README.md) for more details about testing this library. Predis uses GitHub Actions for continuous integration and the history for past and current builds can be found [on its actions page](https://github.com/predis/predis/actions). ### License ### The code for Predis is distributed under the terms of the MIT license (see [LICENSE](LICENSE)). [ico-license]: https://img.shields.io/github/license/predis/predis.svg?style=flat-square [ico-version-stable]: https://img.shields.io/github/v/tag/predis/predis?label=stable&style=flat-square [ico-version-dev]: https://img.shields.io/github/v/tag/predis/predis?include_prereleases&label=pre-release&style=flat-square [ico-downloads-monthly]: https://img.shields.io/packagist/dm/predis/predis.svg?style=flat-square [ico-build]: https://img.shields.io/github/actions/workflow/status/predis/predis/tests.yml?branch=main&style=flat-square [ico-coverage]: https://img.shields.io/coverallsCoverage/github/predis/predis?style=flat-square [link-releases]: https://github.com/predis/predis/releases [link-actions]: https://github.com/predis/predis/actions [link-downloads]: https://packagist.org/packages/predis/predis/stats [link-coverage]: https://coveralls.io/github/predis/predis PK)_]C"["" composer.jsonnu[{ "name": "predis/predis", "type": "library", "description": "A flexible and feature-complete Redis client for PHP.", "keywords": ["nosql", "redis", "predis"], "homepage": "http://github.com/predis/predis", "license": "MIT", "support": { "issues": "https://github.com/predis/predis/issues" }, "authors": [ { "name": "Till Krüss", "homepage": "https://till.im", "role": "Maintainer" } ], "funding": [ { "type": "github", "url": "https://github.com/sponsors/tillkruss" } ], "require": { "php": "^7.2 || ^8.0" }, "require-dev": { "friendsofphp/php-cs-fixer": "^3.3", "phpstan/phpstan": "^1.9", "phpunit/phpunit": "^8.0 || ^9.4" }, "suggest": { "ext-relay": "Faster connection with in-memory caching (>=0.6.2)" }, "scripts": { "phpstan": "phpstan analyse", "style": "php-cs-fixer fix --diff --dry-run", "style:fix": "php-cs-fixer fix" }, "autoload": { "psr-4": { "Predis\\": "src/" } }, "config": { "sort-packages": true, "preferred-install": "dist" }, "minimum-stability": "dev", "prefer-stable": true } PK)_]j<||LICENSEnu[MIT License Copyright (c) 2009-2020 Daniele Alessandri (original work) Copyright (c) 2021-2024 Till Krüss (modified work) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. PK\X]aD/ )predis/src/Transaction/MultiExecState.phpnu[PK\X]e ::46 predis/src/Transaction/AbortedMultiExecException.phpnu[PK\X]>|6|6$predis/src/Transaction/MultiExec.phpnu[PK\X]Q*Gpredis/src/Collection/Iterator/ListKey.phpnu[PK\X]uT  /Ypredis/src/Collection/Iterator/SortedSetKey.phpnu[PK\X]lC+I_predis/src/Collection/Iterator/Keyspace.phpnu[PK\X]oc){cpredis/src/Collection/Iterator/SetKey.phpnu[PK\X]&t*gpredis/src/Collection/Iterator/HashKey.phpnu[PK\X]- DD6Dmpredis/src/Collection/Iterator/CursorBasedIterator.phpnu[PK\X]577&predis/src/PubSub/AbstractConsumer.phpnu[PK\X]j~${predis/src/PubSub/DispatcherLoop.phpnu[PK\X]U #jpredis/src/PubSub/RelayConsumer.phpnu[PK\X]k0Spredis/src/PubSub/Consumer.phpnu[PK\X]c%!NN.predis/src/Connection/Cluster/RedisCluster.phpnu[PK\X]2predis/src/Connection/Cluster/ClusterInterface.phpnu[PK\X].ѹ/predis/src/Connection/Cluster/PredisCluster.phpnu[PK\X]i tRtR93,predis/src/Connection/Replication/SentinelReplication.phpnu[PK\X]P(99<predis/src/Connection/Replication/MasterSlaveReplication.phpnu[PK\X]'o:predis/src/Connection/Replication/ReplicationInterface.phpnu[PK\X]e-e-*mpredis/src/Connection/StreamConnection.phpnu[PK\X]!883,predis/src/Connection/PhpiredisStreamConnection.phpnu[PK\X]0- predis/src/Connection/ConnectionException.phpnu[PK\X]: : & predis/src/Connection/RelayMethods.phpnu[PK\X]X:.:.3zpredis/src/Connection/PhpiredisSocketConnection.phpnu[PK\X]fqЛ6Gpredis/src/Connection/CompositeConnectionInterface.phpnu[PK\X]Akk*Lpredis/src/Connection/FactoryInterface.phpnu[PK\X]}"/$$*Ppredis/src/Connection/WebdisConnection.phpnu[PK\X] j 3upredis/src/Connection/CompositeStreamConnection.phpnu[PK\X]!predis/src/Connection/Factory.phpnu[PK\X]͑N""1*predis/src/Connection/NodeConnectionInterface.phpnu[PK\X]Qr#-predis/src/Connection/ConnectionInterface.phpnu[PK\X]_($$)predis/src/Connection/RelayConnection.phpnu[PK\X]wD9o$predis/src/Connection/Parameters.phpnu[PK\X]m ,predis/src/Connection/AbstractConnection.phpnu[PK\X]G.$$6predis/src/Connection/AggregateConnectionInterface.phpnu[PK\X]AMZ Z -predis/src/Connection/ParametersInterface.phpnu[PK\X]kig g !Rpredis/src/Cluster/Hash/CRC16.phpnu[PK\X]nx* predis/src/Cluster/Hash/PhpiredisCRC16.phpnu[PK\X]fʌ2%predis/src/Cluster/Hash/HashGeneratorInterface.phpnu[PK\X]Vǡ+predis/src/Cluster/Distributor/HashRing.phpnu[PK\X];$$70predis/src/Cluster/Distributor/DistributorInterface.phpnu[PK\X]Aee-7predis/src/Cluster/Distributor/KetamaRing.phpnu[PK\X]5\?predis/src/Cluster/Distributor/EmptyRingException.phpnu[PK\X]g%`Apredis/src/Cluster/PredisStrategy.phpnu[PK\X]/^ = =&8Hpredis/src/Cluster/ClusterStrategy.phpnu[PK\X])=  predis/src/Cluster/SlotMap.phpnu[PK\X]/j$predis/src/Cluster/RedisStrategy.phpnu[PK\X].-  ([predis/src/Cluster/StrategyInterface.phpnu[PK\X]U+Iӣpredis/src/Command/Strategy/ContainerCommands/Functions/FlushStrategy.phpnu[PK\X] ]H\predis/src/Command/Strategy/ContainerCommands/Functions/ListStrategy.phpnu[PK\X]>gDDIspredis/src/Command/Strategy/ContainerCommands/Functions/StatsStrategy.phpnu[PK\X]¸'!!K0predis/src/Command/Strategy/ContainerCommands/Functions/RestoreStrategy.phpnu[PK\X]xH̱predis/src/Command/Strategy/ContainerCommands/Functions/LoadStrategy.phpnu[PK\X]CCH'predis/src/Command/Strategy/ContainerCommands/Functions/DumpStrategy.phpnu[PK\X]CCHpredis/src/Command/Strategy/ContainerCommands/Functions/KillStrategy.phpnu[PK\X]a EEJpredis/src/Command/Strategy/ContainerCommands/Functions/DeleteStrategy.phpnu[PK\X]X  ;\predis/src/Command/Strategy/SubcommandStrategyInterface.phpnu[PK\X]/*9predis/src/Command/Strategy/StrategyResolverInterface.phpnu[PK\X]j :predis/src/Command/Strategy/SubcommandStrategyResolver.phpnu[PK\X]TF) predis/src/Command/Traits/To/ServerTo.phpnu[PK\X]g66*Cpredis/src/Command/Traits/From/GeoFrom.phpnu[PK\X].C2predis/src/Command/Traits/Expire/ExpireOptions.phpnu[PK\X]X/predis/src/Command/Traits/Limit/LimitObject.phpnu[PK\X])!predis/src/Command/Traits/Limit/Limit.phpnu[PK\X]=%:predis/src/Command/Traits/Get/Get.phpnu[PK\X]:@X+predis/src/Command/Traits/With/WithDist.phpnu[PK\X]r!,predis/src/Command/Traits/With/WithCoord.phpnu[PK\X]ޝz-@predis/src/Command/Traits/With/WithValues.phpnu[PK\X]a$+bpredis/src/Command/Traits/With/WithHash.phpnu[PK\X]*܅-predis/src/Command/Traits/With/WithScores.phpnu[PK\X]T/{predis/src/Command/Traits/Json/NxXxArgument.phpnu[PK\X]EgDȰ( predis/src/Command/Traits/Json/Space.phpnu[PK\X]p!*predis/src/Command/Traits/Json/Newline.phpnu[PK\X]/5)predis/src/Command/Traits/Json/Indent.phpnu[PK\X] $$&predis/src/Command/Traits/By/GeoBy.phpnu[PK\X]99-:"predis/src/Command/Traits/By/ByLexByScore.phpnu[PK\X]Pq44+'predis/src/Command/Traits/By/ByArgument.phpnu[PK\X]OO5_,predis/src/Command/Traits/BloomFilters/BucketSize.phpnu[PK\X]BFT  43predis/src/Command/Traits/BloomFilters/Expansion.phpnu[PK\X]Xss89predis/src/Command/Traits/BloomFilters/MaxIterations.phpnu[PK\X];0^@predis/src/Command/Traits/BloomFilters/Error.phpnu[PK\X]TJWW0Fpredis/src/Command/Traits/BloomFilters/Items.phpnu[PK\X]43Kpredis/src/Command/Traits/BloomFilters/NoCreate.phpnu[PK\X] 663Qpredis/src/Command/Traits/BloomFilters/Capacity.phpnu[PK\X]t%Wpredis/src/Command/Traits/Sorting.phpnu[PK\X]  ,^predis/src/Command/Traits/MinMaxModifier.phpnu[PK\X]ٕQQ%ubpredis/src/Command/Traits/BitByte.phpnu[PK\X]Rꌿ#fpredis/src/Command/Traits/Count.phpnu[PK\X]<'-npredis/src/Command/Traits/Storedist.phpnu[PK\X]f55!spredis/src/Command/Traits/Rev.phpnu[PK\X]t8 xpredis/src/Command/Traits/DB.phpnu[PK\X]]iVll"~predis/src/Command/Traits/Keys.phpnu[PK\X]}]%σpredis/src/Command/Traits/Replace.phpnu[PK\X]%%φpredis/src/Command/Traits/Weights.phpnu[PK\X]3QQ'&predis/src/Command/Traits/LeftRight.phpnu[PK\X]| 'Γpredis/src/Command/Traits/Aggregate.phpnu[PK\X]|v%predis/src/Command/Traits/Timeout.phpnu[PK\X]h WW"&predis/src/Command/Redis/LMPOP.phpnu[PK\X]޳.Ϧpredis/src/Command/Redis/GEORADIUSBYMEMBER.phpnu[PK\X]e..$predis/src/Command/Redis/SORT_RO.phpnu[PK\X]o#"~predis/src/Command/Redis/MULTI.phpnu[PK\X]F$$سpredis/src/Command/Redis/PEXPIRE.phpnu[PK\X]@ #:predis/src/Command/Redis/ZRANGE.phpnu[PK\X]tPTT$>predis/src/Command/Redis/GEOHASH.phpnu[PK\X]tpX-predis/src/Command/Redis/Search/FTEXPLAIN.phpnu[PK\X]M88-predis/src/Command/Redis/Search/FTTAGVALS.phpnu[PK\X]g/kpredis/src/Command/Redis/Search/FTSYNUPDATE.phpnu[PK\X]w(o~~,predis/src/Command/Redis/Search/FTCREATE.phpnu[PK\X]&,,-ypredis/src/Command/Redis/Search/FTPROFILE.phpnu[PK\X] 0`.predis/src/Command/Redis/Search/FTALIASADD.phpnu[PK\X]b{{,}predis/src/Command/Redis/Search/FTSEARCH.phpnu[PK\X]}},Tpredis/src/Command/Redis/Search/FTSUGADD.phpnu[PK\X]Y#/-predis/src/Command/Redis/Search/FTAGGREGATE.phpnu[PK\X]c55,?predis/src/Command/Redis/Search/FTSUGLEN.phpnu[PK\X]"H#SS,predis/src/Command/Redis/Search/FTSUGGET.phpnu[PK\X]e%,predis/src/Command/Redis/Search/FTCURSOR.phpnu[PK\X]z<"".predis/src/Command/Redis/Search/FTALIASDEL.phpnu[PK\X]ƿ''*lpredis/src/Command/Redis/Search/FTINFO.phpnu[PK\X]hs++.predis/src/Command/Redis/Search/FTDICTDUMP.phpnu[PK\X]-&ߌ1vpredis/src/Command/Redis/Search/FTALIASUPDATE.phpnu[PK\X]z# ..0}predis/src/Command/Redis/Search/FTSPELLCHECK.phpnu[PK\X]bv+ predis/src/Command/Redis/Search/FTALTER.phpnu[PK\X]T&&-predis/src/Command/Redis/Search/FTSYNDUMP.phpnu[PK\X]|/predis/src/Command/Redis/Search/FTDROPINDEX.phpnu[PK\X]xr-predis/src/Command/Redis/Search/FTDICTADD.phpnu[PK\X]!w  - predis/src/Command/Redis/Search/FTDICTDEL.phpnu[PK\X]+&&,t predis/src/Command/Redis/Search/FTSUGDEL.phpnu[PK\X],predis/src/Command/Redis/Search/FTCONFIG.phpnu[PK\X]> predis/src/Command/Redis/GET.phpnu[PK\X]a Npredis/src/Command/Redis/TTL.phpnu[PK\X]_))-predis/src/Command/Redis/ZREMRANGEBYSCORE.phpnu[PK\X]p  #&predis/src/Command/Redis/HSETNX.phpnu[PK\X]gN,\\%predis/src/Command/Redis/SHUTDOWN.phpnu[PK\X] x+5!predis/src/Command/Redis/ZREVRANGEBYLEX.phpnu[PK\X]h* #predis/src/Command/Redis/DEL.phpnu[PK\X][!&predis/src/Command/Redis/KEYS.phpnu[PK\X]s!(predis/src/Command/Redis/LSET.phpnu[PK\X]@ :XX"N+predis/src/Command/Redis/XTRIM.phpnu[PK\X]#/predis/src/Command/Redis/EXPIRE.phpnu[PK\X]ȝ(Z3predis/src/Command/Redis/ZRANGESTORE.phpnu[PK\X],Un::$O9predis/src/Command/Redis/HEXPIRE.phpnu[PK\X]J!>predis/src/Command/Redis/QUIT.phpnu[PK\X]y%3Apredis/src/Command/Redis/SETRANGE.phpnu[PK\X]$Cpredis/src/Command/Redis/FLUSHDB.phpnu[PK\X]OpK#Epredis/src/Command/Redis/BLMOVE.phpnu[PK\X]u'"Gpredis/src/Command/Redis/HPTTL.phpnu[PK\X]nbD"Ipredis/src/Command/Redis/HMGET.phpnu[PK\X]KK.Lpredis/src/Command/Redis/TimeSeries/TSINFO.phpnu[PK\X]xxWW-nPpredis/src/Command/Redis/TimeSeries/TSGET.phpnu[PK\X]7>>4"Tpredis/src/Command/Redis/TimeSeries/TSQUERYINDEX.phpnu[PK\X]7p;;-Vpredis/src/Command/Redis/TimeSeries/TSDEL.phpnu[PK\X]M&(tt/\Ypredis/src/Command/Redis/TimeSeries/TSALTER.phpnu[PK\X]j]''4/]predis/src/Command/Redis/TimeSeries/TSDELETERULE.phpnu[PK\X]JT**._predis/src/Command/Redis/TimeSeries/TSMADD.phpnu[PK\X]ƣT'$$3Bbpredis/src/Command/Redis/TimeSeries/TSMREVRANGE.phpnu[PK\X]Ag4dpredis/src/Command/Redis/TimeSeries/TSCREATERULE.phpnu[PK\X]gyy/hpredis/src/Command/Redis/TimeSeries/TSRANGE.phpnu[PK\X]` 0lpredis/src/Command/Redis/TimeSeries/TSINCRBY.phpnu[PK\X]>0 qpredis/src/Command/Redis/TimeSeries/TSDECRBY.phpnu[PK\X]]]-cupredis/src/Command/Redis/TimeSeries/TSADD.phpnu[PK\X]nY660ypredis/src/Command/Redis/TimeSeries/TSCREATE.phpnu[PK\X]w"predis/src/Command/Redis/SSCAN.phpnu[PK\X]r! predis/src/Command/Redis/DUMP.phpnu[PK\X]Dhh!vpredis/src/Command/Redis/ZADD.phpnu[PK\X]D(/predis/src/Command/Redis/ZUNIONSTORE.phpnu[PK\X]t""predis/src/Command/Redis/BITOP.phpnu[PK\X]"W&&,predis/src/Command/Redis/ZREMRANGEBYRANK.phpnu[PK\X]mI!xpredis/src/Command/Redis/HDEL.phpnu[PK\X]uill%predis/src/Command/Redis/BZPOPMIN.phpnu[PK\X]z!Ypredis/src/Command/Redis/SADD.phpnu[PK\X]ɲ&ypredis/src/Command/Redis/RANDOMKEY.phpnu[PK\X]͉`!jpredis/src/Command/Redis/LPOP.phpnu[PK\X]V͔"predis/src/Command/Redis/HKEYS.phpnu[PK\X]8e&predis/src/Command/Redis/SUBSCRIBE.phpnu[PK\X]) ;$Opredis/src/Command/Redis/SLOWLOG.phpnu[PK\X];2\\$predis/src/Command/Redis/HGETALL.phpnu[PK\X] )/  "Ppredis/src/Command/Redis/WATCH.phpnu[PK\X](u'predis/src/Command/Redis/PSUBSCRIBE.phpnu[PK\X]3͹$predis/src/Command/Redis/WAITAOF.phpnu[PK\X]J#predis/src/Command/Redis/XRANGE.phpnu[PK\X]y<!predis/src/Command/Redis/HTTL.phpnu[PK\X]"#!predis/src/Command/Redis/XDEL.phpnu[PK\X]X5" " !8predis/src/Command/Redis/INFO.phpnu[PK\X]t7$predis/src/Command/Redis/EVAL_RO.phpnu[PK\X]Cdd5predis/src/Command/Redis/CountMinSketch/CMSINCRBY.phpnu[PK\X] c{_XX9predis/src/Command/Redis/CountMinSketch/CMSINITBYPROB.phpnu[PK\X]:]%QQ8Bpredis/src/Command/Redis/CountMinSketch/CMSINITBYDIM.phpnu[PK\X]M!3 predis/src/Command/Redis/CountMinSketch/CMSINFO.phpnu[PK\X]! 444predis/src/Command/Redis/CountMinSketch/CMSMERGE.phpnu[PK\X]6ũ::4predis/src/Command/Redis/CountMinSketch/CMSQUERY.phpnu[PK\X]1]&Rpredis/src/Command/Redis/ZLEXCOUNT.phpnu[PK\X]  #predis/src/Command/Redis/APPEND.phpnu[PK\X]՜"predis/src/Command/Redis/XREAD.phpnu[PK\X]&,8&&#!predis/src/Command/Redis/ZUNION.phpnu[PK\X]"$predis/src/Command/Redis/LMOVE.phpnu[PK\X] L!&predis/src/Command/Redis/DECR.phpnu[PK\X]/α'(predis/src/Command/Redis/ZDIFFSTORE.phpnu[PK\X].ѡ!,predis/src/Command/Redis/LREM.phpnu[PK\X]5X!;/predis/src/Command/Redis/HLEN.phpnu[PK\X]+9!1predis/src/Command/Redis/PING.phpnu[PK\X]`(ox!3predis/src/Command/Redis/SAVE.phpnu[PK\X]Y#=6predis/src/Command/Redis/CLIENT.phpnu[PK\X]R<<' =predis/src/Command/Redis/SMISMEMBER.phpnu[PK\X]m|"?predis/src/Command/Redis/SMOVE.phpnu[PK\X]X" Bpredis/src/Command/Redis/LPUSH.phpnu[PK\X]݃H $1Epredis/src/Command/Redis/MONITOR.phpnu[PK\X]!Gpredis/src/Command/Redis/COPY.phpnu[PK\X]~b3 %Kpredis/src/Command/Redis/LASTSAVE.phpnu[PK\X]cb'-!)Npredis/src/Command/Redis/PTTL.phpnu[PK\X]#Ppredis/src/Command/Redis/BITPOS.phpnu[PK\X]-W8saa XSpredis/src/Command/Redis/SET.phpnu[PK\X]-K$ Wpredis/src/Command/Redis/ZPOPMAX.phpnu[PK\X]əNKK#Zpredis/src/Command/Redis/CONFIG.phpnu[PK\X]$_predis/src/Command/Redis/EVALSHA.phpnu[PK\X]'v  #~bpredis/src/Command/Redis/RENAME.phpnu[PK\X]'E)dpredis/src/Command/Redis/TopK/TOPKADD.phpnu[PK\X]_kk*(hpredis/src/Command/Redis/TopK/TOPKINFO.phpnu[PK\X]zI,kpredis/src/Command/Redis/TopK/TOPKINCRBY.phpnu[PK\X]ju* opredis/src/Command/Redis/TopK/TOPKLIST.phpnu[PK\X]k9VV+upredis/src/Command/Redis/TopK/TOPKQUERY.phpnu[PK\X]ͮ-3xpredis/src/Command/Redis/TopK/TOPKRESERVE.phpnu[PK\X]C&|predis/src/Command/Redis/ZREVRANGE.phpnu[PK\X]ar!~predis/src/Command/Redis/HSET.phpnu[PK\X]l)<predis/src/Command/Redis/PUNSUBSCRIBE.phpnu[PK\X]c$}predis/src/Command/Redis/UNWATCH.phpnu[PK\X]gW!/#߆predis/src/Command/Redis/SUNION.phpnu[PK\X]b,0*predis/src/Command/Redis/ZRANGEBYSCORE.phpnu[PK\X]2&Fpredis/src/Command/Redis/PEXPIREAT.phpnu[PK\X]Jgg(predis/src/Command/Redis/ZRANGEBYLEX.phpnu[PK\X]q q  #opredis/src/Command/Redis/INCRBY.phpnu[PK\X]̼mm%͙predis/src/Command/Redis/BZPOPMAX.phpnu[PK\X] %ii#predis/src/Command/Redis/GEOADD.phpnu[PK\X]?1&Kpredis/src/Command/Redis/HEXPIREAT.phpnu[PK\X]sI$+predis/src/Command/Redis/ZMSCORE.phpnu[PK\X]J~qb$Jpredis/src/Command/Redis/SLAVEOF.phpnu[PK\X]O&/)predis/src/Command/Redis/BGREWRITEAOF.phpnu[PK\X]MoCC"ͬpredis/src/Command/Redis/BRPOP.phpnu[PK\X]d'bpredis/src/Command/Redis/SINTERCARD.phpnu[PK\X] "^predis/src/Command/Redis/ZMPOP.phpnu[PK\X]#&>(Spredis/src/Command/Redis/PEXPIRETIME.phpnu[PK\X]l]]"3predis/src/Command/Redis/HVALS.phpnu[PK\X]46predis/src/Command/Redis/AbstractCommand/BZPOPBase.phpnu[PK\X]5'!predis/src/Command/Redis/INCR.phpnu[PK\X]U$predis/src/Command/Redis/CLUSTER.phpnu[PK\X]D%(predis/src/Command/Redis/SMEMBERS.phpnu[PK\X]g^i$predis/src/Command/Redis/COMMAND.phpnu[PK\X] fLL%predis/src/Command/Redis/FAILOVER.phpnu[PK\X]ԫUb$opredis/src/Command/Redis/ZINCRBY.phpnu[PK\X]އ_#predis/src/Command/Redis/PUBSUB.phpnu[PK\X]&%predis/src/Command/Redis/HPEXPIRE.phpnu[PK\X]<"predis/src/Command/Redis/SDIFF.phpnu[PK\X]_k"predis/src/Command/Redis/ECHO_.phpnu[PK\X]o-LL1Opredis/src/Command/Redis/TDigest/TDIGESTRESET.phpnu[PK\X]>b/predis/src/Command/Redis/TDigest/TDIGESTMAX.phpnu[PK\X]b~  4Ypredis/src/Command/Redis/TDigest/TDIGESTQUANTILE.phpnu[PK\X]9qnn0predis/src/Command/Redis/TDigest/TDIGESTINFO.phpnu[PK\X]}3predis/src/Command/Redis/TDigest/TDIGESTREVRANK.phpnu[PK\X]0@2predis/src/Command/Redis/TDigest/TDIGESTBYRANK.phpnu[PK\X]^/.predis/src/Command/Redis/TDigest/TDIGESTMIN.phpnu[PK\X]kl88/predis/src/Command/Redis/TDigest/TDIGESTADD.phpnu[PK\X]]n80"predis/src/Command/Redis/TDigest/TDIGESTRANK.phpnu[PK\X]3 A2ipredis/src/Command/Redis/TDigest/TDIGESTCREATE.phpnu[PK\X]5m predis/src/Command/Redis/TDigest/TDIGESTBYREVRANK.phpnu[PK\X]뻀}}1predis/src/Command/Redis/TDigest/TDIGESTMERGE.phpnu[PK\X]q,,/predis/src/Command/Redis/TDigest/TDIGESTCDF.phpnu[PK\X]~ˑ1__8.predis/src/Command/Redis/TDigest/TDIGESTTRIMMED_MEAN.phpnu[PK\X]6)c%predis/src/Command/Redis/SENTINEL.phpnu[PK\X]ь$(%predis/src/Command/Redis/HINCRBY.phpnu[PK\X]+'predis/src/Command/Redis/GEOSEARCHSTORE.phpnu[PK\X]K@$  #.predis/src/Command/Redis/LINDEX.phpnu[PK\X]!(1predis/src/Command/Redis/TYPE.phpnu[PK\X] l7%s5predis/src/Command/Redis/FCALL_RO.phpnu[PK\X]e!9predis/src/Command/Redis/MOVE.phpnu[PK\X]]$<predis/src/Command/Redis/HEXISTS.phpnu[PK\X]lj__'g>predis/src/Command/Redis/ZINTERCARD.phpnu[PK\X]a~!Cpredis/src/Command/Redis/XADD.phpnu[PK\X]P P &Ipredis/src/Command/Redis/GEOSEARCH.phpnu[PK\X]I  #Vpredis/src/Command/Redis/DBSIZE.phpnu[PK\X]ǘ! Ypredis/src/Command/Redis/RPOP.phpnu[PK\X]-%a[predis/src/Command/Redis/RENAMENX.phpnu[PK\X]ܳ"]predis/src/Command/Redis/SETEX.phpnu[PK\X]s/e%!`predis/src/Command/Redis/HPERSIST.phpnu[PK\X]7#Bcpredis/src/Command/Redis/MSETNX.phpnu[PK\X]**"kepredis/src/Command/Redis/GETEX.phpnu[PK\X]&kpredis/src/Command/Redis/RPOPLPUSH.phpnu[PK\X]$Qnpredis/src/Command/Redis/HSTRLEN.phpnu[PK\X]-D[[(ppredis/src/Command/Redis/ZRANDMEMBER.phpnu[PK\X]Ɋ&ftpredis/src/Command/Redis/XREVRANGE.phpnu[PK\X]F~@!vpredis/src/Command/Redis/SPOP.phpnu[PK\X],c!xpredis/src/Command/Redis/AUTH.phpnu[PK\X]4I{predis/src/Command/Redis/CuckooFilter/CFSCANDUMP.phpnu[PK\X]:FF1K~predis/src/Command/Redis/CuckooFilter/CFADDNX.phpnu[PK\X]9;/predis/src/Command/Redis/CuckooFilter/CFDEL.phpnu[PK\X]zYY4predis/src/Command/Redis/CuckooFilter/CFINSERTNX.phpnu[PK\X]-predis/src/Command/Redis/TIME.phpnu[PK\X]"predis/src/Command/Redis/LTRIM.phpnu[PK\X]Ut%predis/src/Command/Redis/BITFIELD.phpnu[PK\X]@=<<(Tpredis/src/Command/Redis/SINTERSTORE.phpnu[PK\X]a --'predis/src/Command/Redis/EVALSHA_RO.phpnu[PK\X]YZ"lpredis/src/Command/Redis/ZCARD.phpnu[PK\X]n"ƽpredis/src/Command/Redis/ZRANK.phpnu[PK\X]҈jj4 predis/src/Command/Redis/BloomFilter/BFLOADCHUNK.phpnu[PK\X]&T/predis/src/Command/Redis/BloomFilter/BFMADD.phpnu[PK\X]Mzz.predis/src/Command/Redis/BloomFilter/BFADD.phpnu[PK\X].nw2predis/src/Command/Redis/BloomFilter/BFRESERVE.phpnu[PK\X]R_43Vpredis/src/Command/Redis/BloomFilter/BFSCANDUMP.phpnu[PK\X],sEE2Tpredis/src/Command/Redis/BloomFilter/BFMEXISTS.phpnu[PK\X]cZEE/predis/src/Command/Redis/BloomFilter/BFINFO.phpnu[PK\X]wACC1predis/src/Command/Redis/BloomFilter/BFEXISTS.phpnu[PK\X]p}1Cpredis/src/Command/Redis/BloomFilter/BFINSERT.phpnu[PK\X]7t6)predis/src/Command/Redis/Container/Search/FTCURSOR.phpnu[PK\X]926fpredis/src/Command/Redis/Container/Search/FTCONFIG.phpnu[PK\X]9+EE5]predis/src/Command/Redis/Container/Json/JSONDEBUG.phpnu[PK\X]A[շ8predis/src/Command/Redis/Container/AbstractContainer.phpnu[PK\X]ЯYa a 7&predis/src/Command/Redis/Container/ContainerFactory.phpnu[PK\X]=lQmzz.predis/src/Command/Redis/Container/CLUSTER.phpnu[PK\X] dee8predis/src/Command/Redis/Container/FunctionContainer.phpnu[PK\X]cnjM9predis/src/Command/Redis/Container/ContainerInterface.phpnu[PK\X]u]n*predis/src/Command/Redis/Container/ACL.phpnu[PK\X],?dd" predis/src/Command/Redis/FCALL.phpnu[PK\X]G=+  $ predis/src/Command/Redis/OBJECT_.phpnu[PK\X]1 q%predis/src/Command/Redis/FLUSHALL.phpnu[PK\X]$tpredis/src/Command/Redis/PUBLISH.phpnu[PK\X]mm$predis/src/Command/Redis/RESTORE.phpnu[PK\X]/$8predis/src/Command/Redis/LINSERT.phpnu[PK\X]&|#predis/src/Command/Redis/SINTER.phpnu[PK\X]!predis/src/Command/Redis/SREM.phpnu[PK\X]S|XX$predis/src/Command/Redis/MIGRATE.phpnu[PK\X]\R'#predis/src/Command/Redis/HRANDFIELD.phpnu[PK\X] `&(predis/src/Command/Redis/FUNCTIONS.phpnu[PK\X]UU*-predis/src/Command/Redis/Json/JSONMSET.phpnu[PK\X]Te)x0predis/src/Command/Redis/Json/JSONDEL.phpnu[PK\X]e==,2predis/src/Command/Redis/Json/JSONOBJLEN.phpnu[PK\X]GH55,q5predis/src/Command/Redis/Json/JSONSTRLEN.phpnu[PK\X] ''EE*8predis/src/Command/Redis/Json/JSONRESP.phpnu[PK\X]R844,:predis/src/Command/Redis/Json/JSONARRLEN.phpnu[PK\X]\UU/1=predis/src/Command/Redis/Json/JSONARRAPPEND.phpnu[PK\X]KB!!*?predis/src/Command/Redis/Json/JSONTYPE.phpnu[PK\X]6x<<)`Bpredis/src/Command/Redis/Json/JSONGET.phpnu[PK\X]ɸBB+Gpredis/src/Command/Redis/Json/JSONCLEAR.phpnu[PK\X]OO)Jpredis/src/Command/Redis/Json/JSONSET.phpnu[PK\X]b*:Npredis/src/Command/Redis/Json/JSONMGET.phpnu[PK\X]q::,uQpredis/src/Command/Redis/Json/JSONARRPOP.phpnu[PK\X]qf**, Tpredis/src/Command/Redis/Json/JSONFORGET.phpnu[PK\X]!z77+Vpredis/src/Command/Redis/Json/JSONDEBUG.phpnu[PK\X] __/#Ypredis/src/Command/Redis/Json/JSONARRINSERT.phpnu[PK\X] VUU-[predis/src/Command/Redis/Json/JSONARRTRIM.phpnu[PK\X]v'',^predis/src/Command/Redis/Json/JSONTOGGLE.phpnu[PK\X]t3CC.apredis/src/Command/Redis/Json/JSONARRINDEX.phpnu[PK\X]}Q+cpredis/src/Command/Redis/Json/JSONMERGE.phpnu[PK\X]->>/fpredis/src/Command/Redis/Json/JSONNUMINCRBY.phpnu[PK\X] r["<<-?ipredis/src/Command/Redis/Json/JSONOBJKEYS.phpnu[PK\X]? >>/kpredis/src/Command/Redis/Json/JSONSTRAPPEND.phpnu[PK\X]T#unpredis/src/Command/Redis/GETDEL.phpnu[PK\X]vY"~ppredis/src/Command/Redis/TOUCH.phpnu[PK\X]8>X)spredis/src/Command/Redis/HINCRBYFLOAT.phpnu[PK\X]NY)&vpredis/src/Command/Redis/GEORADIUS.phpnu[PK\X]m&U~predis/src/Command/Redis/SISMEMBER.phpnu[PK\X]u)predis/src/Command/Redis/HPEXPIRETIME.phpnu[PK\X]B  #predis/src/Command/Redis/RPUSHX.phpnu[PK\X]y% predis/src/Command/Redis/ZREVRANK.phpnu[PK\X]=-!ppredis/src/Command/Redis/ZREM.phpnu[PK\X] Xx"predis/src/Command/Redis/HSCAN.phpnu[PK\X]B  #lpredis/src/Command/Redis/SUBSTR.phpnu[PK\X]]"ʕpredis/src/Command/Redis/SCARD.phpnu[PK\X]~ $predis/src/Command/Redis/LCS.phpnu[PK\X]3P(predis/src/Command/Redis/SRANDMEMBER.phpnu[PK\X]H<<(ypredis/src/Command/Redis/SUNIONSTORE.phpnu[PK\X]o," predis/src/Command/Redis/HMSET.phpnu[PK\X]%Apredis/src/Command/Redis/EXPIREAT.phpnu[PK\X]4&&#predis/src/Command/Redis/ZINTER.phpnu[PK\X]T**"predis/src/Command/Redis/ZDIFF.phpnu[PK\X] (predis/src/Command/Redis/UNSUBSCRIBE.phpnu[PK\X]pZ  #طpredis/src/Command/Redis/PSETEX.phpnu[PK\X]C'$6predis/src/Command/Redis/PFCOUNT.phpnu[PK\X]f\,, cpredis/src/Command/Redis/ACL.phpnu[PK\X]c6  #predis/src/Command/Redis/DECRBY.phpnu[PK\X]u](=predis/src/Command/Redis/ZINTERSTORE.phpnu[PK\X]b#predis/src/Command/Redis/BGSAVE.phpnu[PK\X]z$predis/src/Command/Redis/PERSIST.phpnu[PK\X]& %predis/src/Command/Redis/BITCOUNT.phpnu[PK\X]j++#predis/src/Command/Redis/BLMPOP.phpnu[PK\X]9]m$@predis/src/Command/Redis/GEODIST.phpnu[PK\X]?yw#predis/src/Command/Redis/BZMPOP.phpnu[PK\X]  #predis/src/Command/Redis/STRLEN.phpnu[PK\X] =  #predis/src/Command/Redis/ZCOUNT.phpnu[PK\X]yn  #<predis/src/Command/Redis/LPUSHX.phpnu[PK\X]!predis/src/Command/Redis/HGET.phpnu[PK\X]Џ}"predis/src/Command/Redis/RPUSH.phpnu[PK\X]wYCC"predis/src/Command/Redis/BLPOP.phpnu[PK\X]S"predis/src/Command/Redis/SETNX.phpnu[PK\X]  #predis/src/Command/Redis/LRANGE.phpnu[PK\X]/2!apredis/src/Command/Redis/XLEN.phpnu[PK\X]<1  #predis/src/Command/Redis/ZSCORE.phpnu[PK\X]d2  #predis/src/Command/Redis/SCRIPT.phpnu[PK\X]R'spredis/src/Command/Redis/HPEXPIREAT.phpnu[PK\X]m+c  #Vpredis/src/Command/Redis/GETSET.phpnu[PK\X]嘞"predis/src/Command/Redis/EVAL_.phpnu[PK\X]rSpMM"predis/src/Command/Redis/ZSCAN.phpnu[PK\X];%{ predis/src/Command/Redis/GETRANGE.phpnu[PK\X]v7! predis/src/Command/Redis/MGET.phpnu[PK\X]99' predis/src/Command/Redis/SDIFFSTORE.phpnu[PK\X]ǽPN! predis/src/Command/Redis/MSET.phpnu[PK\X]G  # predis/src/Command/Redis/SELECT.phpnu[PK\X] ( predis/src/Command/Redis/INCRBYFLOAT.phpnu[PK\X]9y##+ predis/src/Command/Redis/ZREMRANGEBYLEX.phpnu[PK\X]@ $ predis/src/Command/Redis/ZPOPMIN.phpnu[PK\X]ghh' predis/src/Command/Redis/EXPIRETIME.phpnu[PK\X]*Q>" predis/src/Command/Redis/PFADD.phpnu[PK\X]@G6uu? predis/src/Command/Argument/Search/SchemaFields/VectorField.phpnu[PK\X]A$ predis/src/Command/Argument/Search/SchemaFields/GeoShapeField.phpnu[PK\X]/q__< + predis/src/Command/Argument/Search/SchemaFields/TagField.phpnu[PK\X]K B0 predis/src/Command/Argument/Search/SchemaFields/FieldInterface.phpnu[PK\X]BJ\;;A+3 predis/src/Command/Argument/Search/SchemaFields/AbstractField.phpnu[PK\X]52N]]<: predis/src/Command/Argument/Search/SchemaFields/GeoField.phpnu[PK\X]`L=> predis/src/Command/Argument/Search/SchemaFields/TextField.phpnu[PK\X]4qee@E predis/src/Command/Argument/Search/SchemaFields/NumericField.phpnu[PK\X]6cc6I predis/src/Command/Argument/Search/SugGetArguments.phpnu[PK\X]/bb6M predis/src/Command/Argument/Search/CreateArguments.phpnu[PK\X]196N_ predis/src/Command/Argument/Search/CursorArguments.phpnu[PK\X]}W67c predis/src/Command/Argument/Search/CommonArguments.phpnu[PK\X]1F7ps predis/src/Command/Argument/Search/ProfileArguments.phpnu[PK\X]%"":xy predis/src/Command/Argument/Search/SpellcheckArguments.phpnu[PK\X]%$$4 predis/src/Command/Argument/Search/DropArguments.phpnu[PK\X]?aa9 predis/src/Command/Argument/Search/SynUpdateArguments.phpnu[PK\X] "]]5V predis/src/Command/Argument/Search/AlterArguments.phpnu[PK\X]Sy9 predis/src/Command/Argument/Search/AggregateArguments.phpnu[PK\X],|.!.!6F predis/src/Command/Argument/Search/SearchArguments.phpnu[PK\X]{ u6ڹ predis/src/Command/Argument/Search/SugAddArguments.phpnu[PK\X]__7N predis/src/Command/Argument/Search/ExplainArguments.phpnu[PK\X]l? __7 predis/src/Command/Argument/TimeSeries/GetArguments.phpnu[PK\X]Cbb:ڿ predis/src/Command/Argument/TimeSeries/CreateArguments.phpnu[PK\X]All: predis/src/Command/Argument/TimeSeries/MRangeArguments.phpnu[PK\X]K.:| predis/src/Command/Argument/TimeSeries/CommonArguments.phpnu[PK\X]+.<" predis/src/Configuration/Option/Exceptions.phpnu[PK\X]'ud˳,& predis/src/Configuration/OptionInterface.phpnu[PK\X]iz-** predis/src/Configuration/OptionsInterface.phpnu[PK\X]Q' $72 predis/src/Configuration/Options.phpnu[PK\X]S*D> predis/src/Response/Iterator/MultiBulk.phpnu[PK\X]u /zF predis/src/Response/Iterator/MultiBulkTuple.phpnu[PK\X]ތb 2O predis/src/Response/Iterator/MultiBulkIterator.phpnu[PK\X]򯁃'Y predis/src/Response/ServerException.phpnu[PK\X]@֟yy)] predis/src/Response/ResponseInterface.phpnu[PK\X]#Z~_ predis/src/Response/Status.phpnu[PK\X]SSqf predis/src/Response/Error.phpnu[PK\X]|B&k predis/src/Response/ErrorInterface.phpnu[PK\X]k/< < Pn predis/src/Session/Handler.phpnu[PK\X]LG(z predis/src/Replication/RoleException.phpnu[PK\X]@תV V .} predis/src/Replication/ReplicationStrategy.phpnu[PK\X]$1ҝ predis/src/Replication/MissingMasterException.phpnu[PK\X]Se´226 predis/src/Protocol/Text/Handler/MultiBulkResponse.phpnu[PK\X]C4 predis/src/Protocol/Text/Handler/IntegerResponse.phpnu[PK\X] 5/@ predis/src/Protocol/Text/Handler/StreamableMultiBulkResponse.phpnu[PK\X]^~1 predis/src/Protocol/Text/Handler/BulkResponse.phpnu[PK\X]iXX=ø predis/src/Protocol/Text/Handler/ResponseHandlerInterface.phpnu[PK\X]I=ۉ2 predis/src/Protocol/Text/Handler/ErrorResponse.phpnu[PK\X]@ MM3 predis/src/Protocol/Text/Handler/StatusResponse.phpnu[PK\X]&m + predis/src/Protocol/Text/ResponseReader.phpnu[PK\X] 00. predis/src/Protocol/Text/RequestSerializer.phpnu[PK\X] 7 predis/src/Protocol/Text/CompositeProtocolProcessor.phpnu[PK\X]Ml . predis/src/Protocol/Text/ProtocolProcessor.phpnu[PK\X]lrr2c predis/src/Protocol/RequestSerializerInterface.phpnu[PK\X]8)7 predis/src/Protocol/ProtocolException.phpnu[PK\X]hupp2o predis/src/Protocol/ProtocolProcessorInterface.phpnu[PK\X]œr3/A predis/src/Protocol/ResponseReaderInterface.phpnu[PK\X] Q M M  predis/src/Pipeline/Atomic.phpnu[PK\X]i & predis/src/Pipeline/Pipeline.phpnu[PK\X]Yt҂%b" predis/src/Pipeline/RelayPipeline.phpnu[PK\X],9+ predis/src/Pipeline/ConnectionErrorProof.phpnu[PK\X]<<  %9: predis/src/Pipeline/FireAndForget.phpnu[PK\X]ͶLtt#= predis/src/Pipeline/RelayAtomic.phpnu[PK\X]waE predis/src/Monitor/Consumer.phpnu[PK\X] X]I]I?V predis/src/Client.phpnu[PK\X]nendSdS% predis/src/ClientContextInterface.phpnu[PK\X]8~~" predis/src/ClientConfiguration.phpnu[PK\X]d2j predis/src/PredisException.phpnu[PK\X]xL predis/src/Autoloader.phpnu[PK\X]DG $m predis/src/NotSupportedException.phpnu[PK\X]Y]]% predis/src/CommunicationException.phpnu[PK\X]e< predis/src/ClientException.phpnu[PK\X]Rnn predis/src/ClientInterface.phpnu[PK\X]eB} predis/autoload.phpnu[PK\X]);OO~ predis/README.mdnu[PK\X]C"["" predis/composer.jsonnu[PK\X]j<|| predis/LICENSEnu[PK)_]aD/ " src/Transaction/MultiExecState.phpnu[PK)_]e ::- src/Transaction/AbortedMultiExecException.phpnu[PK)_]>|6|6 src/Transaction/MultiExec.phpnu[PK)_]Q#L src/Collection/Iterator/ListKey.phpnu[PK)_]uT  (2src/Collection/Iterator/SortedSetKey.phpnu[PK)_]lC$7src/Collection/Iterator/Keyspace.phpnu[PK)_]oc"<src/Collection/Iterator/SetKey.phpnu[PK)_]&t#r@src/Collection/Iterator/HashKey.phpnu[PK)_]- DD/Esrc/Collection/Iterator/CursorBasedIterator.phpnu[PK)_]577lXsrc/PubSub/AbstractConsumer.phpnu[PK)_]j~nsrc/PubSub/DispatcherLoop.phpnu[PK)_]U src/PubSub/RelayConsumer.phpnu[PK)_]k0src/PubSub/Consumer.phpnu[PK)_]c%!NN' src/Connection/Cluster/RedisCluster.phpnu[PK)_]+src/Connection/Cluster/ClusterInterface.phpnu[PK)_].ѹ(osrc/Connection/Cluster/PredisCluster.phpnu[PK)_]i tRtR2src/Connection/Replication/SentinelReplication.phpnu[PK)_]P(995VWsrc/Connection/Replication/MasterSlaveReplication.phpnu[PK)_]'o3Qsrc/Connection/Replication/ReplicationInterface.phpnu[PK)_]e-e-#src/Connection/StreamConnection.phpnu[PK)_]!88,]src/Connection/PhpiredisStreamConnection.phpnu[PK)_]0&src/Connection/ConnectionException.phpnu[PK)_]: :  src/Connection/RelayMethods.phpnu[PK)_]X:.:.,src/Connection/PhpiredisSocketConnection.phpnu[PK)_]fqЛ/,src/Connection/CompositeConnectionInterface.phpnu[PK)_]Akk#&$src/Connection/FactoryInterface.phpnu[PK)_]}"/$$#(src/Connection/WebdisConnection.phpnu[PK)_] j ,Msrc/Connection/CompositeStreamConnection.phpnu[PK)_]Ysrc/Connection/Factory.phpnu[PK)_]͑N""*psrc/Connection/NodeConnectionInterface.phpnu[PK)_]Qr#&usrc/Connection/ConnectionInterface.phpnu[PK)_]_($$"{src/Connection/RelayConnection.phpnu[PK)_]wD9osrc/Connection/Parameters.phpnu[PK)_]m %src/Connection/AbstractConnection.phpnu[PK)_]G.$$/src/Connection/AggregateConnectionInterface.phpnu[PK)_]AMZ Z &csrc/Connection/ParametersInterface.phpnu[PK)_]kig g src/Cluster/Hash/CRC16.phpnu[PK)_]nx#src/Cluster/Hash/PhpiredisCRC16.phpnu[PK)_]fʌ+src/Cluster/Hash/HashGeneratorInterface.phpnu[PK)_]Vǡ$src/Cluster/Distributor/HashRing.phpnu[PK)_];$$0src/Cluster/Distributor/DistributorInterface.phpnu[PK)_]Aee&8src/Cluster/Distributor/KetamaRing.phpnu[PK)_].src/Cluster/Distributor/EmptyRingException.phpnu[PK)_]gsrc/Cluster/PredisStrategy.phpnu[PK)_]/^ = =src/Cluster/ClusterStrategy.phpnu[PK)_])=  0]src/Cluster/SlotMap.phpnu[PK)_]/jpsrc/Cluster/RedisStrategy.phpnu[PK)_].-  !usrc/Cluster/StrategyInterface.phpnu[PK)_]U+B@{src/Command/Strategy/ContainerCommands/Functions/FlushStrategy.phpnu[PK)_] ]A~src/Command/Strategy/ContainerCommands/Functions/ListStrategy.phpnu[PK)_]>gDDB҂src/Command/Strategy/ContainerCommands/Functions/StatsStrategy.phpnu[PK)_]¸'!!Dsrc/Command/Strategy/ContainerCommands/Functions/RestoreStrategy.phpnu[PK)_]xAsrc/Command/Strategy/ContainerCommands/Functions/LoadStrategy.phpnu[PK)_]CCAqsrc/Command/Strategy/ContainerCommands/Functions/DumpStrategy.phpnu[PK)_]CCA%src/Command/Strategy/ContainerCommands/Functions/KillStrategy.phpnu[PK)_]a EECْsrc/Command/Strategy/ContainerCommands/Functions/DeleteStrategy.phpnu[PK)_]X  4src/Command/Strategy/SubcommandStrategyInterface.phpnu[PK)_]/*2src/Command/Strategy/StrategyResolverInterface.phpnu[PK)_]j 3src/Command/Strategy/SubcommandStrategyResolver.phpnu[PK)_]TF"*src/Command/Traits/To/ServerTo.phpnu[PK)_]g66#\src/Command/Traits/From/GeoFrom.phpnu[PK)_].C+src/Command/Traits/Expire/ExpireOptions.phpnu[PK)_]X(Яsrc/Command/Traits/Limit/LimitObject.phpnu[PK)_]"%src/Command/Traits/Limit/Limit.phpnu[PK)_]=7src/Command/Traits/Get/Get.phpnu[PK)_]:@X$src/Command/Traits/With/WithDist.phpnu[PK)_]r!%src/Command/Traits/With/WithCoord.phpnu[PK)_]ޝz&(src/Command/Traits/With/WithValues.phpnu[PK)_]a$$Csrc/Command/Traits/With/WithHash.phpnu[PK)_]*܅&ssrc/Command/Traits/With/WithScores.phpnu[PK)_]T(Nsrc/Command/Traits/Json/NxXxArgument.phpnu[PK)_]EgDȰ!Psrc/Command/Traits/Json/Space.phpnu[PK)_]p!#Qsrc/Command/Traits/Json/Newline.phpnu[PK)_]/5"jsrc/Command/Traits/Json/Indent.phpnu[PK)_] $$wsrc/Command/Traits/By/GeoBy.phpnu[PK)_]99&src/Command/Traits/By/ByLexByScore.phpnu[PK)_]Pq44$ysrc/Command/Traits/By/ByArgument.phpnu[PK)_]OO.src/Command/Traits/BloomFilters/BucketSize.phpnu[PK)_]BFT  - src/Command/Traits/BloomFilters/Expansion.phpnu[PK)_]Xss1src/Command/Traits/BloomFilters/MaxIterations.phpnu[PK)_];)src/Command/Traits/BloomFilters/Error.phpnu[PK)_]TJWW)Vsrc/Command/Traits/BloomFilters/Items.phpnu[PK)_]4,"src/Command/Traits/BloomFilters/NoCreate.phpnu[PK)_] 66,|'src/Command/Traits/BloomFilters/Capacity.phpnu[PK)_]t.src/Command/Traits/Sorting.phpnu[PK)_]  %y4src/Command/Traits/MinMaxModifier.phpnu[PK)_]ٕQQ8src/Command/Traits/BitByte.phpnu[PK)_]Rꌿw<src/Command/Traits/Count.phpnu[PK)_]< Dsrc/Command/Traits/Storedist.phpnu[PK)_]f55Isrc/Command/Traits/Rev.phpnu[PK)_]t8fNsrc/Command/Traits/DB.phpnu[PK)_]]iVllQTsrc/Command/Traits/Keys.phpnu[PK)_]}]Zsrc/Command/Traits/Replace.phpnu[PK)_]%]src/Command/Traits/Weights.phpnu[PK)_]3QQ Qcsrc/Command/Traits/LeftRight.phpnu[PK)_]|  isrc/Command/Traits/Aggregate.phpnu[PK)_]|vqsrc/Command/Traits/Timeout.phpnu[PK)_]h WW9src/Command/Redis/GET.phpnu[PK)_]asrc/Command/Redis/TTL.phpnu[PK)_]_))&src/Command/Redis/ZREMRANGEBYSCORE.phpnu[PK)_]p  Nsrc/Command/Redis/HSETNX.phpnu[PK)_]gN,\\src/Command/Redis/SHUTDOWN.phpnu[PK)_] x$Osrc/Command/Redis/ZREVRANGEBYLEX.phpnu[PK)_]h*src/Command/Redis/DEL.phpnu[PK)_][src/Command/Redis/KEYS.phpnu[PK)_]ssrc/Command/Redis/LSET.phpnu[PK)_]@ :XXLsrc/Command/Redis/XTRIM.phpnu[PK)_]src/Command/Redis/EXPIRE.phpnu[PK)_]ȝ!Jsrc/Command/Redis/ZRANGESTORE.phpnu[PK)_],Un::8src/Command/Redis/HEXPIRE.phpnu[PK)_]Jsrc/Command/Redis/QUIT.phpnu[PK)_]ysrc/Command/Redis/SETRANGE.phpnu[PK)_]msrc/Command/Redis/FLUSHDB.phpnu[PK)_]OpKsrc/Command/Redis/BLMOVE.phpnu[PK)_]u'src/Command/Redis/HPTTL.phpnu[PK)_]nbD`src/Command/Redis/HMGET.phpnu[PK)_]KK'}!src/Command/Redis/TimeSeries/TSINFO.phpnu[PK)_]xxWW&%src/Command/Redis/TimeSeries/TSGET.phpnu[PK)_]7>>-(src/Command/Redis/TimeSeries/TSQUERYINDEX.phpnu[PK)_]7p;;&g+src/Command/Redis/TimeSeries/TSDEL.phpnu[PK)_]M&(tt(-src/Command/Redis/TimeSeries/TSALTER.phpnu[PK)_]j]''-1src/Command/Redis/TimeSeries/TSDELETERULE.phpnu[PK)_]JT**'H4src/Command/Redis/TimeSeries/TSMADD.phpnu[PK)_]ƣT'$$,6src/Command/Redis/TimeSeries/TSMREVRANGE.phpnu[PK)_]Ag-I9src/Command/Redis/TimeSeries/TSCREATERULE.phpnu[PK)_]gyy(S=src/Command/Redis/TimeSeries/TSRANGE.phpnu[PK)_]` )$Asrc/Command/Redis/TimeSeries/TSINCRBY.phpnu[PK)_]>)uEsrc/Command/Redis/TimeSeries/TSDECRBY.phpnu[PK)_]]]&Isrc/Command/Redis/TimeSeries/TSADD.phpnu[PK)_]nY66)zMsrc/Command/Redis/TimeSeries/TSCREATE.phpnu[PK)_]wzsrc/Command/Redis/SSCAN.phpnu[PK)_]rsrc/Command/Redis/DUMP.phpnu[PK)_]Dhhcsrc/Command/Redis/ZADD.phpnu[PK)_]D!src/Command/Redis/ZUNIONSTORE.phpnu[PK)_]tsrc/Command/Redis/BITOP.phpnu[PK)_]"W&&%Αsrc/Command/Redis/ZREMRANGEBYRANK.phpnu[PK)_]mIIsrc/Command/Redis/HDEL.phpnu[PK)_]uillbsrc/Command/Redis/BZPOPMIN.phpnu[PK)_]zsrc/Command/Redis/SADD.phpnu[PK)_]ɲ5src/Command/Redis/RANDOMKEY.phpnu[PK)_]͉`src/Command/Redis/LPOP.phpnu[PK)_]V͔nsrc/Command/Redis/HKEYS.phpnu[PK)_]8esrc/Command/Redis/SUBSCRIBE.phpnu[PK)_]) ;src/Command/Redis/SLOWLOG.phpnu[PK)_];2\\9src/Command/Redis/HGETALL.phpnu[PK)_] )/  src/Command/Redis/WATCH.phpnu[PK)_](u 6src/Command/Redis/PSUBSCRIBE.phpnu[PK)_]3͹hsrc/Command/Redis/WAITAOF.phpnu[PK)_]Jnsrc/Command/Redis/XRANGE.phpnu[PK)_]y<ysrc/Command/Redis/HTTL.phpnu[PK)_]"#src/Command/Redis/XDEL.phpnu[PK)_]X5" " src/Command/Redis/INFO.phpnu[PK)_]t7 src/Command/Redis/EVAL_RO.phpnu[PK)_]Cdd.src/Command/Redis/CountMinSketch/CMSINCRBY.phpnu[PK)_] c{_XX2src/Command/Redis/CountMinSketch/CMSINITBYPROB.phpnu[PK)_]:]%QQ1src/Command/Redis/CountMinSketch/CMSINITBYDIM.phpnu[PK)_]M!,@src/Command/Redis/CountMinSketch/CMSINFO.phpnu[PK)_]! 44-Zsrc/Command/Redis/CountMinSketch/CMSMERGE.phpnu[PK)_]6ũ::-src/Command/Redis/CountMinSketch/CMSQUERY.phpnu[PK)_]1]src/Command/Redis/ZLEXCOUNT.phpnu[PK)_]  src/Command/Redis/APPEND.phpnu[PK)_]՜<src/Command/Redis/XREAD.phpnu[PK)_]&,8&&#src/Command/Redis/ZUNION.phpnu[PK)_]src/Command/Redis/LMOVE.phpnu[PK)_] Lsrc/Command/Redis/DECR.phpnu[PK)_]/α src/Command/Redis/ZDIFFSTORE.phpnu[PK)_].ѡsrc/Command/Redis/LREM.phpnu[PK)_]5X3src/Command/Redis/HLEN.phpnu[PK)_]+9src/Command/Redis/PING.phpnu[PK)_]`(oxsrc/Command/Redis/SAVE.phpnu[PK)_]Y src/Command/Redis/CLIENT.phpnu[PK)_]R<< src/Command/Redis/SMISMEMBER.phpnu[PK)_]m|src/Command/Redis/SMOVE.phpnu[PK)_]Xsrc/Command/Redis/LPUSH.phpnu[PK)_]݃H src/Command/Redis/MONITOR.phpnu[PK)_]Ssrc/Command/Redis/COPY.phpnu[PK)_]~b3 |src/Command/Redis/LASTSAVE.phpnu[PK)_]cb'- src/Command/Redis/PTTL.phpnu[PK)_]*#src/Command/Redis/BITPOS.phpnu[PK)_]-W8saa%src/Command/Redis/SET.phpnu[PK)_]-K)src/Command/Redis/ZPOPMAX.phpnu[PK)_]əNKK-src/Command/Redis/CONFIG.phpnu[PK)_]2src/Command/Redis/EVALSHA.phpnu[PK)_]'v  5src/Command/Redis/RENAME.phpnu[PK)_]'E"]7src/Command/Redis/TopK/TOPKADD.phpnu[PK)_]_kk#:src/Command/Redis/TopK/TOPKINFO.phpnu[PK)_]zI%`>src/Command/Redis/TopK/TOPKINCRBY.phpnu[PK)_]ju#xAsrc/Command/Redis/TopK/TOPKLIST.phpnu[PK)_]k9VV$Gsrc/Command/Redis/TopK/TOPKQUERY.phpnu[PK)_]ͮ&Jsrc/Command/Redis/TopK/TOPKRESERVE.phpnu[PK)_]COsrc/Command/Redis/ZREVRANGE.phpnu[PK)_]ar6Qsrc/Command/Redis/HSET.phpnu[PK)_]l"Ssrc/Command/Redis/PUNSUBSCRIBE.phpnu[PK)_]cVsrc/Command/Redis/UNWATCH.phpnu[PK)_]gW!/Ysrc/Command/Redis/SUNION.phpnu[PK)_]b,0#<\src/Command/Redis/ZRANGEBYSCORE.phpnu[PK)_]2sbsrc/Command/Redis/PEXPIREAT.phpnu[PK)_]Jgg!dsrc/Command/Redis/ZRANGEBYLEX.phpnu[PK)_]q q  isrc/Command/Redis/INCRBY.phpnu[PK)_]̼mmksrc/Command/Redis/BZPOPMAX.phpnu[PK)_] %iiosrc/Command/Redis/GEOADD.phpnu[PK)_]?1Ussrc/Command/Redis/HEXPIREAT.phpnu[PK)_]sI.usrc/Command/Redis/ZMSCORE.phpnu[PK)_]J~qbFxsrc/Command/Redis/SLAVEOF.phpnu[PK)_]O&/"{src/Command/Redis/BGREWRITEAOF.phpnu[PK)_]MoCC~src/Command/Redis/BRPOP.phpnu[PK)_]d Isrc/Command/Redis/SINTERCARD.phpnu[PK)_] >src/Command/Redis/ZMPOP.phpnu[PK)_]#&>!,src/Command/Redis/PEXPIRETIME.phpnu[PK)_]l]]src/Command/Redis/HVALS.phpnu[PK)_]4/Xsrc/Command/Redis/AbstractCommand/BZPOPBase.phpnu[PK)_]5'Rsrc/Command/Redis/INCR.phpnu[PK)_]Usrc/Command/Redis/CLUSTER.phpnu[PK)_]Dޛsrc/Command/Redis/SMEMBERS.phpnu[PK)_]g^i=src/Command/Redis/COMMAND.phpnu[PK)_] fLLvsrc/Command/Redis/FAILOVER.phpnu[PK)_]ԫUbsrc/Command/Redis/ZINCRBY.phpnu[PK)_]އ_ksrc/Command/Redis/PUBSUB.phpnu[PK)_]&src/Command/Redis/HPEXPIRE.phpnu[PK)_]<^src/Command/Redis/SDIFF.phpnu[PK)_]_k|src/Command/Redis/ECHO_.phpnu[PK)_]o-LL*ʹsrc/Command/Redis/TDigest/TDIGESTRESET.phpnu[PK)_]>b(ssrc/Command/Redis/TDigest/TDIGESTMAX.phpnu[PK)_]b~  -ɻsrc/Command/Redis/TDigest/TDIGESTQUANTILE.phpnu[PK)_]9qnn)3src/Command/Redis/TDigest/TDIGESTINFO.phpnu[PK)_]},src/Command/Redis/TDigest/TDIGESTREVRANK.phpnu[PK)_]0@+Msrc/Command/Redis/TDigest/TDIGESTBYRANK.phpnu[PK)_]^(src/Command/Redis/TDigest/TDIGESTMIN.phpnu[PK)_]kl88(src/Command/Redis/TDigest/TDIGESTADD.phpnu[PK)_]]n8)hsrc/Command/Redis/TDigest/TDIGESTRANK.phpnu[PK)_]3 A+src/Command/Redis/TDigest/TDIGESTCREATE.phpnu[PK)_].src/Command/Redis/TDigest/TDIGESTBYREVRANK.phpnu[PK)_]뻀}}*src/Command/Redis/TDigest/TDIGESTMERGE.phpnu[PK)_]q,,(src/Command/Redis/TDigest/TDIGESTCDF.phpnu[PK)_]~ˑ1__1Qsrc/Command/Redis/TDigest/TDIGESTTRIMMED_MEAN.phpnu[PK)_]6)csrc/Command/Redis/SENTINEL.phpnu[PK)_]ь=src/Command/Redis/HINCRBY.phpnu[PK)_]$src/Command/Redis/GEOSEARCHSTORE.phpnu[PK)_]K@$  src/Command/Redis/LINDEX.phpnu[PK)_](src/Command/Redis/TYPE.phpnu[PK)_] l7lsrc/Command/Redis/FCALL_RO.phpnu[PK)_]e src/Command/Redis/MOVE.phpnu[PK)_]] src/Command/Redis/HEXISTS.phpnu[PK)_]lj__ Ksrc/Command/Redis/ZINTERCARD.phpnu[PK)_]a~src/Command/Redis/XADD.phpnu[PK)_]P P src/Command/Redis/GEOSEARCH.phpnu[PK)_]I  |'src/Command/Redis/DBSIZE.phpnu[PK)_]ǘ)src/Command/Redis/RPOP.phpnu[PK)_]-",src/Command/Redis/RENAMENX.phpnu[PK)_]ܳ.src/Command/Redis/SETEX.phpnu[PK)_]s/e0src/Command/Redis/HPERSIST.phpnu[PK)_]73src/Command/Redis/MSETNX.phpnu[PK)_]**6src/Command/Redis/GETEX.phpnu[PK)_]<src/Command/Redis/RPOPLPUSH.phpnu[PK)_]>src/Command/Redis/HSTRLEN.phpnu[PK)_]-D[[!CAsrc/Command/Redis/ZRANDMEMBER.phpnu[PK)_]ɊDsrc/Command/Redis/XREVRANGE.phpnu[PK)_]F~@Gsrc/Command/Redis/SPOP.phpnu[PK)_],cnIsrc/Command/Redis/AUTH.phpnu[PK)_]-Ksrc/Command/Redis/CuckooFilter/CFSCANDUMP.phpnu[PK)_]:FF*Nsrc/Command/Redis/CuckooFilter/CFADDNX.phpnu[PK)_]9;(XQsrc/Command/Redis/CuckooFilter/CFDEL.phpnu[PK)_]zYY-XTsrc/Command/Redis/CuckooFilter/CFINSERTNX.phpnu[PK)_]-%src/Command/Redis/Json/JSONDEBUG.phpnu[PK)_] __('src/Command/Redis/Json/JSONARRINSERT.phpnu[PK)_] VUU&*src/Command/Redis/Json/JSONARRTRIM.phpnu[PK)_]v''%+-src/Command/Redis/Json/JSONTOGGLE.phpnu[PK)_]t3CC'/src/Command/Redis/Json/JSONARRINDEX.phpnu[PK)_]}Q$A2src/Command/Redis/Json/JSONMERGE.phpnu[PK)_]->>(%5src/Command/Redis/Json/JSONNUMINCRBY.phpnu[PK)_] r["<<&7src/Command/Redis/Json/JSONOBJKEYS.phpnu[PK)_]? >>(M:src/Command/Redis/Json/JSONSTRAPPEND.phpnu[PK)_]T<src/Command/Redis/GETDEL.phpnu[PK)_]vY>src/Command/Redis/TOUCH.phpnu[PK)_]8>X"Bsrc/Command/Redis/HINCRBYFLOAT.phpnu[PK)_]NY)rDsrc/Command/Redis/GEORADIUS.phpnu[PK)_]mLsrc/Command/Redis/SISMEMBER.phpnu[PK)_]u" Osrc/Command/Redis/HPEXPIRETIME.phpnu[PK)_]B  Psrc/Command/Redis/RPUSHX.phpnu[PK)_]yGSsrc/Command/Redis/ZREVRANK.phpnu[PK)_]=-Usrc/Command/Redis/ZREM.phpnu[PK)_] XxXsrc/Command/Redis/HSCAN.phpnu[PK)_]B  asrc/Command/Redis/SUBSTR.phpnu[PK)_]]csrc/Command/Redis/SCARD.phpnu[PK)_]~>fsrc/Command/Redis/LCS.phpnu[PK)_]3P!msrc/Command/Redis/SRANDMEMBER.phpnu[PK)_]H<<!osrc/Command/Redis/SUNIONSTORE.phpnu[PK)_]o,ssrc/Command/Redis/HMSET.phpnu[PK)_]?wsrc/Command/Redis/EXPIREAT.phpnu[PK)_]4&&zsrc/Command/Redis/ZINTER.phpnu[PK)_]T**~src/Command/Redis/ZDIFF.phpnu[PK)_] !src/Command/Redis/UNSUBSCRIBE.phpnu[PK)_]pZ  src/Command/Redis/PSETEX.phpnu[PK)_]C'src/Command/Redis/PFCOUNT.phpnu[PK)_]f\,,7src/Command/Redis/ACL.phpnu[PK)_]c6  src/Command/Redis/DECRBY.phpnu[PK)_]u]!src/Command/Redis/ZINTERSTORE.phpnu[PK)_]b@src/Command/Redis/BGSAVE.phpnu[PK)_]z7src/Command/Redis/PERSIST.phpnu[PK)_]& src/Command/Redis/BITCOUNT.phpnu[PK)_]j++lsrc/Command/Redis/BLMPOP.phpnu[PK)_]9]msrc/Command/Redis/GEODIST.phpnu[PK)_]?yw>src/Command/Redis/BZMPOP.phpnu[PK)_]  src/Command/Redis/STRLEN.phpnu[PK)_] =  lsrc/Command/Redis/ZCOUNT.phpnu[PK)_]yn  èsrc/Command/Redis/LPUSHX.phpnu[PK)_]src/Command/Redis/HGET.phpnu[PK)_]Џ}isrc/Command/Redis/RPUSH.phpnu[PK)_]wYCCsrc/Command/Redis/BLPOP.phpnu[PK)_]Ssrc/Command/Redis/SETNX.phpnu[PK)_]  gsrc/Command/Redis/LRANGE.phpnu[PK)_]/2src/Command/Redis/XLEN.phpnu[PK)_]<1   src/Command/Redis/ZSCORE.phpnu[PK)_]d2  dsrc/Command/Redis/SCRIPT.phpnu[PK)_]R src/Command/Redis/HPEXPIREAT.phpnu[PK)_]m+c  src/Command/Redis/GETSET.phpnu[PK)_]嘞src/Command/Redis/EVAL_.phpnu[PK)_]rSpMMsrc/Command/Redis/ZSCAN.phpnu[PK)_];src/Command/Redis/GETRANGE.phpnu[PK)_]v7src/Command/Redis/MGET.phpnu[PK)_]99  src/Command/Redis/SDIFFSTORE.phpnu[PK)_]ǽPNsrc/Command/Redis/MSET.phpnu[PK)_]G  src/Command/Redis/SELECT.phpnu[PK)_] !src/Command/Redis/INCRBYFLOAT.phpnu[PK)_]9y##$src/Command/Redis/ZREMRANGEBYLEX.phpnu[PK)_]@ src/Command/Redis/ZPOPMIN.phpnu[PK)_]ghh src/Command/Redis/EXPIRETIME.phpnu[PK)_]*Q>src/Command/Redis/PFADD.phpnu[PK)_]@G6uu8src/Command/Argument/Search/SchemaFields/VectorField.phpnu[PK)_]:src/Command/Argument/Search/SchemaFields/GeoShapeField.phpnu[PK)_]/q__5src/Command/Argument/Search/SchemaFields/TagField.phpnu[PK)_]K ;src/Command/Argument/Search/SchemaFields/FieldInterface.phpnu[PK)_]BJ\;;:src/Command/Argument/Search/SchemaFields/AbstractField.phpnu[PK)_]52N]]5src/Command/Argument/Search/SchemaFields/GeoField.phpnu[PK)_]`L6\ src/Command/Argument/Search/SchemaFields/TextField.phpnu[PK)_]4qee9src/Command/Argument/Search/SchemaFields/NumericField.phpnu[PK)_]6cc/ksrc/Command/Argument/Search/SugGetArguments.phpnu[PK)_]/bb/-src/Command/Argument/Search/CreateArguments.phpnu[PK)_]19/+src/Command/Argument/Search/CursorArguments.phpnu[PK)_]}W//src/Command/Argument/Search/CommonArguments.phpnu[PK)_]1F0@src/Command/Argument/Search/ProfileArguments.phpnu[PK)_]%""3Fsrc/Command/Argument/Search/SpellcheckArguments.phpnu[PK)_]%$$-Lsrc/Command/Argument/Search/DropArguments.phpnu[PK)_]?aa2 Psrc/Command/Argument/Search/SynUpdateArguments.phpnu[PK)_] "]].Qsrc/Command/Argument/Search/AlterArguments.phpnu[PK)_]Sy2Ssrc/Command/Argument/Search/AggregateArguments.phpnu[PK)_],|.!.!/dsrc/Command/Argument/Search/SearchArguments.phpnu[PK)_]{ u/;src/Command/Argument/Search/SugAddArguments.phpnu[PK)_]__0src/Command/Argument/Search/ExplainArguments.phpnu[PK)_]l? __0gsrc/Command/Argument/TimeSeries/GetArguments.phpnu[PK)_]Cbb3&src/Command/Argument/TimeSeries/CreateArguments.phpnu[PK)_]All3src/Command/Argument/TimeSeries/MRangeArguments.phpnu[PK)_]K.3src/Command/Argument/TimeSeries/CommonArguments.phpnu[PK)_]src/Command/ScriptCommand.phpnu[PK)_]Cz?XX*sHsrc/Command/PrefixableCommandInterface.phpnu[PK)_]NN %Ksrc/Command/FactoryInterface.phpnu[PK)_]Ƹò22Osrc/Command/Factory.phpnu[PK)_]i  <`src/Command/Command.phpnu[PK)_]ٞ)) jsrc/Command/CommandInterface.phpnu[PK)_]mb b rsrc/Command/RawCommand.phpnu[PK)_])@ @ |src/Command/RedisFactory.phpnu[PK)_]3 +'psrc/Configuration/Option/Exceptions.phpnu[PK)_]'ud˳%Hsrc/Configuration/OptionInterface.phpnu[PK)_]iz&Psrc/Configuration/OptionsInterface.phpnu[PK)_]Q' Vsrc/Configuration/Options.phpnu[PK)_]S#\ src/Response/Iterator/MultiBulk.phpnu[PK)_]u (src/Response/Iterator/MultiBulkTuple.phpnu[PK)_]ތb +src/Response/Iterator/MultiBulkIterator.phpnu[PK)_]򯁃 $src/Response/ServerException.phpnu[PK)_]@֟yy"(src/Response/ResponseInterface.phpnu[PK)_]#Zs*src/Response/Status.phpnu[PK)_]SS_1src/Response/Error.phpnu[PK)_]|B5src/Response/ErrorInterface.phpnu[PK)_]k/< < 09src/Session/Handler.phpnu[PK)_]LG!Esrc/Replication/RoleException.phpnu[PK)_]@תV V 'Gsrc/Replication/ReplicationStrategy.phpnu[PK)_]$*hsrc/Replication/MissingMasterException.phpnu[PK)_]Se´22/jsrc/Protocol/Text/Handler/MultiBulkResponse.phpnu[PK)_]C-Xrsrc/Protocol/Text/Handler/IntegerResponse.phpnu[PK)_] 5/9gwsrc/Protocol/Text/Handler/StreamableMultiBulkResponse.phpnu[PK)_]^~*Z}src/Protocol/Text/Handler/BulkResponse.phpnu[PK)_]iXX6ksrc/Protocol/Text/Handler/ResponseHandlerInterface.phpnu[PK)_]I=ۉ+)src/Protocol/Text/Handler/ErrorResponse.phpnu[PK)_]@ MM,src/Protocol/Text/Handler/StatusResponse.phpnu[PK)_]&m $Lsrc/Protocol/Text/ResponseReader.phpnu[PK)_] 00'src/Protocol/Text/RequestSerializer.phpnu[PK)_] 02src/Protocol/Text/CompositeProtocolProcessor.phpnu[PK)_]Ml 'src/Protocol/Text/ProtocolProcessor.phpnu[PK)_]lrr+ڷsrc/Protocol/RequestSerializerInterface.phpnu[PK)_]8"src/Protocol/ProtocolException.phpnu[PK)_]hupp+ؼsrc/Protocol/ProtocolProcessorInterface.phpnu[PK)_]œr3(src/Protocol/ResponseReaderInterface.phpnu[PK)_] Q M M src/Pipeline/Atomic.phpnu[PK)_]izsrc/Pipeline/Pipeline.phpnu[PK)_]Yt҂src/Pipeline/RelayPipeline.phpnu[PK)_]%src/Pipeline/ConnectionErrorProof.phpnu[PK)_]<<  xsrc/Pipeline/FireAndForget.phpnu[PK)_]ͶLttsrc/Pipeline/RelayAtomic.phpnu[PK)_]wsrc/Monitor/Consumer.phpnu[PK)_] X]I]Ii src/Client.phpnu[PK)_]nendSdSjsrc/ClientContextInterface.phpnu[PK)_]8~~src/ClientConfiguration.phpnu[PK)_]d2src/PredisException.phpnu[PK)_]xZsrc/Autoloader.phpnu[PK)_]DG tsrc/NotSupportedException.phpnu[PK)_]Y]]src/CommunicationException.phpnu[PK)_]e5src/ClientException.phpnu[PK)_]Rnnsrc/ClientInterface.phpnu[PK)_]e -Gautoload.phpnu[PK)_]);OO mHREADME.mdnu[PK)_]C"["" zcomposer.jsonnu[PK)_]j<||ٝLICENSEnu[PKDDʶ