Cli::executeCommand()   F
last analyzed

Complexity

Conditions 41
Paths > 20000

Size

Total Lines 159
Code Lines 97

Duplication

Lines 16
Ratio 10.06 %

Code Coverage

Tests 0
CRAP Score 1722

Importance

Changes 2
Bugs 0 Features 0
Metric Value
c 2
b 0
f 0
dl 16
loc 159
ccs 0
cts 130
cp 0
rs 2
cc 41
eloc 97
nc 63574
nop 0
crap 1722

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
 * Akamai {OPEN} EdgeGrid Auth Client
4
 *
5
 * @author Davey Shafik <[email protected]>
6
 * @copyright Copyright 2016 Akamai Technologies, Inc. All rights reserved.
7
 * @license Apache 2.0
8
 * @link https://github.com/akamai-open/AkamaiOPEN-edgegrid-php-client
9
 * @link https://developer.akamai.com
10
 * @link https://developer.akamai.com/introduction/Client_Auth.html
11
 */
12
namespace Akamai\Open\EdgeGrid;
13
14
/**
15
 * Class Cli
16
 * @package Akamai\Open\EdgeGrid\Client
17
 */
18
class Cli
19
{
20
    /**
21
     * @var \League\CLImate\CLImate
22
     */
23
    protected $climate;
24
25
    /**
26
     * Cli constructor.
27
     */
28
    public function __construct()
29
    {
30
        $this->climate = new \League\CLImate\CLImate();
31
    }
32
33
    /**
34
     * Execute the CLI
35
     */
36
    public function run()
37
    {
38
        if ($this->parseArguments()) {
39
            $this->executeCommand();
40
        }
41
    }
42
43
    /**
44
     * Parse incoming arguments
45
     *
46
     * @return bool|void
47
     */
48
    protected function parseArguments()
0 ignored issues
show
Coding Style introduced by
parseArguments 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...
49
    {
50
        $args = $this->getNamedArgs();
51
52
        $this->climate->arguments->add($args);
53
54
        if ($_SERVER['argc'] === 1) {
55
            $this->help();
56
            return false;
57
        }
58
59
        if ($this->climate->arguments->defined('help')) {
60
            $this->help();
61
            return;
62
        }
63
64
        if ($this->climate->arguments->defined('version')) {
65
            echo $this->version();
66
            return;
67
        }
68
69
        try {
70
            $this->climate->arguments->parse($_SERVER['argv']);
71
72
            $padding = count($args);
73
            foreach ($this->climate->arguments->toArray() as $arg) {
74
                if ($arg === null) {
75
                    --$padding;
76
                }
77
            }
78
            $argSize = count($_SERVER['argv']) - $padding - 1;
79
            for ($i = 0; $i < $argSize; $i++) {
80
                $args['arg-' . $i] = [];
81
            }
82
            $this->climate->arguments->add($args);
83
            $this->climate->arguments->parse($_SERVER['argv']);
84
        } catch (\Exception $e) {
0 ignored issues
show
Coding Style Comprehensibility introduced by
Consider adding a comment why this CATCH block is empty.
Loading history...
85
        }
86
87
        return true;
88
    }
89
90
    /**
91
     * Execute the HTTP request
92
     *
93
     * @return mixed|\Psr\Http\Message\ResponseInterface
94
     */
95
    protected function executeCommand()
96
    {
97
        static $methods = [
98
            'HEAD',
99
            'GET',
100
            'POST',
101
            'PUT',
102
            'DELETE'
103
        ];
104
105
        \Akamai\Open\EdgeGrid\Client::setDebug(true);
106
        \Akamai\Open\EdgeGrid\Client::setVerbose(true);
107
108
        $args = $this->climate->arguments->all();
109
        $client = new Client();
110
111
        if ($this->climate->arguments->defined('auth-type')) {
112
            $auth = $this->climate->arguments->get('auth');
113
            if ($this->climate->arguments->get('auth-type') === 'edgegrid' ||
114
                (!$this->climate->arguments->defined('auth-type'))) {
115
                $section = 'default';
116
                if ($this->climate->arguments->defined('auth')) {
117
                    $section = (substr($auth, -1) === ':') ? substr($auth, 0, -1) : $auth;
118
                }
119
                $client = Client::createFromEdgeRcFile($section);
120
            }
121
122
            if (in_array($this->climate->arguments->get('auth-type'), ['basic', 'digest'])) {
123
                if (!$this->climate->arguments->defined('auth') || $this->climate->arguments->get('auth') === null) {
124
                    $this->help();
125
                    return;
126
                }
127
128
                $auth = [
129
                    $auth,
130
                    null,
131
                    $this->climate->arguments->get('auth-type')
132
                ];
133
134
                if (strpos(':', $auth[0]) !== false) {
135
                    list($auth[0], $auth[1]) = explode(':', $auth[0]);
136
                }
137
138
                $client = new Client(['auth' => $auth]);
139
            }
140
        }
141
142
        $method = 'GET';
143
        $options = [];
144
        $body = [];
145
146
        foreach ($args as $arg) {
147
            $value = $arg->value();
148
            if (empty($value) || is_bool($value) || $arg->longPrefix()) {
149
                continue;
150
            }
151
152
            if (in_array(strtoupper($value), $methods)) {
153
                $method = $arg->value();
154
                continue;
155
            }
156
157
            if (!isset($url) && preg_match('@^(http(s?)://|:).*$@', trim($value))) {
158
                $url = $value;
159
160
                if ($url{0} === ':') {
161
                    $url = substr($url, 1);
162
                }
163
164
                continue;
165
            }
166
167
            $matches = [];
168 View Code Duplication
            if (preg_match('/^(?<key>.*?):=(?<file>@?)(?<value>.*?)$/', $value, $matches)) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across 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...
169
                if (!$value = $this->getArgValue($matches)) {
170
                    return false;
171
                }
172
173
                $body[$matches['key']] = json_decode($value);
174
                continue;
175
            }
176
177
            if (preg_match('/^(?<header>.*?):(?<value>.*?)$/', $value, $matches)
178
                && !preg_match('@^http(s?)://@', $value)) {
179
                $options['headers'][$matches['header']] = $matches['value'];
180
                continue;
181
            }
182
183 View Code Duplication
            if (preg_match('/^(?<key>.*?)=(?<file>@?)(?<value>.*?)$/', $value, $matches)) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across 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...
184
                if (!$value = $this->getArgValue($matches)) {
185
                    return false;
186
                }
187
188
                $body[$matches['key']] = $matches['value'];
189
                continue;
190
            }
191
192
            if (!isset($url)) {
193
                $url = $value;
194
                continue;
195
            }
196
197
            $this->help();
198
            $this->climate->error('Unknown argument: ' . $value);
199
200
            return false;
201
        }
