Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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

This comment has been minimized.

Copy link

@Haehnchen Haehnchen commented Aug 25, 2013

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
You can’t perform that action at this time.