First of all I'd like to note that such a requirement seems rather inconvenient. If the reponse is to be expected to have a body in JSON format, then the custom reason phrase could be easily defined just in there.
Response::httpCodes()
only works with the "old" front controller
That being said, generally this is possible, but when using the PSR compatible request/reponse components introduced with CakePHP 3.3, this is currently not directly supported, as custom reason phrases will not be passed over to the PSR compatible response. With the pre 3.3 dispatching mechanisms it will still work however, check the "old" application templates front controller (webroot/index.php
file).
Can be done easily again as of 3.4
As of CakePHP 3.4, Response::httpCodes()
is deprecated, and it will be removed in 4.0. Also as of 3.4, the CakePHP response class will be fully PSR-7 compatible, and you will be able to set statuses with custom reason phrases via the Response::withStatus()
method, like
return $this->response->withStatus(400, 'Bad Origin');
Have in mind that the PSR-7 compatible reponse objects are immutable! ie, if you wish to modify $this->response
in your controller for further use, you'd have to overwrite it, like:
$this->response = $this->response->withStatus(/* ... */);
Requires "workaround" in 3.3/3.4 transition
In the transition between 3.3 and 3.4, when using the PSR compatible front controller, you can add support for custom reason phrases by overriding Application::__invoke()
(the Application
class file is by default located in your apps src
folder.
You'd have to reimplement the BaseApplication::__invoke()
code, and pass over the reason phrase obtained from Response::httpCodes()
, something along the lines of:
use Cake\Http\RequestTransformer;
use Cake\Http\ResponseTransformer;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
// ...
public function __invoke(ServerRequestInterface $request, ResponseInterface $response, $next)
{
$cakeRequest = RequestTransformer::toCake($request);
$cakeResponse = ResponseTransformer::toCake($response);
$cakeResponse = $this->getDispatcher()->dispatch($cakeRequest, $cakeResponse);
$psrResponse = ResponseTransformer::toPsr($cakeResponse);
$status = $psrResponse->getStatusCode();
$httpCodes = $cakeResponse->httpCodes($status);
if ($httpCodes !== null && isset($httpCodes[$status])) {
return $psrResponse->withStatus($status, $httpCodes[$status]);
}
return $psrResponse;
}
See also