Completed
Branch hotfix/5.4.1 (9732a4)
by Schlaefer
02:32
created

Cron::_getLastRuns()   A

Complexity

Conditions 4
Paths 3

Size

Total Lines 21

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 4
nc 3
nop 0
dl 0
loc 21
rs 9.584
c 0
b 0
f 0
1
<?php
2
3
declare(strict_types=1);
4
5
/**
6
 * Saito - The Threaded Web Forum
7
 *
8
 * @copyright Copyright (c) the Saito Project Developers
9
 * @link https://github.com/Schlaefer/Saito
10
 * @license http://opensource.org/licenses/MIT
11
 */
12
13
namespace Cron\Lib;
14
15
use Cake\Cache\Cache;
16
17
class Cron
18
{
19
    /** @var array */
20
    protected $jobs = [];
21
22
    /** @var int */
23
    protected $now;
24
25
    /** @var array|null Null if not intialized */
26
    private $lastRuns = null;
27
28
    /**
29
     * Constructor
30
     */
31
    public function __construct()
32
    {
33
        $this->now = time();
34
    }
35
36
    /**
37
     * Add cron job
38
     *
39
     * @param string $id unique ID for cron job
40
     * @param string $due due intervall
41
     * @param callable $func cron job
42
     * @return self
43
     */
44
    public function addCronJob(string $id, string $due, callable $func): self
45
    {
46
        $this->jobs[$id] = new CronJob($id, $due, $func);
47
48
        return $this;
49
    }
50
51
    /**
52
     * Run cron jobs
53
     *
54
     * @return void
55
     */
56
    public function execute()
57
    {
58
        $this->lastRuns = $this->getLastRuns();
59
        $jobsExecuted = false;
60
        foreach ($this->jobs as $job) {
61
            $uid = $job->getUid();
62
            $due = $job->getDue();
63
            if (!empty($this->lastRuns[$uid])) {
64
                if ($this->now < $this->lastRuns[$uid]) {
65
                    continue;
66
                }
67
            }
68
            $job->execute();
69
            $jobsExecuted = true;
70
            $this->lastRuns[$uid] = $due;
71
        }
72
        if ($jobsExecuted) {
73
            $this->saveLastRuns();
74
        }
75
    }
76
77
    /**
78
     * Clear history
79
     *
80
     * @return void
81
     */
82
    public function clearHistory()
83
    {
84
        $this->now = time();
85
        $this->lastRuns = [];
86
        $this->saveLastRuns();
87
    }
88
89
    /**
90
     * Get last cron runs
91
     *
92
     * @return array
93
     */
94
    protected function getLastRuns(): array
95
    {
96
        if ($this->lastRuns === null) {
97
            $this->lastRuns = Cache::read('Plugin.Cron.lastRuns', 'long') ?: [];
98
        }
99
100
        return $this->lastRuns;
101
    }
102
103
    /**
104
     * Create new cache data
105
     *
106
     * @return void
107
     */
108
    protected function saveLastRuns(): void
109
    {
110
        Cache::write('Plugin.Cron.lastRuns', $this->lastRuns, 'long');
111
    }
112
}
113