setMaxAge() public method

This methods sets the Cache-Control max-age directive.
public setMaxAge ( integer $value ) : Response
$value integer Number of seconds
return Response
Example #1
0
 public function testDisableCache()
 {
     // disable cache
     $this->structure->getCacheLifeTime()->willReturn(0);
     $this->response->setPublic()->shouldNotBeCalled();
     $this->response->setMaxAge($this->maxAge)->shouldNotBeCalled();
     $this->response->setSharedMaxAge($this->sharedMaxAge)->shouldNotBeCalled();
     $this->handler->updateResponse($this->response->reveal(), $this->structure->reveal());
 }
Example #2
0
 public function indexAction($campaignHash, $platformHash, $isNextButton)
 {
     if ($campaignHash === 'next') {
         $campaign = null;
     } else {
         $campaignRepo = $this->em->getRepository('VifeedCampaignBundle:Campaign');
         $campaign = $campaignRepo->findOneBy(['hashId' => $campaignHash]);
         if (!$campaign) {
             throw $this->createNotFoundException('The video is not found');
         }
         if (!$campaign->getUser()->isEnabled()) {
             throw $this->createNotFoundException();
         }
     }
     $platformRepo = $this->em->getRepository('VifeedPlatformBundle:Platform');
     $platform = $platformRepo->findOneBy(['hashId' => $platformHash]);
     if ($platform && !$platform->getUser()->isEnabled()) {
         throw $this->createNotFoundException();
     }
     $videoHash = $campaign ? $campaign->getHash() : null;
     $meta = $this->getMeta($campaign);
     $meta['og:url'] = $this->get('router')->generate('vifeed_video_promo_homepage', ['platformHash' => $platformHash, 'campaignHash' => $campaignHash, 'domain' => $this->container->getParameter('promo_domain')]);
     $response = new Response();
     $response->setPublic();
     $response->setMaxAge(60 * 60 * 3);
     return $this->render('VifeedVideoPromoBundle:Default:index.html.twig', ['platformHash' => $platformHash, 'campaignHash' => $campaignHash, 'campaignTitle' => $campaign ? $campaign->getName() : null, 'campaignDescription' => $campaign ? $campaign->getDescription() : null, 'videoHash' => $videoHash, 'nextBtn' => $isNextButton, 'meta' => $meta], $response);
 }
    /**
     * 
     *
     * @param Event $event An Event instance
     */
    public function filter(Event $event, Response $response)
    {
        if (!$configuration = $event->get('request')->attributes->get('_cache')) {
            return $response;
        }

        if (!$response->isSuccessful()) {
            return $response;
        }

        if (null !== $configuration->getSMaxAge()) {
            $response->setSharedMaxAge($configuration->getSMaxAge());
        }

        if (null !== $configuration->getMaxAge()) {
            $response->setMaxAge($configuration->getMaxAge());
        }

        if (null !== $configuration->getExpires()) {
            $date = \DateTime::create(\DateTime::createFromFormat('U', $configuration->getExpires(), new \DateTimeZone('UTC')));

            $response->setLastModified($date);
        }

        return $response;
    }
 /**
  * {@inheritdoc}
  */
 public function update(Response $response)
 {
     // if we have no embedded Response, do nothing
     if (0 === $this->embeddedResponses) {
         return;
     }
     // Remove validation related headers in order to avoid browsers using
     // their own cache, because some of the response content comes from
     // at least one embedded response (which likely has a different caching strategy).
     if ($response->isValidateable()) {
         $response->setEtag(null);
         $response->setLastModified(null);
         $this->cacheable = false;
     }
     if (!$this->cacheable) {
         $response->headers->set('Cache-Control', 'no-cache, must-revalidate');
         return;
     }
     $this->ttls[] = $response->getTtl();
     $this->maxAges[] = $response->getMaxAge();
     if (null !== ($maxAge = min($this->maxAges))) {
         $response->setSharedMaxAge($maxAge);
         $response->headers->set('Age', $maxAge - min($this->ttls));
     }
     $response->setMaxAge(0);
 }
 function apiIntroAction()
 {
     $response = new Response();
     $response->setPublic();
     $response->setMaxAge($this->container->getParameter('cache_expiration'));
     return $this->render('AppBundle:Default:apiIntro.html.twig', array("pagetitle" => "API", "game_name" => $this->container->getParameter('game_name'), "publisher_name" => $this->container->getParameter('publisher_name')), $response);
 }
