Skip to content

Helper fot transform $ttl to int #2

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
h4kuna opened this issue Dec 12, 2024 · 0 comments
Open

Helper fot transform $ttl to int #2

h4kuna opened this issue Dec 12, 2024 · 0 comments

Comments

@h4kuna
Copy link

h4kuna commented Dec 12, 2024

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();
	}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant