事件监听器的响应类型

时间:2016-01-15 13:40:27

标签: php symfony

我有一个非常简单的控制器返回JSON响应:

<?php

namespace AppBundle\Controller;

use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\JsonResponse;

class DefaultController extends Controller
{

    /**
     * @Route("/", name="homepage")
     */
    public function indexAction(Request $request) : JsonResponse
    {
        return new JsonResponse(array('aaa'));
    }

}

Chrome控制台在标题中显示type/json,这是正确的。我想设置事件监听器将这些json响应转换为html并添加一些html标记,所以我创建了`AppBundle \ Event \ Listener'命名空间:

<?php

namespace AppBundle\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://google-code-prettify.googlecode.com/svn/loader/run_prettify.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);
    }

}

并将其添加到services.yml

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

问题是事件监听器中的$event -> getResponse()返回'html',监听器内的响应头也是html,控制器和方法是正确的。只有chrome控制台显示正确的标题。

怎么了?

0 个答案:

没有答案