setCache() public method

Available options are: etag, last_modified, max_age, s_maxage, private, and public.
public setCache ( array $options ) : Response
$options array An array of cache options
return Response
 /**
  * @param Request $request
  * @param $storageKey
  *
  * @return Response
  */
 protected function createFileResponse(Request $request, $storageKey)
 {
     $response = new Response();
     $parts = explode('/', $storageKey);
     $file = $this->getFile($parts[0]);
     if (!$file) {
         return $response->setContent('File not found.')->setStatusCode(Response::HTTP_NOT_FOUND);
     }
     if ($request->get('dl') !== null) {
         $filename = $file->getFilename();
         if (count($parts) > 1) {
             $filename = $parts[count($parts) - 1];
         }
         $filenameFallback = filter_var($filename, FILTER_SANITIZE_URL);
         if ($filenameFallback != $filename) {
             $guesser = ExtensionGuesser::getInstance();
             $extension = filter_var($guesser->guess($file->getMimeType()) ?: $file->getExtension(), FILTER_SANITIZE_URL);
             $filenameFallback = $file->getStorageKey() . ($extension ? '.' . $extension : '');
         }
         $response->headers->set('Content-Disposition', $response->headers->makeDisposition(ResponseHeaderBag::DISPOSITION_ATTACHMENT, $filename, $filenameFallback));
     } else {
         $response->setCache(array('etag' => $file->getStorageKey(), 'last_modified' => $file->getCreatedAt()));
         if ($response->isNotModified($request)) {
             return $response;
         }
     }
     $response->setContent($file->getContents());
     $response->headers->set('Content-type', $file->getMimeType());
     $response->headers->set('Content-length', $file->getSize());
     return $response;
 }
 public function intercept(MethodInvocation $invocation)
 {
     /*
      * First let's make sure we can even bother caching this
      * if we can't then just return the controller response
      */
     if (!$this->decider->decide()) {
         return $invocation->proceed();
     }
     /* @var $controller ResourceController */
     $controller = $invocation->object;
     /* @var $request Request */
     $request = $invocation->arguments[0];
     // Current Resource
     $resource = $controller->findOr404($request);
     // Cache Options
     $options = $request->attributes->get('_sylius', []);
     $cacheOptions = array_key_exists('cache', $options) ? $options['cache'] : [];
     // Build the actual cache options since we'll need to use it twice
     $this->parser->process($cacheOptions, $resource);
     // Create a preliminary response to see if it is already cached
     $cachedResponse = new Response();
     $cachedResponse->setCache($cacheOptions);
     if ($cachedResponse->isNotModified($request)) {
         return $cachedResponse;
     }
     // If not we take the response back from the controller and modify it again
     $controllerResponse = $invocation->proceed();
     $controllerResponse->setCache($cacheOptions);
     return $controllerResponse;
 }
