<?php
namespace App\Controller\Api;
use Psr\Cache\InvalidArgumentException;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\Cache\Adapter\FilesystemAdapter;
use Symfony\Component\HttpClient\HttpClient;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Contracts\Cache\ItemInterface;
class ScriptCacheController extends AbstractController
{
public const UPSTREAM_GA_SCRIPT_SOURCE = 'https://www.google-analytics.com/analytics.js';
public const UPSTREAM_HUBSPOT_SCRIPT_SOURCE = 'https://js.hs-scripts.com/6356269.js';
/**
* Fetch and cache GA script.
*
* @Route("/api/script_cache/analytics", methods={"GET"})
* @return Response
* @throws InvalidArgumentException
*/
public function getGaAnalytics(): Response
{
$cache = new FilesystemAdapter();
$script = $cache->get('ga_script', function (ItemInterface $item) {
$item->expiresAfter(86400);
$httpClient = HttpClient::create();
$request = $httpClient->request('GET', self::UPSTREAM_GA_SCRIPT_SOURCE);
return $request->getContent();
});
$response = new Response();
$response->setContent($script);
$response->headers->set('Content-Type', 'text/javascript');
$response->setPublic();
$response->setMaxAge(86400);
return $response;
}
/**
* Fetch and cache HubSpot script.
*
* @Route("/api/script_cache/hubspot", methods={"GET"})
* @return Response
* @throws InvalidArgumentException
*/
public function getHubSpot(): Response
{
$cache = new FilesystemAdapter();
$script = $cache->get('hs_script', function (ItemInterface $item) {
$item->expiresAfter(86400);
$httpClient = HttpClient::create();
$request = $httpClient->request('GET', self::UPSTREAM_HUBSPOT_SCRIPT_SOURCE);
return $request->getContent();
});
$response = new Response();
$response->setContent($script);
$response->headers->set('Content-Type', 'text/javascript');
$response->setPublic();
$response->setMaxAge(86400);
return $response;
}
}