Completed
Push — master ( d29062...de4eee )
by Alexey
9s
created

InteractWithTimeTrait::secondsUntil()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 8
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 8
rs 9.4285
c 0
b 0
f 0
cc 2
eloc 5
nc 2
nop 1
1
<?php
2
3
namespace SfCod\QueueBundle\Base;
4
5
use DateInterval;
6
use DateTime;
7
use DateTimeInterface;
8
9
/**
10
 * Trait TimeTrait
11
 *
12
 * @author Virchenko Maksim <[email protected]>
13
 *
14
 * @package SfCod\QueueBundle\Job
15
 */
16
trait InteractWithTimeTrait
17
{
18
    /**
19
     * Get the number of seconds until the given DateTime.
20
     *
21
     * @param DateTimeInterface|DateInterval|int $delay
22
     *
23
     * @return int
24
     */
25
    protected function secondsUntil($delay): int
26
    {
27
        $delay = $this->parseDateInterval($delay);
28
29
        return $delay instanceof DateTimeInterface
30
            ? max(0, $delay->getTimestamp() - $this->currentTime())
31
            : (int)$delay;
32
    }
33
34
    /**
35
     * Get the "available at" UNIX timestamp.
36
     *
37
     * @param DateTimeInterface|DateInterval|int $delay
38
     *
39
     * @return int
40
     */
41
    protected function availableAt($delay = 0): int
42
    {
43
        $delay = $this->parseDateInterval($delay);
44
45
        return $delay instanceof DateTimeInterface
46
            ? $delay->getTimestamp()
47
            : (new DateTime())->add(new DateInterval(sprintf('PT%dS', $delay)))->getTimestamp();
48
    }
49
50
    /**
51
     * If the given value is an interval, convert it to a DateTime instance.
52
     *
53
     * @param \DateTimeInterface|\DateInterval|int $delay
54
     *
55
     * @return \DateTimeInterface|int
56
     */
57
    protected function parseDateInterval($delay)
58
    {
59
        if ($delay instanceof DateInterval) {
60
            $delay = (new DateTime())->add($delay);
61
        }
62
63
        return $delay;
64
    }
65
66
    /**
67
     * Get the current system time as a UNIX timestamp.
68
     *
69
     * @return int
70
     */
71
    protected function currentTime(): int
72
    {
73
        return time();
74
    }
75
}
76