comsolit / clock-bundle
Clock 服务用于表示一个请求常量,系统范围内的实例时间。
1.0.0
2018-02-20 10:09 UTC
Requires
- php: >=5.5.0
Requires (Dev)
- phpunit/phpunit: ~4.3
- symfony/symfony: ~2.5
This package is auto-updated.
Last update: 2024-08-28 14:50:52 UTC
README
Symfony 的 Clock Bundle
如果测试代码直接访问系统时间,则对时间相关的任何内容进行单元测试都很困难。因此,此包提供了一个包装 DateTime 实例的时钟服务,该实例表示 "现在"。
另一个优点是,在单个请求期间 "现在" 保持不变。
用法示例
时钟还包含一些辅助函数,有助于创建易于理解的时间相关代码。
测试用户是否可以再次尝试登录
在给定的 IP 地址尝试登录失败几次后,用户可能需要等待几分钟才能再次登录
$clock->hasElapsed($blockingPeriod, $lastFailedLogin->getDateTime())
没有辅助方法,这看起来会是这样
((int)$lastFailedLogin->getDateTime()->format('U')) + $blockingPeriod >= $clock->getTimestamp()
测试令牌是否仍然有效
$clock->isExpired($tokenExpirationTime)
将时间作为文件名的一部分保存文件
$fileName = $clock->getFileName() . '_datadump'; // e.g. $fileName === '2015-03-25_23-12-59_datadump'
类 Clock 中的辅助方法
class Clock { // SNIPP some stuff /** * Time representation usable as (part of) a file name, e.g.: 2014-05-23_13-45-23 * @return string */ public function getFileName() { return $this->now->format('Y-m-d_H-i-s'); } /** * @return \DateTime */ public function getDateTime() { return $this->now; } /** * @return int */ public function getSeconds() { return (int)$this->now->format('U'); } /** * @return int */ public function getSecondsSince(\DateTimeInterface $past) { return $this->getSeconds() - (int)$past->format('U'); } /** * @return int */ public function getSecondsUntil(\DateTimeInterface $future) { return - $this->getSecondsSince($future); } /** * @return bool * @param int $seconds */ public function hasElapsed($seconds, \DateTimeInterface $since) { return $this->getSecondsSince($since) > $seconds; } /** * @return bool */ public function isExpired(\DateTimeInterface $expiryDate) { return (int)$this->now->format('U') > (int)$expiryDate->format('U'); } /** * Create new DateTime object with the timezone of this clock * * @param String $time */ public function createDateTime($time) { return (new \DateTime($time, $this->now->getTimezone()))->setTimezone($this->now->getTimezone()); } /** * Returns an instance of DateTimeImmutable for the given implementation of DateTimeInterface. * * This method should rather exist in the DateTimeImmutable class but Derick Rethans doesn't * think so. * * @param \DateTimeInterface $datetime * @return \DateTimeImmutable */ public static function createDateTimeImmutable(\DateTimeInterface $datetime) { if ($datetime instanceof \DateTimeImmutable) { return $datetime; } return \DateTimeImmutable::createFromMutable($datetime); } }