1313namespace PHPinnacle \Ridge ;
1414
1515use Amp \Loop ;
16+ use PHPinnacle \Ridge \Exception \ConnectionException ;
1617use function Amp \asyncCall ;
1718use function Amp \call ;
1819use Amp \Deferred ;
@@ -148,6 +149,8 @@ function () {
148149 function (): void
149150 {
150151 if ($ this ->connection ->connected () === false ) {
152+ $ this ->state = self ::STATE_NOT_CONNECTED ;
153+
151154 throw Exception \ClientException::disconnected ();
152155 }
153156 }
@@ -167,37 +170,41 @@ public function disconnect(int $code = 0, string $reason = ''): Promise
167170
168171 return call (
169172 function () use ($ code , $ reason ) {
170- if (\in_array ($ this ->state , [self ::STATE_NOT_CONNECTED , self ::STATE_DISCONNECTING ])) {
171- return ;
172- }
173-
174- if ($ this ->state !== self ::STATE_CONNECTED ) {
175- throw Exception \ClientException::notConnected ();
176- }
173+ try {
174+ if (\in_array ($ this ->state , [self ::STATE_NOT_CONNECTED , self ::STATE_DISCONNECTING ])) {
175+ return ;
176+ }
177177
178- if ($ this ->connectionMonitorWatcherId !== null ){
179- Loop::cancel ($ this ->connectionMonitorWatcherId );
178+ if ($ this ->state !== self ::STATE_CONNECTED ) {
179+ throw Exception \ClientException::notConnected ();
180+ }
180181
181- $ this ->connectionMonitorWatcherId = null ;
182- }
182+ if ( $ this ->connectionMonitorWatcherId !== null ){
183+ Loop:: cancel ( $ this -> connectionMonitorWatcherId );
183184
184- $ this ->state = self ::STATE_DISCONNECTING ;
185+ $ this ->connectionMonitorWatcherId = null ;
186+ }
185187
186- if ($ code === 0 ) {
187- $ promises = [];
188+ $ this ->state = self ::STATE_DISCONNECTING ;
188189
189- foreach ($ this ->channels as $ channel ) {
190- $ promises [] = $ channel ->close ($ code , $ reason );
191- }
190+ if ($ code === 0 ) {
191+ $ promises = [];
192192
193- yield $ promises ;
194- }
193+ foreach ($ this ->channels as $ channel ) {
194+ $ promises [] = $ channel ->close ($ code , $ reason );
195+ }
195196
196- yield $ this ->connectionClose ($ code , $ reason );
197+ yield $ promises ;
198+ }
197199
198- $ this ->connection -> close ( );
200+ yield $ this ->connectionClose ( $ code , $ reason );
199201
200- $ this ->state = self ::STATE_NOT_CONNECTED ;
202+ $ this ->connection ->close ();
203+ }
204+ finally
205+ {
206+ $ this ->state = self ::STATE_NOT_CONNECTED ;
207+ }
201208 }
202209 );
203210 }
@@ -250,7 +257,13 @@ function () {
250257 });
251258
252259 return $ channel ;
253- } catch (\Throwable $ error ) {
260+ }
261+ catch (ConnectionException $ exception ) {
262+ $ this ->state = self ::STATE_NOT_CONNECTED ;
263+
264+ throw $ exception ;
265+ }
266+ catch (\Throwable $ error ) {
254267 throw Exception \ClientException::unexpectedResponse ($ error );
255268 }
256269 }
0 commit comments