用一个map 保存验证码和过期时间,调用 generate时,将验证码-过期时间对直接插入 map中, 调用renew 时,判断验证码存在并且未过期,更新过期时间, 调用countUnexpiredTokens 时,遍历整个map,统计未过期的验证码的数量
<?php
class AuthenticationManager
{
public $timeToLive;
public $map = [];
/**
* @param Integer $timeToLive
*/
function __construct($timeToLive)
{
$this->timeToLive = $timeToLive;
$this->map = [];
}
/**
* @param String $tokenId
* @param Integer $currentTime
* @return NULL
*/
function generate($tokenId, $currentTime)
{
$this->map[$tokenId] = $currentTime + $this->timeToLive;
}
/**
* @param String $tokenId
* @param Integer $currentTime
* @return NULL
*/
function renew($tokenId, $currentTime)
{
if (isset($this->map[$tokenId]) && $this->map[$tokenId] > $currentTime) {
$this->generate($tokenId, $currentTime);
}
}
/**
* @param Integer $currentTime
* @return Integer
*/
function countUnexpiredTokens($currentTime)
{
$num = 0;
foreach ($this->map as $tokenId => $time) {
if ($time > $currentTime) {
$num++;
}
}
return $num;
}
}
$obj = new AuthenticationManager(5);
$obj->generate('aaa', 5);
$obj->generate('bbb', 5);
$obj->renew('aaa', 7);
var_dump($obj->countUnexpiredTokens(20));