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

LastTime   A

Complexity

Total Complexity 11

Size/Duplication

Total Lines 51
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 16
c 1
b 0
f 0
dl 0
loc 51
rs 10
wmc 11

5 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 3 1
A get() 0 7 3
A setWasRun() 0 10 3
A set() 0 3 1
A wasRunSince() 0 9 3
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