|
1
|
|
|
<?php |
|
2
|
|
|
declare(strict_types=1); |
|
3
|
|
|
namespace Watchmaker\lib; |
|
4
|
|
|
|
|
5
|
|
|
use ErrorException; |
|
6
|
|
|
use Watchmaker\error\FailedInstallCrontabException; |
|
7
|
|
|
use Watchmaker\error\MissingCrontabException; |
|
8
|
|
|
use Watchmaker\error\NotInstalledCrontabException; |
|
9
|
|
|
|
|
10
|
|
|
class CronWriter |
|
11
|
|
|
{ |
|
12
|
|
|
/** |
|
13
|
|
|
* @param array $watchmakerList |
|
14
|
|
|
* @return bool |
|
15
|
|
|
* @throws FailedInstallCrontabException |
|
16
|
|
|
* @throws MissingCrontabException |
|
17
|
|
|
* @throws NotInstalledCrontabException |
|
18
|
|
|
* @throws ErrorException |
|
19
|
|
|
*/ |
|
20
|
|
|
public function write(array $watchmakerList) : bool |
|
21
|
|
|
{ |
|
22
|
|
|
$ret = $this->isInstalledCrontab(); |
|
23
|
|
|
if ($ret === false) { |
|
24
|
|
|
throw new NotInstalledCrontabException(); |
|
25
|
|
|
} |
|
26
|
|
|
|
|
27
|
|
|
$error = fopen('php://temp', 'wb+'); |
|
28
|
|
|
if ($error === false) { |
|
29
|
|
|
throw new ErrorException(); |
|
30
|
|
|
|
|
31
|
|
|
} |
|
32
|
|
|
$descriptorspec = [ |
|
33
|
|
|
0 => array('pipe', 'r'), |
|
34
|
|
|
1 => array('pipe', 'w'), |
|
35
|
|
|
2 => $error |
|
36
|
|
|
]; |
|
37
|
|
|
$process = proc_open('/usr/bin/crontab -', $descriptorspec, $pipes); |
|
38
|
|
|
if ($process === false) { |
|
39
|
|
|
throw new MissingCrontabException(); |
|
40
|
|
|
} |
|
41
|
|
|
stream_set_blocking($pipes[1], false); |
|
42
|
|
|
|
|
43
|
|
|
foreach ($watchmakerList as $watchmaker) |
|
44
|
|
|
{ |
|
45
|
|
|
fputs($pipes[0], $watchmaker->generate() . "\n"); |
|
46
|
|
|
} |
|
47
|
|
|
fclose($pipes[0]); |
|
48
|
|
|
fclose($pipes[1]); |
|
49
|
|
|
|
|
50
|
|
|
$ret = proc_close($process); |
|
51
|
|
|
if ($ret !== 0) { |
|
52
|
|
|
// error (Error is output after proc_close) |
|
53
|
|
|
fseek($error, 0); |
|
54
|
|
|
$errorMessage = stream_get_contents($error); |
|
55
|
|
|
throw new FailedInstallCrontabException($errorMessage); |
|
56
|
|
|
} |
|
57
|
|
|
|
|
58
|
|
|
fclose($error); |
|
59
|
|
|
|
|
60
|
|
|
return true; |
|
61
|
|
|
} |
|
62
|
|
|
|
|
63
|
|
|
private function isInstalledCrontab() : bool |
|
64
|
|
|
{ |
|
65
|
|
|
$out = null; |
|
66
|
|
|
$return = null; |
|
67
|
|
|
exec("which crontab", $out, $return); |
|
68
|
|
|
if ($return !== 0) { |
|
69
|
|
|
return false; |
|
70
|
|
|
} |
|
71
|
|
|
|
|
72
|
|
|
return true; |
|
73
|
|
|
} |
|
74
|
|
|
} |
|
75
|
|
|
|