HostsFileResolutionWriter   A
last analyzed

Complexity

Total Complexity 8

Size/Duplication

Total Lines 85
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 1

Importance

Changes 0
Metric Value
wmc 8
lcom 1
cbo 1
dl 0
loc 85
rs 10
c 0
b 0
f 0

6 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
A write() 0 11 1
A removeHostname() 0 18 3
A getFilePath() 0 4 1
A writeAsRoot() 0 7 1
A getHostsFileResolutionLine() 0 4 1
1
<?php
2
3
namespace Dock\Plugins\ExtraHostname;
4
5
use Dock\IO\ProcessRunner;
6
7
class HostsFileResolutionWriter implements HostnameResolutionWriter
8
{
9
    /**
10
     * @var ProcessRunner
11
     */
12
    private $processRunner;
13
14
    /**
15
     * @param ProcessRunner $processRunner
16
     */
17
    public function __construct(ProcessRunner $processRunner)
18
    {
19
        $this->processRunner = $processRunner;
20
    }
21
22
    /**
23
     * {@inheritdoc}
24
     */
25
    public function write($hostname, $address)
26
    {
27
        $this->removeHostname($hostname);
28
29
        $hostsFilePath = $this->getFilePath();
30
        $contents = file_get_contents($hostsFilePath);
31
        $resolutionLine = $this->getHostsFileResolutionLine($hostname, $address);
32
        $contents .= PHP_EOL.$resolutionLine.PHP_EOL;
33
34
        $this->writeAsRoot($hostsFilePath, $contents);
35
    }
36
37
    /**
38
     * Remove hostname reference from `/etc/hosts`.
39
     *
40
     * @param string $hostname
41
     */
42
    private function removeHostname($hostname)
43
    {
44
        $filePath = $this->getFilePath();
45
        $quotedHostname = preg_quote($hostname);
46
        $fileContents = '';
47
48
        foreach (file($filePath) as $line) {
49
            $trimmedLine = trim($line);
50
51
            if (preg_match('#'.$quotedHostname.' \# dock-cli$#i', $trimmedLine)) {
52
                continue;
53
            }
54
55
            $fileContents .= $line;
56
        }
57
58
        $this->writeAsRoot($filePath, $fileContents);
59
    }
60
61
    /**
62
     * @return string
63
     */
64
    private function getFilePath()
65
    {
66
        return '/etc/hosts';
67
    }
68
69
    /**
70
     * @param string $targetPath
71
     * @param string $fileContents
72
     */
73
    private function writeAsRoot($targetPath, $fileContents)
74
    {
75
        $temporaryFile = tempnam(sys_get_temp_dir(), 'hostFile');
76
        file_put_contents($temporaryFile, $fileContents);
77
78
        $this->processRunner->run(sprintf('sudo cp %s %s', $temporaryFile, $targetPath));
79
    }
80
81
    /**
82
     * @param string $hostname
83
     * @param string $address
84
     *
85
     * @return string
86
     */
87
    private function getHostsFileResolutionLine($hostname, $address)
88
    {
89
        return $address.' '.$hostname.' # dock-cli';
90
    }
91
}
92