Skip to content

Helper fot transform $ttl to int #2

@h4kuna

Description

@h4kuna

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

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions