33namespace Voryx \WebSocketMiddleware ;
44
55use Psr \Http \Message \ServerRequestInterface ;
6+ use Ratchet \RFC6455 \Handshake \PermessageDeflateOptions ;
67use Ratchet \RFC6455 \Handshake \RequestVerifier ;
78use Ratchet \RFC6455 \Handshake \ServerNegotiator ;
89use React \Http \Message \Response ;
@@ -14,12 +15,14 @@ final class WebSocketMiddleware
1415 private $ paths ;
1516 private $ connectionHandler = null ;
1617 private $ subProtocols ;
18+ private $ webSocketOptions = null ;
1719
18- public function __construct (array $ paths = [], callable $ connectionHandler = null , array $ subProtocols = [])
20+ public function __construct (array $ paths = [], callable $ connectionHandler = null , array $ subProtocols = [], WebSocketOptions $ webSocketOptions = null )
1921 {
2022 $ this ->paths = $ paths ;
2123 $ this ->connectionHandler = $ connectionHandler ?: function () {};
2224 $ this ->subProtocols = $ subProtocols ;
25+ $ this ->webSocketOptions = $ webSocketOptions ?? WebSocketOptions::getDefault ();
2326 }
2427
2528 public function __invoke (ServerRequestInterface $ request , callable $ next = null )
@@ -35,7 +38,7 @@ public function __invoke(ServerRequestInterface $request, callable $next = null)
3538 }
3639 }
3740
38- $ negotiator = new ServerNegotiator (new RequestVerifier ());
41+ $ negotiator = new ServerNegotiator (new RequestVerifier (), $ this -> webSocketOptions -> isPermessageDeflateEnabled () );
3942 $ negotiator ->setSupportedSubProtocols ($ this ->subProtocols );
4043 $ negotiator ->setStrictSubProtocolCheck (true );
4144
@@ -50,6 +53,19 @@ public function __invoke(ServerRequestInterface $request, callable $next = null)
5053 return $ next ($ request );
5154 }
5255
56+ try {
57+ $ permessageDeflateOptions = PermessageDeflateOptions::fromRequestOrResponse ($ request );
58+ } catch (\Exception $ e ) {
59+ // 500 - Internal server error
60+ return new Response (500 , [], 'Error negotiating websocket permessage-deflate: ' . $ e ->getMessage ());
61+ }
62+
63+ if (!$ this ->webSocketOptions ->isPermessageDeflateEnabled ()) {
64+ $ permessageDeflateOptions = [
65+ PermessageDeflateOptions::createDisabled ()
66+ ];
67+ }
68+
5369 $ inStream = new ThroughStream ();
5470 $ outStream = new ThroughStream ();
5571
@@ -62,7 +78,11 @@ public function __invoke(ServerRequestInterface $request, callable $next = null)
6278 )
6379 );
6480
65- $ conn = new WebSocketConnection (new CompositeStream ($ inStream , $ outStream ));
81+ $ conn = new WebSocketConnection (
82+ new CompositeStream ($ inStream , $ outStream ),
83+ $ this ->webSocketOptions ,
84+ $ permessageDeflateOptions [0 ]
85+ );
6686
6787 call_user_func ($ this ->connectionHandler , $ conn , $ request , $ response );
6888
0 commit comments