IoEmittingEntityBody.php 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. <?php
  2. namespace Guzzle\Http;
  3. use Guzzle\Common\Event;
  4. use Guzzle\Common\HasDispatcherInterface;
  5. use Symfony\Component\EventDispatcher\EventDispatcher;
  6. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  7. use Symfony\Component\EventDispatcher\EventDispatcherInterface;
  8. /**
  9. * EntityBody decorator that emits events for read and write methods
  10. */
  11. class IoEmittingEntityBody extends AbstractEntityBodyDecorator implements HasDispatcherInterface
  12. {
  13. /** @var EventDispatcherInterface */
  14. protected $eventDispatcher;
  15. public static function getAllEvents()
  16. {
  17. return array('body.read', 'body.write');
  18. }
  19. /**
  20. * {@inheritdoc}
  21. * @codeCoverageIgnore
  22. */
  23. public function setEventDispatcher(EventDispatcherInterface $eventDispatcher)
  24. {
  25. $this->eventDispatcher = $eventDispatcher;
  26. return $this;
  27. }
  28. public function getEventDispatcher()
  29. {
  30. if (!$this->eventDispatcher) {
  31. $this->eventDispatcher = new EventDispatcher();
  32. }
  33. return $this->eventDispatcher;
  34. }
  35. public function dispatch($eventName, array $context = array())
  36. {
  37. return $this->getEventDispatcher()->dispatch($eventName, new Event($context));
  38. }
  39. /**
  40. * {@inheritdoc}
  41. * @codeCoverageIgnore
  42. */
  43. public function addSubscriber(EventSubscriberInterface $subscriber)
  44. {
  45. $this->getEventDispatcher()->addSubscriber($subscriber);
  46. return $this;
  47. }
  48. public function read($length)
  49. {
  50. $event = array(
  51. 'body' => $this,
  52. 'length' => $length,
  53. 'read' => $this->body->read($length)
  54. );
  55. $this->dispatch('body.read', $event);
  56. return $event['read'];
  57. }
  58. public function write($string)
  59. {
  60. $event = array(
  61. 'body' => $this,
  62. 'write' => $string,
  63. 'result' => $this->body->write($string)
  64. );
  65. $this->dispatch('body.write', $event);
  66. return $event['result'];
  67. }
  68. }