How to display the symfony profiler for API request made in the browser?

前端 未结 5 1039
-上瘾入骨i
-上瘾入骨i 2021-02-02 08:15

I\'m developing a REST api with Symfony2 + FOSRest bundle.

I would like to know if there is any way for a call to the api in dev mode (app_dev.php) from the

5条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-02-02 08:53

    The reason the WebDebugToolbar isn't displayed when developing a JSON or XML API is that the toolbar is set to only be injected into HTML-type responses.

    To overcome this you could add a kernel.response Event Listener in your Bundle which converts your JSON or XML responses into HTML.

    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(
          '' .
          '
    ' .
          htmlspecialchars($content) .
          '
    ' . '' . '' ); // 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); } }

    Then you just need to register the listener inside your bundle to the kernel.response event, which I suggest you do only in the dev environment config.

    services:
      # ...
      acme.listener.kernel.convert_html:
        class: Acme\APIBundle\Event\Listener\ConvertToHtmlResponse
        tags:
          - { name: kernel.event_listener, event: kernel.response }
    

提交回复
热议问题