Beispiel #3
0
 /**
 * Aby powstrzymać przed downloadem, tak aby otwarło w przeglądarce:
    return DownloadFile::downloadGenerated($pdfContent, $filename, array(
        'Content-Type' => 'application/pdf',
        'Content-Disposition' => false
    ));
 
 * @param type $data
 * @param type $filename
 * @param type $headers
 * @return type
 */
 public static function downloadGenerated($data, $filename, $headers = array())
 {
     $response = new Response();
     if (!is_array($headers)) {
         $headers = array();
     }
     $disposition = $response->headers->makeDisposition(ResponseHeaderBag::DISPOSITION_ATTACHMENT, pathinfo($filename, PATHINFO_BASENAME));
     $headers = array_merge(array('Content-Type' => 'application/octet-stream', 'Content-Disposition' => $disposition), $headers);
     //niechginie($headers);
     foreach ($headers as $key => &$value) {
         $response->headers->set($key, $value);
     }
     return $response->setCache(array('last_modified' => new DateTime(), 'max_age' => 0, 's_maxage' => 0, 'private' => false, 'public' => true))->setContent($data);
 }
 /**
  * @Route(
  *     "/bushidoioqrcode/{text}.{_format}",
  *     name="bushidoio_qrcode_url",
  *     requirements={
  *         "text" = ".+"
  *     },
  *     defaults={
  *         "_format": "png"
  *     }
  * )
  * @Method("GET")
  * @param Request $request The Request object
  * @param string $text The text to be converted to a QRCode image
  * @return Response The response with the image
  */
 public function qrcodeAction(Request $request, $text = '')
 {
     $format = $request->getRequestFormat();
     $size = $request->query->get('size');
     if (is_null($size)) {
         $size = 3;
     } else {
         $size = intval($size);
     }
     $contentType = '';
     switch ($format) {
         case 'png':
             $contentType = 'image/png';
             break;
             //case 'jpg':
             //    $contentType = 'image/jpeg';
             //    break;
         //case 'jpg':
         //    $contentType = 'image/jpeg';
         //    break;
         default:
             $contentType = '';
             break;
     }
     if ($text === '' || $contentType === '' || !is_int($size) || $size < 1 || $size > 40) {
         throw new HttpException(400);
     }
     $qrCodeService = $this->get('bushidoio_qrcode');
     $qrCode = $qrCodeService->getQRCode(urldecode($text), $size, $format);
     $localFilePath = $qrCode['filePath'];
     try {
         $content = file_get_contents($localFilePath);
     } catch (\Exception $e) {
         throw new NotFoundHttpException();
     }
     $response = new Response();
     $response->headers->set('Content-Type', $contentType);
     $response->headers->set('Content-Disposition', 'attachment;filename="' . urlencode($text) . '.' . $format . '"');
     $response->setContent($content);
     $response->setCache(array('max_age' => $this->http_max_age, 's_maxage' => $this->https_max_age, 'private' => false, 'public' => true));
     return $response;
 }
 public function testSetCache()
 {
     $response = new Response();
     //array('etag', 'last_modified', 'max_age', 's_maxage', 'private', 'public')
     try {
         $response->setCache(array("wrong option" => "value"));
         $this->fail('->setCache() throws an InvalidArgumentException if an option is not supported');
     } catch (\Exception $e) {
         $this->assertInstanceOf('InvalidArgumentException', $e, '->setCache() throws an InvalidArgumentException if an option is not supported');
         $this->assertContains('"wrong option"', $e->getMessage());
     }
     $options = array('etag' => '"whatever"');
     $response->setCache($options);
     $this->assertEquals($response->getEtag(), '"whatever"');
     $now = new \DateTime();
     $options = array('last_modified' => $now);
     $response->setCache($options);
     $this->assertEquals($response->getLastModified()->getTimestamp(), $now->getTimestamp());
     $options = array('max_age' => 100);
     $response->setCache($options);
     $this->assertEquals($response->getMaxAge(), 100);
     $options = array('s_maxage' => 200);
     $response->setCache($options);
     $this->assertEquals($response->getMaxAge(), 200);
     $this->assertTrue($response->headers->hasCacheControlDirective('public'));
     $this->assertFalse($response->headers->hasCacheControlDirective('private'));
     $response->setCache(array('public' => true));
     $this->assertTrue($response->headers->hasCacheControlDirective('public'));
     $this->assertFalse($response->headers->hasCacheControlDirective('private'));
     $response->setCache(array('public' => false));
     $this->assertFalse($response->headers->hasCacheControlDirective('public'));
     $this->assertTrue($response->headers->hasCacheControlDirective('private'));
     $response->setCache(array('private' => true));
     $this->assertFalse($response->headers->hasCacheControlDirective('public'));
     $this->assertTrue($response->headers->hasCacheControlDirective('private'));
     $response->setCache(array('private' => false));
     $this->assertTrue($response->headers->hasCacheControlDirective('public'));
     $this->assertFalse($response->headers->hasCacheControlDirective('private'));
 }
 /**
  * Create Response object for resource.
  *
  * @param string $filename valid filepath (file exists and readable)
  *
  * @return Response
  */
 private function createResourceResponse($filename)
 {
     $response = new Response();
     $filestats = stat($filename);
     $response->headers->set('Content-Type', MimeType::getInstance()->guess($filename));
     $response->headers->set('Content-Length', $filestats['size']);
     $response->setCache(array('etag' => basename($filename), 'last_modified' => new \DateTime('@' . $filestats['mtime']), 'public' => 'public'));
     $response->setContent(file_get_contents($filename));
     return $response;
 }
 /**
  * Set cache headers on response.
  *
  * @param Response $response
  * @param array    $directives
  * @param bool     $overwrite  Whether to keep existing cache headers or to overwrite them
  */
 private function setCache(Response $response, array $directives, $overwrite)
 {
     if ($overwrite) {
         $response->setCache($directives);
         return;
     }
     if ('no-cache' === $response->headers->get('cache-control')) {
         // this single header is set by default. if its the only thing, we override it.
         $response->setCache($directives);
         return;
     }
     foreach (array_keys($this->supportedDirectives) as $key) {
         $directive = str_replace('_', '-', $key);
         if ($response->headers->hasCacheControlDirective($directive)) {
             $directives[$key] = $response->headers->getCacheControlDirective($directive);
         }
         if ('public' === $directive && $response->headers->hasCacheControlDirective('private') || 'private' === $directive && $response->headers->hasCacheControlDirective('public')) {
             unset($directives[$key]);
         }
     }
     $response->setCache($directives);
 }
