CronTaskController::isTaskDue()   B
last analyzed

Complexity

Conditions 6
Paths 4

Size

Total Lines 25

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 25
rs 8.8977
c 0
b 0
f 0
cc 6
nc 4
nop 2
1
<?php
2
3
namespace SilverStripe\CronTask\Controllers;
4
5
use Cron\CronExpression;
6
use DateTime;
7
use Exception;
8
use SilverStripe\Control\Controller;
9
use SilverStripe\Control\Director;
10
use SilverStripe\Core\ClassInfo;
11
use SilverStripe\Core\Convert;
12
use SilverStripe\Control\HTTPRequest;
13
use SilverStripe\Core\Injector\Injector;
14
use SilverStripe\CronTask\CronTaskStatus;
15
use SilverStripe\CronTask\Interfaces\CronTask;
16
use SilverStripe\ORM\FieldType\DBDatetime;
17
use SilverStripe\Security\Permission;
18
use SilverStripe\Security\Security;
19
20
/**
21
 * This is the controller that finds, checks and process all crontasks
22
 *
23
 * The default route to this controller is 'dev/cron'
24
 *
25
 */
26
class CronTaskController extends Controller
27
{
28
    /**
29
     * If this controller is in quiet mode
30
     *
31
     * @deprecated Use $verbosity instead
32
     *
33
     * @var bool
34
     */
35
    protected $quiet = false;
36
37
    /**
38
     * Tell the controller how noisy it may be
39
     *
40
     * @var int A number from 0 to 2
41
     */
42
    protected $verbosity = 1;
43
44
    /**
45
     * Tell the controller how noisy it may be
46
     * @deprecated Use setVerbosity instead
47
     * @param bool $quiet If set to true this controller will not emit debug noise
48
     */
49
    public function setQuiet($quiet)
50
    {
51
        $this->setVerbosity($quiet ? 0 : 1);
52
53
        $this->quiet = (bool) $quiet;
0 ignored issues
show
Deprecated Code introduced by
The property SilverStripe\CronTask\Co...nTaskController::$quiet has been deprecated with message: Use $verbosity instead

This property has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the property will be removed from the class and what other property to use instead.

Loading history...
54
    }
55
56
    /**
57
     * Tell the controller how noisy it may be
58
     *
59
     * @param int $verbosity An integer from 0 to 2. 0 = no output, 1 = normal, 2 = debug
60
     */
61
    public function setVerbosity($verbosity)
62
    {
63
        $this->verbosity = (int) $verbosity;
64
    }
65
66
    /**
67
     * Checks for cli or admin permissions and include the library
68
     *
69
     * @throws Exception
70
     */
71
    public function init()
72
    {
73
        parent::init();
74
75
        // Unless called from the command line, we need ADMIN privileges
76
        if (!Director::is_cli() && !Permission::check('ADMIN')) {
77
            Security::permissionFailure();
78
        }
79
80
        // set quiet flag based on CLI parameter
81
        if ($this->getRequest()->getVar('quiet')) {
82
            $this->setVerbosity(0);
83
        }
84
        if ($this->getRequest()->getVar('debug')) {
85
            $this->setVerbosity(2);
86
        }
87
    }
88
89
    /**
90
     * Determine if a task should be run
91
     *
92
     * @param CronTask $task
93
     * @param CronExpression $cron
94
     */
95
    public function isTaskDue(CronTask $task, CronExpression $cron)
96
    {
97
        // Get last run status
98
        $status = CronTaskStatus::get_status(get_class($task));
99
100
        // If the cron is due immediately, then run it
101
        $now = new DateTime(DBDatetime::now()->getValue());
102
        if ($cron->isDue($now)) {
103
            if (empty($status) || empty($status->LastRun)) {
104
                return true;
105
            }
106
            // In case this process is invoked twice in one minute, supress subsequent executions
107
            $lastRun = new DateTime($status->LastRun);
108
            return $lastRun->format('Y-m-d H:i') != $now->format('Y-m-d H:i');
109
        }
110
111
        // If this is the first time this task is ever checked, no way to detect postponed execution
112
        if (empty($status) || empty($status->LastChecked)) {
113
            return false;
114
        }
115
116
        // Determine if we have passed the last expected run time
117
        $nextExpectedDate = $cron->getNextRunDate($status->LastChecked);
118
        return $nextExpectedDate <= $now;
119
    }
120
121
    /**
122
     * Default controller action
123
     *
124
     * @param HTTPRequest $request
125
     */
126
    public function index(HTTPRequest $request)
127
    {
128
        // Show more debug info with ?debug=1
129
        $isDebug = (bool)$request->getVar('debug');
130
131
        // Check each task
132
        $tasks = ClassInfo::implementorsOf(CronTask::class);
133
        if (empty($tasks)) {
134
            $this->output("There are no implementators of CronTask to run", 2);
135
            return;
136
        }
137
        foreach ($tasks as $subclass) {
138
            $task = Injector::inst()->create($subclass);
139
            // falsey schedule = don't run task
140
            if ($task->getSchedule()) {
141
                $this->runTask($task, $isDebug);
0 ignored issues
show
Unused Code introduced by
The call to CronTaskController::runTask() has too many arguments starting with $isDebug.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
142
            }
143
        }
144
    }
145
146
    /**
147
     * Checks and runs a single CronTask
148
     *
149
     * @param CronTask $task
150
     */
151
    public function runTask(CronTask $task)
152
    {
153
        $cron = CronExpression::factory($task->getSchedule());
154
        $isDue = $this->isTaskDue($task, $cron);
155
        // Update status of this task prior to execution in case of interruption
156
        CronTaskStatus::update_status(get_class($task), $isDue);
157
        if ($isDue) {
158
            $this->output(get_class($task) . ' will start now.');
159
            $task->process();
160
        } else {
161
            $this->output(get_class($task) . ' will run at ' . $cron->getNextRunDate()->format('Y-m-d H:i:s') . '.', 2);
162
        }
163
    }
164
165
    /**
166
     * Output a message to the browser or CLI
167
     *
168
     * @param string $message
169
     */
170
    public function output($message, $minVerbosity = 1)
171
    {
172
        if ($this->verbosity < $minVerbosity) {
173
            return;
174
        }
175
        $timestamp = DBDatetime::now()->Rfc2822();
176
        if (Director::is_cli()) {
177
            echo $timestamp . ' - ' . $message . PHP_EOL;
178
        } else {
179
            echo Convert::raw2xml($timestamp . ' - ' . $message) . '<br />' . PHP_EOL;
180
        }
181
    }
182
}
183