Example #6
0
 /**
  * Cache the response 1 year (31536000 sec)
  */
 protected function cacheResponse(Response $response)
 {
     $response->setSharedMaxAge(31536000);
     $response->setMaxAge(31536000);
     $response->setExpires(new \DateTime('+1 year'));
     return $response;
 }
 public function importAction()
 {
     $response = new Response();
     $response->setPublic();
     $response->setMaxAge($this->container->getParameter('long_cache'));
     return $this->render('NetrunnerdbBuilderBundle:Builder:directimport.html.twig', array('pagetitle' => "Import a deck", 'locales' => $this->renderView('NetrunnerdbCardsBundle:Default:langs.html.twig')), $response);
 }
 /**
  * Update a valid non cacheable Response with http cache headers
  *
  * @see http://symfony.com/fr/doc/current/book/http_cache.html
  */
 public function handleResponse(Response $response)
 {
     // do not handle invalid response
     if (!$response->isOk()) {
         return $response;
     }
     // do not handle response with http cache headers
     if ($response->isCacheable()) {
         return $response;
     }
     // seek for optional configuration
     $this->readRoutingConfiguration();
     // mark the response as private
     $response->setPrivate();
     // set the private or shared max age
     $response->setMaxAge($this->duration);
     $response->setSharedMaxAge($this->duration);
     // set expires
     $date = new \DateTime();
     $date->modify(sprintf('+%d seconds', $this->duration));
     $response->setExpires($date);
     // set a custom Cache-Control directive
     $response->headers->addCacheControlDirective('must-revalidate', true);
     return $response;
 }
 /**
  * Get the details of a person.
  *
  * @param int $id The ID of the person as assigned by MyAnimeList
  *
  * @return View
  */
 public function getAction($id)
 {
     // http://myanimelist.net/people/#{id}
     $downloader = $this->get('atarashii_api.communicator');
     try {
         $personDetails = $downloader->fetch('/people/' . $id);
     } catch (Exception\CurlException $e) {
         return $this->view(array('error' => 'network-error'), 500);
     } catch (Exception\ClientErrorResponseException $e) {
         $personDetails = $e->getResponse();
     }
     if (strpos($personDetails, 'This page doesn\'t exist') !== false) {
         return $this->view(array('error' => 'not-found'), 200);
     } else {
         $person = PersonParser::parse($personDetails);
         $response = new Response();
         $response->setPublic();
         $response->setMaxAge(86400);
         //One day
         $response->headers->addCacheControlDirective('must-revalidate', true);
         //Also, set "expires" header for caches that don't understand Cache-Control
         $date = new \DateTime();
         $date->modify('+172800 seconds');
         //two days
         $response->setExpires($date);
         $view = $this->view($person);
         $view->setResponse($response);
         $view->setStatusCode(200);
         return $view;
     }
 }
 function apidocAction()
 {
     $response = new Response();
     $response->setPublic();
     $response->setMaxAge($this->container->getParameter('cache_expiration'));
     return $this->render('AppBundle:Default:apidoc.html.twig', array("pagetitle" => "API documentation"), $response);
 }
