2016-04-09 1 views
0

私はExceptionListenerを使用していますが、一部のコントローラでは、エラーをjsonレスポンスとしてフォーマットする必要があります。ExceptionListener内のルートオプションの取得

/** 
* @Route("/route/path", name="route_name", options={"response_type": "json"}) 
*/ 

と::私は@Route注釈にオプションを定義し、その後のExceptionListenerにそれを使用するだろうと思っ

class ExceptionListener 
{ 
    public function onKernelException(GetResponseForExceptionEvent $event) 
    { 
     // ... 
    } 
} 

が、マッチしたルートに関するあらゆる情報をGetResponseForExceptionEvent含まれていません。 ExceptionListener内にoptions配列を取得する方法はありますか?

ありがとうございました。

答えて

1

あなたは、あなたのクラスにrouterサービスを注入した場合、その後、あなたは

$route = $this->router->getRouteCollection()->get($routeName); 
とルートのインスタンスを取得することができます

$request = $event->getRequest(); 
$routeName = $request->attributes->get('_route'); 

と属性要求からのルート名を取得することができるはずです

ついに

$options = $route->getOptions(); 
echo $options['response_type'] 

use Symfony\Component\Routing\RouterInterface; 

class ExceptionListener 
{ 
    private $router; 

    public function __construct(RouterInterface $router) 
    { 
     $this->router = $router; 
    } 

    public function onKernelException(GetResponseForExceptionEvent $event) 
    { 
     $request = $event->getRequest(); 
     $route = $this->router->getRouteCollection()->get(
      $request->attributes->get('_route') 
     ); 

     $options = $route->getOptions(); 
     // $options['response_type']; 
    } 
} 
+0

すばやく詳細な回答をいただきありがとうございます。チャームのような作品:) – Karolis