MonitorContext.php 1.8 KB

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