MonitorContext.php 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. <?php
  2. namespace Predis;
  3. class MonitorContext implements \Iterator {
  4. private $_client;
  5. private $_isValid;
  6. private $_position;
  7. public function __construct(Client $client) {
  8. $this->checkCapabilities($client);
  9. $this->_client = $client;
  10. $this->openContext();
  11. }
  12. public function __destruct() {
  13. $this->closeContext();
  14. }
  15. private function checkCapabilities(Client $client) {
  16. if (Helpers::isCluster($client->getConnection())) {
  17. throw new ClientException(
  18. 'Cannot initialize a monitor context over a cluster of connections'
  19. );
  20. }
  21. if ($client->getProfile()->supportsCommand('monitor') === false) {
  22. throw new ClientException(
  23. 'The current profile does not support the MONITOR command'
  24. );
  25. }
  26. }
  27. protected function openContext() {
  28. $this->_isValid = true;
  29. $monitor = $this->_client->createCommand('monitor');
  30. $this->_client->executeCommand($monitor);
  31. }
  32. public function closeContext() {
  33. $this->_client->disconnect();
  34. $this->_isValid = false;
  35. }
  36. public function rewind() {
  37. // NOOP
  38. }
  39. public function current() {
  40. return $this->getValue();
  41. }
  42. public function key() {
  43. return $this->_position;
  44. }
  45. public function next() {
  46. $this->_position++;
  47. }
  48. public function valid() {
  49. return $this->_isValid;
  50. }
  51. private function getValue() {
  52. $database = 0;
  53. $event = $this->_client->getConnection()->read();
  54. $callback = function($matches) use (&$database) {
  55. if (isset($matches[1])) {
  56. $database = (int) $matches[1];
  57. }
  58. return ' ';
  59. };
  60. $event = preg_replace_callback('/ \(db (\d+)\) /', $callback, $event, 1);
  61. @list($timestamp, $command, $arguments) = split(' ', $event, 3);
  62. return (object) array(
  63. 'timestamp' => (float) $timestamp,
  64. 'database' => $database,
  65. 'command' => substr($command, 1, -1),
  66. 'arguments' => $arguments,
  67. );
  68. }
  69. }