202
203
        $stdin = '';
204
        $fp = fopen('php://stdin', 'rb');
205
        if ($fp) {
206
            stream_set_blocking($fp, false);
207
            $stdin = fgets($fp);
208
            if (!empty(trim($stdin))) {
209
                while (!feof($fp)) {
210
                    $stdin .= fgets($fp);
211
                }
212
                fclose($fp);
213
            }
214
            $stdin = rtrim($stdin);
215
        }
216
217
        if (!empty($stdin) && !empty($body)) {
218
            $this->help();
219
            $this->climate->error(
220
                'error: Request body (from stdin or a file) and request data (key=value) cannot be mixed.'
221
            );
222
            return;
223
        }
224
225
        if (!empty($stdin)) {
226
            $body = $stdin;
227
        }
228
229
        if (count($body) && !$this->climate->arguments->defined('form')) {
230
            if (!isset($options['headers']['Content-Type'])) {
231
                $options['headers']['Content-Type'] = 'application/json';
232
            }
233
            if (!isset($options['headers']['Accept'])) {
234
                $options['headers']['Accept'] = 'application/json';
235
            }
236
            $options['body'] = (!is_string($body)) ? json_encode($body) : $body;
237
        }
238
239
        if (count($body) && $this->climate->arguments->defined('form')) {
240
            if (!isset($options['headers']['Content-Type'])) {
241
                $options['headers']['Content-Type'] = 'application/x-www-form-urlencoded; charset=utf-8';
242
            }
243
244
            $options['body'] = (!is_string($body)) ? http_build_query($body, null, null, PHP_QUERY_RFC1738) : $body;
245
        }
