private function writeJson(
        ResponseInterface $response,
        $json,
        int $code = 200
    ): ResponseInterface {
        if ($json instanceof \JsonSerializable) {
            $json = $json->jsonSerialize();
        }

        if (is_array($json) && isset($json['status'])) {
            $code = $json['status'];
        }

        $response->getBody()->write(json_encode($json));

        return $response->withStatus($code)->withHeader(
            'Content-Type',
            'application/json'
        );
    }