Completed
Pull Request — master (#2)
by
unknown
38:19
created

InteractWithTimeTrait   A

Complexity

Total Complexity 7

Size/Duplication

Total Lines 60
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 0

Importance

Changes 0
Metric Value
wmc 7
lcom 1
cbo 0
dl 0
loc 60
rs 10
c 0
b 0
f 0

4 Methods

Rating   Name   Duplication   Size   Complexity  
A secondsUntil() 0 8 2
A availableAt() 0 8 2
A parseDateInterval() 0 8 2
A currentTime() 0 4 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