Expires   A
last analyzed

Complexity

Total Complexity 10

Size/Duplication

Total Lines 51
Duplicated Lines 0 %

Importance

Changes 5
Bugs 0 Features 2
Metric Value
eloc 20
c 5
b 0
f 2
dl 0
loc 51
rs 10
wmc 10

3 Methods

Rating   Name   Duplication   Size   Complexity  
A getExpires() 0 3 1
A __construct() 0 4 1
B setExpires() 0 26 8
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Enjoys\Cookie;
6
7
class Expires
8
{
9
    private int $expires = -1;
10
    private int $currentTimestamp;
11
12
    /**
13
     * @throws NotCorrectTtlString
14
     */
15
    public function __construct(bool|int|string|\DateTimeInterface $ttl, ?int $currentTimestamp = null)
16
    {
17
        $this->currentTimestamp = $currentTimestamp ?? time();
18
        $this->setExpires($ttl);
19
    }
20
21
    /**
22
     * @throws NotCorrectTtlString
23
     * @see http://php.net/manual/ru/datetime.formats.relative.php
24
     */
25
    private function setExpires(bool|int|string|\DateTimeInterface $ttl): void
26
    {
27
        if ($ttl instanceof \DateTimeInterface) {
28
            $this->expires = $ttl->getTimestamp();
29
            return;
30
        }
31
32
        //Срок действия cookie истечет с окончанием сессии (при закрытии браузера).
33
        if ($ttl === 0 || $ttl === true || strtolower((string)$ttl) === 'session') {
34
            $this->expires = 0;
35
            return;
36
        }
37
38
        // Если число, то прибавляем значение к метке времени timestamp
39
        // Для установки сессионной куки надо использовать FALSE
40
        if (is_numeric($ttl)) {
41
            $this->expires = $this->currentTimestamp + (int)$ttl;
42
            return;
43
        }
44
45
        if (is_string($ttl)) {
46
            if (false !== $returnTtl = strtotime($ttl, $this->currentTimestamp)) {
47
                $this->expires = $returnTtl;
48
                return;
49
            }
50
            throw new NotCorrectTtlString($ttl);
51
        }
52
    }
53
54
55
    public function getExpires(): int
56
    {
57
        return $this->expires;
58
    }
59
}
60