30 lines
696 B
PHP
30 lines
696 B
PHP
<?php
|
|||
|
|
|
||
|
|
declare(strict_types=1);
|
||
|
|
|
||
|
|
namespace App\Http\Controllers;
|
||
|
|
|
||
|
|
use Psr\Http\Message\ResponseInterface as Response;
|
||
|
|
|
||
|
|
/**
|
||
|
|
* Shared helpers for HTTP controllers.
|
||
|
|
*/
|
||
|
|
abstract class Controller
|
||
|
|
{
|
||
|
|
/**
|
||
|
|
* Write a JSON body and return the response with the appropriate headers.
|
||
|
|
*
|
||
|
|
* @param array<string, mixed> $data
|
||
|
|
*/
|
||
|
|
protected function json(Response $response, array $data, int $status = 200): Response
|
||
|
|
{
|
||
|
|
$response->getBody()->write(
|
||
|
|
(string) json_encode($data, JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT)
|
||
|
|
);
|
||
|
|
|
||
|
|
return $response
|
||
|
|
->withHeader('Content-Type', 'application/json')
|
||
|
|
->withStatus($status);
|
||
|
|
}
|
||
|
|
}
|