MonitorContext.php 2.4 KB

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