1: <?php
2:
3: namespace Guzzle\Plugin\History;
4:
5: use Guzzle\Common\Event;
6: use Guzzle\Http\Message\RequestInterface;
7: use Guzzle\Http\Message\Response;
8: use Symfony\Component\EventDispatcher\EventSubscriberInterface;
9:
10: /**
11: * Maintains a list of requests and responses sent using a request or client
12: */
13: class HistoryPlugin implements EventSubscriberInterface, \IteratorAggregate, \Countable
14: {
15: /**
16: * @var int The maximum number of requests to maintain in the history
17: */
18: protected $limit = 10;
19:
20: /**
21: * @var array Requests that have passed through the plugin
22: */
23: protected $requests = array();
24:
25: /**
26: * {@inheritdoc}
27: */
28: public static function getSubscribedEvents()
29: {
30: return array('request.complete' => 'onRequestComplete');
31: }
32:
33: /**
34: * Add a request to the history
35: *
36: * @param RequestInterface $request Request to add
37: *
38: * @return HistoryPlugin
39: */
40: public function add(RequestInterface $request)
41: {
42: if ($request->getResponse()) {
43: $this->requests[] = $request;
44: if (count($this->requests) > $this->getlimit()) {
45: array_shift($this->requests);
46: }
47: }
48:
49: return $this;
50: }
51:
52: /**
53: * Set the max number of requests to store
54: *
55: * @param int $limit Limit
56: *
57: * @return HistoryPlugin
58: */
59: public function setLimit($limit)
60: {
61: $this->limit = (int) $limit;
62:
63: return $this;
64: }
65:
66: /**
67: * Get the request limit
68: *
69: * @return int
70: */
71: public function getLimit()
72: {
73: return $this->limit;
74: }
75:
76: /**
77: * Get the requests in the history
78: *
79: * @return \ArrayIterator
80: */
81: public function getIterator()
82: {
83: return new \ArrayIterator($this->requests);
84: }
85:
86: /**
87: * Get the number of requests in the history
88: *
89: * @return int
90: */
91: public function count()
92: {
93: return count($this->requests);
94: }
95:
96: /**
97: * Get the last request sent
98: *
99: * @return RequestInterface
100: */
101: public function getLastRequest()
102: {
103: return end($this->requests);
104: }
105:
106: /**
107: * Get the last response in the history
108: *
109: * @return Response
110: */
111: public function getLastResponse()
112: {
113: return $this->getLastRequest()->getResponse();
114: }
115:
116: /**
117: * Clears the history
118: *
119: * @return HistoryPlugin
120: */
121: public function clear()
122: {
123: $this->requests = array();
124:
125: return $this;
126: }
127:
128: /**
129: * {@inheritdoc}
130: */
131: public function onRequestComplete(Event $event)
132: {
133: $this->add($event['request']);
134: }
135: }
136: