setLastModified() public method

Passing null as value will remove the header.
public setLastModified ( DateTime $date = null ) : Response
$date DateTime A \DateTime instance or null to remove the header
return Response
Example #1
0
 function handle(Request $request, $type = HttpFoundation::MASTER_REQUEST, $catch = true)
 {
     $pathinfo = $request->getPathInfo();
     if (preg_match('{^/_pipe/(.+)$}', $pathinfo, $matches)) {
         $path = $matches[1];
         if (!$path or !($asset = $this->env->find($path, array('bundled' => true)))) {
             $this->log->error("pipe: Asset '{$path}' not found");
             return new Response('Not Found', 404);
         }
         $lastModified = new \DateTime();
         $lastModified->setTimestamp($asset->getLastModified());
         $response = new Response();
         $response->setPublic();
         $response->setLastModified($lastModified);
         if ($response->isNotModified($request)) {
             $this->log->info("pipe: 302 {$path}");
             return $response;
         }
         $start = microtime(true);
         $response->setContent($asset->getBody());
         $this->log->info(sprintf('pipe: Rendered "%s" in %d seconds', $path, microtime(true) - $start));
         $response->headers->set('Content-Type', $asset->getContentType());
         $response->prepare($request);
         return $response;
     }
     return $this->app->handle($request, $type, $catch);
 }
 /**
  * {@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);
 }
 public function onKernelController(FilterControllerEvent $event)
 {
     $controller = $event->getController();
     $request = $event->getRequest();
     $annotation = $this->findAnnotation($controller);
     if (!$annotation) {
         return;
     }
     $lastTouched = $annotation->calculateLastModified($this->metaQueryFactory);
     if (!$lastTouched) {
         return;
     }
     $this->lastTouchedResults[$request] = $lastTouched;
     /*
      * Für kernel.debug = 1 senden wir niemals
      * 304-Responses, anstatt den Kernel auszuführen:
      *
      * Das Ergebnis hängt auch von vielen Dingen außerhalb
      * wfd_meta ab (z. B. template-Code), die wir hier nicht
      * berücksichtigen können.
      */
     if ($this->debug) {
         return;
     }
     $response = new Response();
     $response->setLastModified($lastTouched);
     if ($response->isNotModified($request)) {
         $event->setController(function () use($response) {
             return $response;
         });
     }
 }
 public function analyze(Request $request = null)
 {
     $request = $request ?: $this->request;
     $response = null;
     $key = $request->getPathInfo();
     if ($this['http.cache']->contains($key)) {
         $value = $this['http.cache']->fetch($key);
         $content = $value['content'];
         $modified = \DateTime::createFromFormat('Y-m-d H:i:s', $value['modified']);
         $statusCode = Response::HTTP_OK;
         $ifModified = $this->request->headers->get('if-modified-since', null);
         if (null !== $ifModified) {
             $ifModified = \DateTime::createFromFormat('D, d M Y H:i:s T', $ifModified);
             if ($modified->getTimestamp() === $ifModified->getTimestamp()) {
                 $content = null;
                 $statusCode = Response::HTTP_NOT_MODIFIED;
             }
         }
         $response = new Response($content, $statusCode);
         $response->setLastModified($modified);
     }
     if (null === $response) {
         $this->forceHydrate();
         $response = parent::analyze($request);
     }
     return $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;
    }
Example #6
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;
 }
 public function resultatAction(Request $request, AbstractTerritoire $territoire)
 {
     $response = new Response();
     $response->setLastModified($this->get('repository.cache_info')->getLastModified($territoire));
     $response->setPublic();
     if ($response->isNotModified($request)) {
         return $response;
     }
     $allEcheances = $this->get('repository.echeance')->getAll();
     $form = $this->createForm(new EcheanceChoiceType($allEcheances), array(), array('method' => 'GET'));
     $form->handleRequest($request);
     if ($form->isSubmitted() && $form->isValid() && ($data = $form->getData())) {
         $reference = $data['comparaison'] ? $data['comparaison']->getNom() : null;
         $echeances = $data['echeances'];
         if (!in_array($reference, $echeances->toArray(), true)) {
             $reference = null;
         }
     } else {
         $echeances = array_filter($allEcheances, function ($element) {
             return $element->getType() !== Echeance::MUNICIPALES;
         });
         $reference = null;
         $form->get('echeances')->setData(new ArrayCollection($echeances));
     }
     $results = $this->getResults($territoire, $echeances);
     return $this->render('resultat.html.twig', array('form' => $form->createView(), 'resultats' => $results, 'territoire' => $territoire->getNom(), 'reference' => $reference), $response);
 }
 /**
  * Handle request to convert it to a Response object.
  */
 public function handle()
 {
     try {
         if (!$this->request->query->has('image')) {
             throw new FileNotFoundException("No valid image path found in URI", 1);
         }
         $nativePath = $this->configuration->getImagesPath() . '/' . $this->request->query->get('image');
         $this->nativeImage = new File($nativePath);
         $this->parseQuality();
         if ($this->configuration->hasCaching()) {
             $cache = new FileCache($this->request, $this->nativeImage, $this->configuration->getCachePath(), $this->logger, $this->quality, $this->configuration->getTtl(), $this->configuration->getGcProbability(), $this->configuration->getUseFileChecksum());
             $cache->setDispatcher($this->dispatcher);
             /** @var Response response */
             $this->response = $cache->getResponse(function (InterventionRequest $interventionRequest) {
                 return $interventionRequest->processImage();
             }, $this);
         } else {
             $this->processImage();
             $this->response = new Response((string) $this->image->encode(null, $this->quality), Response::HTTP_OK, ['Content-Type' => $this->image->mime(), 'Content-Disposition' => 'filename="' . $this->nativeImage->getFilename() . '"', 'X-Generator-First-Render' => true]);
             $this->response->setLastModified(new \DateTime('now'));
         }
     } catch (FileNotFoundException $e) {
         $this->response = $this->getNotFoundResponse($e->getMessage());
     } catch (\RuntimeException $e) {
         $this->response = $this->getBadRequestResponse($e->getMessage());
     }
 }
Example #9
0
 public function show()
 {
     $assetic = $this->getServices()->get($this->getServices()->getProperty('asseticServiceName', 'assetic'));
     $response = new Response();
     $response->setExpires(new \DateTime());
     if (empty($this->asset) || strpos($this->asset, '/') === false) {
         $response->setStatusCode(400);
         return $response;
     }
     list(, $formulaName, ) = explode('/', $this->asset);
     // asset not found
     if (empty($formulaName) || !$assetic->getAssetManager()->has($formulaName)) {
         $response->setStatusCode(404);
         return $response;
     }
     $formula = $assetic->getAssetManager()->getFormula($formulaName);
     if ($formula[0] instanceof AssetInterface) {
         $asset = $formula[0];
     } else {
         $asset = $assetic->getFactory()->createAsset($formula[0], $formula[1], $formula[2]);
     }
     if (null !== ($lastModified = $asset->getLastModified())) {
         $date = new \DateTime();
         $date->setTimestamp($lastModified);
         $response->setLastModified($date);
     }
     $formula['last_modified'] = $lastModified;
     $response->setETag(md5($asset->getContent()));
     $this->defineContentType($response);
     if ($response->isNotModified($this->getContext()->getRequest())) {
         return $response;
     }
     $response->setContent($this->cacheAsset($asset)->dump());
     return $response;
 }
