-
Notifications
You must be signed in to change notification settings - Fork 1
Open
Description
Hello,
I have implemented this static class that helps me save time. I think it could be helpful for others as well.
What do you think?
Here is the link and a copy of the class. If you agree, I will prepare a PR with the class and tests.
If I implement the method CacheInterface::set(string $key, mixed $value, DateInterval|int|null $ttl = null): bool;, the third parameter becomes useful. You can simply call Expire::at($ttl) to get a nullable integer, which is common for many storage systems.
use DateInterval;
use DateTimeImmutable;
use DateTimeInterface;
use Psr\Clock\ClockInterface;
/**
* @phpstan-type TypeKey string|int|float|list<string|int|float>
*/
final class Expire
{
public static function at(int|null|DateInterval|DateTimeInterface $ttl, ?ClockInterface $clock = null): ?int
{
return self::toDate($ttl, $clock)?->getTimestamp();
}
public static function toDate(
int|null|DateInterval|DateTimeInterface $ttl,
?ClockInterface $clock = null,
): ?DateTimeInterface {
if ($ttl === null) {
return null;
} elseif (is_int($ttl)) {
return self::createDateTimeImmutable($clock)->modify("$ttl seconds");
} elseif ($ttl instanceof DateTimeInterface) {
return $ttl;
}
return self::createDateTimeImmutable($clock)->add($ttl);
}
private static function createDateTimeImmutable(?ClockInterface $clock = null): DateTimeImmutable
{
return $clock === null ? new DateTimeImmutable() : $clock->now();
}
public static function after(int|null|DateInterval|DateTimeInterface $ttl, ?ClockInterface $clock = null): ?int
{
if ($ttl === null || is_int($ttl)) {
return $ttl;
}
$now = self::createDateTimeImmutable($clock);
if ($ttl instanceof DateTimeInterface) {
$timestamp = $ttl->getTimestamp();
} else {
$timestamp = $now->add($ttl)->getTimestamp();
}
return $timestamp - $now->getTimestamp();
}
}Metadata
Metadata
Assignees
Labels
No labels