1 | <?php |
||
11 | class CronManager |
||
12 | { |
||
13 | /** |
||
14 | * The lines of the cron table, can be cron command or comment |
||
15 | * |
||
16 | * @var string[]|Cron[] |
||
17 | */ |
||
18 | protected $lines = []; |
||
19 | |||
20 | /** |
||
21 | * The error when using the comment 'crontab' |
||
22 | * |
||
23 | * @var string |
||
24 | */ |
||
25 | protected $error; |
||
26 | |||
27 | /** |
||
28 | * The output when using the command 'crontab' |
||
29 | * |
||
30 | * @var string |
||
31 | */ |
||
32 | protected $output; |
||
33 | |||
34 | public function __construct() |
||
35 | { |
||
36 | // parsing cron file |
||
37 | $process = new Process('crontab -l'); |
||
38 | $process->run(); |
||
39 | $lines = array_filter(explode(PHP_EOL, $process->getOutput()), function ($line) { |
||
40 | return '' != trim($line); |
||
41 | }); |
||
42 | |||
43 | foreach ($lines as $lineNumber => $line) { |
||
44 | // if line is not a comment, convert it to a cron |
||
45 | if (strpos($line, '#suspended: ', 0) === 0 || 0 !== strpos($line, '#', 0)) { |
||
46 | try { |
||
47 | $line = Cron::parse($line); |
||
48 | } catch (\Exception $e) { |
||
49 | $process->addErrorOutput('CronManager was unable to parse crontab at line ' . $lineNumber); |
||
50 | } |
||
51 | } |
||
52 | $this->lines['l' . $lineNumber] = $line; |
||
53 | } |
||
54 | |||
55 | $this->error = $process->getErrorOutput(); |
||
56 | } |
||
57 | |||
58 | /** |
||
59 | * Gets the array of crons indexed by line number |
||
60 | * |
||
61 | * @return Cron[] |
||
62 | */ |
||
63 | public function getCrons() |
||
69 | |||
70 | /** |
||
71 | * Get a specific cron by its id |
||
72 | * |
||
73 | * @param int $id |
||
74 | * |
||
75 | * @return Cron |
||
76 | */ |
||
77 | public function getById($id) |
||
86 | |||
87 | /** |
||
88 | * Add a cron to the cron table |
||
89 | * |
||
90 | * @param Cron $cron |
||
91 | */ |
||
92 | public function add(Cron $cron) |
||
97 | |||
98 | /** |
||
99 | * Remove a cron from the cron table |
||
100 | * |
||
101 | * @param int $index - the line number |
||
102 | */ |
||
103 | public function remove($index) |
||
108 | |||
109 | /** |
||
110 | * Write the current crons in the cron table |
||
111 | */ |
||
112 | public function write() |
||
124 | |||
125 | /** |
||
126 | * Gets the error output when using the 'crontab' command |
||
127 | * |
||
128 | * @return string |
||
129 | */ |
||
130 | public function getError() |
||
134 | |||
135 | /** |
||
136 | * Gets the output when using the 'crontab' command |
||
137 | * |
||
138 | * @return string |
||
139 | */ |
||
140 | public function getOutput() |
||
144 | |||
145 | /** |
||
146 | * Gets a representation of the cron table file |
||
147 | * |
||
148 | * @return string |
||
149 | */ |
||
150 | public function getRaw() |
||
154 | } |
||
155 |