Example #10
0
 /**
  * View a single content page
  *
  * This Controller action is being routed to from either our custom ContentRouter,
  * or the ExceptionController.
  * @see Opifer\SiteBundle\Router\ContentRouter
  *
  * @param Request          $request
  * @param ContentInterface $content
  * @param int              $statusCode
  *
  * @return Response
  *
  * @throws \Exception
  */
 public function viewAction(Request $request, ContentInterface $content, $statusCode = 200)
 {
     $version = $request->query->get('_version');
     $debug = $this->getParameter('kernel.debug');
     $contentDate = $content->getUpdatedAt();
     $templateDate = $content->getTemplate()->getUpdatedAt();
     $date = $contentDate > $templateDate ? $contentDate : $templateDate;
     $response = new Response();
     $response->setLastModified($date);
     $response->setPublic();
     if (null === $version && false == $debug && $response->isNotModified($request)) {
         // return the 304 Response immediately
         return $response;
     }
     $version = $request->query->get('_version');
     /** @var Environment $environment */
     $environment = $this->get('opifer.content.block_environment');
     $environment->setObject($content);
     $response->setStatusCode($statusCode);
     if (null !== $version && $this->isGranted('ROLE_ADMIN')) {
         $environment->setDraft(true);
     }
     $environment->load();
     return $this->render($environment->getView(), $environment->getViewParameters(), $response);
 }
Example #11
0
 /**
  * Handles HTTP validation headers.
  */
 public function onKernelController(FilterControllerEvent $event)
 {
     $request = $event->getRequest();
     if (!($configuration = $request->attributes->get('_cache'))) {
         return;
     }
     $response = new Response();
     $lastModifiedDate = '';
     if ($configuration->getLastModified()) {
         $lastModifiedDate = $this->getExpressionLanguage()->evaluate($configuration->getLastModified(), $request->attributes->all());
         $response->setLastModified($lastModifiedDate);
     }
     $etag = '';
     if ($configuration->getETag()) {
         $etag = hash('sha256', $this->getExpressionLanguage()->evaluate($configuration->getETag(), $request->attributes->all()));
         $response->setETag($etag);
     }
     if ($response->isNotModified($request)) {
         $event->setController(function () use($response) {
             return $response;
         });
     } else {
         if ($etag) {
             $this->etags[$request] = $etag;
         }
         if ($lastModifiedDate) {
             $this->lastModifiedDates[$request] = $lastModifiedDate;
         }
     }
 }
Example #12
0
File: Server.php Project: chh/pipe
 function handle(HttpFoundation\Request $request, $type = HttpKernelInterface::MASTER_REQUEST, $catch = true)
 {
     $path = ltrim($request->getPathInfo(), '/');
     $asset = $this->environment->find($path, array("bundled" => true));
     $debug = $request->query->get("debug", false);
     $cache = !$request->query->get("nocache", false);
     if (!$asset or $path == '') {
         return $this->renderNotFound($request);
     }
     if ($debug) {
         $this->environment->bundleProcessors->clear();
     }
     $lastModified = new \DateTime();
     $lastModified->setTimestamp($asset->getLastModified());
     $response = new HttpFoundation\Response();
     $response->setPublic();
     $response->setLastModified($lastModified);
     if ($cache and $response->isNotModified($request)) {
         return $response;
     }
     $response->setContent($asset->getBody());
     $response->headers->set('Content-Type', $asset->getContentType());
     $response->prepare($request);
     return $response;
 }
 /**
  * Generate a Response object
  *
  * @param  mixed    $date     a single namespace, an array of namespaces, or a \DateTime object
  * @param  Response $response
  * @return Response
  */
 public function generate($date = 'global', Response $response = null)
 {
     if (!$response) {
         $response = new Response();
     }
     if ($this->maxAge) {
         $response->setMaxAge($this->maxAge);
     }
     if ($this->sharedMaxAge) {
         $response->setSharedMaxAge($this->sharedMaxAge);
     }
     if ($date instanceof \DateTime) {
         $response->setLastModified($date);
     } else {
         $response->setLastModified($this->manager->getLastUpdate($date));
     }
     return $response;
 }
Example #14
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);
 }
Example #15
0
 public function hasCachedResponse(Request $request, DateTime $lastWriteTime)
 {
     $response = new Response();
     $response->setLastModified($lastWriteTime);
     if ($response->isNotModified($request)) {
         return $response;
     }
     return false;
 }
