Search code examples
ajaxfosrestbundlesymfony-3.4

How to check once for a whole bundle if $request->isXmlHttpRequest?


For a project, i use FOSrestbundle for every bundle and i have an ApiBundle where every route is called by ajax. On each action, i do this check:

if $request->isXmlHttpRequest() {
    throw ...
}

I look for a way to make this check only once for the whole bundle.

Thank you


Solution

  • I put here a solution for those want to do the same

    In every controller of the ApiBundle, i put this annotation the be sure every route name have the same 'api_' prefix

    /**
     * Class SomeController.
     *
     * @Route("/some", name="api_")
     */
    class SomeController extends Controller
    

    in a request event listener, i put this check on the KernelEvents::REQUEST event

    $request = $event->getRequest();
    
    if (!$event->isMasterRequest()) {
        return;
    }
    
    if ('api_' === substr($request->get('_route'), 0, 4) && !$request->isXmlHttpRequest()) {
        throw new MethodNotAllowedException(['ajax']);
    }