Example #11
0
 private function getResponse(Request $request, $name, array $files, $content_type)
 {
     if (!isset($files[$name])) {
         return new Response('Not Found', 404, array('Content-Type' => 'text/plain'));
     }
     $file = $files[$name];
     $response = new Response();
     $response->setPublic();
     $response->setMaxAge(self::EXPIRED_TIME);
     $response->setSharedMaxAge(self::EXPIRED_TIME);
     $response->headers->set('Content-Type', $content_type);
     // set a custom Cache-Control directive
     $response->headers->addCacheControlDirective('must-revalidate', true);
     $date = new \DateTime();
     $date->setTimestamp(strtotime($this->container->getParameter('sf.version')));
     $response->setETag($date->getTimestamp());
     $response->setLastModified($date);
     if ($response->isNotModified($request)) {
         return $response;
     }
     if (!file_exists($file)) {
         throw new \Exception(sprintf("file `%s`, `%s` not exists", $name, $file));
     }
     $response->setContent(file_get_contents($file));
     return $response;
 }
 /**
  * Set response max age
  * 
  * @param Response $response
  * @param int      $maxAge
  */
 protected function setResponseMaxAge(Response $response, $maxAge)
 {
     if (-1 === $maxAge) {
         $maxAge = 2629743;
     }
     $response->setMaxAge($maxAge);
 }
Example #13
0
 /**
  * @Route("/catalog/fulltree", name="spb_shop_catalog_fulltree")
  */
 public function fullTreeAction()
 {
     $em = $this->getDoctrine()->getManager();
     $repo = $em->getRepository('SpbShopBundle:Category');
     $controller = $this;
     $options = array('decorate' => true, 'rootOpen' => '<ul class="dropdown-menu">', 'rootClose' => '</ul>', 'childOpen' => function ($child) {
         if ($child['rgt'] - $child['lft'] == 1) {
             return '<li>';
         } else {
             return '<li class="dropdown-submenu">';
         }
     }, 'childClose' => '</li>', 'nodeDecorator' => function ($node) use(&$controller) {
         return '<a href="' . $controller->generateUrl('spb_shop_catalog_category', array('slug' => $node['slug'], 'tag' => $node['tag'])) . '">' . $node['title'] . '</a>';
     });
     $htmlTree = $repo->childrenHierarchy(null, false, $options);
     $response = new Response($htmlTree);
     // пометить ответ как public или private
     $response->setPublic();
     //$response->setPrivate();
     //
     // установить max age для private и shared ответов
     $response->setMaxAge(6000);
     $response->setSharedMaxAge(6000);
     // установить специальную директиву Cache-Control
     $response->headers->addCacheControlDirective('must-revalidate', true);
     return $response;
 }
Example #14
0
 /**
  * @Route("/feed")
  */
 public function feedAction()
 {
     $em = $this->getDoctrine()->getManager();
     $manager = $this->getDoctrine()->getManager();
     $core = $this->getParameter('core');
     $dql = "SELECT p, pTrans FROM BlogBundle:Post p JOIN p.translations pTrans ORDER BY p.created DESC";
     $entities = $manager->createQuery($dql)->getResult();
     $rssfeed = '<?xml version="1.0" encoding="ISO-8859-1"?>';
     $rssfeed .= '<rss version="2.0">';
     $rssfeed .= '<channel>';
     $rssfeed .= '<title>Kundalini Woman RSS feed</title>';
     $rssfeed .= '<link>http://www.undaliniwoman.com</link>';
     $rssfeed .= '<description>This is an example Kundalini Woman RSS feed</description>';
     $rssfeed .= '<language>en-us</language>';
     $rssfeed .= '<copyright>Copyright (C) 2009 mywebsite.com</copyright>';
     foreach ($entities as $value) {
         $rssfeed .= '<item>';
         $rssfeed .= '<title>' . utf8_decode($value->getTitle()) . '</title>';
         $rssfeed .= '<description>' . utf8_decode($value->getDescription()) . '</description>';
         $rssfeed .= '<link>' . $core['server_base_url'] . $this->generateUrl('blog_blog_show', array('slug' => $value->getSlug())) . '</link>';
         $rssfeed .= '<pubDate>' . $value->getCreated()->format("D, d M Y H:i:s O") . '</pubDate>';
         $rssfeed .= '</item>';
     }
     $rssfeed .= '</channel>';
     $rssfeed .= '</rss>';
     $response = new Response($rssfeed);
     $response->headers->set('Content-Type', 'application/rss+xml');
     $response->setPublic();
     $response->setMaxAge(3600);
     $now = new DateTime();
     $response->setLastModified($now);
     return $response;
 }
