Skip to content

Commit 327f519

Browse files
committed
代码简化
1 parent 1ee157b commit 327f519

File tree

1 file changed

+7
-12
lines changed

1 file changed

+7
-12
lines changed

src/Throttle.php

Lines changed: 7 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -63,10 +63,6 @@ class Throttle
6363
protected $max_requests = 0; // 规定时间内允许的最大请求次数
6464
protected $expire = 0; // 规定时间
6565
protected $remaining = 0; // 规定时间内还能请求的次数
66-
/**
67-
* @var ThrottleAbstract|null
68-
*/
69-
protected $driver_class = null;
7066

7167
/**
7268
* Throttle constructor.
@@ -98,24 +94,23 @@ protected function allowRequest(Request $request): bool
9894
[$max_requests, $duration] = $this->parseRate($this->config['visit_rate']);
9995

10096
$micronow = microtime(true);
101-
$now = (int) $micronow;
10297

103-
$this->driver_class = Container::getInstance()->invokeClass($this->config['driver_name']);
104-
if (!$this->driver_class instanceof ThrottleAbstract) {
98+
$driver = Container::getInstance()->invokeClass($this->config['driver_name']);
99+
if (!($driver instanceof ThrottleAbstract)) {
105100
throw new \TypeError('The throttle driver must extends ' . ThrottleAbstract::class);
106101
}
107-
$allow = $this->driver_class->allowRequest($key, $micronow, $max_requests, $duration, $this->cache);
102+
$allow = $driver->allowRequest($key, $micronow, $max_requests, $duration, $this->cache);
108103

109104
if ($allow) {
110105
// 允许访问
111-
$this->now = $now;
106+
$this->now = (int) $micronow;
112107
$this->expire = $duration;
113108
$this->max_requests = $max_requests;
114-
$this->remaining = $max_requests - $this->driver_class->getCurRequests();
109+
$this->remaining = $max_requests - $driver->getCurRequests();
115110
return true;
116111
}
117112

118-
$this->wait_seconds = $this->driver_class->getWaitSeconds();
113+
$this->wait_seconds = $driver->getWaitSeconds();
119114
return false;
120115
}
121116

@@ -165,7 +160,7 @@ protected function getCacheKey(Request $request): ?string
165160

166161
if ($key === true) {
167162
$key = $request->ip();
168-
} elseif (false !== strpos($key, '__')) {
163+
} elseif (is_string($key) && false !== strpos($key, '__')) {
169164
$key = str_replace(['__CONTROLLER__', '__ACTION__', '__IP__'], [$request->controller(), $request->action(), $request->ip()], $key);
170165
}
171166

0 commit comments

Comments
 (0)