Example #16
0
 public function renderAction(Request $request, $ulClass = null)
 {
     $lastUpdated = $this->getPageRepository()->getLastUpdated();
     $response = new Response();
     $response->setLastModified($lastUpdated)->setPublic();
     if ($response->isNotModified($request)) {
         return $response;
     }
     return $this->render('@SymEdit/Menu/render.html.twig', ['ulClass' => $ulClass], $response);
 }
Example #17
0
 private function checkUpdatedAt(Request $request, \DateTime $updatedAt)
 {
     $response = new Response();
     $response->setLastModified($updatedAt);
     if (!$response->isNotModified($request)) {
         //is newer, need to generate a new response and cannot use the old one
         $response = null;
     }
     return $response;
 }
Example #18
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);
 }
Example #19
0
 public function getResponse($name, array $options = array())
 {
     $service = $this->getAssetService();
     $response = new Response('', 200, array('Content-Type' => $service->getContentType($name)));
     $response->setLastModified($service->getLastModified($name));
     $response->setPublic();
     if (!array_key_exists('request', $options) || !$response->isNotModified($options['request'])) {
         $response->setContent($service->getContent($name));
     }
     return $response;
 }
Example #20
0
 public function execute(Request $request, Config $config, WorkingFolder $workingFolder, ResizedImageRepository $resizedImageRepository, CacheManager $cache)
 {
     $fileName = (string) $request->query->get('fileName');
     list($requestedWidth, $requestedHeight) = Image::parseSize((string) $request->get('size'));
     $downloadedFile = new DownloadedFile($fileName, $this->app);
     $downloadedFile->isValid();
     if (!Image::isSupportedExtension(pathinfo($fileName, PATHINFO_EXTENSION), $config->get('thumbnails.bmpSupported'))) {
         throw new InvalidExtensionException('Unsupported image type or not image file');
     }
     Utils::removeSessionCacheHeaders();
     $response = new Response();
     $response->setPublic();
     $response->setEtag(dechex($downloadedFile->getTimestamp()) . "-" . dechex($downloadedFile->getSize()));
     $lastModificationDate = new \DateTime();
     $lastModificationDate->setTimestamp($downloadedFile->getTimestamp());
     $response->setLastModified($lastModificationDate);
     if ($response->isNotModified($request)) {
         return $response;
     }
     $imagePreviewCacheExpires = (int) $config->get('cache.imagePreview');
     if ($imagePreviewCacheExpires > 0) {
         $response->setMaxAge($imagePreviewCacheExpires);
         $expireTime = new \DateTime();
         $expireTime->modify('+' . $imagePreviewCacheExpires . 'seconds');
         $response->setExpires($expireTime);
     }
     $cachedInfoPath = Path::combine($workingFolder->getResourceType()->getName(), $workingFolder->getClientCurrentFolder(), $fileName);
     $cachedInfo = $cache->get($cachedInfoPath);
     $resultImage = null;
     // Try to reuse existing resized image
     if ($cachedInfo && isset($cachedInfo['width']) && isset($cachedInfo['height'])) {
         // Fix received aspect ratio
         $size = Image::calculateAspectRatio($requestedWidth, $requestedHeight, $cachedInfo['width'], $cachedInfo['height']);
         $resizedImage = $resizedImageRepository->getResizedImageBySize($workingFolder->getResourceType(), $workingFolder->getClientCurrentFolder(), $fileName, $size['width'], $size['height']);
         if ($resizedImage) {
             $resultImage = Image::create($resizedImage->getImageData());
         }
     }
     // Fallback - get and resize the original image
     if (null === $resultImage) {
         $resultImage = Image::create($downloadedFile->getContents(), $config->get('thumbnails.bmpSupported'));
         $cache->set($cachedInfoPath, $resultImage->getInfo());
         $resultImage->resize($requestedWidth, $requestedHeight);
     }
     $mimeType = $resultImage->getMimeType();
     if (in_array($mimeType, array('image/bmp', 'image/x-ms-bmp'))) {
         $mimeType = 'image/jpeg';
         // Image::getData() by default converts resized images to JPG
     }
     $response->headers->set('Content-Type', $mimeType . '; name="' . $downloadedFile->getFileName() . '"');
     $response->setContent($resultImage->getData());
     return $response;
 }
 /**
  * output image direct to browser, retrieve from cache if activated.
  *
  * @param Request $request
  * @param $id
  * @param string $format
  *
  * @return Response
  */
 public function viewImageAction(Request $request, $id, $format = 'reference')
 {
     $media = $this->getMedia($id);
     if (!$media) {
         throw new NotFoundHttpException(sprintf('unable to find the media with the id : %s', $id));
     }
     if (!$this->get('sonata.media.pool')->getDownloadSecurity($media)->isGranted($media, $request)) {
         throw new AccessDeniedException();
     }
     /** @var \Networking\InitCmsBundle\Lib\PhpCache $phpCache */
     $phpCache = $this->get('networking_init_cms.lib.php_cache');
     if ($phpCache->isActive()) {
         if ($phpCache->get(sprintf('image_%s_updated_at', $id)) != $media->getUpdatedAt()) {
             $phpCache->delete('image_' . $id);
         }
         if (!($response = $phpCache->get('image_' . $media->getId()))) {
             $provider = $this->getProvider($media);
             if ($format == 'reference') {
                 $file = $provider->getReferenceFile($media);
             } else {
                 $file = $provider->getFilesystem()->get($provider->generatePrivateUrl($media, $format));
             }
             $content = $file->getContent();
             $headers = array_merge(array('Content-Type' => $media->getContentType(), 'Accept-Ranges' => 'bytes', 'Content-Length' => $media->getSize(), 'Content-Disposition' => sprintf('inline; filename="%s"', $media->getMetadataValue('filename'))), array());
             $response = new Response($content, 200, $headers);
             $response->setPublic();
             $response->setMaxAge(604800);
             $response->setLastModified($media->getUpdatedAt());
             $response->getEtag(md5(sprintf('image_%s_updated_at', $id)));
             $phpCache->set('image_' . $media->getId(), $response, null);
             $phpCache->set(sprintf('image_%s_updated_at', $media->getId()), $media->getUpdatedAt(), null);
         } else {
             $phpCache->touch('image_' . $media->getId(), null);
             $phpCache->touch(sprintf('image_%s_updated_at', $media->getId()), null);
         }
     } else {
         $provider = $this->getProvider($media);
         if ($format == 'reference') {
             $file = $provider->getReferenceFile($media);
         } else {
             $file = $provider->getFilesystem()->get($provider->generatePrivateUrl($media, $format));
         }
         $content = $file->getContent();
         $headers = array_merge(array('Content-Type' => $media->getContentType(), 'Accept-Ranges' => 'bytes', 'Content-Length' => $media->getSize(), 'Content-Disposition' => sprintf('inline; filename="%s"', $media->getMetadataValue('filename'))), array());
         $response = new Response($content, 200, $headers);
         $response->setPublic();
         $response->setMaxAge(604800);
         $response->setLastModified($media->getUpdatedAt());
         $response->getEtag(md5(sprintf('image_%s_updated_at', $id)));
     }
     return $response;
 }
Example #22
0
 public function showPageAction($id, $extraParams = null, $currentpage = null, $totalpageitems = null, $linkUrlParams = null)
 {
     // Get data to display
     $page = $this->getDoctrine()->getRepository('BlogBundle:Blog')->find($id);
     $userRole = $this->get('sonata_user.services.helpers')->getLoggedUserHighestRole();
     $settings = $this->get('bardiscms_settings.load_settings')->loadSettings();
     // Simple ACL for publishing
     if ($page->getPublishState() == 0) {
         return $this->render404Page();
     }
     if ($page->getPublishState() == 2 && $userRole == '') {
         return $this->render404Page();
     }
     if ($userRole == "") {
         $publishStates = array(1);
     } else {
         $publishStates = array(1, 2);
     }
     if ($this->container->getParameter('kernel.environment') == 'prod' && $settings->getActivateHttpCache()) {
         $response = new Response();
         // set a custom Cache-Control directive
         $response->headers->addCacheControlDirective('must-revalidate', true);
         // set multiple vary headers
         $response->setVary(array('Accept-Encoding', 'User-Agent'));
         // create a Response with a Last-Modified header
         $response->setLastModified($page->getDateLastModified());
         // Set response as public. Otherwise it will be private by default.
         $response->setPublic();
         //var_dump($response->isNotModified($this->getRequest()));
         //var_dump($response->getStatusCode());
         if (!$response->isNotModified($this->getRequest())) {
             // Marks the Response stale
             $response->expire();
         } else {
             // return the 304 Response immediately
             $response->setSharedMaxAge(3600);
             return $response;
         }
     }
     // Set the website settings and metatags
     $page = $this->get('bardiscms_settings.set_page_settings')->setPageSettings($page);
     // Set the pagination variables
     if (!$totalpageitems) {
         if (is_object($settings)) {
             $totalpageitems = $settings->getBlogItemsPerPage();
         } else {
             $totalpageitems = 10;
         }
     }
     // Render the correct view depending on pagetype
     return $this->renderPage($page, $id, $publishStates, $extraParams, $currentpage, $totalpageitems, $linkUrlParams);
 }
 /**
  * Action rendering the tree menu for admin interface.
  * Note that parameters are not used at all since the request is entirely forwarded to the legacy kernel.
  *
  * @param int $nodeId
  * @param int $modified
  * @param int $expiry
  * @param string $perm
  *
  * @return \Symfony\Component\HttpFoundation\Response
  */
 public function viewMenu($nodeId, $modified, $expiry, $perm)
 {
     $response = new Response();
     if ($this->getParameter('treemenu.http_cache')) {
         $response->setMaxAge($this->getParameter('treemenu.ttl_cache'));
     }
     $result = $this->treeMenuKernel->run();
     if ($result->hasAttribute('lastModified')) {
         $response->setLastModified($result->getAttribute('lastModified'));
     }
     $response->setContent($result->getContent());
     return $response;
 }