Example #15
0
 public function indexAction()
 {
     $response = new Response();
     $response->setMaxAge(60);
     $response->setStatusCode(Response::HTTP_OK);
     return $response;
 }
Example #16
0
 /**
  * Creates a Symfony response, and apply appropriate caching headers
  * @param $config array
  * @param $image string
  * @return Response
  */
 protected function generateResponse($config, $image)
 {
     $response = new Response($image, 200, array('Content-Type' => 'image/png'));
     $response->setPublic();
     $response->setMaxAge($config['time']);
     $response->setSharedMaxAge($config['time']);
     return $response;
 }
 /**
  * {@inheritdoc}
  */
 public function deliverData($data, $filename, $mimeType, $disposition = self::DISPOSITION_INLINE, $cacheDuration = 0)
 {
     $response = new Response($data);
     $response->headers->set('Content-Disposition', $response->headers->makeDisposition($disposition, $this->sanitizeFilename($filename), $this->sanitizeFilenameFallback($filename)));
     $response->headers->set('Content-Type', $mimeType);
     $response->setMaxAge($cacheDuration);
     return $response;
 }
Example #18
0
 public function setLastModified($timestamp = 0, $max_age = 0)
 {
     $time = new \DateTime('@' . $timestamp);
     $etag = md5($this->builder->getTheme()->getDir() . $this->builder->getStyle() . '|' . $timestamp . '|' . $max_age);
     $this->response->headers->addCacheControlDirective('must-revalidate', true);
     $this->response->setLastModified($time);
     $this->response->setEtag($etag);
     $this->response->setMaxAge($max_age);
 }
 function rulesAction()
 {
     $response = new Response();
     $response->setPublic();
     $response->setMaxAge($this->container->getParameter('long_cache'));
     $page = $this->get('cards_data')->replaceSymbols($this->renderView('NetrunnerdbCardsBundle:Default:rules.html.twig'));
     $response->setContent($page);
     return $response;
 }
 public function getResponse()
 {
     global $CONFIG;
     $response = new Response($this->getContents());
     $response->headers->set('Content-Type', 'application/xml');
     $response->setPublic();
     $response->setMaxAge($CONFIG->cacheFeedsInSeconds);
     return $response;
 }
 /**
  * @Method("GET")
  * @Route("/", name="homepage", options={"sitemap" = true})
  */
 public function defaultAction()
 {
     $response = new Response();
     $response->setPublic();
     $response->setMaxAge(60);
     $response->setSharedMaxAge(60);
     $response->setContent($this->renderView('page/homepage.html.twig'));
     return $response;
 }
Example #22
0
 public function importAction()
 {
     $response = new Response();
     $response->setPublic();
     $response->setMaxAge($this->container->getParameter('cache_expiration'));
     $factions = $this->getDoctrine()->getRepository('AppBundle:Faction')->findAll();
     return $this->render('AppBundle:Builder:directimport.html.twig', array('pagetitle' => "Import a deck", 'factions' => array_map(function ($faction) {
         return ['code' => $faction->getCode(), 'name' => $faction->getName()];
     }, $factions)), $response);
 }
 /**
  * List comments from a certain contentId
  *
  * @param \Symfony\Component\HttpFoundation\Request $request
  * @param $contentId id from current content
  * @param $locationId
  * @param array $params
  * @return Response
  */
 public function getCommentsAction($contentId, $locationId, $params = array())
 {
     $response = new Response();
     $response->setMaxAge($this->container->getParameter('pvr_ezcomment.maxage'));
     $response->headers->set('X-Location-Id', $locationId);
     $data = $this->container->get('pvr_ezcomment.service')->getComments($locationId, $contentId);
     $data += array('params' => $params);
     $template = isset($params['template']) ? $params['template'] : 'PvrEzCommentBundle:blog:list_comments.html.twig';
     return $this->render($template, $data, $response);
 }
