GitHub Access Token became invalid

It seems like the GitHub access token used for retrieving details about this repository from GitHub became invalid. This might prevent certain types of inspections from being run (in particular, everything related to pull requests).
Please ask an admin of your repository to re-new the access token on this website.
Passed
Push — master ( c8c077...b88116 )
by Steeven
02:09
created

Router::setCommander()   C

Complexity

Conditions 12
Paths 11

Size

Total Lines 57
Code Lines 39

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 2 Features 0
Metric Value
cc 12
eloc 39
c 2
b 2
f 0
nc 11
nop 2
dl 0
loc 57
rs 6.9666

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
 * This file is part of the O2System Framework package.
4
 *
5
 * For the full copyright and license information, please view the LICENSE
6
 * file that was distributed with this source code.
7
 *
8
 * @author         Steeve Andrian Salim
9
 * @copyright      Copyright (c) Steeve Andrian Salim
10
 */
11
12
// ------------------------------------------------------------------------
13
14
namespace O2System\Kernel\Cli;
15
16
// ------------------------------------------------------------------------
17
18
use O2System\Kernel\Cli\Router\DataStructures\Commander;
0 ignored issues
show
Bug introduced by
This use statement conflicts with another class in this namespace, O2System\Kernel\Cli\Commander. Consider defining an alias.

Let?s assume that you have a directory layout like this:

