ScheduleController::options()   A
last analyzed

Complexity

Conditions 2
Paths 1

Size

Total Lines 7
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

Changes 0
Metric Value
dl 0
loc 7
ccs 0
cts 5
cp 0
rs 9.4285
c 0
b 0
f 0
cc 2
eloc 4
nc 1
nop 1
crap 6
1
<?php
2
3
/*
4
 * This file is part of the mytheam/yii2-schedule.
5
 *
6
 * (c) mytheam <[email protected]>
7
 *
8
 * This source file is subject to the BSD license that is bundled
9
 * with this source code in the file LICENSE.
10
 */
11
12
namespace mythteam\schedule;
13
14
use Yii;
15
use yii\di\Instance;
16
use yii\console\Controller;
17
18
/**
19
 * ~~~
20
 * * * * * * php /path/to/yii yii schedule 1>> /dev/null 2>&1
21
 * ~~.
22
 */
23
class ScheduleController extends Controller
24
{
25
    /**
26
     * @var string|Schedule
27
     */
28
    public $schedule = 'schedule';
29
30
    /**
31
     * @var string Schedule file path
32
     */
33
    public $scheduleFile;
34
35
    /**
36
     * {@inheritdoc}
37
     */
38
    public $defaultAction = 'run';
39
40
    /**
41
     * {@inheritdoc}
42
     */
43
    public function options($actionId)
44
    {
45
        return array_merge(
46
            parent::options($actionId),
47
            $actionId == 'run' ? ['scheduleFile'] : []
48
        );
49
    }
50
51
    /**
52
     * {@inheritdoc}
53
     */
54
    public function init()
55
    {
56
        if (is_string($this->schedule)
57
            && Yii::$app->has($this->schedule)
58
        ) {
59
            $this->schedule = Instance::ensure($this->schedule, Schedule::className());
60
        } else {
61
            $this->schedule = Yii::createObject(Schedule::className());
62
        }
63
        parent::init();
64
    }
65
66
    public function actionRun()
67
    {
68
        $this->stdout(PHP_EOL);
69
        $this->importScheduleFile();
70
71
        /** @var Event[] $events */
72
        $events = $this->schedule->dueEvents(Yii::$app);
73
74
        foreach ($events as $event) {
75
            $this->stdout('Runing scheduled command ' . $event->getSummaryForDisplay() . PHP_EOL);
76
            $event->run(Yii::$app);
77
        }
78
        if (count($events) == 0) {
79
            $this->stdout('No scheduled commands are ready to run.' . PHP_EOL);
80
        }
81
    }
82
83
    /**
84
     * Import the schedule file and set the scheduled evetns.
85
     */
86
    protected function importScheduleFile()
87
    {
88
        if (null === $this->scheduleFile) {
89
            return;
90
        }
91
92
        $scheduleFile = Yii::getAlias($this->scheduleFile);
93
94
        if (file_exists($scheduleFile) === false) {
95
            $this->stderr("Can not load schedule file {$this->scheduleFile}" . PHP_EOL);
96
97
            return;
98
        }
99
        $schedule = $this->schedule;
100
101
        call_user_func(function () use ($schedule, $scheduleFile) {
102
            require $scheduleFile;
103
        });
104
    }
105
}
106