Total Complexity | 48 |
Total Lines | 563 |
Duplicated Lines | 0 % |
Changes | 0 |
Complex classes like Connection often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.
Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.
While breaking up the class, it is a good idea to analyze how other classes use Connection, and based on these observations, apply Extract Interface, too.
1 | <?php |
||
251 | class Connection |
||
252 | { |
||
253 | /** |
||
254 | * @var string the hostname or ip address to use for connecting to the redis server. Defaults to 'localhost'. |
||
255 | * If [[unixSocket]] is specified, hostname and [[port]] will be ignored. |
||
256 | */ |
||
257 | public $hostname = 'localhost'; |
||
258 | /** |
||
259 | * @var integer the port to use for connecting to the redis server. Default port is 6379. |
||
260 | * If [[unixSocket]] is specified, [[hostname]] and port will be ignored. |
||
261 | */ |
||
262 | public $port = 6379; |
||
263 | /** |
||
264 | * @var string the unix socket path (e.g. `/var/run/redis/redis.sock`) to use for connecting to the redis server. |
||
265 | * This can be used instead of [[hostname]] and [[port]] to connect to the server using a unix socket. |
||
266 | * If a unix socket path is specified, [[hostname]] and [[port]] will be ignored. |
||
267 | */ |
||
268 | public $unixSocket; |
||
269 | /** |
||
270 | * @var string the password for establishing DB connection. Defaults to null meaning no AUTH command is sent. |
||
271 | * See http://redis.io/commands/auth |
||
272 | */ |
||
273 | public $password; |
||
274 | /** |
||
275 | * @var integer the redis database to use. This is an integer value starting from 0. Defaults to 0. |
||
276 | */ |
||
277 | public $database = 0; |
||
278 | /** |
||
279 | * @var float timeout to use for connection to redis. If not set the timeout set in php.ini will be used: `ini_get("default_socket_timeout")`. |
||
280 | */ |
||
281 | public $connectionTimeout = null; |
||
282 | /** |
||
283 | * @var float timeout to use for redis socket when reading and writing data. If not set the php default value will be used. |
||
284 | */ |
||
285 | public $dataTimeout = null; |
||
286 | /** |
||
287 | * @var integer Bitmask field which may be set to any combination of connection flags passed to [stream_socket_client()](http://php.net/manual/en/function.stream-socket-client.php). |
||
288 | * Currently the select of connection flags is limited to `STREAM_CLIENT_CONNECT` (default), `STREAM_CLIENT_ASYNC_CONNECT` and `STREAM_CLIENT_PERSISTENT`. |
||
289 | * |
||
290 | * > Warning: `STREAM_CLIENT_PERSISTENT` will make PHP reuse connections to the same server. If you are using multiple |
||
291 | * > connection objects to refer to different redis [[$database|databases]] on the same [[port]], redis commands may |
||
292 | * > get executed on the wrong database. `STREAM_CLIENT_PERSISTENT` is only safe to use if you use only one database. |
||
293 | * > |
||
294 | * > You may still use persistent connections in this case when disambiguating ports as described |
||
295 | * > in [a comment on the PHP manual](http://php.net/manual/en/function.stream-socket-client.php#105393) |
||
296 | * > e.g. on the connection used for session storage, specify the port as: |
||
297 | * > |
||
298 | * > ```php |
||
299 | * > 'port' => '6379/session' |
||
300 | * > ``` |
||
301 | * |
||
302 | * @see http://php.net/manual/en/function.stream-socket-client.php |
||
303 | */ |
||
304 | public $socketClientFlags = STREAM_CLIENT_CONNECT; |
||
305 | /** |
||
306 | * @var integer The number of times a command execution should be retried when a connection failure occurs. |
||
307 | * This is used in [[executeCommand()]] when a [[SocketException]] is thrown. |
||
308 | * Defaults to 0 meaning no retries on failure. |
||
309 | */ |
||
310 | public $retries = 0; |
||
311 | |||
312 | /** |
||
313 | * @var array List of available redis commands. |
||
314 | * @see http://redis.io/commands |
||
315 | */ |
||
316 | public $redisCommands = [ |
||
317 | 'APPEND', // Append a value to a key |
||
318 | 'AUTH', // Authenticate to the server |
||
319 | 'BGREWRITEAOF', // Asynchronously rewrite the append-only file |
||
320 | 'BGSAVE', // Asynchronously save the dataset to disk |
||
321 | 'BITCOUNT', // Count set bits in a string |
||
322 | 'BITFIELD', // Perform arbitrary bitfield integer operations on strings |
||
323 | 'BITOP', // Perform bitwise operations between strings |
||
324 | 'BITPOS', // Find first bit set or clear in a string |
||
325 | 'BLPOP', // Remove and get the first element in a list, or block until one is available |
||
326 | 'BRPOP', // Remove and get the last element in a list, or block until one is available |
||
327 | 'BRPOPLPUSH', // Pop a value from a list, push it to another list and return it; or block until one is available |
||
328 | 'CLIENT KILL', // Kill the connection of a client |
||
329 | 'CLIENT LIST', // Get the list of client connections |
||
330 | 'CLIENT GETNAME', // Get the current connection name |
||
331 | 'CLIENT PAUSE', // Stop processing commands from clients for some time |
||
332 | 'CLIENT REPLY', // Instruct the server whether to reply to commands |
||
333 | 'CLIENT SETNAME', // Set the current connection name |
||
334 | 'CLUSTER ADDSLOTS', // Assign new hash slots to receiving node |
||
335 | 'CLUSTER COUNTKEYSINSLOT', // Return the number of local keys in the specified hash slot |
||
336 | 'CLUSTER DELSLOTS', // Set hash slots as unbound in receiving node |
||
337 | 'CLUSTER FAILOVER', // Forces a slave to perform a manual failover of its master. |
||
338 | 'CLUSTER FORGET', // Remove a node from the nodes table |
||
339 | 'CLUSTER GETKEYSINSLOT', // Return local key names in the specified hash slot |
||
340 | 'CLUSTER INFO', // Provides info about Redis Cluster node state |
||
341 | 'CLUSTER KEYSLOT', // Returns the hash slot of the specified key |
||
342 | 'CLUSTER MEET', // Force a node cluster to handshake with another node |
||
343 | 'CLUSTER NODES', // Get Cluster config for the node |
||
344 | 'CLUSTER REPLICATE', // Reconfigure a node as a slave of the specified master node |
||
345 | 'CLUSTER RESET', // Reset a Redis Cluster node |
||
346 | 'CLUSTER SAVECONFIG', // Forces the node to save cluster state on disk |
||
347 | 'CLUSTER SETSLOT', // Bind a hash slot to a specific node |
||
348 | 'CLUSTER SLAVES', // List slave nodes of the specified master node |
||
349 | 'CLUSTER SLOTS', // Get array of Cluster slot to node mappings |
||
350 | 'COMMAND', // Get array of Redis command details |
||
351 | 'COMMAND COUNT', // Get total number of Redis commands |
||
352 | 'COMMAND GETKEYS', // Extract keys given a full Redis command |
||
353 | 'COMMAND INFO', // Get array of specific Redis command details |
||
354 | 'CONFIG GET', // Get the value of a configuration parameter |
||
355 | 'CONFIG REWRITE', // Rewrite the configuration file with the in memory configuration |
||
356 | 'CONFIG SET', // Set a configuration parameter to the given value |
||
357 | 'CONFIG RESETSTAT', // Reset the stats returned by INFO |
||
358 | 'DBSIZE', // Return the number of keys in the selected database |
||
359 | 'DEBUG OBJECT', // Get debugging information about a key |
||
360 | 'DEBUG SEGFAULT', // Make the server crash |
||
361 | 'DECR', // Decrement the integer value of a key by one |
||
362 | 'DECRBY', // Decrement the integer value of a key by the given number |
||
363 | 'DEL', // Delete a key |
||
364 | 'DISCARD', // Discard all commands issued after MULTI |
||
365 | 'DUMP', // Return a serialized version of the value stored at the specified key. |
||
366 | 'ECHO', // Echo the given string |
||
367 | 'EVAL', // Execute a Lua script server side |
||
368 | 'EVALSHA', // Execute a Lua script server side |
||
369 | 'EXEC', // Execute all commands issued after MULTI |
||
370 | 'EXISTS', // Determine if a key exists |
||
371 | 'EXPIRE', // Set a key's time to live in seconds |
||
372 | 'EXPIREAT', // Set the expiration for a key as a UNIX timestamp |
||
373 | 'FLUSHALL', // Remove all keys from all databases |
||
374 | 'FLUSHDB', // Remove all keys from the current database |
||
375 | 'GEOADD', // Add one or more geospatial items in the geospatial index represented using a sorted set |
||
376 | 'GEOHASH', // Returns members of a geospatial index as standard geohash strings |
||
377 | 'GEOPOS', // Returns longitude and latitude of members of a geospatial index |
||
378 | 'GEODIST', // Returns the distance between two members of a geospatial index |
||
379 | 'GEORADIUS', // Query a sorted set representing a geospatial index to fetch members matching a given maximum distance from a point |
||
380 | 'GEORADIUSBYMEMBER', // Query a sorted set representing a geospatial index to fetch members matching a given maximum distance from a member |
||
381 | 'GET', // Get the value of a key |
||
382 | 'GETBIT', // Returns the bit value at offset in the string value stored at key |
||
383 | 'GETRANGE', // Get a substring of the string stored at a key |
||
384 | 'GETSET', // Set the string value of a key and return its old value |
||
385 | 'HDEL', // Delete one or more hash fields |
||
386 | 'HEXISTS', // Determine if a hash field exists |
||
387 | 'HGET', // Get the value of a hash field |
||
388 | 'HGETALL', // Get all the fields and values in a hash |
||
389 | 'HINCRBY', // Increment the integer value of a hash field by the given number |
||
390 | 'HINCRBYFLOAT', // Increment the float value of a hash field by the given amount |
||
391 | 'HKEYS', // Get all the fields in a hash |
||
392 | 'HLEN', // Get the number of fields in a hash |
||
393 | 'HMGET', // Get the values of all the given hash fields |
||
394 | 'HMSET', // Set multiple hash fields to multiple values |
||
395 | 'HSET', // Set the string value of a hash field |
||
396 | 'HSETNX', // Set the value of a hash field, only if the field does not exist |
||
397 | 'HSTRLEN', // Get the length of the value of a hash field |
||
398 | 'HVALS', // Get all the values in a hash |
||
399 | 'INCR', // Increment the integer value of a key by one |
||
400 | 'INCRBY', // Increment the integer value of a key by the given amount |
||
401 | 'INCRBYFLOAT', // Increment the float value of a key by the given amount |
||
402 | 'INFO', // Get information and statistics about the server |
||
403 | 'KEYS', // Find all keys matching the given pattern |
||
404 | 'LASTSAVE', // Get the UNIX time stamp of the last successful save to disk |
||
405 | 'LINDEX', // Get an element from a list by its index |
||
406 | 'LINSERT', // Insert an element before or after another element in a list |
||
407 | 'LLEN', // Get the length of a list |
||
408 | 'LPOP', // Remove and get the first element in a list |
||
409 | 'LPUSH', // Prepend one or multiple values to a list |
||
410 | 'LPUSHX', // Prepend a value to a list, only if the list exists |
||
411 | 'LRANGE', // Get a range of elements from a list |
||
412 | 'LREM', // Remove elements from a list |
||
413 | 'LSET', // Set the value of an element in a list by its index |
||
414 | 'LTRIM', // Trim a list to the specified range |
||
415 | 'MGET', // Get the values of all the given keys |
||
416 | 'MIGRATE', // Atomically transfer a key from a Redis instance to another one. |
||
417 | 'MONITOR', // Listen for all requests received by the server in real time |
||
418 | 'MOVE', // Move a key to another database |
||
419 | 'MSET', // Set multiple keys to multiple values |
||
420 | 'MSETNX', // Set multiple keys to multiple values, only if none of the keys exist |
||
421 | 'MULTI', // Mark the start of a transaction block |
||
422 | 'OBJECT', // Inspect the internals of Redis objects |
||
423 | 'PERSIST', // Remove the expiration from a key |
||
424 | 'PEXPIRE', // Set a key's time to live in milliseconds |
||
425 | 'PEXPIREAT', // Set the expiration for a key as a UNIX timestamp specified in milliseconds |
||
426 | 'PFADD', // Adds the specified elements to the specified HyperLogLog. |
||
427 | 'PFCOUNT', // Return the approximated cardinality of the set(s) observed by the HyperLogLog at key(s). |
||
428 | 'PFMERGE', // Merge N different HyperLogLogs into a single one. |
||
429 | 'PING', // Ping the server |
||
430 | 'PSETEX', // Set the value and expiration in milliseconds of a key |
||
431 | 'PSUBSCRIBE', // Listen for messages published to channels matching the given patterns |
||
432 | 'PUBSUB', // Inspect the state of the Pub/Sub subsystem |
||
433 | 'PTTL', // Get the time to live for a key in milliseconds |
||
434 | 'PUBLISH', // Post a message to a channel |
||
435 | 'PUNSUBSCRIBE', // Stop listening for messages posted to channels matching the given patterns |
||
436 | 'QUIT', // Close the connection |
||
437 | 'RANDOMKEY', // Return a random key from the keyspace |
||
438 | 'READONLY', // Enables read queries for a connection to a cluster slave node |
||
439 | 'READWRITE', // Disables read queries for a connection to a cluster slave node |
||
440 | 'RENAME', // Rename a key |
||
441 | 'RENAMENX', // Rename a key, only if the new key does not exist |
||
442 | 'RESTORE', // Create a key using the provided serialized value, previously obtained using DUMP. |
||
443 | 'ROLE', // Return the role of the instance in the context of replication |
||
444 | 'RPOP', // Remove and get the last element in a list |
||
445 | 'RPOPLPUSH', // Remove the last element in a list, prepend it to another list and return it |
||
446 | 'RPUSH', // Append one or multiple values to a list |
||
447 | 'RPUSHX', // Append a value to a list, only if the list exists |
||
448 | 'SADD', // Add one or more members to a set |
||
449 | 'SAVE', // Synchronously save the dataset to disk |
||
450 | 'SCARD', // Get the number of members in a set |
||
451 | 'SCRIPT DEBUG', // Set the debug mode for executed scripts. |
||
452 | 'SCRIPT EXISTS', // Check existence of scripts in the script cache. |
||
453 | 'SCRIPT FLUSH', // Remove all the scripts from the script cache. |
||
454 | 'SCRIPT KILL', // Kill the script currently in execution. |
||
455 | 'SCRIPT LOAD', // Load the specified Lua script into the script cache. |
||
456 | 'SDIFF', // Subtract multiple sets |
||
457 | 'SDIFFSTORE', // Subtract multiple sets and store the resulting set in a key |
||
458 | 'SELECT', // Change the selected database for the current connection |
||
459 | 'SET', // Set the string value of a key |
||
460 | 'SETBIT', // Sets or clears the bit at offset in the string value stored at key |
||
461 | 'SETEX', // Set the value and expiration of a key |
||
462 | 'SETNX', // Set the value of a key, only if the key does not exist |
||
463 | 'SETRANGE', // Overwrite part of a string at key starting at the specified offset |
||
464 | 'SHUTDOWN', // Synchronously save the dataset to disk and then shut down the server |
||
465 | 'SINTER', // Intersect multiple sets |
||
466 | 'SINTERSTORE', // Intersect multiple sets and store the resulting set in a key |
||
467 | 'SISMEMBER', // Determine if a given value is a member of a set |
||
468 | 'SLAVEOF', // Make the server a slave of another instance, or promote it as master |
||
469 | 'SLOWLOG', // Manages the Redis slow queries log |
||
470 | 'SMEMBERS', // Get all the members in a set |
||
471 | 'SMOVE', // Move a member from one set to another |
||
472 | 'SORT', // Sort the elements in a list, set or sorted set |
||
473 | 'SPOP', // Remove and return one or multiple random members from a set |
||
474 | 'SRANDMEMBER', // Get one or multiple random members from a set |
||
475 | 'SREM', // Remove one or more members from a set |
||
476 | 'STRLEN', // Get the length of the value stored in a key |
||
477 | 'SUBSCRIBE', // Listen for messages published to the given channels |
||
478 | 'SUNION', // Add multiple sets |
||
479 | 'SUNIONSTORE', // Add multiple sets and store the resulting set in a key |
||
480 | 'SWAPDB', // Swaps two Redis databases |
||
481 | 'SYNC', // Internal command used for replication |
||
482 | 'TIME', // Return the current server time |
||
483 | 'TOUCH', // Alters the last access time of a key(s). Returns the number of existing keys specified. |
||
484 | 'TTL', // Get the time to live for a key |
||
485 | 'TYPE', // Determine the type stored at key |
||
486 | 'UNSUBSCRIBE', // Stop listening for messages posted to the given channels |
||
487 | 'UNLINK', // Delete a key asynchronously in another thread. Otherwise it is just as DEL, but non blocking. |
||
488 | 'UNWATCH', // Forget about all watched keys |
||
489 | 'WAIT', // Wait for the synchronous replication of all the write commands sent in the context of the current connection |
||
490 | 'WATCH', // Watch the given keys to determine execution of the MULTI/EXEC block |
||
491 | 'ZADD', // Add one or more members to a sorted set, or update its score if it already exists |
||
492 | 'ZCARD', // Get the number of members in a sorted set |
||
493 | 'ZCOUNT', // Count the members in a sorted set with scores within the given values |
||
494 | 'ZINCRBY', // Increment the score of a member in a sorted set |
||
495 | 'ZINTERSTORE', // Intersect multiple sorted sets and store the resulting sorted set in a new key |
||
496 | 'ZLEXCOUNT', // Count the number of members in a sorted set between a given lexicographical range |
||
497 | 'ZRANGE', // Return a range of members in a sorted set, by index |
||
498 | 'ZRANGEBYLEX', // Return a range of members in a sorted set, by lexicographical range |
||
499 | 'ZREVRANGEBYLEX', // Return a range of members in a sorted set, by lexicographical range, ordered from higher to lower strings. |
||
500 | 'ZRANGEBYSCORE', // Return a range of members in a sorted set, by score |
||
501 | 'ZRANK', // Determine the index of a member in a sorted set |
||
502 | 'ZREM', // Remove one or more members from a sorted set |
||
503 | 'ZREMRANGEBYLEX', // Remove all members in a sorted set between the given lexicographical range |
||
504 | 'ZREMRANGEBYRANK', // Remove all members in a sorted set within the given indexes |
||
505 | 'ZREMRANGEBYSCORE', // Remove all members in a sorted set within the given scores |
||
506 | 'ZREVRANGE', // Return a range of members in a sorted set, by index, with scores ordered from high to low |
||
507 | 'ZREVRANGEBYSCORE', // Return a range of members in a sorted set, by score, with scores ordered from high to low |
||
508 | 'ZREVRANK', // Determine the index of a member in a sorted set, with scores ordered from high to low |
||
509 | 'ZSCORE', // Get the score associated with the given member in a sorted set |
||
510 | 'ZUNIONSTORE', // Add multiple sorted sets and store the resulting sorted set in a new key |
||
511 | 'SCAN', // Incrementally iterate the keys space |
||
512 | 'SSCAN', // Incrementally iterate Set elements |
||
513 | 'HSCAN', // Incrementally iterate hash fields and associated values |
||
514 | 'ZSCAN', // Incrementally iterate sorted sets elements and associated scores |
||
515 | ]; |
||
516 | |||
517 | /** |
||
518 | * @var bool|Resource |
||
519 | */ |
||
520 | private $_socket = false; |
||
521 | |||
522 | /** |
||
523 | * Connection constructor. |
||
524 | * @param array $config |
||
525 | */ |
||
526 | public function __construct($config = []) |
||
534 | } |
||
535 | |||
536 | /** |
||
537 | * Initializes the object. |
||
538 | * This method is invoked at the end of the constructor after the object is initialized with the |
||
539 | * given configuration. |
||
540 | */ |
||
541 | public function init() |
||
542 | { |
||
543 | } |
||
544 | |||
545 | /** |
||
546 | * Closes the connection when this component is being serialized. |
||
547 | * @return array |
||
548 | * @throws \Exception |
||
549 | */ |
||
550 | public function __sleep() |
||
551 | { |
||
552 | $this->close(); |
||
553 | return array_keys(get_object_vars($this)); |
||
554 | } |
||
555 | |||
556 | /** |
||
557 | * Returns a value indicating whether the DB connection is established. |
||
558 | * @return bool whether the DB connection is established |
||
559 | */ |
||
560 | public function getIsActive() |
||
561 | { |
||
562 | return $this->_socket !== false; |
||
563 | } |
||
564 | |||
565 | /** |
||
566 | * Establishes a DB connection. |
||
567 | * It does nothing if a DB connection has already been established. |
||
568 | * @throws Exception if connection fails |
||
569 | * @throws \Exception |
||
570 | */ |
||
571 | public function open() |
||
572 | { |
||
573 | if ($this->_socket !== false) { |
||
574 | return; |
||
575 | } |
||
576 | $connection = ($this->unixSocket ?: $this->hostname . ':' . $this->port) . ', database=' . $this->database; |
||
|
|||
577 | $this->_socket = @stream_socket_client( |
||
578 | $this->unixSocket ? 'unix://' . $this->unixSocket : 'tcp://' . $this->hostname . ':' . $this->port, |
||
579 | $errorNumber, |
||
580 | $errorDescription, |
||
581 | $this->connectionTimeout ? $this->connectionTimeout : ini_get('default_socket_timeout'), |
||
582 | $this->socketClientFlags |
||
583 | ); |
||
584 | if ($this->_socket) { |
||
585 | if ($this->dataTimeout !== null) { |
||
586 | stream_set_timeout($this->_socket, $timeout = (int) $this->dataTimeout, (int) (($this->dataTimeout - $timeout) * 1000000)); |
||
587 | } |
||
588 | if ($this->password !== null) { |
||
589 | $this->executeCommand('AUTH', [$this->password]); |
||
590 | } |
||
591 | if ($this->database !== null) { |
||
592 | $this->executeCommand('SELECT', [$this->database]); |
||
593 | } |
||
594 | } else { |
||
595 | $message = 'Failed to open DB connection.'; |
||
596 | throw new Exception($message, $errorDescription, $errorNumber); |
||
597 | } |
||
598 | } |
||
599 | |||
600 | /** |
||
601 | * Closes the currently active DB connection. |
||
602 | * It does nothing if the connection is already closed. |
||
603 | * @throws \Exception |
||
604 | */ |
||
605 | public function close() |
||
606 | { |
||
607 | if ($this->_socket !== false) { |
||
608 | $connection = ($this->unixSocket ?: $this->hostname . ':' . $this->port) . ', database=' . $this->database; |
||
609 | try { |
||
610 | $this->executeCommand('QUIT'); |
||
611 | } catch (SocketException $e) { |
||
612 | // ignore errors when quitting a closed connection |
||
613 | } |
||
614 | fclose($this->_socket); |
||
615 | $this->_socket = false; |
||
616 | } |
||
617 | } |
||
618 | |||
619 | /** |
||
620 | * Returns the name of the DB driver for the current [[dsn]]. |
||
621 | * @return string name of the DB driver |
||
622 | */ |
||
623 | public function getDriverName() |
||
624 | { |
||
625 | return 'redis'; |
||
626 | } |
||
627 | |||
628 | /** |
||
629 | * Allows issuing all supported commands via magic methods. |
||
630 | * |
||
631 | * ```php |
||
632 | * $redis->hmset('test_collection', 'key1', 'val1', 'key2', 'val2') |
||
633 | * OR |
||
634 | * $redis->hmset(['test_collection', 'key1', 'val1', 'key2', 'val2']) |
||
635 | * OR |
||
636 | * $redis->hmset('test_collection', ['key1', 'val1', 'key2', 'val2']) |
||
637 | * ``` |
||
638 | * |
||
639 | * @param string $name name of the missing method to execute |
||
640 | * @param array $params method call arguments |
||
641 | * @return mixed |
||
642 | * @throws Exception |
||
643 | * @throws \Exception |
||
644 | */ |
||
645 | public function __call($name, $params) |
||
646 | { |
||
647 | if (false !== strpos($name, '_a')) { |
||
648 | $name = substr($name, 0, -2); |
||
649 | $params = $this->normalizeParams($name, $params); |
||
650 | } |
||
651 | $redisCommand = strtoupper(Inflector::camel2words($name, false)); |
||
652 | if (in_array($redisCommand, $this->redisCommands)) { |
||
653 | return $this->executeCommand($redisCommand, $params); |
||
654 | } |
||
655 | |||
656 | throw new Exception("method {$name} not found"); |
||
657 | } |
||
658 | |||
659 | /** |
||
660 | * 如果参数是二维数组,转化为一维,为了支持函数调用时传数组参数 |
||
661 | * @param $name |
||
662 | * @param $params |
||
663 | * @return array |
||
664 | */ |
||
665 | private function normalizeParams($name, $params) |
||
666 | { |
||
667 | $arguments = []; |
||
668 | foreach ($params as $args) { |
||
669 | if (is_array($args)) { |
||
670 | foreach ($args as $arg) { |
||
671 | $arguments[] = $arg; |
||
672 | } |
||
673 | } else { |
||
674 | $arguments[] = $args; |
||
675 | } |
||
676 | } |
||
677 | return $arguments; |
||
678 | } |
||
679 | |||
680 | /** |
||
681 | * Executes a redis command. |
||
682 | * For a list of available commands and their parameters see http://redis.io/commands. |
||
683 | * |
||
684 | * The params array should contain the params separated by white space, e.g. to execute |
||
685 | * `SET mykey somevalue NX` call the following: |
||
686 | * |
||
687 | * ```php |
||
688 | * $redis->executeCommand('SET', ['mykey', 'somevalue', 'NX']); |
||
689 | * ``` |
||
690 | * |
||
691 | * @param string $name the name of the command |
||
692 | * @param array $params list of parameters for the command |
||
693 | * @return array|bool|null|string Dependent on the executed command this method |
||
694 | * will return different data types: |
||
695 | * |
||
696 | * - `true` for commands that return "status reply" with the message `'OK'` or `'PONG'`. |
||
697 | * - `string` for commands that return "status reply" that does not have the message `OK` (since version 2.0.1). |
||
698 | * - `string` for commands that return "integer reply" |
||
699 | * as the value is in the range of a signed 64 bit integer. |
||
700 | * - `string` or `null` for commands that return "bulk reply". |
||
701 | * - `array` for commands that return "Multi-bulk replies". |
||
702 | * |
||
703 | * <number of arguments> CR LF |
||
704 | * $<number of bytes of argument 1> CR LF |
||
705 | * <argument data> CR LF |
||
706 | * ... |
||
707 | * $<number of bytes of argument N> CR LF |
||
708 | * <argument data> CR LF |
||
709 | * |
||
710 | * See [redis protocol description](http://redis.io/topics/protocol) |
||
711 | * for details on the mentioned reply types. |
||
712 | * @throws Exception for commands that return [error reply](http://redis.io/topics/protocol#error-reply). |
||
713 | * @throws \Exception |
||
714 | */ |
||
715 | public function executeCommand($name, $params = []) |
||
716 | { |
||
717 | $this->open(); |
||
718 | |||
719 | $params = array_merge(explode(' ', $name), $params); |
||
720 | $command = '*' . count($params) . "\r\n"; |
||
721 | foreach ($params as $arg) { |
||
722 | $command .= '$' . mb_strlen($arg, '8bit') . "\r\n" . $arg . "\r\n"; |
||
723 | } |
||
724 | |||
725 | if ($this->retries > 0) { |
||
726 | $tries = $this->retries; |
||
727 | while ($tries-- > 0) { |
||
728 | try { |
||
729 | return $this->sendCommandInternal($command, $params); |
||
730 | } catch (SocketException $e) { |
||
731 | // backup retries, fail on commands that fail inside here |
||
732 | $retries = $this->retries; |
||
733 | $this->retries = 0; |
||
734 | $this->close(); |
||
735 | $this->open(); |
||
736 | $this->retries = $retries; |
||
737 | } |
||
738 | } |
||
739 | } |
||
740 | return $this->sendCommandInternal($command, $params); |
||
741 | } |
||
742 | |||
743 | /** |
||
744 | * Sends RAW command string to the server. |
||
745 | * @throws SocketException on connection error. |
||
746 | * @throws \Exception |
||
747 | */ |
||
748 | private function sendCommandInternal($command, $params) |
||
749 | { |
||
750 | $written = @fwrite($this->_socket, $command); |
||
751 | if ($written === false) { |
||
752 | throw new SocketException("Failed to write to socket.\nRedis command was: " . $command); |
||
753 | } |
||
754 | if ($written !== ($len = mb_strlen($command, '8bit'))) { |
||
755 | throw new SocketException("Failed to write to socket. $written of $len bytes written.\nRedis command was: " . $command); |
||
756 | } |
||
757 | return $this->parseResponse(implode(' ', $params)); |
||
758 | } |
||
759 | |||
760 | /** |
||
761 | * For Simple Strings the first byte of the reply is "+" "+OK\r\n" |
||
762 | * For Errors the first byte of the reply is "-" "-Error message\r\n" |
||
763 | * For Integers the first byte of the reply is ":" ":1000\r\n" |
||
764 | * For Bulk Strings the first byte of the reply is "$" "$6\r\nfoobar\r\n" "$0\r\n\r\n" "$-1\r\n" |
||
765 | * For Arrays the first byte of the reply is "*" "*0\r\n" "*-1\r\n" *3\r\n:1\r\n:2\r\n$6\r\nfoobar\r\n |
||
766 | * @param string $command |
||
767 | * @return mixed |
||
768 | * @throws Exception on error |
||
769 | */ |
||
770 | private function parseResponse($command) |
||
814 | } |
||
815 | } |
||
816 | } |
||
817 |