MonitorContext.php 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  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. $database = 0;
  51. $event = $this->_client->getConnection()->read();
  52. $callback = function($matches) use (&$database) {
  53. if (isset($matches[1])) {
  54. $database = (int) $matches[1];
  55. }
  56. return ' ';
  57. };
  58. $event = preg_replace_callback('/ \(db (\d+)\) /', $callback, $event, 1);
  59. @list($timestamp, $command, $arguments) = split(' ', $event, 3);
  60. return (object) array(
  61. 'timestamp' => (float) $timestamp,
  62. 'database' => $database,
  63. 'command' => substr($command, 1, -1),
  64. 'arguments' => $arguments,
  65. );
  66. }
  67. }