Example #24
0
 public static function createFromImage(Image $image, $status, $maxage = 3600, $smaxage = 3600)
 {
     $response = new Response((string) $image, $status);
     $response->headers->set('Content-Type', 'image/svg+xml;charset=utf-8');
     $contentDisposition = $response->headers->makeDisposition(ResponseHeaderBag::DISPOSITION_INLINE, $image->getOutputFileName());
     $response->headers->set('Content-Disposition', $contentDisposition);
     $response->setMaxAge($maxage);
     $response->setSharedMaxAge($smaxage);
     return $response;
 }
 public function getResponse()
 {
     global $CONFIG;
     $response = new Response($this->getContents());
     $response->headers->set('Content-Type', 'text/csv');
     $response->headers->set('Content-disposition', 'attachment;filename=events.csv');
     $response->setPublic();
     $response->setMaxAge($CONFIG->cacheFeedsInSeconds);
     return $response;
 }
 /**
  * @param Request $request
  * @param Response $response
  * @return Response
  */
 public function setCacheHeaders(Request $request, Response $response)
 {
     $response->setMaxAge($this->defaultMaxAge);
     if ($this->isLoggedIn($request) || $this->isWordpressAdminPage($request)) {
         $response->setPrivate();
     } else {
         $response->setPublic();
     }
     return $response;
 }
Example #27
0
 private function updateHeaders(Response $response, Response $subResponse)
 {
     if ($this->response->isCacheable() && $subResponse->isCacheable()) {
         $maxAge = (int) min($response->headers->getCacheControlDirective('max-age'), $subResponse->headers->getCacheControlDirective('max-age'));
         $sMaxAge = (int) min($response->headers->getCacheControlDirective('s-maxage'), $subResponse->headers->getCacheControlDirective('s-maxage'));
         $response->setSharedMaxAge($sMaxAge);
         $response->setMaxAge($maxAge);
     } else {
         $this->response->headers->set('Cache-Control', 'no-cache, must-revalidate');
     }
 }
Example #28
0
 /**
  * Set the appripriate HTTP cache headers
  *
  * @param \DateTime $lastModified The last time the resource was modified.
  * @param String    $eTag         Unique eTag for the resource.
  * @param Integer   $maxAge       The max age (in seconds).
  * @return Void
  */
 private function setHttpCacheHeaders(\DateTime $lastModified, $eTag, $maxAge)
 {
     $this->response->setMaxAge($maxAge);
     $this->response->setPublic();
     if ($this->maxAge === 0) {
         $this->response->headers->set('Cache-Control', 'no-cache');
         return;
     }
     $this->response->setLastModified($lastModified);
     $this->response->setEtag($eTag);
 }
 /**
  * Updates the Response HTTP headers based on the embedded Responses.
  *
  * @param Response $response
  */
 public function update(Response $response)
 {
     if (!$this->cacheable) {
         $response->headers->set('Cache-Control', 'no-cache, must-revalidate');
         return;
     }
     $maxAge = min($this->maxAges);
     $response->setSharedMaxAge($maxAge);
     $response->setMaxAge(0);
     $response->headers->set('Age', $maxAge - min($this->ttls));
 }
 /**
  * Set response max age
  *
  * @param Response $response
  * @param string   $status
  * @param int      $maxAge
  * @param bool     $hasEsi
  */
 protected function setResponseMaxAge(Response $response, $status, $maxAge, $hasEsi)
 {
     if (-1 === $maxAge) {
         $maxAge = 2629743;
     }
     if (true === $hasEsi && CacheableInterface::CACHE_PUBLIC == $status) {
         $response->setSharedMaxAge($maxAge);
     } else {
         $response->setMaxAge($maxAge);
     }
 }