TtlHelper::dateIntervalToSeconds()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 3
c 1
b 0
f 0
nc 1
nop 1
dl 0
loc 6
ccs 0
cts 4
cp 0
crap 2
rs 10
1
<?php
2
3
declare(strict_types=1);
4
5
/*
6
 * This file is part of Laravel GitLab.
7
 *
8
 * (c) Graham Campbell <[email protected]>
9
 *
10
 * For the full copyright and license information, please view the LICENSE
11
 * file that was distributed with this source code.
12
 */
13
14
namespace GrahamCampbell\GitLab\Http;
15
16
use DateInterval;
17
use DateTimeImmutable;
18
use Illuminate\Contracts\Cache\Repository;
19
use ReflectionClass;
20
21
/**
22
 * This is TTL helper.
23
 *
24
 * The purpose of this class is to detect if the Laravel cache repository is
25
 * working with minutes or seconds, and also to enforce a min and max TTL.
26
 *
27
 * @author Graham Campbell <[email protected]>
28
 */
29
class TtlHelper
30
{
31
    /**
32
     * Computes the correct TTL to use.
33
     *
34
     * @param int                    $min
35
     * @param int                    $max
36
     * @param null|int|\DateInterval $ttl
37
     *
38
     * @return int
39
     */
40
    public static function computeTtl(int $min, int $max, $ttl = null)
41
    {
42
        if ($ttl instanceof DateInterval) {
43
            $ttl = self::dateIntervalToSeconds($ttl);
44
        }
45
46
        $ttl = max($min, min($ttl ?: $min, $max));
47
48
        return self::isLegacy() ? (int) floor($ttl / 60.0) : $ttl;
49
    }
50
51
    /**
52
     * Convert a date interval to seconds.
53
     *
54
     * @param \DateInterval $ttl
55
     *
56
     * @return int
57
     */
58
    private static function dateIntervalToSeconds(DateInterval $ttl)
59
    {
60
        $reference = new DateTimeImmutable();
61
        $endTime = $reference->add($ttl);
62
63
        return $endTime->getTimestamp() - $reference->getTimestamp();
64
    }
65
66
    /**
67
     * If the Laravel cache repository is legacy.
68
     *
69
     * Legacy cache repositories work in minutes.
70
     *
71
     * @return bool
72
     */
73
    private static function isLegacy()
74
    {
75
        static $legacy;
76
77
        if ($legacy === null) {
78
            $params = (new ReflectionClass(Repository::class))->getMethod('put')->getParameters();
79
            $legacy = $params[2]->getName() === 'minutes';
80
        }
81
82
        return $legacy;
83
    }
84
}
85