ConcurrentSearch.php 924 Bytes
<?php

namespace FootyRoom\Support;

use FootyRoom\Support\ConcurrencyLimiter;
use Symfony\Component\HttpKernel\Exception\TooManyRequestsHttpException;

class ConcurrentSearch
{
    /** @var int */
    protected const LIMIT = 50;

    /** @var int */
    protected const RESET_INTERVAL_MINUTES = 10;

    /** @var string */
    protected const KEY = 'concurrent-search';

    /** @var \FootyRoom\Support\ConcurrencyLimiter */
    protected $limiter;

    public function __construct(ConcurrencyLimiter $limiter)
    {
        $this->limiter = $limiter;
    }

    /**
     * Start search.
     */
    public function start(): void
    {
        if (!$this->limiter->lock(self::KEY, self::LIMIT, self::RESET_INTERVAL_MINUTES)) {
            throw new TooManyRequestsHttpException();
        }
    }

    /**
     * End search.
     */
    public function end(): void
    {
        $this->limiter->release(self::KEY);
    }
}