.
|-- OtherDir
|   |-- Bar.php
|   `-- Foo.php
`-- SomeDir
    `-- Foo.php

and let?s assume the following content of Bar.php:

// Bar.php
namespace OtherDir;

use SomeDir\Foo; // This now conflicts the class OtherDir\Foo

If both files OtherDir/Foo.php and SomeDir/Foo.php are loaded in the same runtime, you will see a PHP error such as the following:

PHP Fatal error:  Cannot use SomeDir\Foo as Foo because the name is already in use in OtherDir/Foo.php

However, as OtherDir/Foo.php does not necessarily have to be loaded and the error is only triggered if it is loaded before OtherDir/Bar.php, this problem might go unnoticed for a while. In order to prevent this error from surfacing, you must import the namespace with a different alias:

// Bar.php
namespace OtherDir;

use SomeDir\Foo as SomeDirFoo; // There is no conflict anymore.
Loading history...
19
20
/**
21
 * Class Router
22
 *
23
 * @package O2System\Framework\Cli
24
 */
25
class Router
26
{
27
    /**
28
     * Router::$string
29
     *
30
     * Router request string.
31
     *
32
     * @var string
33
     */
34
    protected $string;
35
36
    /**
37
     * Router::$commands
38
     *
39
     * Router request commands.
40
     *
41
     * @var array
42
     */
43
    protected $commands = [];
44
45
    /**
46
     * Router::$commander
47
     *
48
     * Router request commander.
49
     *
50
     * @var Commander
51
     */
52
    protected $commander;
53
54
    // -----------------------------------------------------------------------
55
56
    /**
57
     * Router::handle
58
     *
59
     * Parse server argv to determine requested commander.
60
     *
61
     * @return void
62
     * @throws \ReflectionException
63
     */
64
    public function handle()
65
    {
66
        $argv = $_SERVER[ 'argv' ];
67
68
        if ($_SERVER[ 'SCRIPT_NAME' ] === $_SERVER[ 'argv' ][ 0 ]) {
69
            array_shift($argv);
70
71
            if (empty($argv)) {
72
                return;
73
            }
74
        }
75
76
        $this->string = str_replace(['/', '\\', ':'], '/', $argv[ 0 ]);
77
        $this->commands = explode('/', $this->string);
78
79
        if (strpos($this->commands[ 0 ], '--') !== false
80
            || strpos($this->commands[ 0 ], '-') !== false
81
        ) {
82
            $options = $this->commands;
83
            $this->commands = [];
84
        } else {
85
            $options = array_slice($argv, 1);
86
        }
87
88
        foreach ($options as $option) {
89
            if (strpos($option, '--') !== false
90
                || strpos($option, '-') !== false
91
            ) {
92
                $option = str_replace(['-', '--'], '', $option);
93
                $option = str_replace(':', '=', $option);
94
                $option = str_replace('"', '', $option);
95
                $value = null;
96
97
                if (strpos($option, '=') !== false) {
98
                    $optionParts = explode('=', $option);
99
                    $option = $optionParts[ 0 ];
100
                    $value = $optionParts[ 1 ];
101
                } else {
102
                    $value = current($options);
103
                }
104
105
                if ($value === 'true') {
106
                    $value = true;
107
                } elseif ($value === 'false') {
108
                    $value = false;
109
                }
110
111
                if (strpos($value, '--') === false
112
                    || strpos($value, '-') === false
113
                ) {
114
                    $_GET[ $option ] = $value;
115
                } else {
116
                    $_GET[ $option ] = null;
117
                }
118
            } else {
119
                $keys = array_keys($_GET);
120
                if (count($keys)) {
121
                    $key = end($keys);
122
                    $_GET[ $key ] = $option;
123
                }
124
            }
125
        }
126
127
        if (array_key_exists('verbose', $_GET) or array_key_exists('v', $_GET)) {
128
            $_ENV[ 'VERBOSE' ] = true;
129
        }
130
131
        $this->parseCommands($this->commands);
132
    }
133
134
    // ------------------------------------------------------------------------
135
136
    /**
137
     * Router::parseSegments
138
     *
139
     * Parse and validate requested commands.
140
     *
141
     * @param array $segments
142
     *
143
     * @throws \ReflectionException
144
     */
145
    final private function parseCommands(array $commands)
146
    {
147
        static $reflection;
148
149
        if (empty($reflection)) {
150
            $reflection = new \ReflectionClass($this);
151
        }
152
153
        foreach ($reflection->getMethods() as $method) {
154
            if (strpos($method->name, 'validateCommands') !== false) {
155
                if ($this->{$method->name}($commands)) {
156
                    break;
157
                }
158
            }
159
        }
160
    }
161
162
    // ------------------------------------------------------------------------
163
164
    /**
165
     * Router::getCommander
166
     *
167
     * Gets requested commander.
168
     *
169
     * @return \O2System\Kernel\Cli\Router\DataStructures\Commander
170
     */
171
    public function getCommander()
172
    {
173
        return $this->commander;
174
    }
175
176
    // ------------------------------------------------------------------------
177
178
    /**
179
     * Router::setCommander
180
     *
181
     * Sets requested commander.
182
     *
183
     * @param \O2System\Kernel\Cli\Router\DataStructures\Commander $commander
184
     * @param array                                                $uriSegments
185
     *
186
     * @throws \ReflectionException
187
     */
188
    final protected function setCommander(Router\DataStructures\Commander $commander, array $uriSegments = [])
189
    {
190
        // Add Commander PSR4 Namespace
191
        loader()->addNamespace($commander->getNamespaceName(), $commander->getFileInfo()->getPath());
0 ignored issues
show
Bug introduced by
The function loader was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

191
        /** @scrutinizer ignore-call */ 
192
        loader()->addNamespace($commander->getNamespaceName(), $commander->getFileInfo()->getPath());
Loading history...
192
193
        $commanderMethod = camelcase(reset($uriSegments));
194
        $commanderMethodParams = array_slice($uriSegments, 1);
195
196
        if (null !== $commander->getRequestMethod()) {
197
            $commander->setRequestMethodArgs($commanderMethodParams);
198
        } elseif (count($uriSegments)) {
199
            if ($commander->hasMethod('route')) {
200
                $commander
201
                    ->setRequestMethod('route')
202
                    ->setRequestMethodArgs(
203
                        [
204
                            $commanderMethod,
205
                            $commanderMethodParams,
206
                        ]
207
                    );
208
            } elseif ($commander->hasMethod($commanderMethod)) {
209
                $method = $commander->getMethod($commanderMethod);
210
211
                if ($method->isPublic()) {
212
                    $commander
213
                        ->setRequestMethod($commanderMethod)
214
                        ->setRequestMethodArgs($commanderMethodParams);
215
                } elseif (is_ajax() AND $method->isProtected()) {
216
                    $commander
217
                        ->setRequestMethod($commanderMethod)
218
                        ->setRequestMethodArgs($commanderMethodParams);
219
                }
220
            } elseif ($commander->hasMethod('execute')) {
221
                $execute = $commander->getMethod('execute');
222
223
                if ($execute->getNumberOfParameters() > 0) {
224
225
                    array_unshift($commanderMethodParams, $commanderMethod);
226
227
                    $commander
228
                        ->setRequestMethod('execute')
229
                        ->setRequestMethodArgs($commanderMethodParams);
230
                } else {
231
                    output()->sendError(404);
232
                }
233
            }
234
        } elseif ($commander->hasMethod('route')) {
235
            $commander
236
                ->setRequestMethod('route')
237
                ->setRequestMethodArgs(['execute', []]);
238
        } elseif ($commander->hasMethod('execute')) {
239
            $commander
240
                ->setRequestMethod('execute');
241
        }
242
243
        // Set Router Commander
244
        $this->commander = $commander;
245
    }
246
247
    // ------------------------------------------------------------------------
248
249
    /**
250
     * Router::validateCommandsCommander
251
     *
252
     * @param array $segments
253
     *
254
     * @return bool
255
     * @throws \ReflectionException
256
     */
257
    final private function validateCommandsCommander(array $segments)
258
    {
259
        $numSegments = count($segments);
260
        $commanderRegistry = null;
261
        $uriSegments = [];
262
        $commandersDirectories = [
263
            defined('PATH_REACTOR') ? PATH_REACTOR . 'Cli' . DIRECTORY_SEPARATOR . 'Commanders' . DIRECTORY_SEPARATOR : PATH_FRAMEWORK . 'Cli' . DIRECTORY_SEPARATOR . 'Commanders' . DIRECTORY_SEPARATOR,
0 ignored issues
show
Bug introduced by
The constant O2System\Kernel\Cli\PATH_FRAMEWORK was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
Bug introduced by
The constant O2System\Kernel\Cli\PATH_REACTOR was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
264
            PATH_APP . 'Commanders' . DIRECTORY_SEPARATOR
0 ignored issues
show
Bug introduced by
The constant O2System\Kernel\Cli\PATH_APP was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
265
        ];
266
267
        if (function_exists('modules')) {
268
            $commandersDirectories = modules()->getDirs('Commanders');
269
        }
270
271
        for ($i = 0; $i <= $numSegments; $i++) {
272
            $routedSegments = array_slice($segments, 0, ($numSegments - $i));
273
274
            $commanderFilename = implode(DIRECTORY_SEPARATOR, $routedSegments);
275
            $commanderFilename = prepare_filename($commanderFilename) . '.php';
276
277
            foreach ($commandersDirectories as $commanderDirectory) {
278
                if (is_file($commanderFilePath = $commanderDirectory . $commanderFilename)) {
279
                    $uriSegments = array_diff($segments, $routedSegments);
280
                    $commanderRegistry = new Router\DataStructures\Commander($commanderFilePath);
281
                    break;
282
                }
283
            }
284
285
            if ($commanderRegistry instanceof Router\DataStructures\Commander) {
286
                $this->setCommander($commanderRegistry, $uriSegments);
287
                break;
288
289
                return true;
0 ignored issues
show
Unused Code introduced by
return true is not 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...
290
            }
291
        }
292
293
        return false;
294
    }
295
}