ProcessorChain.php 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  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\Commands\Processors;
  11. use Predis\Commands\ICommand;
  12. class ProcessorChain implements ICommandProcessorChain, \ArrayAccess
  13. {
  14. private $_processors;
  15. public function __construct($processors = array())
  16. {
  17. foreach ($processors as $processor) {
  18. $this->add($processor);
  19. }
  20. }
  21. public function add(ICommandProcessor $processor)
  22. {
  23. $this->_processors[] = $processor;
  24. }
  25. public function remove(ICommandProcessor $processor)
  26. {
  27. $index = array_search($processor, $this->_processors, true);
  28. if ($index !== false) {
  29. unset($this[$index]);
  30. }
  31. }
  32. public function process(ICommand $command)
  33. {
  34. $count = count($this->_processors);
  35. for ($i = 0; $i < $count; $i++) {
  36. $this->_processors[$i]->process($command);
  37. }
  38. }
  39. public function getProcessors()
  40. {
  41. return $this->_processors;
  42. }
  43. public function getIterator()
  44. {
  45. return new \ArrayIterator($this->_processors);
  46. }
  47. public function count()
  48. {
  49. return count($this->_processors);
  50. }
  51. public function offsetExists($index)
  52. {
  53. return isset($this->_processors[$index]);
  54. }
  55. public function offsetGet($index)
  56. {
  57. return $this->_processors[$index];
  58. }
  59. public function offsetSet($index, $processor)
  60. {
  61. if (!$processor instanceof ICommandProcessor) {
  62. throw new \InvalidArgumentException(
  63. 'A processor chain can hold only instances of classes implementing '.
  64. 'the Predis\Commands\Preprocessors\ICommandProcessor interface'
  65. );
  66. }
  67. $this->_processors[$index] = $processor;
  68. }
  69. public function offsetUnset($index)
  70. {
  71. unset($this->_processors[$index]);
  72. }
  73. }