1<?php 2 3namespace ILIAS\HTTP\Response\Sender; 4 5use Psr\Http\Message\ResponseInterface; 6 7/** 8 * Class DefaultResponseSenderStrategy 9 * 10 * The default response sender strategy rewinds the current body 11 * stream and sends the entire stream out to the client. 12 * 13 * @author Nicolas Schäfli <ns@studer-raimann.ch> 14 */ 15class DefaultResponseSenderStrategy implements ResponseSenderStrategy 16{ 17 18 /** 19 * Sends the rendered response to the client. 20 * 21 * @param ResponseInterface $response The response which should be send to the client. 22 * 23 * @return void 24 * @throws ResponseSendingException Thrown if the response was already sent to the client. 25 */ 26 public function sendResponse(ResponseInterface $response) : void 27 { 28 //check if the request is already send 29 if (headers_sent()) { 30 throw new ResponseSendingException("Response was already sent."); 31 } 32 33 //set status code 34 http_response_code($response->getStatusCode()); 35 36 //render all headers 37 foreach ($response->getHeaders() as $key => $header) { 38 header("$key: " . $response->getHeaderLine($key)); 39 } 40 41 //rewind body stream 42 $response->getBody()->rewind(); 43 44 //detach psr-7 stream from resource 45 $resource = $response->getBody()->detach(); 46 47 $sendStatus = false; 48 49 if (is_resource($resource)) { 50 set_time_limit(0); 51 $sendStatus = fpassthru($resource); 52 53 //free up resources 54 fclose($resource); 55 } 56 57 //check if the body was successfully send to the client 58 if ($sendStatus === false) { 59 throw new ResponseSendingException("Could not send body content to client."); 60 } 61 } 62} 63