file, 'c+'); if (!$handle || !flock($handle, LOCK_EX)) { throw new HttpException('ذخیره‌سازی امن سرور در دسترس نیست.', 503); } try { @chmod($this->file, 0600); $rawState = stream_get_contents($handle); $state = $rawState === '' ? [] : json_decode($rawState, true, 32, JSON_THROW_ON_ERROR); if (!is_array($state)) { throw new HttpException('ذخیره‌سازی امن سرور معتبر نیست.', 503); } $now = time(); foreach ($state as $entry => $bucket) { if (($bucket['expires'] ?? 0) <= $now) { unset($state[$entry]); } } $key = hash('sha256', $key); $bucket = $state[$key] ?? ['count' => 0, 'expires' => $now + $window]; if ($bucket['count'] >= $limit || (!isset($state[$key]) && count($state) >= 10000)) { throw new HttpException('تعداد درخواست‌ها زیاد است؛ کمی بعد دوباره تلاش کنید.', 429); } $bucket['count']++; $state[$key] = $bucket; $json = json_encode($state, JSON_THROW_ON_ERROR); rewind($handle); if (!ftruncate($handle, 0) || fwrite($handle, $json) !== strlen($json) || !fflush($handle)) { throw new HttpException('ذخیره‌سازی امن سرور در دسترس نیست.', 503); } } finally { flock($handle, LOCK_UN); fclose($handle); } } }