web-token / jwt-framework

JWT Framework
MIT License
888 stars 105 forks source link

[RFC] Option to rely on PSR Cache instead of HTTP Cache #537

Closed qdequippe closed 6 months ago

qdequippe commented 7 months ago

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;
    }
}
Spomky commented 7 months ago

Hello @qdequippe,

That's interesting. Thank you. I thought the Http Cache would be sufficient.

Spomky commented 6 months ago

Closing as done. Many thanks!

github-actions[bot] commented 5 months ago

This thread has been automatically locked since there has not been any recent activity after it was closed. Please open a new issue for related bugs.