Setting::import()   B
last analyzed

Complexity

Conditions 8
Paths 6

Size

Total Lines 75
Code Lines 42

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 44
CRAP Score 8

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 42
c 1
b 0
f 0
dl 0
loc 75
ccs 44
cts 44
cp 1
rs 8.0035
cc 8
nc 6
nop 0
crap 8

How to fix   Long Method   

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
 * This file is part of the Shieldon package.
4
 *
5
 * (c) Terry L. <[email protected]>
6
 *
7
 * For the full copyright and license information, please view the LICENSE
8
 * file that was distributed with this source code.
9
 *
10
 * php version 7.1.0
11
 *
12
 * @category  Web-security
13
 * @package   Shieldon
14
 * @author    Terry Lin <[email protected]>
15
 * @copyright 2019 terrylinooo
16
 * @license   https://github.com/terrylinooo/shieldon/blob/2.x/LICENSE MIT
17
 * @link      https://github.com/terrylinooo/shieldon
18
 * @see       https://shieldon.io
19
 */
20
21
declare(strict_types=1);
22
23
namespace Shieldon\Firewall\Panel;
24
25
use Psr\Http\Message\ResponseInterface;
26
use Shieldon\Firewall\Panel\BaseController;
27
use function Shieldon\Firewall\__;
28
use function Shieldon\Firewall\get_request;
29
use function Shieldon\Firewall\get_response;
30
use function Shieldon\Firewall\get_session_instance;
31
use function Shieldon\Firewall\unset_superglobal;
32
use function array_keys;
33
use function array_values;
34
use function explode;
35
use function filter_var;
36
use function json_decode;
37
use function json_last_error;
38
use const JSON_PRETTY_PRINT;
39
40
/**
41
 * Home
42
 */
