Change jsonp string to json
public static changeJsonpToJson ( $body, $callback ) : string | ||
$body | ||
$callback | ||
return | string |
/** * @param DispatcherInterface $dispatcher * @return bool true if cache missed(intercepter injected), false if cache hit(intercepter not injected) */ public function injectInterceptor(DispatcherInterface $dispatcher) { /** * @var \Phalcon\DI $di */ $di = $dispatcher->getDI(); $config = $di->getConfig(); // cache is disable if (!$config->cache->enable) { return true; } $params = $this->getInterceptorParams($dispatcher); if (!$params) { return true; } $methodsAllow = $params['methods']; /** * @var \Phalcon\Http\Request $request */ $request = $di->getRequest(); $requestMethod = strtolower($request->getMethod()); if (false === in_array($requestMethod, $methodsAllow)) { return true; } /** * @var \Phalcon\Cache\Backend $cache */ $cache = $di->getViewCache(); $interceptResult = $this->intercept($request, $params, $cache); //cache key matched, response already prepared if (true === $interceptResult) { $di->getResponse()->send(); return false; } $self = $this; //Cache missed /** * @var \Phalcon\Events\Manager $eventsManager */ $eventsManager = $di->getEventsManager(); $eventsManager->attach('application:beforeSendResponse', function ($event, $application) use($self, $params) { $bodyKey = $self->getCacheBodyKey(); $headersKey = $self->getCacheHeadersKey(); if (!$bodyKey || !$headersKey) { return true; } /** * @var \Phalcon\Http\ResponseInterface $response */ $response = $application->getDI()->getResponse(); $body = $response->getContent(); $headers = $response->getHeaders()->toArray(); $headersCache = array(); if ($headers) { //Filter allowed headers $headersCache = array_intersect_key($headers, array_flip($self->getCachableHeaderKeys())); } $headersCache[Dispatch::CACHE_HEADER_FLAG] = date(DATE_ISO8601); $cache = $application->getDI()->getViewCache(); $request = $application->getDI()->getRequest(); $callbackKey = $params['jsonp_callback_key']; //Jsonp change to json if ($params['format'] == 'jsonp' && $callbackKey && ($callbackValue = $request->getQuery($callbackKey))) { $body = Dispatch::changeJsonpToJson($body, $callbackValue); } $cache->save($bodyKey, $body, $params['lifetime']); //$cache->save($headersKey, serialize($headersCache), $params['lifetime']); $cache->save($headersKey, json_encode($headersCache), $params['lifetime']); return true; }); return true; }
public function testJsonpToJson() { $this->assertEquals('', DispatchInterceptor::changeJsonpToJson('', 'abc')); $this->assertEquals('{"foo":"bar"}', DispatchInterceptor::changeJsonpToJson('{"foo":"bar"}', 'abc')); $this->assertEquals('{"foo":"bar"}', DispatchInterceptor::changeJsonpToJson('abc({"foo":"bar"})', 'abc')); $this->assertEquals('{"foo":"bar"}', DispatchInterceptor::changeJsonpToJson(' abc({"foo":"bar"}); ', 'abc')); }