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,13 @@ 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+
5363 $ inStream = new ThroughStream ();
5464 $ outStream = new ThroughStream ();
5565
@@ -62,7 +72,11 @@ public function __invoke(ServerRequestInterface $request, callable $next = null)
6272 )
6373 );
6474
65- $ conn = new WebSocketConnection (new CompositeStream ($ inStream , $ outStream ));
75+ $ conn = new WebSocketConnection (
76+ new CompositeStream ($ inStream , $ outStream ),
77+ $ this ->webSocketOptions ,
78+ $ permessageDeflateOptions [0 ]
79+ );
6680
6781 call_user_func ($ this ->connectionHandler , $ conn , $ request , $ response );
6882
0 commit comments