Skip to content

Commit 22d7076

Browse files
authored
Fix using a formatter with a custom body (#58)
1 parent a32526f commit 22d7076

File tree

3 files changed

+25
-1
lines changed

3 files changed

+25
-1
lines changed

src/DataResponse.php

+1
Original file line numberDiff line numberDiff line change
@@ -186,6 +186,7 @@ public function withBody(StreamInterface $body): self
186186
$new->dataStream = $body;
187187
$new->forcedBody = true;
188188
$new->formatted = false;
189+
$new->data = null;
189190
return $new;
190191
}
191192

tests/DataResponseTest.php

+23
Original file line numberDiff line numberDiff line change
@@ -241,6 +241,29 @@ public function testWithBody(): void
241241
$this->assertSame('test2', $dataResponse->getBody()->getContents());
242242
}
243243

244+
public function testWithBodyAndWithResponseFormatter(): void
245+
{
246+
$dataResponse = $this->createDataResponse('test1')
247+
->withResponseFormatter(new JsonDataResponseFormatter())
248+
->withBody($this->createStream('test2'))
249+
;
250+
251+
$dataResponse->getBody()->rewind();
252+
253+
$this->assertSame(['application/json; charset=UTF-8'], $dataResponse->getHeader(Header::CONTENT_TYPE));
254+
$this->assertSame('test2', $dataResponse->getBody()->getContents());
255+
256+
$dataResponse = $dataResponse
257+
->withBody($this->createStream('test3'))
258+
->withResponseFormatter(new XmlDataResponseFormatter())
259+
;
260+
261+
$dataResponse->getBody()->rewind();
262+
263+
$this->assertSame(['application/xml; charset=UTF-8'], $dataResponse->getHeader(Header::CONTENT_TYPE));
264+
$this->assertSame('test3', $dataResponse->getBody()->getContents());
265+
}
266+
244267
public function testWithBodyIfDataIsNull(): void
245268
{
246269
$dataResponse = $this->createDataResponse(null)->withBody($this->createStream('test'));

tests/Stub/CustomDataResponseFormatter.php

+1-1
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@
99
use Yiisoft\DataResponse\DataResponse;
1010
use Yiisoft\DataResponse\DataResponseFormatterInterface;
1111

12-
class CustomDataResponseFormatter implements DataResponseFormatterInterface
12+
final class CustomDataResponseFormatter implements DataResponseFormatterInterface
1313
{
1414
private int $statusCode = 200;
1515
private array $headers = [];

0 commit comments

Comments
 (0)