Passed
Push — master ( 4017d9...9757db )
by Dev
10:15
created

LastTime::wasRunSince()   A

Complexity

Conditions 3
Paths 2

Size

Total Lines 10
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 3
eloc 5
nc 2
nop 1
dl 0
loc 10
rs 10
c 0
b 0
f 0
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; //$rootDir.'/../var/last/'.$actionName;
19
    }
20
21
    public function wasRunSince(DateInterval $interval): bool
22
    {
23
        $previous = $this->get();
24
25
        if (false !== $previous
26
            && $previous->add($interval) > new DateTime('now')) {
27
            return false;
28
        }
29
30
        return true;
31
    }
32
33
    /**
34
     * Return false if never runned else last datetime it was 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(file_get_contents($this->filePath));
43
    }
44
45
    public function set($datetime = 'now')
46
    {
47
        file_put_contents($this->filePath, (new DateTime($datetime))->format('Y-m-d H:i:s'));
48
    }
49
}
50