Passed
Pull Request — master (#4)
by Aleksandr
03:00
created

Service::ssidToHex()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 11
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 6
nc 2
nop 0
dl 0
loc 11
rs 10
c 0
b 0
f 0
1
<?php
2
3
namespace Sanchescom\WiFi\System\Windows\Profile;
4
5
use Sanchescom\WiFi\System\Windows\Network;
6
7
/**
8
 * Class Service.
9
 */
10
class Service
11
{
12
    /**
13
     * @var string
14
     */
15
    protected static $tmpFolderName = 'tmp';
16
17
    /**
18
     * @var string
19
     */
20
    protected static $templateFolderName = 'templates';
21
22
    /**
23
     * @var string
24
     */
25
    protected static $fileNamePostfix = 'PersonalProfileTemplate.xml';
26
27
    /**
28
     * @var Network
29
     */
30
    protected $network;
31
32
    /**
33
     * Service constructor.
34
     *
35
     * @param Network $network
36
     */
37
    public function __construct(Network $network)
38
    {
39
        $this->network = $network;
40
    }
41
42
    /**
43
     * @param string $password
44
     *
45
     * @return bool
46
     */
47
    public function create(string $password): bool
48
    {
49
        return (bool) file_put_contents($this->getTmpProfileFileName(), $this->renderTemplate($password));
50
    }
51
52
    /**
53
     * Delete tmp profile file created for chosen network.
54
     */
55
    public function delete(): bool
56
    {
57
        $tmpProfile = $this->getTmpProfileFileName();
58
59
        if (file_exists($tmpProfile)) {
60
            return unlink($tmpProfile);
61
        }
62
63
        return false;
64
    }
65
66
    /**
67
     * @return string
68
     */
69
    public function getTmpProfileFileName(): string
70
    {
71
        return __DIR__
72
            .DIRECTORY_SEPARATOR
73
            .static::$tmpFolderName
74
            .DIRECTORY_SEPARATOR
75
            .$this->network->ssid
76
            .'.xml';
77
    }
78
79
    /**
80
     * @param string $password
81
     *
82
     * @return string
83
     */
84
    protected function renderTemplate(string $password): string
85
    {
86
        $content = file_get_contents($this->getTemplateProfileFileName()) ?: '';
87
88
        return str_replace(
89
            [
90
                '{ssid}',
91
                '{hex}',
92
                '{key}',
93
            ],
94
            [
95
                $this->network->ssid,
96
                to_hex($this->network->ssid),
97
                $password,
98
            ],
99
            $content
100
        );
101
    }
102
103
    /**
104
     * @return string
105
     */
106
    protected function getTemplateProfileFileName(): string
107
    {
108
        return __DIR__
109
            .DIRECTORY_SEPARATOR
110
            .static::$templateFolderName
111
            .DIRECTORY_SEPARATOR
112
            .$this->network->getSecurityType()
113
            .'-'
114
            .static::$fileNamePostfix;
115
    }
116
}
117