Passed
Push — develop ( 027947...5e3b9c )
by nguereza
02:57
created

MaintenanceCommand::__construct()   C

Complexity

Conditions 12
Paths 1

Size

Total Lines 90
Code Lines 64

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 12
eloc 64
c 1
b 0
f 0
nc 1
nop 2
dl 0
loc 90
rs 6.3587

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
/**
4
 * Platine Framework
5
 *
6
 * Platine Framework is a lightweight, high-performance, simple and elegant
7
 * PHP Web framework
8
 *
9
 * This content is released under the MIT License (MIT)
10
 *
11
 * Copyright (c) 2020 Platine Framework
12
 *
13
 * Permission is hereby granted, free of charge, to any person obtaining a copy
14
 * of this software and associated documentation files (the "Software"), to deal
15
 * in the Software without restriction, including without limitation the rights
16
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
17
 * copies of the Software, and to permit persons to whom the Software is
18
 * furnished to do so, subject to the following conditions:
19
 *
20
 * The above copyright notice and this permission notice shall be included in all
21
 * copies or substantial portions of the Software.
22
 *
23
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
24
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
25
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
26
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
27
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
28
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
29
 * SOFTWARE.
30
 */
31
32
/**
33
 *  @file MaintenanceCommand.php
34
 *
35
 *  The Maintenance management command class
36
 *
37
 *  @package    Platine\Framework\Console\Command
38
 *  @author Platine Developers team
39
 *  @copyright  Copyright (c) 2020
40
 *  @license    http://opensource.org/licenses/MIT  MIT License
41
 *  @link   https://www.platine-php.com
42
 *  @version 1.0.0
43
 *  @filesource
44
 */
45
46
declare(strict_types=1);
47
48
namespace Platine\Framework\Console\Command;
49
50
use Platine\Config\Config;
51
use Platine\Console\Command\Command;
52
use Platine\Framework\App\Application;
53
use RuntimeException;
54
use Throwable;
55
56
/**
57
 * @class MaintenanceCommand
58
 * @package Platine\Framework\Console\Command
59
 * @template T
60
 */
