22
33use GuzzleHttp \Client ;
44use GuzzleHttp \Exception \RequestException ;
5- use GuzzleHttp \Psr7 \ Request ;
5+ use GuzzleHttp \HandlerStack ;
66use GuzzleHttp \Psr7 \Response ;
77
88class Connection {
@@ -48,6 +48,13 @@ class Connection {
4848 */
4949 private $ client ;
5050
51+ /**
52+ * Array of inserted middleWares
53+ * @var array
54+ */
55+ protected $ middleWares = [];
56+
57+
5158 /**
5259 * @param string $apiKey API key for SendCloud
5360 * @param string $apiSecret API secret for SendCloud
@@ -65,20 +72,29 @@ public function client()
6572 {
6673 if ($ this ->client ) return $ this ->client ;
6774
68- $ this ->client = new Client ([
75+ $ handlerStack = HandlerStack::create ();
76+ foreach ($ this ->middleWares as $ middleWare ) {
77+ $ handlerStack ->push ($ middleWare );
78+ }
79+
80+ $ clientConfig = [
6981 'base_uri ' => $ this ->apiUrl (),
7082 'headers ' => [
7183 'Accept ' => 'application/json ' ,
7284 'Content-Type ' => 'application/json '
7385 ],
74- 'auth ' => [$ this ->apiKey , $ this ->apiSecret ]
75- ]);
86+ 'auth ' => [$ this ->apiKey , $ this ->apiSecret ],
87+ 'handler ' => $ handlerStack
88+ ];
89+
90+ $ this ->client = new Client ($ clientConfig );
7691
7792 return $ this ->client ;
7893 }
7994
80- public function setDebug ( $ handle )
95+ public function insertMiddleWare ( $ middleWare )
8196 {
97+ $ this ->middleWares [] = $ middleWare ;
8298 }
8399
84100 /**
@@ -181,10 +197,14 @@ public function delete($url)
181197 public function parseResponse (Response $ response )
182198 {
183199 try {
184- $ resultArray = json_decode ($ response ->getBody ()->getContents (), true );
200+ // Rewind the response (middlewares might have read it already)
201+ $ response ->getBody ()->rewind ();
202+
203+ $ responseBody = $ response ->getBody ()->getContents ();
204+ $ resultArray = json_decode ($ responseBody , true );
185205
186206 if (! is_array ($ resultArray )) {
187- throw new SendCloudApiException (sprintf ('SendCloud error %s: %s ' , $ response ->getStatusCode (), $ response -> getBody ()-> getContents () ));
207+ throw new SendCloudApiException (sprintf ('SendCloud error %s: %s ' , $ response ->getStatusCode (), $ responseBody ));
188208 }
189209
190210 if (array_key_exists ('error ' , $ resultArray )
0 commit comments