diff --git a/system/API/ResponseTrait.php b/system/API/ResponseTrait.php index 1bf87abf0420..36d00389628c 100644 --- a/system/API/ResponseTrait.php +++ b/system/API/ResponseTrait.php @@ -114,6 +114,19 @@ public function respond($data = null, int $status = null, string $message = '') $output = $this->format($data); } + if (! is_null($output)) + { + if ($this->format === 'json') + { + return $this->response->setJSON($output)->setStatusCode($status, $message); + } + + if ($this->format === 'xml') + { + return $this->response->setXML($output)->setStatusCode($status, $message); + } + } + return $this->response->setBody($output)->setStatusCode($status, $message); } @@ -361,6 +374,7 @@ protected function format($data = null) $contentType = str_replace('application/json', 'text/html', $contentType); $contentType = str_replace('application/', 'text/', $contentType); $this->response->setContentType($contentType); + $this->format = 'html'; return $data; } diff --git a/tests/system/API/ResponseTraitTest.php b/tests/system/API/ResponseTraitTest.php index e7639d21233b..2e3a3ad32e7e 100644 --- a/tests/system/API/ResponseTraitTest.php +++ b/tests/system/API/ResponseTraitTest.php @@ -83,6 +83,11 @@ public function __construct(&$request, &$response, &$formatter) $this->response = $response; $this->formatter = $formatter; } + + public function resetFormatter() + { + $this->formatter = null; + } }; return $controller; @@ -513,10 +518,23 @@ public function testResponseFormat() $controller->respond($data, 201); $this->assertStringStartsWith('application/json', $this->response->getHeaderLine('Content-Type')); + $this->assertEquals($this->formatter->format($data), $this->response->getJSON()); $controller->setResponseFormat('xml'); $controller->respond($data, 201); $this->assertStringStartsWith('application/xml', $this->response->getHeaderLine('Content-Type')); } + + public function testXMLResponseFormat() + { + $data = ['foo' => 'bar']; + $controller = $this->makeController(); + $controller->resetFormatter(); + $controller->setResponseFormat('xml'); + $controller->respond($data, 201); + + $xmlFormatter = new XMLFormatter(); + $this->assertEquals($xmlFormatter->format($data), $this->response->getXML()); + } }