Closed
Description
Description
Sometimes HTTP Cache is not available on provider side so some "hack" is needed to fake Cache headers (for example https://jolicode.com/blog/aggressive-caching-with-symfony-http-client).
If HTTP Cache is not available an option could be to use other cache system instead. This proposition adds an option to inject cache item pool (PSR-6 compatible cache item pool).
Example
<?php
declare(strict_types=1);
namespace Jose\Component\KeyManagement;
use RuntimeException;
use Symfony\Contracts\HttpClient\HttpClientInterface;
use Psr\Cache\CacheItemPoolInterface;
/**
* @see \Jose\Tests\Component\KeyManagement\UrlKeySetFactoryTest
*/
abstract class UrlKeySetFactory
{
public function __construct(
private readonly HttpClientInterface $client,
private readonly ?CacheItemPoolInterface $cache = null,
private ?int $expiresAfter = null,
) {
}
/**
* @param array<string, string|string[]> $header
*/
protected function getContent(string $url, array $header = []): string
{
$response = $this->client->request('GET', $url, [
'headers' => $header,
]);
if ($response->getStatusCode() >= 400) {
throw new RuntimeException('Unable to get the key set.', $response->getStatusCode());
}
if (null === $this->cache) {
return $response->getContent();
}
$cacheKey = 'unique_key_to_generate';
$item = $this->cache->getItem($cacheKey);
if ($item->isHit()) {
return $item->get();
}
if ($this->expiresAfter) {
$item->expiresAfter($this->expiresAfter);
}
$responseContent = $response->getContent();
$item->set($responseContent);
$this->cache->save($item);
return $responseContent;
}
}