Skip to content
This repository has been archived by the owner on Jan 29, 2020. It is now read-only.

Add a TextResponse to easily return plain text HTTP responses #77

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 15 additions & 0 deletions doc/book/custom-responses.md
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,21 @@ Some standard use cases, however, make this un-wieldy:
Starting with version 1.1, Diactoros offers several custom response types for simplifying these
common tasks.

## Text Responses

`Zend\Diactoros\Response\TextResponse` creates a plain text response. It sets the
`Content-Type` header to `text/plain` by default:

```php
$response = new TextResponse('Hello world!');
```

The constructor accepts two additional arguments: a status code and an array of headers.

```php
$response = new TextResponse($text, 200, ['Content-Type' => ['text/csv']]);
```

## HTML Responses

`Zend\Diactoros\Response\HtmlResponse` allows specifying HTML as a payload, and sets the
Expand Down
2 changes: 1 addition & 1 deletion src/Response/HtmlResponse.php
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ public function __construct($html, $status = 200, array $headers = [])
parent::__construct(
$this->createBody($html),
$status,
$this->injectContentType('text/html', $headers)
$this->injectContentType('text/html; charset=utf-8', $headers)
);
}

Expand Down
73 changes: 73 additions & 0 deletions src/Response/TextResponse.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
<?php
/**
* Zend Framework (http://framework.zend.com/)
*
* @see http://github.com/zendframework/zend-diactoros for the canonical source repository
* @copyright Copyright (c) 2015 Zend Technologies USA Inc. (http://www.zend.com)
* @license https://github.com/zendframework/zend-diactoros/blob/master/LICENSE.md New BSD License
*/

namespace Zend\Diactoros\Response;

use InvalidArgumentException;
use Psr\Http\Message\StreamInterface;
use Zend\Diactoros\Response;
use Zend\Diactoros\Stream;

/**
* Plain text response.
*
* Allows creating a response by passing a string to the constructor;
* by default, sets a status code of 200 and sets the Content-Type header to
* text/plain.
*/
class TextResponse extends Response
{
use InjectContentTypeTrait;

/**
* Create a plain text response.
*
* Produces a text response with a Content-Type of text/plain and a default
* status of 200.
*
* @param string|StreamInterface $text String or stream for the message body.
* @param int $status Integer status code for the response; 200 by default.
* @param array $headers Array of headers to use at initialization.
* @throws InvalidArgumentException if $text is neither a string or stream.
*/
public function __construct($text, $status = 200, array $headers = [])
{
parent::__construct(
$this->createBody($text),
$status,
$this->injectContentType('text/plain; charset=utf-8', $headers)
);
}

/**
* Create the message body.
*
* @param string|StreamInterface $text
* @return StreamInterface
* @throws InvalidArgumentException if $html is neither a string or stream.
*/
private function createBody($text)
{
if ($text instanceof StreamInterface) {
return $text;
}

if (! is_string($text)) {
throw new InvalidArgumentException(sprintf(
'Invalid content (%s) provided to %s',
(is_object($text) ? get_class($text) : gettype($text)),
__CLASS__
));
}

$body = new Stream('php://temp', 'wb+');
$body->write($text);
return $body;
}
}
2 changes: 1 addition & 1 deletion test/Response/HtmlResponseTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ public function testConstructorAllowsPassingHeaders()

$response = new HtmlResponse($body, $status, $headers);
$this->assertEquals(['foo-bar'], $response->getHeader('x-custom'));
$this->assertEquals('text/html', $response->getHeaderLine('content-type'));
$this->assertEquals('text/html; charset=utf-8', $response->getHeaderLine('content-type'));
$this->assertEquals(404, $response->getStatusCode());
$this->assertSame($body, (string) $response->getBody());
}
Expand Down
82 changes: 82 additions & 0 deletions test/Response/TextResponseTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
<?php
/**
* Zend Framework (http://framework.zend.com/)
*
* @see http://github.com/zendframework/zend-diactoros for the canonical source repository
* @copyright Copyright (c) 2015 Zend Technologies USA Inc. (http://www.zend.com)
* @license https://github.com/zendframework/zend-diactoros/blob/master/LICENSE.md New BSD License
*/

namespace ZendTest\Diactoros\Response;

use PHPUnit_Framework_TestCase as TestCase;
use Zend\Diactoros\Response\TextResponse;

class TextResponseTest extends TestCase
{
public function testConstructorAcceptsBodyAsString()
{
$body = 'Uh oh not found';

$response = new TextResponse($body);
$this->assertSame($body, (string) $response->getBody());
$this->assertEquals(200, $response->getStatusCode());
}

public function testConstructorAllowsPassingStatus()
{
$body = 'Uh oh not found';
$status = 404;

$response = new TextResponse($body, $status);
$this->assertEquals(404, $response->getStatusCode());
$this->assertSame($body, (string) $response->getBody());
}

public function testConstructorAllowsPassingHeaders()
{
$body = 'Uh oh not found';
$status = 404;
$headers = [
'x-custom' => [ 'foo-bar' ],
];

$response = new TextResponse($body, $status, $headers);
$this->assertEquals(['foo-bar'], $response->getHeader('x-custom'));
$this->assertEquals('text/plain; charset=utf-8', $response->getHeaderLine('content-type'));
$this->assertEquals(404, $response->getStatusCode());
$this->assertSame($body, (string) $response->getBody());
}

public function testAllowsStreamsForResponseBody()
{
$stream = $this->prophesize('Psr\Http\Message\StreamInterface');
$body = $stream->reveal();
$response = new TextResponse($body);
$this->assertSame($body, $response->getBody());
}

public function invalidContent()
{
return [
'null' => [null],
'true' => [true],
'false' => [false],
'zero' => [0],
'int' => [1],
'zero-float' => [0.0],
'float' => [1.1],
'array' => [['php://temp']],
'object' => [(object) ['php://temp']],
];
}

/**
* @dataProvider invalidContent
* @expectedException \InvalidArgumentException
*/
public function testRaisesExceptionforNonStringNonStreamBodyContent($body)
{
new TextResponse($body);
}
}