Skip to content
Permalink
Browse files

Refactoring the stream creation in Response.php

  • Loading branch information...
burzum committed Oct 12, 2016
1 parent f5c2adc commit 76d9359ef1774ebb6037c6aec2461a38a9ac6886
Showing with 53 additions and 12 deletions.
  1. +53 −12 src/Network/Response.php
@@ -404,6 +404,20 @@ class Response implements ResponseInterface
*/
protected $_reasonPhrase = null;
/**
* Stream mode options.
*
* @var string
*/
protected $_streamMode = 'wb+';
/**
* Stream target or resource object.
*
* @var string|resource
*/
protected $_streamTarget = 'php://memory';
/**
* Constructor
*
@@ -416,13 +430,19 @@ class Response implements ResponseInterface
*/
public function __construct(array $options = [])
{
if (isset($options['streamTarget'])) {
$this->_streamTarget = $options['streamTarget'];
}
if (isset($options['streamMode'])) {
$this->_streamMode = $options['streamMode'];
}
if (isset($options['stream'])) {
if (!$options['stream'] instanceof StreamInterface) {
throw new InvalidArgumentException('Stream option must be an object implement StreamInterface');
}
$this->stream = $options['stream'];
} else {
$this->stream = new Stream('php://memory', 'wb+');
$this->createStream();
}
if (isset($options['body'])) {
$this->body($options['body']);
@@ -442,6 +462,16 @@ public function __construct(array $options = [])
$this->charset($options['charset']);
}
/**
* Creates the stream object.
*
* @return void
*/
public function createStream()
{
$this->stream = new Stream($this->_streamTarget, $this->_streamMode);
}
/**
* Sends the complete response to the client including headers and message body.
* Will echo out the content in the response body.
@@ -720,19 +750,10 @@ public function body($content = null)
// BC compatibility
if (is_callable($content)) {
ob_start();
$result1 = $content();
$result2 = ob_get_contents();
ob_get_clean();
if ($result1) {
$content = $result1;
} else {
$content = $result2;
}
$content = $this->_handleCallableBody($content);
}
$this->stream = new Stream('php://memory', 'wb+');
$this->stream = $this->createStream();
$this->stream->write($content);
$this->stream->rewind();
$result = $this->stream->getContents();
@@ -744,6 +765,26 @@ public function body($content = null)
return $result;
}
/**
* Handles the callable body for backward compatibility reasons.
*
* @param callable $content Callable content.
* @return string
*/
protected function _handleCallableBody(callable $content)
{
ob_start();
$result1 = $content();
$result2 = ob_get_contents();
ob_get_clean();
if ($result1) {
return $result1;
}
return $result2;
}
/**
* Sets the HTTP status code to be sent
* if $code is null the current code is returned

0 comments on commit 76d9359

Please sign in to comment.
You can’t perform that action at this time.