Total Complexity | 10 |
Total Lines | 62 |
Duplicated Lines | 0 % |
Changes | 3 | ||
Bugs | 0 | Features | 1 |
1 | <?php |
||
7 | class Expires |
||
8 | { |
||
9 | /** |
||
10 | * @var int |
||
11 | */ |
||
12 | private int $expires = -1; |
||
13 | private ?int $currentTimestamp; |
||
14 | |||
15 | /** |
||
16 | * Expires constructor. |
||
17 | * @param mixed $ttl |
||
18 | * @param int|null $currentTimestamp |
||
19 | * @throws Exception |
||
20 | */ |
||
21 | public function __construct($ttl, int $currentTimestamp = null) |
||
22 | { |
||
23 | $this->currentTimestamp = $currentTimestamp ?? time(); |
||
24 | $this->setExpires($ttl); |
||
25 | |||
26 | } |
||
27 | |||
28 | /** |
||
29 | * @param mixed $ttl |
||
30 | * @return void |
||
31 | * @throws Exception |
||
32 | * @see http://php.net/manual/ru/datetime.formats.relative.php |
||
33 | */ |
||
34 | private function setExpires($ttl): void |
||
35 | { |
||
36 | //Срок действия cookie истечет с окончанием сессии (при закрытии браузера). |
||
37 | if ($ttl === 0 || $ttl === false || strtolower((string)$ttl) === 'session') { |
||
38 | $this->expires = 0; |
||
39 | return; |
||
40 | } |
||
41 | |||
42 | // Устанавливаем время жизни на год |
||
43 | if ($ttl === true) { |
||
44 | $ttl = 60 * 60 * 24 * 365; |
||
45 | } |
||
46 | |||
47 | // Если число то прибавляем значение к метке времени timestamp |
||
48 | // Для установки сессионной куки надо использовать FALSE |
||
49 | if (is_numeric($ttl)) { |
||
50 | $this->expires = $this->currentTimestamp + (int)$ttl; |
||
51 | return; |
||
52 | } |
||
53 | |||
54 | if (is_string($ttl)) { |
||
55 | if (false !== $returnTtl = strtotime($ttl, $this->currentTimestamp)) { |
||
56 | $this->expires = $returnTtl; |
||
57 | return; |
||
58 | } |
||
59 | throw new Exception(sprintf('strtotime() failed to convert string "%s" to timestamp', $ttl)); |
||
60 | } |
||
61 | } |
||
62 | |||
63 | /** |
||
64 | * @return int |
||
65 | */ |
||
66 | public function getExpires(): int |
||
69 | } |
||
70 | } |