Example #24
0
 /**
  * @Rest\View
  */
 public function getLatestCommentsAction($limit)
 {
     $em = $this->getDoctrine()->getEntityManager();
     $comments = $em->getRepository('KoiosBlogBackendBundle:Comment')->getLatestComments($limit);
     $response = new SymResponse();
     $response->setLastModified(count($comments) ? end($comments)->getUpdated() : new \DateTime());
     $response->setPublic();
     if ($response->isNotModified($this->getRequest())) {
         return $response;
     }
     $view = View::create()->setStatusCode(200)->setData($comments);
     return $this->get('fos_rest.view_handler')->handle($view, $this->getRequest(), $response);
 }
Example #25
0
 public function helloWorldCachedAction()
 {
     $response = new Response();
     $response->setPublic();
     $response->setETag("HelloWorldTag");
     $response->setLastModified(new DateTime("2012-01-01 00:00:00+0000"));
     // Check that the Response is not modified for the given Request
     if ($response->isNotModified($this->getRequest())) {
         // return the 304 Response immediately
         return $response;
     }
     $response->setContent("Hello Universe!");
     return $response;
 }
 /**
  * @param Request $request
  *
  * @return Response
  */
 public function changelogAction(Request $request)
 {
     $content = file_get_contents($this->kernelRootDir . '/../changelog.yml');
     $response = new Response();
     $response->setPublic();
     $response->setEtag(md5($content));
     $response->setVary('Accept-Encoding', 'User-Agent');
     if (!$response->isNotModified($request)) {
         $parser = new Parser();
         $response->setLastModified(new \DateTime());
         return $this->engine->renderResponse('@CertificationyWeb/Site/changelog.html.twig', ['changelog' => $parser->parse($content)]);
     }
     return $response;
 }
 /**
  * @Route("/rechercher/{terme}", name="rechercher")
  * @Method({"GET"})
  */
 public function rechercherAction(Request $request, $terme = null)
 {
     $response = new Response();
     $response->setLastModified($this->get('repository.cache_info')->getCacheInvalidateDate());
     $response->setPublic();
     if ($response->isNotModified($request)) {
         return $response;
     }
     $territoires = array();
     if (!empty($terme)) {
         $territoires = $this->get('repository.territoire')->findLike($terme, 90);
     }
     $form = $this->createFormBuilder(array())->setAction('#')->add('terme', 'text', array('label' => 'Rechercher un territoire ' . '(commune, département, région...) : '))->add('Rechercher', 'submit')->getForm();
     return $this->render('rechercher.html.twig', array('form' => $form->createView(), 'territoires' => $territoires), $response);
 }
