1 | <?php |
||
2 | |||
3 | namespace hidev\components; |
||
4 | |||
5 | use hidev\helpers\Sys; |
||
6 | |||
7 | class Systemd |
||
8 | { |
||
9 | private $name; |
||
10 | |||
11 | public function __construct(string $name) |
||
12 | { |
||
13 | $this->name = $name; |
||
14 | } |
||
15 | |||
16 | public function up(string $config = null) |
||
17 | { |
||
18 | if ($config) { |
||
19 | $this->setup($config); |
||
20 | } |
||
21 | $this->enable(); |
||
22 | $this->start(); |
||
23 | $this->status(); |
||
24 | } |
||
25 | |||
26 | public function down() |
||
27 | { |
||
28 | $this->stop(); |
||
29 | $this->disable(); |
||
30 | } |
||
31 | |||
32 | public function checkConfig() |
||
33 | { |
||
34 | $path = $this->getPath(); |
||
35 | if (!file_exists($path)) { |
||
36 | throw new \Exception("no config: $path"); |
||
37 | } |
||
38 | } |
||
39 | |||
40 | private $path; |
||
41 | |||
42 | public function getPath() |
||
43 | { |
||
44 | if ($this->path === null) { |
||
45 | $path = "/etc/systemd/system/{$this->name}.service"; |
||
46 | } |
||
47 | |||
48 | return $path; |
||
0 ignored issues
–
show
Comprehensibility
Best Practice
introduced
by
![]() |
|||
49 | } |
||
50 | |||
51 | public function setup(string $config) |
||
52 | { |
||
53 | $name = $this->name; |
||
54 | $temp = "/tmp/$name.service"; |
||
55 | $dest = $this->getPath(); |
||
56 | file_put_contents($temp, $config); |
||
57 | Sys::passthru("sudo cp $temp $dest"); |
||
58 | } |
||
59 | |||
60 | public function enable() |
||
61 | { |
||
62 | $this->systemctl('enable'); |
||
63 | } |
||
64 | |||
65 | public function disable() |
||
66 | { |
||
67 | $this->systemctl('disable'); |
||
68 | } |
||
69 | |||
70 | public function stop() |
||
71 | { |
||
72 | $this->systemctl('stop'); |
||
73 | } |
||
74 | |||
75 | public function start() |
||
76 | { |
||
77 | $this->systemctl('start'); |
||
78 | } |
||
79 | |||
80 | public function restart() |
||
81 | { |
||
82 | $this->systemctl('restart'); |
||
83 | } |
||
84 | |||
85 | public function status() |
||
86 | { |
||
87 | $this->systemctl('status'); |
||
88 | } |
||
89 | |||
90 | public function systemctl(string $command) |
||
91 | { |
||
92 | $this->checkConfig(); |
||
93 | $sudo = $command === 'status' ? '' : 'sudo'; |
||
94 | Sys::passthru("$sudo systemctl $command {$this->name}"); |
||
95 | } |
||
96 | } |
||
97 |