Beispiel #8
0
            }
            $response = new Response($content, 200);
            $response->headers->add(array('Content-Type' => 'image/jpeg'));
            $lastModified = new \Datetime();
            $lastModified->setTimestamp(filemtime($img));
            $response->setCache(array('last_modified' => new \Datetime(), 'max_age' => 0, 's_maxage' => 0, 'public' => false));
            return $response;
        } else {
            $response = new Response('', 404);
            $response->setCache(array('last_modified' => new \Datetime(), 'max_age' => 0, 's_maxage' => 0, 'public' => false));
            return $response;
        }
    } else {
        if ($actualReferer) {
            $response = new Response('', 403);
            $response->setCache(array('last_modified' => new \Datetime(), 'max_age' => 0, 's_maxage' => 0, 'public' => false));
            return $response;
        } else {
            return new RedirectResponse($urlGenerator->generate('home'), 301);
        }
    }
})->bind('sliderImg');
$app->get((USE_LOCALE ? '/{_locale}' : '') . '/{sliderName}', function ($sliderName) use($twig, $urlGenerator) {
    $sliderName = rtrim($sliderName, '/');
    if ($sliderName === 'home') {
        return new RedirectResponse($urlGenerator->generate('home'));
    }
    if (!file_exists(SLIDESDIR . $sliderName . '/parameters.yml')) {
        throw new NotFoundHttpException('slider_not_found');
    }
    $slides = Yaml::parse(SLIDESDIR . $sliderName . '/parameters.yml');
 /**
  * Request the font-face CSS file listing available fonts.
  *
  * @param Symfony\Component\HttpFoundation\Request $request
  *
  * @return Symfony\Component\HttpFoundation\Response
  */
 public function fontFacesAction(Request $request)
 {
     $repository = $this->getService('em')->getRepository('RZ\\Roadiz\\Core\\Entities\\Font');
     $lastMod = $repository->getLatestUpdateDate();
     $response = new Response('', Response::HTTP_NOT_MODIFIED, ['content-type' => 'text/css']);
     $response->setCache(['last_modified' => new \DateTime($lastMod), 'max_age' => 60 * 60 * 2, 'public' => false]);
     if ($response->isNotModified($request)) {
         return $response;
     }
     $fonts = $repository->findAll();
     $fontOutput = [];
     foreach ($fonts as $font) {
         $fontOutput[] = $font->getViewer()->getCSSFontFace($this->getService('csrfTokenManager'));
     }
     $response->setContent(implode(PHP_EOL, $fontOutput));
     $response->setStatusCode(Response::HTTP_OK);
     return $response;
 }
 /**
  * Set cache settings (simple for now)
  *
  * @param Fideloper\ResourceCache\Resource\ResourceInterface
  * @param Symfony\Component\HttpFoundation\Response
  * @return Symfony\Component\HttpFoundation\Response
  */
 protected function setCache(ResourceInterface $resource, HttpResponse $response)
 {
     $response->setCache(array('etag' => $resource->getEtag(), 'last_modified' => $resource->getLastUpdated()));
     return $response;
 }
Beispiel #11
0
 /**
  * @param WidgetInterface $widget
  *
  * @return Response
  */
 protected function getWidgetResponse(WidgetInterface $widget)
 {
     $response = new Response();
     $response->setCache($this->getStrategy($widget)->getCacheOptions($widget));
     return $response;
 }