Passed
Push — develop ( b91c6d...602856 )
by Nikolay
05:44 queued 10s
created

NginxConf::generateConf()   C

Complexity

Conditions 15
Paths 180

Size

Total Lines 78
Code Lines 59

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 59
c 1
b 0
f 0
dl 0
loc 78
rs 5.25
cc 15
nc 180
nop 2

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
/**
3
 * Copyright (C) MIKO LLC - All Rights Reserved
4
 * Unauthorized copying of this file, via any medium is strictly prohibited
5
 * Proprietary and confidential
6
 * Written by Nikolay Beketov, 7 2020
7
 *
8
 */
9
10
namespace MikoPBX\Core\System\Configs;
11
12
13
use MikoPBX\Core\System\MikoPBXConfig;
14
use MikoPBX\Core\System\Network;
15
use MikoPBX\Core\System\Util;
16
use MikoPBX\Core\System\Verify;
17
use Phalcon\Di\Injectable;
18
19
class NginxConf extends Injectable
20
{
21
    public const LOCATIONS_PATH = '/etc/nginx/mikopbx/locations';
22
23
    private MikoPBXConfig $mikoPBXConfig;
24
25
    /**
26
     * NginxConf constructor.
27
     */
28
    public function __construct()
29
    {
30
        $this->mikoPBXConfig = new MikoPBXConfig();
31
    }
32
33
    /**
34
     *   Restart Nginx and php-fpm
35
     **/
36
    public function reStart(): void
37
    {
38
        if (Util::isSystemctl()) {
39
            $systemCtrlPath = Util::which('systemctl');
40
            Util::mwExec("{$systemCtrlPath} restart php7.4-fpm");
41
            Util::mwExec("{$systemCtrlPath} restart nginx.service");
42
        } else {
43
            $phpFPMPath = Util::which('php-fpm');
44
            $NginxPath  = Util::which('nginx');
45
            Util::killByName('php-fpm');
46
            Util::killByName('nginx');
47
            Util::mwExec("{$phpFPMPath} -c /etc/php.ini");
48
            Util::mwExec($NginxPath);
49
        }
50
    }
51
52
    /**
53
     * Write additional settings the nginx.conf
54
     *
55
     * @param bool $not_ssl
56
     * @param int  $level
57
     */
58
    public function generateConf($not_ssl = false, $level = 0): void
59
    {
60
        $configPath      = '/etc/nginx/mikopbx/conf.d';
61
        $httpConfigFile  = "{$configPath}/http-server.conf";
62
        $httpsConfigFile = "{$configPath}/https-server.conf";
63
        $dns_server      = '127.0.0.1';
64
65
        $net = new Network();
66
        $dns = $net->getHostDNS();
67
        foreach ($dns as $ns) {
68
            if (Verify::isIpAddress($ns)) {
69
                $dns_server = trim($ns);
70
                break;
71
            }
72
        }
73
74
        // HTTP
75
        $WEBPort      = $this->mikoPBXConfig->getGeneralSettings('WEBPort');
76
        $WEBHTTPSPort = $this->mikoPBXConfig->getGeneralSettings('WEBHTTPSPort');
77
78
        $config = file_get_contents("{$httpConfigFile}.original");
79
        $config = str_replace(['<DNS>', '<WEBPort>'], [$dns_server, $WEBPort], $config);
80
81
        $RedirectToHttps = $this->mikoPBXConfig->getGeneralSettings('RedirectToHttps');
82
        if ($RedirectToHttps === '1' && $not_ssl === false) {
83
            $conf_data = 'if ( $remote_addr != "127.0.0.1" ) {' . PHP_EOL
84
                . '        ' . 'return 301 https://$host:' . $WEBHTTPSPort . '$request_uri;' . PHP_EOL
85
                . '       }' . PHP_EOL;
86
            $config    = str_replace('include mikopbx/locations/*.conf;', $conf_data, $config);
87
        }
88
        file_put_contents($httpConfigFile, $config);
89
90
        // SSL
91
        $WEBHTTPSPublicKey  = $this->mikoPBXConfig->getGeneralSettings('WEBHTTPSPublicKey');
92
        $WEBHTTPSPrivateKey = $this->mikoPBXConfig->getGeneralSettings('WEBHTTPSPrivateKey');
93
        if (
94
            $not_ssl === false
95
            && ! empty($WEBHTTPSPublicKey)
96
            && ! empty($WEBHTTPSPrivateKey)
97
        ) {
98
            $public_filename  = '/etc/ssl/certs/nginx.crt';
99
            $private_filename = '/etc/ssl/private/nginx.key';
100
            file_put_contents($public_filename, $WEBHTTPSPublicKey);
101
            file_put_contents($private_filename, $WEBHTTPSPrivateKey);
102
            $config = file_get_contents("{$httpsConfigFile}.original");
103
            $config = str_replace(['<DNS>', '<WEBHTTPSPort>'], [$dns_server, $WEBHTTPSPort], $config);
104
            file_put_contents($httpsConfigFile, $config);
105
        } elseif (file_exists($httpsConfigFile)) {
106
            unlink($httpsConfigFile);
107
        }
108
109
        // Test work
110
        $nginxPath = Util::which('nginx');
111
        $out       = [];
112
        Util::mwExec("{$nginxPath} -t", $out);
113
        $res = implode($out);
114
        if ($level < 1 && false !== strpos($res, 'test failed')) {
115
            ++$level;
116
            Util::sysLogMsg('nginx', 'Failed test config file. SSL will be disable...');
117
            $this->generateConf(true, $level);
118
        }
119
120
        // Add additional rules from modules
121
        $locationsPath     = self::LOCATIONS_PATH;
122
        $additionalModules = $this->di->getShared('pbxConfModules');
123
        $rmPath            = Util::which('rm');
124
        foreach ($additionalModules as $appClass) {
125
            if (method_exists($appClass, 'createNginxLocations')) {
126
                $locationContent = $appClass->createNginxLocations();
127
                if ( ! empty($locationContent)) {
128
                    $confFileName = "{$locationsPath}/{$appClass->moduleUniqueId}.conf";
129
                    file_put_contents($confFileName, $locationContent);
130
                    $out = [];
131
                    Util::mwExec("{$nginxPath} -t", $out);
132
                    $res = implode($out);
133
                    if (false !== strpos($res, 'test failed')) {
134
                        Util::mwExec("{$rmPath} {$confFileName}");
135
                        Util::sysLogMsg('nginx', 'Failed test config file for module' . $appClass->moduleUniqueId);
136
                    }
137
                }
138
            }
139
        }
140
    }
141
}