Test Setup Failed
Push — master ( 2557c0...98b58d )
by Php Easy Api
04:05
created

Schedule::scheduleInstance()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 10
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 5
nc 2
nop 1
dl 0
loc 10
rs 10
c 0
b 0
f 0
1
<?php
2
3
namespace Resta\Console\Source\Schedule;
4
5
use Resta\Schedule\ScheduleManager;
6
use Resta\Support\ClosureDispatcher;
7
use Resta\Support\Utils;
8
use Resta\Console\ConsoleOutputter;
9
use Resta\Console\ConsoleListAccessor;
10
11
class Schedule extends ConsoleOutputter {
12
13
    use ConsoleListAccessor;
14
15
    /**
16
     * @var $type
0 ignored issues
show
Documentation Bug introduced by
The doc comment $type at position 0 could not be parsed: Unknown type name '$type' at position 0 in $type.
Loading history...
17
     */
18
    public $type = 'schedule';
19
20
    /**
21
     * @var $define
0 ignored issues
show
Documentation Bug introduced by
The doc comment $define at position 0 could not be parsed: Unknown type name '$define' at position 0 in $define.
Loading history...
22
     */
23
    public $define = 'creates schedule for application';
24
25
    /**
26
     * @var $commandRule
0 ignored issues
show
Documentation Bug introduced by
The doc comment $commandRule at position 0 could not be parsed: Unknown type name '$commandRule' at position 0 in $commandRule.
Loading history...
27
     */
28
    public $commandRule = [
29
        'create' => ['schedule'],
30
        'register' => ['schedule'],
31
        'run' => ['schedule'],
32
    ];
33
34
    /**
35
     * @return void
36
     */
37
    public function create(){
38
39
        $schedulePath = app()->path()->schedule();
40
41
        if(!file_exists($schedulePath)){
42
            $this->directory['schedule'] = $schedulePath;
43
            $this->file->makeDirectory($this);
44
        }
45
46
        $this->argument['scheduleNamespace'] = app()->namespace()->schedule();
47
        $this->argument['scheduleClass'] = ucfirst($this->argument['schedule']).'';
48
        $this->argument['projectName'] = strtolower($this->projectName());
49
50
        $this->touch['schedule/schedule']= $schedulePath.'/'.$this->argument['schedule'].'.php';
51
52
53
        $this->file->touch($this);
54
55
        echo $this->classical(' > Schedule file called as "'.$this->argument['schedule'].'" has been successfully created in the '.$schedulePath.'');
56
    }
57
58
    public function list()
59
    {
60
        exec('crontab -l',$list);
61
62
        $this->table->setHeaders(['no','minute','hour','day','month','week','schedule','description']);
63
64
65
        foreach ($list as $key=>$item){
66
67
            if(preg_match('@.*php api schedule run '.strtolower($this->projectName()).'.*@is',$item,$result)){
68
                if(isset($result[0])){
69
70
                    $cron = [];
71
72
                    if(preg_match('@(.*)\scd@',$result[0],$cron)){
73
                        $cron = (isset($cron[1])) ? explode(' ',$cron[1]) : '';
74
75
                    }
76
77
                    $scheduleName = '';
78
79
                    if(preg_match('@schedule\:(.*?)\s@',$result[0],$scheduler)){
80
                        $scheduleName = (isset($scheduler[1])) ? $scheduler[1] : '';
81
82
                        $schedulerInstance = $this->scheduleInstance(ucfirst($scheduleName));
83
                        $description = ClosureDispatcher::bind($schedulerInstance)->call(function(){
84
                            return $this->description;
0 ignored issues
show
Bug Best Practice introduced by
The property description does not exist on Resta\Console\Source\Schedule\Schedule. Did you maybe forget to declare it?
Loading history...
85
                        });
86
87
                    }
88
89
                    $this->table->addRow([
90
                        $key+1,
91
                        isset($cron[0]) ? $cron[0] : '',
92
                        isset($cron[1]) ? $cron[1] : '',
93
                        isset($cron[2]) ? $cron[2] : '',
94
                        isset($cron[3]) ? $cron[3] : '',
95
                        isset($cron[4]) ? $cron[4] : '',
96
                        $scheduleName,
97
                        isset($description) ? $description : '',
98
                    ]);
99
                }
100
            }
101
        }
102
103
        echo $this->table->getTable();
104
    }
105
106
    /**
107
     * @return void
108
     */
109
    public function register()
110
    {
111
        $schedules = Utils::glob(app()->path()->schedule());
112
113
114
        if(isset($schedules[$this->argument['schedule']])){
115
116
            $scheduleNamespace = Utils::getNamespace($schedules[$this->argument['schedule']]);
117
            $scheduleInstance = app()->resolve($scheduleNamespace);
118
119
            $scheduleManager = new ScheduleManager();
120
            $scheduleInstance->when($scheduleManager);
121
122
            $cronScheduler = implode(' ',$scheduleManager->getCronScheduler());
123
124
            $command = $cronScheduler.' cd '.root.' && php api schedule run munch schedule:'.lcfirst($this->argument['schedule']).' >> /dev/null 2>&1';
125
126
            if($this->cronjob_exists($command)===false){
127
128
                $output = shell_exec('crontab -l');
129
                file_put_contents('/tmp/crontab.txt', $output.''.$command.''.PHP_EOL);
130
                exec('crontab /tmp/crontab.txt');
131
132
                echo $this->info('Cron has been added');
133
            }
134
135
        }
136
137
138
    }
139
140
    public function run()
141
    {
142
        $schedules = Utils::glob(app()->path()->schedule());
143
144
        if(isset($schedules[$this->argument['schedule']])){
145
            $scheduleNamespace = Utils::getNamespace($schedules[$this->argument['schedule']]);
146
            $scheduleInstance = app()->resolve($scheduleNamespace);
147
148
            $scheduleInstance->command();
149
        }
150
    }
151
152
    private function cronjob_exists($command){
153
154
        $cronjob_exists=false;
155
156
        exec('crontab -l', $crontab);
157
158
159
        if(isset($crontab)&&is_array($crontab)){
160
161
            $crontab = array_flip($crontab);
162
163
            if(isset($crontab[$command])){
164
165
                $cronjob_exists=true;
166
167
            }
168
169
        }
170
        return $cronjob_exists;
171
    }
172
173
    /**
174
     * @param $schedule
175
     * @return mixed|null
176
     */
177
    private function scheduleInstance($schedule)
178
    {
179
        $schedules = Utils::glob(app()->path()->schedule());
180
181
        if(isset($schedules[$schedule])){
182
            $scheduleNamespace = Utils::getNamespace($schedules[$schedule]);
183
            return $scheduleInstance = app()->resolve($scheduleNamespace);
0 ignored issues
show
Unused Code introduced by
The assignment to $scheduleInstance is dead and can be removed.
Loading history...
184
        }
185
186
        return null;
187
188
    }
189
190
}
191