MonitorContext.php 2.2 KB

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