Completed
Push — develop ( 6f95b1...70d143 )
by Schlaefer
02:49
created

Cron   A

Complexity

Total Complexity 15

Size/Duplication

Total Lines 116
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 2

Importance

Changes 0
Metric Value
dl 0
loc 116
rs 10
c 0
b 0
f 0
wmc 15
lcom 1
cbo 2

7 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 5 1
A addCronJob() 0 6 1
A execute() 0 21 5
A enableGc() 0 4 1
A garbageCollection() 0 8 3
A loadLastRuns() 0 4 2
A saveLastRuns() 0 7 2
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 bool Should garbage collection be run before persisting */
23
    protected $runGc = false;
24
25
    /** @var int Now */
26
    protected $now;
27
28
    /** @var array|null Null if not intialized */
29
    protected $lastRuns = null;
30
31
    /**
32
     * Constructor
33
     */
34
    public function __construct()
35
    {
36
        $this->now = time();
37
        $this->addCronJob('Cron.Cron.enableGc', '+1 day', [$this, 'enableGc']);
38
    }
39
40
    /**
41
     * Add cron job
42
     *
43
     * @param string $id unique ID for cron job
44
     * @param string $due due intervall
45
     * @param callable $func cron job
46
     * @return self
47
     */
48
    public function addCronJob(string $id, string $due, callable $func): self
49
    {
50
        $this->jobs[$id] = new CronJob($id, $due, $func);
51
52
        return $this;
53
    }
54
55
    /**
56
     * Run cron jobs
57
     *
58
     * @return void
59
     */
60
    public function execute()
61
    {
62
        $this->loadLastRuns();
63
        $jobsExecuted = false;
64
        foreach ($this->jobs as $job) {
65
            $uid = $job->getUid();
66
            $due = $job->getDue();
67
            if (!empty($this->lastRuns[$uid])) {
68
                if ($this->now < $this->lastRuns[$uid]) {
69
                    continue;
70
                }
71
            }
72
            $job->execute();
73
            $jobsExecuted = true;
74
            $this->lastRuns[$uid] = $due;
75
        }
76
        if (!$jobsExecuted) {
77
            return;
78
        }
79
        $this->saveLastRuns();
80
    }
81
82
    /**
83
     * Enables Gc for outdated cron jobs.
84
     *
85
     * @return void
86
     */
87
    public function enableGc(): void
88
    {
89
        $this->runGc = true;
90
    }
91
92
    /**
93
     * Garbage collection on last-runs data
94
     *
95
     * Jobs that were due but not executed are removed. If the job doesn't exist
96
     * anymore it was GCed. If the job just wasn't registered it will be
97
     * executed without last run date nontheless next time it is registered.
98
     *
99
     * @return void
100
     */
101
    protected function garbageCollection(): void
102
    {
103
        foreach ($this->lastRuns as $key => $lastRun) {
0 ignored issues
show
Bug introduced by
The expression $this->lastRuns of type array|null is not guaranteed to be traversable. How about adding an additional type check?

There are different options of fixing this problem.

  1. If you want to be on the safe side, you can add an additional type-check:

    $collection = json_decode($data, true);
    if ( ! is_array($collection)) {
        throw new \RuntimeException('$collection must be an array.');
    }
    
    foreach ($collection as $item) { /** ... */ }
    
  2. If you are sure that the expression is traversable, you might want to add a doc comment cast to improve IDE auto-completion and static analysis:

    /** @var array $collection */
    $collection = json_decode($data, true);
    
    foreach ($collection as $item) { /** .. */ }
    
  3. Mark the issue as a false-positive: Just hover the remove button, in the top-right corner of this issue for more options.

Loading history...
104
            if ($this->now >= $lastRun) {
105
                unset($this->lastRuns[$key]);
106
            }
107
        }
108
    }
109
110
    /**
111
     * Get last cron runs
112
     *
113
     * @return void
114
     */
115
    protected function loadLastRuns(): void
116
    {
117
        $this->lastRuns = Cache::read('Plugin.Cron.lastRuns', 'long') ?: [];
118
    }
119
120
    /**
121
     * Create new cache data
122
     *
123
     * @return void
124
     */
125
    protected function saveLastRuns(): void
126
    {
127
        if ($this->runGc) {
128
            $this->garbageCollection();
129
        }
130
        Cache::write('Plugin.Cron.lastRuns', $this->lastRuns, 'long');
131
    }
132
}
133