Example #28
0
 /**
  * Retrieves a base response with proper last-modified/expires headers
  * for http caching
  *
  * @param  \Raindrop\RoutingBundle\Entity\ContentInterface $content
  * @param  type                                            $template   template name
  * @param  type                                            $parameters array of template variables
  * @param  int                                             $expires    expiration timestamp
  * @return \Symfony\Component\HttpFoundation\Response
  */
 public function response(ContentInterface $content, $template, $parameters, $expires = null)
 {
     if (is_null($expires)) {
         $expires = time() + 86400;
     }
     $response = new Response();
     $response->setPublic();
     $response->setLastModified($content->getUpdated());
     $response->headers->set('Expires', gmdate("D, d M Y H:i:s", $expires) . " GMT");
     if ($response->isNotModified($this->container->get('request'))) {
         // return the 304 Response immediately
         return $response;
     }
     return $this->container->get('templating')->renderResponse($template, $parameters, $response);
 }
 public function templateAction(Request $request, $template, $maxAge = null, $sharedAge = null, $private = null, $metaTables = null, $metaTableConstants = null, $metaEntities = null, $metaResetInterval = null)
 {
     /** @var \DateTime $lastmod */
     $lastmod = null;
     /** @var $response \Symfony\Component\HttpFoundation\Response */
     $response = null;
     if ($metaTables || $metaTableConstants || $metaEntities) {
         $lastmodHelper = new LastmodHelper();
         if ($metaTables) {
             $lastmodHelper->setTables($metaTables);
         }
         if ($metaTableConstants) {
             $lastmodHelper->setTableIdConstants($metaTableConstants);
         }
         if ($metaEntities) {
             $lastmodHelper->setEntities($metaEntities);
         }
         if ($metaResetInterval) {
             $lastmodHelper->setResetInterval($metaResetInterval);
         }
         $lastmod = $lastmodHelper->calculateLastModified($this->metaQueryFactory);
     }
     if (!$this->debug && $lastmod) {
         $response = new Response();
         $response->setLastModified($lastmod);
         if (!$response->isNotModified($request)) {
             $response = null;
         }
     }
     if (!$response) {
         $response = $this->templating->renderResponse($template);
         if ($lastmod) {
             $response->setLastModified($lastmod);
         }
     }
     if (null !== $maxAge) {
         $response->setMaxAge($maxAge);
     }
     if (null !== $sharedAge) {
         $response->setSharedMaxAge($sharedAge);
     }
     if ($private) {
         $response->setPrivate();
     } elseif ($private === false || null === $private && ($maxAge || $sharedAge)) {
         $response->setPublic($private);
     }
     return $response;
 }
Example #30
0
 /**
  * Thumbnailing à la volée
  */
 public function getAction($storageKey, $size)
 {
     $file = $this->get('social.picture.storage')->getImagePath($storageKey, $size);
     $response = new Response();
     $lastModif = \DateTime::createFromFormat('U', filemtime($file));
     $response->setLastModified($lastModif);
     $response->setEtag(sha1(filesize($file)));
     $response->setSharedMaxAge(3600);
     if ($response->isNotModified($this->getRequest())) {
         return $response;
     }
     $response->headers->set('X-Sendfile', $file);
     $response->headers->set('Content-Type', 'image/' . pathinfo($storageKey, PATHINFO_EXTENSION));
     $this->get('logger')->debug("{$storageKey} xsended");
     return $response;
 }