1+ <?php
2+ /**
3+ * Created by PhpStorm.
4+ * User: inhere
5+ * Date: 2017-10-19
6+ * Time: 14:35
7+ */
8+
9+ namespace Inhere \Library \Helpers ;
10+
11+ use Psr \Http \Message \ResponseInterface ;
12+
13+ /**
14+ * Class Http
15+ * @package Inhere\Library\Helpers
16+ */
17+ class Http
18+ {
19+ /**
20+ * Send the response the client
21+ * @param ResponseInterface $response
22+ * @param array $options
23+ */
24+ public static function respond (ResponseInterface $ response , array $ options = [])
25+ {
26+ $ options = array_merge ([
27+ 'chunkSize ' => 4096 ,
28+ 'addContentLengthHeader ' => false ,
29+ ], $ options );
30+
31+ // Send response
32+ if (!headers_sent ()) {
33+ // Status
34+ header (sprintf (
35+ 'HTTP/%s %s %s ' ,
36+ $ response ->getProtocolVersion (),
37+ $ response ->getStatusCode (),
38+ $ response ->getReasonPhrase ()
39+ ));
40+
41+ // Headers
42+ foreach ($ response ->getHeaders () as $ name => $ values ) {
43+ /** @var array $values */
44+ foreach ($ values as $ value ) {
45+ header (sprintf ('%s: %s ' , $ name , $ value ), false );
46+ }
47+ }
48+ }
49+
50+ // Body
51+ if (!self ::isEmptyResponse ($ response )) {
52+ $ body = $ response ->getBody ();
53+ if ($ body ->isSeekable ()) {
54+ $ body ->rewind ();
55+ }
56+
57+ $ chunkSize = $ options ['chunkSize ' ];
58+ $ contentLength = $ response ->getHeaderLine ('Content-Length ' );
59+
60+ if (!$ contentLength ) {
61+ $ contentLength = $ body ->getSize ();
62+ }
63+
64+ if (null !== $ contentLength ) {
65+ $ amountToRead = $ contentLength ;
66+ while ($ amountToRead > 0 && !$ body ->eof ()) {
67+ $ data = $ body ->read (min ($ chunkSize , $ amountToRead ));
68+ echo $ data ;
69+ $ amountToRead -= strlen ($ data );
70+
71+ if (connection_status () !== CONNECTION_NORMAL ) {
72+ break ;
73+ }
74+ }
75+ } else {
76+ while (!$ body ->eof ()) {
77+ echo $ body ->read ($ chunkSize );
78+ if (connection_status () !== CONNECTION_NORMAL ) {
79+ break ;
80+ }
81+ }
82+ }
83+ }
84+ }
85+
86+ /**
87+ * Helper method, which returns true if the provided response must not output a body and false
88+ * if the response could have a body.
89+ * @see https://tools.ietf.org/html/rfc7231
90+ * @param ResponseInterface $response
91+ * @return bool
92+ */
93+ public static function isEmptyResponse (ResponseInterface $ response )
94+ {
95+ if (method_exists ($ response , 'isEmpty ' )) {
96+ return $ response ->isEmpty ();
97+ }
98+
99+ return in_array ($ response ->getStatusCode (), [204 , 205 , 304 ], true );
100+ }
101+
102+ }
0 commit comments