lock !== null && !($this->lock)($key)) { return false; } try { return $this->count($key, $limit, $windowSeconds); } finally { if ($this->unlock !== null) { ($this->unlock)($key); } } } private function count(string $key, int $limit, int $windowSeconds): bool { $now = $this->now !== null ? ($this->now)() : time(); $state = ($this->get)($key); if (!is_array($state) || !isset($state['n'], $state['t']) || $now - (int) $state['t'] >= $windowSeconds) { $state = ['n' => 0, 't' => $now]; } if ((int) $state['n'] >= $limit) { return false; } $state['n'] = (int) $state['n'] + 1; ($this->set)($key, $state, max(1, $windowSeconds - ($now - (int) $state['t']))); return true; } }