Completed
Push — master ( da521e...2646ae )
by Richan
01:12
created

WebServer::stop()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 7
rs 10
c 0
b 0
f 0
cc 2
nc 2
nop 0
1
<?php
2
3
namespace Suitmedia\LighthouseAudit;
4
5
use Suitmedia\LighthouseAudit\Concerns\CanResolveDocumentRoot;
6
use Suitmedia\LighthouseAudit\Concerns\SanitizeInput;
7
use Symfony\Component\Console\Input\InputInterface;
8
use Symfony\Component\Process\Process;
9
10
class WebServer
11
{
12
    use CanResolveDocumentRoot;
13
    use SanitizeInput;
14
15
    /**
16
     * Console input interface.
17
     *
18
     * @var InputInterface
19
     */
20
    protected $input;
21
22
    /**
23
     * Current web server process.
24
     *
25
     * @var Process
26
     */
27
    protected $process;
28
29
    /**
30
     * Process builder instance.
31
     *
32
     * @var ProcessBuilder
33
     */
34
    protected $processBuilder;
35
36
    /**
37
     * WebServer constructor.
38
     *
39
     * @param InputInterface $input
40
     * @param ProcessBuilder $processBuilder
41
     */
42
    public function __construct(InputInterface $input, ProcessBuilder $processBuilder)
43
    {
44
        $this->input = $input;
45
        $this->processBuilder = $processBuilder;
46
    }
47
48
    /**
49
     * Create and run the web server process.
50
     *
51
     * @return void
52
     */
53
    public function run() :void
54
    {
55
        $documentRoot = $this->getDocumentRoot(
56
            $this->input->getArgument('path')
57
        );
58
        $server = $this->getListenAddressAndPort();
59
60
        $this->process = $this->processBuilder->create([
61
            'php',
62
            '-t',
63
            $documentRoot,
64
            '-S',
65
            $server,
66
        ]);
67
        $this->process->setTimeout(0);
68
69
        $this->process->start();
70
    }
71
72
    /**
73
     * Stop the web server.
74
     *
75
     * @return void
76
     */
77
    public function stop() :void
78
    {
79
        if (isset($this->process)) {
80
            $this->process->stop(1);
81
            unset($this->process);
82
        }
83
    }
84
85
    /**
86
     * Get listen address and port from input.
87
     *
88
     * @return string
89
     */
90
    protected function getListenAddressAndPort() :string
91
    {
92
        $server = $this->input->getOption('server');
93
94
        return $this->trimDoubleQuotes(is_string($server) ? $server : Command::DEFAULT_SERVER);
95
    }
96
97
    /**
98
     * Web server destructor.
99
     */
100
    public function __destruct()
101
    {
102
        $this->stop();
103
    }
104
}
105