246
247
        $options['allow_redirects'] = false;
248
        if ($this->climate->arguments->defined('follow')) {
249
            $options['allow_redirects'] = true;
250
        }
251
252
        return $client->request($method, $url, $options);
0 ignored issues
show
Bug introduced by
The variable $url does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
253
    }
254
255
    /**
256
     * Display CLI help
257
     */
258
    public function help()
0 ignored issues
show
Coding Style introduced by
help 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...
259
    {
260
        $arguments = new \League\CLImate\Argument\Manager();
261
        $arguments->description('Akamai {OPEN} Edgegrid Auth for PHP Client (v' .Client::VERSION. ')');
262
        $arguments->add($this->getNamedArgs());
263
        $arguments->usage($this->climate, $_SERVER['argv']);
264
    }
265
266
    /**
267
     * Return the client version
268
     *
269
     * @return string
270
     */
271
    public function version()
272
    {
273
        return Client::VERSION;
274
    }
275
276
    /**
277
     * Handle named arguments
278
     *
279
     * @return array
280
     */
281
    protected function getNamedArgs()
282
    {
283
        $args = [
284
            'help' => [
285
                'longPrefix' => 'help',
286
                'prefix' => 'h',
287
                'description' => 'Show this help output',
288
                'noValue' => true
289
            ],
290
            'auth-type' => [
291
                'longPrefix' => 'auth-type',
292
                'prefix' => 'A',
293
                'description' => '{basic, digest, edgegrid}'
294
            ],
295
            'auth' => [
296
                'longPrefix' => 'auth',
297
                'prefix' => 'a',
298
                'description' => '.edgerc section name, or user[:password]'
299
            ],
300
            'json' => [
301
                'longPrefix' => 'json',
302
                'prefix' => 'j',
303
                'description' => '(default) Data items from the command line are serialized as a JSON object.',
304
                'noValue' => true
305
            ],
306
            'follow' => [
307
                'longPrefix' => 'follow',
308
                'description' => 'Set this flag if redirects are allowed',
309
                'noValue' => true
310
            ],
311
            'form' => [
312
                'longPrefix' => 'form',
313
                'prefix' => 'f',
314
                'description' => 'Data items from the command line are serialized as form fields',
315
                'noValue' => true
316
            ],
317
            'version' => [
318
                'longPrefix' => 'version',
319
                'description' => 'Show version',
320
                'noValue' => true
321
            ],
322
            'METHOD' => [
323
                'description' => 'HTTP Method (default: GET)'
324
            ],
325
            'URL' => [
326
                'required' => true,
327
            ]
328
        ];
329
330
        return $args;
331
    }
332
333
    /**
334
     * Get argument values
335
     *
336
     * @param $matches
337
     * @return bool|string
338
     */
339
    protected function getArgValue($matches)
340
    {
341
        $value = $matches['value'];
342
        if (!empty($matches['file'])) {
343
            if (!file_exists($matches['value']) || !is_readable($matches['value'])) {
344
                $this->climate->error('Unable to read input file: ' . $matches['value']);
345
                return false;
346
            }
347
            $value = file_get_contents($matches['value']);
348
        }
349
350
        return $value;
351
    }
352
}
353