Passed
Push — master ( 8a6050...5a6ead )
by Andrii
11:18
created

Systemd::status()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

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