61
class MaintenanceCommand extends Command
62
{
63
    /**
64
     * The configuration to use
65
     * @var Config<T>
66
     */
67
    protected Config $config;
68
69
    /**
70
     * The Platine Application
71
     * @var Application
72
     */
73
    protected Application $application;
74
75
    /**
76
     * Create new instance
77
     * @param Application $app
78
     * @param Config $config
79
     */
80
    public function __construct(
81
        Application $app,
82
        Config $config
83
    ) {
84
        $this->application = $app;
85
        $this->config = $config;
86
87
        $this->setName('maintenance')
88
             ->setDescription('The Maintenance management command');
89
90
        $this->addArgument('type', 'type of action [up|down]', 'up', true, true, false, function ($val) {
91
            if (!in_array($val, ['up', 'down'])) {
92
                throw new RuntimeException(sprintf(
93
                    'Invalid argument type [%s], must be one of [up, down]',
94
                    $val
95
                ));
96
            }
97
98
             return $val;
99
        });
100
101
        $this->addOption(
102
            '-t|--template',
103
            'The template that should be rendered for display during maintenance mode',
104
            null,
105
            false,
106
            true
107
        );
108
109
        $this->addOption(
110
            '-r|--retry',
111
            'The number of seconds after which the request may be retried',
112
            3600,
113
            false,
114
            true,
115
            false,
116
            function ($val) {
117
                if (strlen($val) > 0 && (!is_numeric($val) || (int) $val <= 0)) {
118
                    throw new RuntimeException(sprintf(
119
                        'Invalid retry value [%s], must be an integer greather than zero',
120
                        $val
121
                    ));
122
                }
123
            }
124
        );
125
        $this->addOption(
126
            '-e|--refresh',
127
            'The number of seconds after which the browser may refresh',
128
            3600,
129
            false,
130
            true,
131
            false,
132
            function ($val) {
133
                if (strlen($val) > 0 && (!is_numeric($val) || (int) $val <= 0)) {
134
                    throw new RuntimeException(sprintf(
135
                        'Invalid refresh value [%s], must be an integer greather than zero',
136
                        $val
137
                    ));
138
                }
139
            }
140
        );
141
        $this->addOption(
142
            '-s|--secret',
143
            'The secret phrase that may be used to bypass maintenance mode',
144
            null,
145
            false,
146
            true
147
        );
148
        $this->addOption(
149
            '-c|--status',
150
            'The status code that should be used when returning the maintenance mode response',
151
            503,
152
            false,
153
            true,
154
            false,
155
            function ($val) {
156
                if (strlen($val) > 0 && (!is_numeric($val) || (int) $val < 200 || (int) $val > 505)) {
157
                    throw new RuntimeException(sprintf(
158
                        'Invalid HTTP status value [%s], must be between 200 and 505',
159
                        $val
160
                    ));
161
                }
162
            }
163
        );
164
        $this->addOption(
165
            '-m|--message',
166
            'The message that will be shown to user during maintenance mode',
167
            null,
168
            false,
169
            true
170
        );
171
    }
172
173
    /**
174
     * {@inheritdoc}
175
     */
176
    public function execute()
177
    {
178
        $type = $this->getArgumentValue('type');
179
180
        $io = $this->io();
181
        $writer = $io->writer();
182
        $writer->boldYellow('APPLICATION MAINTENANCE MANAGEMENT', true)->eol();
183
184
        if ($type === 'up') {
185
            $this->online();
186
        } else {
187
            $this->down();
188
        }
189
    }
190
191
    /**
192
     * Put application online
193
     * @return void
194
     */
195
    public function online(): void
196
    {
197
        $writer = $this->io()->writer();
198
199
        try {
200
            if ($this->application->isInMaintenance() === false) {
201
                $writer->boldRed('Application already online')->eol();
202
                return;
203
            }
204
205
            $this->application->maintenance()->deactivate();
206
207
            $writer->boldRed('Application is now online')->eol();
208
        } catch (Throwable $ex) {
209
            $writer->boldRed(sprintf(
210
                'Failed to disable maintenance mode: %s.',
211
                $ex->getMessage()
212
            ))->eol();
213
        }
214
    }
215
216
    /**
217
     * Put application in maintenance mode
218
     * @return void
219
     */
220
    public function down(): void
221
    {
222
        $writer = $this->io()->writer();
223
224
        try {
225
            if ($this->application->isInMaintenance()) {
226
                $writer->boldRed('Application is already down.')->eol();
227
                return;
228
            }
229
230
            $data = $this->getPayload();
231
            $this->application->maintenance()->activate($data);
232
233
            $writer->boldRed('Application is now in maintenance mode.')->eol();
234
        } catch (Throwable $ex) {
235
            $writer->boldRed(sprintf(
236
                'Failed to enable maintenance mode: %s.',
237
                $ex->getMessage()
238
            ))->eol();
239
        }
240
    }
241
242
    /**
243
     * Get the payload to be placed in the maintenance file.
244
     * @return array<string, mixed>
245
     */
246
    protected function getPayload(): array
247
    {
248
        $retry = $this->getOptionValue('retry') ?? 3600;
249
        if ($retry) {
250
            $retry = (int) $retry;
251
        }
252
253
        $refresh = $this->getOptionValue('refresh') ?? 3600;
254
        if ($refresh) {
255
            $refresh = (int) $refresh;
256
        }
257
258
        $status = $this->getOptionValue('status') ?? 503;
259
        if ($status) {
260
            $status = (int) $status;
261
        }
262
263
        return [
264
            'except' => $this->config->get('maintenance.url_whitelist', []),
265
            'template' => $this->getOptionValue('template') ?? '',
266
            'retry' => $retry,
267
            'refresh' => $refresh,
268
            'secret' => $this->getOptionValue('secret') ?? '',
269
            'status' => $status,
270
            'message' => $this->getOptionValue('message') ?? '',
271
        ];
272
    }
273
}
274