Skip to content

Instantly share code, notes, and snippets.

@raphaelstolt
Created March 13, 2012 10:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save raphaelstolt/2028006 to your computer and use it in GitHub Desktop.
Save raphaelstolt/2028006 to your computer and use it in GitHub Desktop.
Only apply JSONP(adding) via a Silex after filter on configured routes
$app->after(function (Request $request, Response $response) {
$appl = $request->attributes->get('app');
if ($request->get('jsonp_callback') !== null
&& $request->getMethod() === 'GET')
{
/**
* Configured via ConfigServiceProvider (https://github.com/igorw/ConfigServiceProvider)
* Example:
*
* $config['jsonp_able_route_patterns'] = array(
* '/{query}',
* '/teaser/{amount}'
* );
*/
$jsonpAbleRoutePatterns = $appl['jsonp_able_route_patterns'];
$actualRouteKey = str_replace('GET_', '', $request->attributes->get('_route'));
$routes = $appl['routes']->all();
foreach ($routes as $routeKey => $route) {
$routeKey = str_replace('GET_', '', $routeKey);
if ($routeKey === $actualRouteKey
&& !in_array($route->getPattern(), $jsonpAbleRoutePatterns))
{
return;
}
}
$response->headers->set('Content-Type', 'application/javascript');
$response->setContent($request->get('jsonp_callback') . '(' . $response->getContent() . ');');
}
});
@Haehnchen
Copy link

or globally add it

$app->after(function (Request $request, Response $response) {
    if(($response instanceof \Symfony\Component\HttpFoundation\JsonResponse) && $request->get('jsonp_callback')) {
        $response->setCallback($request->get('jsonp_callback'));
    }
});

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment