开发 JSON 或 XML API 时不显示 WebDebugToolbar 的原因是工具栏设置为仅注入 HTML 类型的响应中。
为了克服这个问题,您可以在捆绑包中添加一个事件侦听器,它将JSON或XML响应转换为HTML。kernel.response
namespace Acme\APIBundle\Event\Listener;
use Symfony\Component\HttpKernel\Event\FilterResponseEvent;
class ConvertToHtmlResponse {
public function onKernelResponse(FilterResponseEvent $event) {
if (!$event->isMasterRequest()) {
return;
}
$request = $event->getRequest();
// Only send back HTML if the requestor allows it
if (!$request->headers->has('Accept') || (false === strpos($request->headers->get('Accept'), 'text/html'))) {
return;
}
$response = $event->getResponse();
switch ($request->getRequestFormat()) {
case 'json':
$prettyprint_lang = 'js';
$content = json_encode(json_decode($response->getContent()), JSON_PRETTY_PRINT);
break;
case 'xml':
$prettyprint_lang = 'xml';
$content = $response->getContent();
break;
default:
return;
}
$response->setContent(
'<html><body>' .
'<pre class="prettyprint lang-' . $prettyprint_lang . '">' .
htmlspecialchars($content) .
'</pre>' .
'<script src="https://cdnjs.cloudflare.com/ajax/libs/prettify/r298/run_prettify.min.js"></script>' .
'</body></html>'
);
// Set the request type to HTML
$response->headers->set('Content-Type', 'text/html; charset=UTF-8');
$request->setRequestFormat('html');
// Overwrite the original response
$event->setResponse($response);
}
}
然后,您只需要将捆绑包中的侦听器注册到事件中,我建议您仅在开发环境配置中执行此操作。kernel.response
services:
# ...
acme.listener.kernel.convert_html:
class: Acme\APIBundle\Event\Listener\ConvertToHtmlResponse
tags:
- { name: kernel.event_listener, event: kernel.response }