43
class Setting extends BaseController
44
{
45
    /**
46
     *   Public methods       | Desctiotion
47
     *  ----------------------|---------------------------------------------
48
     *   basic                | The page for managing page authentication.
49
     *   ipManager            | The page for managing XSS protection.
50
     *   exclusion            | The page for managing excluded list.
51
     *   export               | Export the settings as a JSON file.
52
     *   import               | Improt the setting by a JSON file.
53
     *  ----------------------|---------------------------------------------
54
     */
55
56
    /**
57
     * Constructor
58
     */
59 16
    public function __construct()
60
    {
61 16
        parent::__construct();
62
    }
63
64
    /**
65
     * Set up basic settings.
66
     *
67
     * @return ResponseInterface
68
     */
69 2
    public function basic(): ResponseInterface
70
    {
71 2
        $data = [];
72
73 2
        $postParams = get_request()->getParsedBody();
74
75 2
        if (isset($postParams['tab'])) {
76 1
            unset_superglobal('tab', 'post');
77 1
            $this->saveConfig();
78
        }
79
80 2
        $data['title'] = __('panel', 'title_basic_setting', 'Basic Settings');
81
82 2
        return $this->renderPage('panel/setting', $data);
83
    }
84
85
    /**
86
     * Set up basic settings.
87
     *
88
     * @return ResponseInterface
89
     */
90 2
    public function messenger(): ResponseInterface
91
    {
92 2
        $data = [];
93
94 2
        $postParams = get_request()->getParsedBody();
95
96 2
        $data['ajaxUrl'] = $this->url('ajax/tryMessenger');
97
98 2
        if (isset($postParams['tab'])) {
99 1
            unset_superglobal('tab', 'post');
100 1
            $this->saveConfig();
101
        }
102
103 2
        $data['title'] = __('panel', 'title_messenger', 'Messenger');
104
105 2
        return $this->renderPage('panel/messenger', $data);
106
    }
107
108
    /**
109
     * IP manager.
110
     *
111
     * @return ResponseInterface
112
     */
113 5
    public function ipManager(): ResponseInterface
114
    {
115 5
        $postParams = get_request()->getParsedBody();
116
117
        if (isset($postParams['ip']) &&
118 5
            filter_var(explode('/', $postParams['ip'])[0], FILTER_VALIDATE_IP)
119 5
        ) {
120
            $url = $postParams['url'];
121
            $ip = $postParams['ip'];
122 4
            $rule = $postParams['action'];
123 4
            $order = (int) $postParams['order'];
124 4
125 4
            if ($order > 0) {
126
                $order--;
127 4
            }
128 1
129
            $ipList = (array) $this->getConfig('ip_manager');
130
131 4
            if ('allow' === $rule || 'deny' === $rule) {
132
                $newIpList = [];
133 4
                $newIpList[$order]['url'] = $url;
134
                $newIpList[$order]['ip'] = $ip;
135 2
                $newIpList[$order]['rule'] = $rule;
136 2
                array_splice($ipList, $order, 0, $newIpList);
137 2
                $this->setConfig('ip_manager', $ipList);
138 2
            } elseif ('remove' === $rule) {
139
                unset($ipList[$order]);
140 2
                $ipList = array_values($ipList);
141
                $this->setConfig('ip_manager', $ipList);
142 2
            }
143
144 2
            unset_superglobal('url', 'post');
145 2
            unset_superglobal('ip', 'post');
146 2
            unset_superglobal('action', 'post');
147 2
            unset_superglobal('order', 'post');
148
149
            $this->saveConfig();
150 4
        }
151 4
152 4
        $data = [];
153 4
154
        $data['ip_list'] = $this->getConfig('ip_manager');
155 4
156
        $data['title'] = __('panel', 'title_ip_manager', 'IP Manager');
157
158 5
        return $this->renderPage('panel/ip_manager', $data);
159
    }
160 5
161
    /**
162 5
     * Exclude the URLs that they don't need protection.
163
     *
164 5
     * @return ResponseInterface
165
     */
166
    public function exclusion(): ResponseInterface
167
    {
168
        $postParams = get_request()->getParsedBody();
169
170
        if (isset($postParams['url'])) {
171
            $url = $postParams['url'];
172 3
            $action = $postParams['action'];
173
            $order = (int) $postParams['order'];
174 3
175
            $excludedUrls = (array) $this->getConfig('excluded_urls');
176 3
177
            if ('add' === $action) {
178 2
                array_push(
179 2
                    $excludedUrls,
180 2
                    [
181
                        'url' => $url,
182 2
                    ]
183
                );
184 2
            } elseif ('remove' === $action) {
185 1
                unset($excludedUrls[$order]);
186 1
187 1
                $excludedUrls = array_values($excludedUrls);
188 1
            }
189 1
190 1
            $this->setConfig('excluded_urls', $excludedUrls);
191
192 1
            unset_superglobal('url', 'post');
193 1
            unset_superglobal('action', 'post');
194
            unset_superglobal('order', 'post');
195 1
196
            $this->saveConfig();
197
        }
198 2
199
        $data = [];
200 2
201 2
        $data['exclusion_list'] = $this->getConfig('excluded_urls');
202 2
203
        $data['title'] = __('panel', 'title_exclusion_list', 'Exclusion List');
204 2
205
        return $this->renderPage('panel/exclusion', $data);
206
    }
207 3
208
    /**
209 3
     * Export settings.
210
     *
211 3
     * @return ResponseInterface
212
     */
213 3
    public function export(): ResponseInterface
214
    {
215
        $response = get_response();
216
217
        $stream = $response->getBody();
218
        $stream->write(json_encode($this->configuration, JSON_PRETTY_PRINT));
219
        $stream->rewind();
220
221 1
        $filename = 'shieldon_' . date('Y-m-d-Hi') . '.json';
222
223 1
        $response = $response->withHeader('Content-Type', 'text/plain');
224
        $response = $response->withHeader('Content-Disposition', 'attachment; filename=' . $filename);
225 1
        $response = $response->withHeader('Expires', '0');
226 1
        $response = $response->withHeader('Cache-Control', 'must-revalidate, post-check=0, pre-check=0');
227 1
        $response = $response->withHeader('Pragma', 'public');
228
        $response = $response->withBody($stream);
229 1
230
        return $response;
0 ignored issues
show
Bug Best Practice introduced by
The expression return $response returns the type Psr\Http\Message\MessageInterface which includes types incompatible with the type-hinted return Psr\Http\Message\ResponseInterface.
Loading history...
231 1
    }
232 1
233 1
    /**
234 1
     * Import settings.
235 1
     *
236 1
     * @return ResponseInterface
237
     */
238 1
    public function import(): ResponseInterface
239
    {
240
        $request = get_request();
241
        $response = get_response();
242
243
        $uploadedFileArr = $request->getUploadedFiles();
244
        $importedFileContent = $uploadedFileArr['json_file']->getStream()->getContents();
245
246 3
        if (!empty($importedFileContent)) {
247
            $jsonData = json_decode($importedFileContent, true);
248 3
249 3
            if (json_last_error() !== JSON_ERROR_NONE) {
250
                $this->pushMessage(
251 3
                    'error',
252 3
                    __(
253
                        'panel',
254 3
                        'error_invalid_json_file',
255 3
                        'Invalid JSON file.'
256
                    )
257 3
                );
258 1
                get_session_instance()->set('flash_messages', $this->messages);
259 1
260 1
                // Return failed result message.
261 1
                return $response->withHeader('Location', $this->url('setting/basic'));
0 ignored issues
show
Bug Best Practice introduced by
The expression return $response->withHe...->url('setting/basic')) returns the type Psr\Http\Message\MessageInterface which includes types incompatible with the type-hinted return Psr\Http\Message\ResponseInterface.
Loading history...
262 1
            }
263 1
264 1
            $checkFileVaild = true;
265 1
266 1
            foreach (array_keys($this->configuration) as $key) {
267
                if (!isset($jsonData[$key])) {
268
                    $checkFileVaild = false;
269 1
                }
270
            }
271
272 2
            if ($checkFileVaild) {
273
                foreach (array_keys($jsonData) as $key) {
274 2
                    if (isset($this->configuration[$key])) {
275 2
                        unset($this->configuration[$key]);
276 2
                    }
277
                }
278
279
                $this->configuration = $this->configuration + $jsonData;
280 2
281 1
                // Save settings into a configuration file.
282 1
                $configFilePath = $this->directory . '/' . $this->filename;
283 1
                file_put_contents($configFilePath, json_encode($this->configuration));
284
285
                $this->pushMessage(
286
                    'success',
287 1
                    __(
288
                        'panel',
289
                        'success_json_imported',
290 1
                        'JSON file imported successfully.'
291 1
                    )
292
                );
293 1
294 1
                get_session_instance()->set('flash_messages', $this->messages);
295 1
296 1
                // Return succesfull result message.
297 1
                return $response->withHeader('Location', $this->url('setting/basic'));
0 ignored issues
show
Bug Best Practice introduced by
The expression return $response->withHe...->url('setting/basic')) returns the type Psr\Http\Message\MessageInterface which includes types incompatible with the type-hinted return Psr\Http\Message\ResponseInterface.
Loading history...
298 1
            }
299 1
        }
300 1
301
        $this->pushMessage(
302 1
            'error',
303
            __(
304
                'panel',
305 1
                'error_invalid_config_file',
306
                'Invalid Shieldon configuration file.'
307
            )
308
        );
309 1
310 1
        get_session_instance()->set('flash_messages', $this->messages);
311 1
312 1
        return $response->withHeader('Location', $this->url('setting/basic'));
0 ignored issues
show
Bug Best Practice introduced by
The expression return $response->withHe...->url('setting/basic')) returns the type Psr\Http\Message\MessageInterface which includes types incompatible with the type-hinted return Psr\Http\Message\ResponseInterface.
Loading history...
313 1
    }
314
}
315