1717use Buzz \Message \RequestInterface ;
1818use Buzz \Message \Request ;
1919use Buzz \Message \Response ;
20+ use Bitbucket \API \Http \Listener \ListenerInterface ;
2021
2122/**
2223 * @author Alexandru G. <alex@gentle.ro>
@@ -52,6 +53,11 @@ class Client implements ClientInterface
5253 */
5354 private $ lastResponse ;
5455
56+ /**
57+ * @var ListenerInterface[]
58+ */
59+ protected $ listeners = array ();
60+
5561 public function __construct (array $ options = array (), BuzzClientInterface $ client = null )
5662 {
5763 $ this ->client = (is_null ($ client )) ? new Curl : $ client ;
@@ -61,6 +67,18 @@ public function __construct(array $options = array(), BuzzClientInterface $clien
6167 $ this ->client ->setVerifyPeer ($ this ->options ['verify_peer ' ]);
6268 }
6369
70+ /**
71+ * @access public
72+ * @param ListenerInterface $listener
73+ * @return $this
74+ */
75+ public function addListener (ListenerInterface $ listener )
76+ {
77+ $ this ->listeners [$ listener ->getName ()] = $ listener ;
78+
79+ return $ this ;
80+ }
81+
6482 /**
6583 * {@inheritDoc}
6684 */
@@ -125,8 +143,12 @@ public function request($endpoint, array $params = array(), $method, array $head
125143
126144 $ response = new Response ;
127145
146+ $ this ->executeListeners ($ request , 'preSend ' );
147+
128148 $ this ->client ->send ($ request , $ response );
129149
150+ $ this ->executeListeners ($ request , 'postSend ' , $ response );
151+
130152 $ this ->lastRequest = $ request ;
131153 $ this ->lastResponse = $ response ;
132154
@@ -229,4 +251,33 @@ protected function createRequest($method, $url)
229251
230252 return $ request ;
231253 }
254+
255+ /**
256+ * Execute all available listeners
257+ *
258+ * $when can be: preSend or postSend
259+ *
260+ * @access protected
261+ * @param RequestInterface $request
262+ * @param string $when When to execute the listener
263+ * @param MessageInterface $response
264+ */
265+ protected function executeListeners (RequestInterface $ request , $ when = 'preSend ' , MessageInterface $ response = null )
266+ {
267+ $ haveListeners = count ($ this ->listeners ) > 0 ;
268+
269+ if (!$ haveListeners ) {
270+ return ;
271+ }
272+
273+ $ params = array ($ request );
274+
275+ if (!is_null ($ response )) {
276+ $ params [] = $ response ;
277+ }
278+
279+ foreach ($ this ->listeners as $ listener ) {
280+ call_user_func_array (array ($ listener , $ when ), $ params );
281+ }
282+ }
232283}
0 commit comments