Passed
Push — master ( 936030...79aedb )
by Dev
12:10
created

LastTime::setWasRun()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 10
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 3
eloc 5
c 1
b 0
f 0
nc 3
nop 2
dl 0
loc 10
rs 10
1
<?php
2
3
namespace PiedWeb\CMSBundle\Utils;
4
5
use DateInterval;
6
use DateTime;
7
8
/**
9
 * Usage
10
 * (new LastTime($rootDir.'/../var/lastNoficationUpdatePageSendAt'))->wasRunSince(new DateInterval('P2H')).
11
 */
12
class LastTime
13
{
14
    protected $filePath;
15
16
    public function __construct(string $filePath)
17
    {
18
        $this->filePath = $filePath;
19
    }
20
21
    public function wasRunSince(DateInterval $interval): bool
22
    {
23
        $previous = $this->get();
24
25
        if (false === $previous || $previous->add($interval) < new DateTime('now')) {
26
            return false;
27
        }
28
29
        return true;
30
    }
31
32
    /**
33
     * Return false if never runned else last datetime it was runned.
34
     * If $default is set, return $default time if never runned.
35
     */
36
    public function get($default = false)
37
    {
38
        if (!file_exists($this->filePath)) {
39
            return false === $default ? false : new DateTime($default);
40
        }
41
42
        return new DateTime('@'.filemtime($this->filePath));
43
    }
44
45
    public function setWasRun($datetime = 'now', $setIfNotExist = true): void
46
    {
47
        if (!file_exists($this->filePath)) {
48
            if (false === $setIfNotExist) {
49
                return;
50
            }
51
            file_put_contents($this->filePath, '');
52
        }
53
54
        touch($this->filePath, (new DateTime($datetime))->getTimestamp());
55
    }
56
57
    /**
58
     * alias for set was run.
59
     */
60
    public function set($datetime = 'now')
61
    {
62
        $this->setWasRun($datetime);
63
    }
64
}
65