Main::run()   F
last analyzed

Complexity

Conditions 31
Paths 258

Size

Total Lines 138
Code Lines 98

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 992

Importance

Changes 0
Metric Value
dl 0
loc 138
ccs 0
cts 0
cp 0
rs 3.4536
c 0
b 0
f 0
cc 31
eloc 98
nc 258
nop 0
crap 992

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
 *
5
 * This file is part of the Apix Project.
6
 *
7
 * (c) Franck Cassedanne <franck at ouarz.net>
8
 *
9
 * @license     http://opensource.org/licenses/BSD-3-Clause  New BSD License
10
 *
11
 */
12
13
namespace Apix\Console;
14
15
use Apix\Console,
16
    Apix\Server,
17
    Apix\Input;
18
19
/**
20
 * Main Console class.
21
 *
22
 * @codeCoverageIgnore
23
 */
24
class Main extends Console
25
{
26
27
    protected $version;
28
    protected $version_program;
29
30
    protected $src;
31
    protected $src_file = 'apix.phar';
32
    protected $src_url;
33
34
    protected $phar_name = null;
35
36
    public function __construct(array $options = null)
37
    {
38
        $this->src_url = 'http://api.ouarz.net/v1/%s/%s/in/%s';
39
40
        #$this->src = realpath(__DIR__ . '/../../../../../');
0 ignored issues
show
Unused Code Comprehensibility introduced by
47% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
41
        $this->src = realpath(__DIR__ . '/../../../../');
42
43
        $this->version = Server::VERSION;
44
        $this->version_program =
45
            sprintf('Apix Server %s by Franck Cassedanne.', $this->version);
46
47
        parent::__construct($options);
48
    }
49
50
    public function setPharName($name)
51
    {
52
        $this->phar_name = $name;
53
        $this->src = $name;
54
    }
55
56
    public function setSrcFile($name)
57
    {
58
        $this->src_file = $name;
59
    }
60
61
    public function run()
0 ignored issues
show
Coding Style introduced by
run uses the super-global variable $_SERVER which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

    public function __construct($host)
    {
        $this->host = $host;
    }

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
62
    {
63
        $args = $this->getArgs();
64
        $args[0] = 'php ' . $args[0];
65
66
        $cmd = empty($args[1])
67
                ? '--help'
68
                : $args[1];
69
70
        $this->out($this->version_program . PHP_EOL .PHP_EOL);
71
72
        switch ($cmd):
73
            case '-r': case '--readme':
0 ignored issues
show
Coding Style introduced by
The case body in a switch statement must start on the line following the statement.

According to the PSR-2, the body of a case statement must start on the line immediately following the case statement.

switch ($expr) {
case "A":
    doSomething(); //right
    break;
case "B":

    doSomethingElse(); //wrong
    break;

}

To learn more about the PSR-2 coding standard, please refer to the PHP-Fig.

Loading history...
74
                $this->out('README' . PHP_EOL . PHP_EOL, 'bold', 'underline');
75
                $this->out(
76
                    file_get_contents($this->src . '/README.md')
77
                );
78
                $this->out();
79
            break;
80
81
            case '--version':
82
                exit(0);
0 ignored issues
show
Coding Style Compatibility introduced by
The method run() contains an exit expression.

An exit expression should only be used in rare cases. For example, if you write a short command line script.

In most cases however, using an exit expression makes the code untestable and often causes incompatibilities with other libraries. Thus, unless you are absolutely sure it is required here, we recommend to refactor your code to avoid its usage.

Loading history...
83
            break;
0 ignored issues
show
Unused Code introduced by
break; does not seem to be reachable.

This check looks for unreachable code. It uses sophisticated control flow analysis techniques to find statements which will never be executed.

Unreachable code is most often the result of return, die or exit statements that have been added for debug purposes.

function fx() {
    try {
        doSomething();
        return true;
    }
    catch (\Exception $e) {
        return false;
    }

    return false;
}

In the above example, the last return false will never be executed, because a return statement has already been met in every possible execution path.

Loading history...
84
85
            case '--extractdist': case '-e':
0 ignored issues
show
Coding Style introduced by
The case body in a switch statement must start on the line following the statement.

According to the PSR-2, the body of a case statement must start on the line immediately following the case statement.

switch ($expr) {
case "A":
    doSomething(); //right
    break;
case "B":

    doSomethingElse(); //wrong
    break;

}

To learn more about the PSR-2 coding standard, please refer to the PHP-Fig.

Loading history...
86
                $src = $this->src . '/src/data/distribution/';
87
                $dest = $_SERVER['PWD'];
88
                try {
89
                    $it = new \DirectoryIterator($src);
90
                    $this->out("Latest distribution files: " . PHP_EOL, 'green');
91
92
                    foreach ($it as $file) {
93
                        if ($file->isFile()) {
94
                            $this->out(" --> " . $file . PHP_EOL, "red");
95
                            file_put_contents(
96
                                $dest . '/' . $file,
97
                                file_get_contents($src . '/' .$file)
98
                            );
99
                        }
100
                    }
101
                } catch (\Exception $e) {
102
                    $this->outputError($e);
103
                }
104
                $this->out(PHP_EOL . "have been copied into:" . PHP_EOL, 'green');
105
                $this->out(" --> " . $dest . PHP_EOL .PHP_EOL, 'red');
106
                $this->out("Manually rename each files from '*.dist.php' to '*.php' to use them." . PHP_EOL);
107
                $this->out("e.g." . PHP_EOL . "cp -i config.dist.php projectname-config.php" . PHP_EOL, 'blue');
108
            break;
109
110
            case '-c': case '--check':
0 ignored issues
show
Coding Style introduced by
The case body in a switch statement must start on the line following the statement.

According to the PSR-2, the body of a case statement must start on the line immediately following the case statement.

switch ($expr) {
case "A":
    doSomething(); //right
    break;
case "B":

    doSomethingElse(); //wrong
    break;

}

To learn more about the PSR-2 coding standard, please refer to the PHP-Fig.

Loading history...
111
112
                try {
113
                    $url = sprintf($this->src_url, 'version', $this->src_file, $this->version);
114
115
                    if ($this->verbose) {
116
                        $this->outRegex("Contacting...\n<brown>${url}</brown>\n\n");
117
                    }
118
                    $response = trim($this->getContents($url));
119
120
                    $input = new Input\Json();
121
                    $r = $input->decode($response, true);
122
                    if ($this->verbose > 2) {
123
                        print_r($r);
124
                    }
125
126
                    $latest = $r['apix']['version'][$this->src_file]['latest'];
127
                    if (empty($latest)) {
128
                        throw new \Exception("Something, somewhere failed!");
129
                    }
130
131
                    if ( version_compare($this->version, $latest, '>=') != 1) {
132
                        $this->out(sprintf("A newer version is available (%s).", $latest));
133
                        $this->outRegex(sprintf("\nTo update, run: <brown>%s --selfupdate</brown>\n",  $args[0]));
134
                    } else {
135
                        $this->out("You are using the latest version.");
136
                    }
137
                } catch (\Exception $e) {
138
                    $this->outputError($e);
139
                }
140
            break;
141
142
            case '--selfupdate':
143
                $url = sprintf($this->src_url, 'download', $this->src_file, $this->version);
144
                $dest = $_SERVER['argv'][0];
145
146
                if ($this->verbose > 2) {
147
                    $this->out(' --> ' . $dest);
148
                    $this->out();
149
                }
150
151
                $this->retrieveUpdate($url, $dest);
152
            break;
153
154
            case '-s': case '--syscheck':
0 ignored issues
show
Coding Style introduced by
The case body in a switch statement must start on the line following the statement.

According to the PSR-2, the body of a case statement must start on the line immediately following the case statement.

switch ($expr) {
case "A":
    doSomething(); //right
    break;
case "B":

    doSomethingElse(); //wrong
    break;

}

To learn more about the PSR-2 coding standard, please refer to the PHP-Fig.

Loading history...
155
                $syscheck = new SystemCheck();
156
                $syscheck->setArgs(array('--all', '--no-credits'));
157
                $syscheck->run();
158
                break;
159
160
            case '--license':
161
                $this->out(file_get_contents($this->src .'/LICENSE.txt'));
162
            break;
163
164
            case '-i': case '--info':
0 ignored issues
show
Coding Style introduced by
The case body in a switch statement must start on the line following the statement.

According to the PSR-2, the body of a case statement must start on the line immediately following the case statement.

switch ($expr) {
case "A":
    doSomething(); //right
    break;
case "B":

    doSomethingElse(); //wrong
    break;

}

To learn more about the PSR-2 coding standard, please refer to the PHP-Fig.

Loading history...
165
                phpinfo();
166
            break;
167
168
            case '-h': case '--help':
0 ignored issues
show
Coding Style introduced by
The case body in a switch statement must start on the line following the statement.

According to the PSR-2, the body of a case statement must start on the line immediately following the case statement.

switch ($expr) {
case "A":
    doSomething(); //right
    break;
case "B":

    doSomethingElse(); //wrong
    break;

}

To learn more about the PSR-2 coding standard, please refer to the PHP-Fig.

Loading history...
169
                $this->help();
170
            break;
171
172
            case '-t': case '--tests':
0 ignored issues
show
Coding Style introduced by
The case body in a switch statement must start on the line following the statement.

According to the PSR-2, the body of a case statement must start on the line immediately following the case statement.

switch ($expr) {
case "A":
    doSomething(); //right
    break;
case "B":

    doSomethingElse(); //wrong
    break;

}

To learn more about the PSR-2 coding standard, please refer to the PHP-Fig.

Loading history...
173
                $cmd = 'phpunit';
174
                if ($this->verbose) {
175
                    $cmd .= ' --verbose';
176
                }
177
                if ($this->verbose > 2) {
178
                    $cmd .= ' --debug';
179
                }
180
                if (false == $this->no_colors) {
181
                    $cmd .= ' --colors';
182
                }
183
                $cmd .= ' --bootstrap src/tests/unit-tests/pharstrap.php';
184
                $cmd .= ' -c src/tests/unit-tests/pharunit.xml';
185
                system($cmd);
186
            break;
187
188
            default:
189
                $this->out('Error: ', $args[1], 'bold', 'red');
190
                $this->out(sprintf('unknown option/command "%s".' . PHP_EOL, $args[1]), 'red');
191
                $this->out(sprintf('You should try "%s --help".', $args[0]), 'green');
192
193
        endswitch;
194
195
        $this->out();
196
197
        exit(0);
0 ignored issues
show
Coding Style Compatibility introduced by
The method run() contains an exit expression.

An exit expression should only be used in rare cases. For example, if you write a short command line script.

In most cases however, using an exit expression makes the code untestable and often causes incompatibilities with other libraries. Thus, unless you are absolutely sure it is required here, we recommend to refactor your code to avoid its usage.

Loading history...
198
    }
199
200 View Code Duplication
    public function help()
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
201
    {
202
        $args = $this->getArgs();
203
        $args[0] = 'php ' . $args[0];
204
205
        $this->outRegex(
206
<<<HELP
207
<bold>Usage:</bold> <brown>{$args[0]}</brown> [OPTIONS]\r\n
208
<bold>Options:</bold>\r
209
   --readme <brown>|</brown> -r\t<brown>Display the README file</brown>
210
   --extractdist <brown>|</brown> -e\t<brown>Extract the latest distribution data</brown>
211
   --check <brown>|</brown> -c\t\t<brown>Check for updates</brown>
212
   --selfupdate\t\t<brown>Upgrade Apix to the latest version available</brown>
213
   --version\t\t<brown>Display the version information and exit</brown>
214
   --info <brown>|</brown> -i\t\t<brown>PHP information and configuration</brown>
215
   --license\t\t<brown>Display the software license</brown>
216
   --syscheck <brown>|</brown> -s\t<brown>Run a system check</brown>
217
   --tests <brown>|</brown> -t\t\t<brown>Run some unit & functional tests</brown>
218
   --no-colors\t\t<brown>Don't use colors in the outputs</brown>
219
   --verbose <brown>|</brown> -v\t<brown>Add some verbosity to the outputs.\n\t\t\tMultiple -v options increase the verbosity.</brown>
220
   --help <brown>|</brown> -h\t\t<brown>Display this help</brown>\n\n
221
HELP
222
        );
223
        exit;
0 ignored issues
show
Coding Style Compatibility introduced by
The method help() contains an exit expression.

An exit expression should only be used in rare cases. For example, if you write a short command line script.

In most cases however, using an exit expression makes the code untestable and often causes incompatibilities with other libraries. Thus, unless you are absolutely sure it is required here, we recommend to refactor your code to avoid its usage.

Loading history...
224
    }
225
226
    public function outputError(\Exception $e)
227
    {
228
        $this->out('Error: ', 'bold', 'red');
229
        $this->out("\tUnable to proceed.\n");
230
231
        if ($this->verbose > 1) {
232
            $this->out("\t" . $e->getMessage() . "\n");
233
        }
234
235
        $errors = error_get_last();
236
        if ($this->verbose == 3 && null !== $errors) {
237
            $this->out();
238
            print_r($errors);
239
        }
240
241
        $this->out();
242
243
        exit;
0 ignored issues
show
Coding Style Compatibility introduced by
The method outputError() contains an exit expression.

An exit expression should only be used in rare cases. For example, if you write a short command line script.

In most cases however, using an exit expression makes the code untestable and often causes incompatibilities with other libraries. Thus, unless you are absolutely sure it is required here, we recommend to refactor your code to avoid its usage.

Loading history...
244
    }
245
246
    public function getContents($url, $method='GET', $body=null)
247
    {
248
        $opts = array('http' => array(
249
            'method'  => $method,
250
            'header'  => "Content-Type: text/xml\r\n".
251
            'Authorization: Basic ' . base64_encode($this->src_file . ":sesame") . "\r\n",
252
            'content' => $body,
253
            'timeout' => 60
254
            )
255
        );
256
257
        $ctx  = stream_context_create($opts);
258
        $body = @file_get_contents($url, false, $ctx);
259
        if (isset($http_response_header)) {
260
            $code = substr($http_response_header[0], 9, 3);
261
            if (floor($code/100)>3) {
262
                throw new \Exception($http_response_header[0]);
263
            }
264
265
            return $body;
266
        } else {
267
            throw new \Exception("Request failed.");
268
        }
269
270
        return null;
0 ignored issues
show
Unused Code introduced by
return null; does not seem to be reachable.

This check looks for unreachable code. It uses sophisticated control flow analysis techniques to find statements which will never be executed.

Unreachable code is most often the result of return, die or exit statements that have been added for debug purposes.

function fx() {
    try {
        doSomething();
        return true;
    }
    catch (\Exception $e) {
        return false;
    }

    return false;
}

In the above example, the last return false will never be executed, because a return statement has already been met in every possible execution path.

Loading history...
271
    }
272
273
    protected function retrieveUpdate($url, $dest)
274
    {
275
        $temp = basename($dest, '.phar').'-temp.phar';
276
277
        try {
278
            copy($url, $temp);
279
            chmod($temp, 0777 & ~umask());
280
281
            // test the phar validity
282
            $phar = new \Phar($temp);
283
            // free the variable to unlock the file
284
            unset($phar);
285
            rename($temp, $dest);
286
        } catch (\Exception $e) {
287
            if (!$e instanceof \UnexpectedValueException&& !$e instanceof \PharException) {
288
                throw $e;
289
            }
290
            unlink($temp);
291
            $this->outputError('The dowloading ('.$e->getMessage().').');
292
            $output->out('Please re-run this again.');
0 ignored issues
show
Bug introduced by
The variable $output does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
293
        }
294
295
        $this->out($this->src_file . " has been updated.");
296
    }
297
298
    //     ini_set('phar.readonly', 0);
0 ignored issues
show
Unused Code Comprehensibility introduced by
67% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
299
    //     if (true) {
0 ignored issues
show
Unused Code Comprehensibility introduced by
63% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
300
    //         $this->out("Please, re-run this as: ");
0 ignored issues
show
Unused Code Comprehensibility introduced by
75% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
301
    //         $this->out();
0 ignored issues
show
Unused Code Comprehensibility introduced by
72% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
302
    //         $this->out('$ php -d phar.readonly=0 ' . $args[0], 'brown');
0 ignored issues
show
Unused Code Comprehensibility introduced by
67% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
303
    //         exit(0);
0 ignored issues
show
Unused Code Comprehensibility introduced by
84% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
304
    //     }
305
    //     if (false !== @file_put_contents($local, $this->getContents($url))) {
0 ignored issues
show
Unused Code Comprehensibility introduced by
63% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
306
    //         $this->out($this->src_file . " has been updated.");
0 ignored issues
show
Unused Code Comprehensibility introduced by
58% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
307
    //     } else {
0 ignored issues
show
Unused Code Comprehensibility introduced by
50% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
308
    //          throw new \Exception;
0 ignored issues
show
Unused Code Comprehensibility introduced by
43% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
309
    //     }
310
    // } catch (\Exception $e) {
0 ignored issues
show
Unused Code Comprehensibility introduced by
50% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
311
    //     $this->outputError($e);
0 ignored issues
show
Unused Code Comprehensibility introduced by
75% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
312
313
}
314