Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Symfony Cache Adapter #4

Open
mbolli opened this issue Dec 21, 2023 · 0 comments
Open

Symfony Cache Adapter #4

mbolli opened this issue Dec 21, 2023 · 0 comments

Comments

@mbolli
Copy link

mbolli commented Dec 21, 2023

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));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant