DavidGoodwin / RateLimit

PHP Rate Limiting Library With Token Bucket Algorithm
12 stars 2 forks source link

Symfony Cache Adapter #4

Open mbolli opened 9 months ago

mbolli commented 9 months ago

Maybe someone can use it:

<?php

use PalePurple\RateLimit\Adapter;
use Psr\Cache\InvalidArgumentException;
use Symfony\Component\Cache\Adapter\AbstractAdapter;

class RateLimitSymfonyAdapter extends Adapter {
    public function __construct(private AbstractAdapter $adapter) {}

    /**
     * @param int $ttl - seconds after which this entry will expire, e.g. 50
     *
     * @throws InvalidArgumentException
     */
    public function set($key, $value, $ttl): bool {
        $item = $this->adapter->getItem($key)->expiresAfter($ttl)->set($value);
        return $this->adapter->save($item);
    }

    /**
     * @throws InvalidArgumentException
     */
    public function get($key): mixed {
        return $this->adapter->getItem($key)->get();
    }

    /**
     * @throws InvalidArgumentException
     */
    public function exists($key): bool {
        return $this->adapter->hasItem($key);
    }

    /**
     * @throws InvalidArgumentException
     */
    public function del($key): bool {
        return $this->adapter->delete($key);
    }
}

Usage:

$adapter = new PdoAdapter(
    connOrDsn: $this->container->getPDO(),
    namespace: 'rate-limiter',
    defaultLifetime: 0,
    options: [
        'db_table' => 'api_rate_limiter',
    ],
);

$rater = new RateLimit('namespace', 100, 60*60, new RateLimitSymfonyAdapter($adapter));