src/Controller/Api/ScriptCacheController.php line 26

Open in your IDE?
  1. <?php
  2. namespace App\Controller\Api;
  3. use Psr\Cache\InvalidArgumentException;
  4. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  5. use Symfony\Component\Cache\Adapter\FilesystemAdapter;
  6. use Symfony\Component\HttpClient\HttpClient;
  7. use Symfony\Component\HttpFoundation\Response;
  8. use Symfony\Component\Routing\Annotation\Route;
  9. use Symfony\Contracts\Cache\ItemInterface;
  10. class ScriptCacheController extends AbstractController
  11. {
  12.     public const UPSTREAM_GA_SCRIPT_SOURCE 'https://www.google-analytics.com/analytics.js';
  13.     public const UPSTREAM_HUBSPOT_SCRIPT_SOURCE 'https://js.hs-scripts.com/6356269.js';
  14.     /**
  15.      * Fetch and cache GA script.
  16.      *
  17.      * @Route("/api/script_cache/analytics", methods={"GET"})
  18.      * @return Response
  19.      * @throws InvalidArgumentException
  20.      */
  21.     public function getGaAnalytics(): Response
  22.     {
  23.         $cache = new FilesystemAdapter();
  24.         $script $cache->get('ga_script', function (ItemInterface $item) {
  25.             $item->expiresAfter(86400);
  26.             $httpClient HttpClient::create();
  27.             $request $httpClient->request('GET'self::UPSTREAM_GA_SCRIPT_SOURCE);
  28.             return $request->getContent();
  29.         });
  30.         $response = new Response();
  31.         $response->setContent($script);
  32.         $response->headers->set('Content-Type''text/javascript');
  33.         $response->setPublic();
  34.         $response->setMaxAge(86400);
  35.         return $response;
  36.     }
  37.     /**
  38.      * Fetch and cache HubSpot script.
  39.      *
  40.      * @Route("/api/script_cache/hubspot", methods={"GET"})
  41.      * @return Response
  42.      * @throws InvalidArgumentException
  43.      */
  44.     public function getHubSpot(): Response
  45.     {
  46.         $cache = new FilesystemAdapter();
  47.         $script $cache->get('hs_script', function (ItemInterface $item) {
  48.             $item->expiresAfter(86400);
  49.             $httpClient HttpClient::create();
  50.             $request $httpClient->request('GET'self::UPSTREAM_HUBSPOT_SCRIPT_SOURCE);
  51.             return $request->getContent();
  52.         });
  53.         $response = new Response();
  54.         $response->setContent($script);
  55.         $response->headers->set('Content-Type''text/javascript');
  56.         $response->setPublic();
  57.         $response->setMaxAge(86400);
  58.         return $response;
  59.     }
  60. }