Skip to content

Commit

Permalink
Merge pull request #3545 from caswell-wc/json-api-response
Browse files Browse the repository at this point in the history
Set response correctly for json API responses
  • Loading branch information
paulbalandan authored Nov 18, 2020
2 parents fa7f19a + 20351c0 commit 868438b
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 0 deletions.
14 changes: 14 additions & 0 deletions system/API/ResponseTrait.php
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}

Expand Down Expand Up @@ -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;
}
Expand Down
18 changes: 18 additions & 0 deletions tests/system/API/ResponseTraitTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,11 @@ public function __construct(&$request, &$response, &$formatter)
$this->response = $response;
$this->formatter = $formatter;
}

public function resetFormatter()
{
$this->formatter = null;
}
};

return $controller;
Expand Down Expand Up @@ -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());
}
}

0 comments on commit 868438b

Please sign in to comment.