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 ( 2dc5e2...4f9464 )
by Steeven
01:50
created

AbstractCommander::setCommandOptions()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 7
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 3
nc 2
nop 1
dl 0
loc 7
rs 10
c 0
b 0
f 0
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\Abstracts;
15
16
// ------------------------------------------------------------------------
17
18
use O2System\Kernel\Cli\Writers\Format;
19
use O2System\Kernel\Cli\Writers\Table;
20
use O2System\Spl\DataStructures\SplArrayObject;
21
22
/**
23
 * Class AbstractCommander
24
 *
25
 * @package O2System\Cli\Abstracts
26
 */
27
abstract class AbstractCommander
28
{
29
    /**
30
     * AbstractCommander::$commandName
31
     *
32
     * Command name.
33
     *
34
     * @var string
35
     */
36
    protected $commandName;
37
38
    /**
39
     * AbstractCommander::$commandVersion
40
     *
41
     * Command version.
42
     *
43
     * @var string
44
     */
45
    protected $commandVersion;
46
47
    /**
48
     * AbstractCommander::$commandDescription
49
     *
50
     * Command description.
51
     *
52
     * @var string
53
     */
54
    protected $commandDescription;
55
56
    /**
57
     * AbstractCommander::$commandOptions
58
     *
59
     * Command options.
60
     *
61
     * @var array
62
     */
63
    protected $commandOptions = [];
64
65
    /**
66
     * AbstractCommander::$commandOptionsShortcuts
67
     *
68
     * Command options.
69
     *
70
     * @var array
71
     */
72
    protected $commandOptionsShortcuts = [
73
        '-h'  => 'help',
74
        '-v'  => 'version',
75
        '-vv' => 'verbose',
76
    ];
77
78
    protected $actionsPool = [];
79
80
    /**
81
     * AbstractCommander::$verbose
82
     *
83
     * Command options.
84
     *
85
     * @var bool
86
     */
87
    protected $optionVerbose = false;
88
89
    // ------------------------------------------------------------------------
90
91
    /**
92
     * AbstractCommander::__construct
93
     *
94
     * Commander class constructor.
95
     *
96
     * @final   This method cannot be overwritten.
97
     */
98
    final public function __construct()
99
    {
100
        language()->loadFile('cli');
101
102
        $className = explode('Commanders\\', get_class($this));
103
        $className = str_replace('\\', '/', end($className));
104
        $this->commandName = implode('/', array_map('strtolower', explode('/', $className)));
105
106
        foreach ($this->commandOptions as $optionName => $optionConfig) {
107
            $shortcut = empty($optionConfig[ 'shortcut' ])
108
                ? '-' . substr($optionName, 0, 1)
109
                : '-' . rtrim($optionConfig[ 'shortcut' ]);
110
111
            if (array_key_exists($shortcut, $this->commandOptionsShortcuts)) {
112
                $shortcut = '-' . substr($optionName, 0, 2);
113
            }
114
115
            $this->commandOptions[ $optionName ][ 'shortcut' ] = $shortcut;
116
117
            $this->commandOptionsShortcuts[ $shortcut ] = $optionName;
118
        }
119
120
        if (array_key_exists('VERBOSE', $_ENV)) {
121
            $this->optionVerbose = true;
122
        }
123
    }
124
125
    // ------------------------------------------------------------------------
126
127
    /**
128
     * AbstractCommander::setCommandOptions
129
     *
130
     * Sets command options.
131
     *
132
     * @param array $commandOptions Array of commander options.
133
     *
134
     * @return static
135
     */
136
    public function setCommandOptions(array $commandOptions)
137
    {
138
        foreach ($commandOptions as $caller => $props) {
139
            call_user_func_array([&$this, 'addOption'], $props);
140
        }
141
142
        return $this;
143
    }
144
145
    // ------------------------------------------------------------------------
146
147
    /**
148
     * AbstractCommander::addCommandOption
149
     *
150
     * Add command option.
151
     *
152
     * @param string $optionName
153
     * @param string $optionDescription
154
     * @param string $optionShortcut
155
     *
156
     * @return $this;
157
     */
158
    public function addCommandOption($optionName, $optionDescription, $optionShortcut = null)
159
    {
160
        $optionShortcut = empty($optionShortcut)
161
            ? '-' . substr($optionName, 0, 1)
162
            : '-' . rtrim($optionShortcut);
163
164
        $this->commandOptions[ $optionName ] = [
165
            'shortcut'    => $optionShortcut,
166
            'description' => $optionDescription,
167
        ];
168
    }
169
170
    // ------------------------------------------------------------------------
171
172
    /**
173
     * AbstractCommander::optionVersion
174
     *
175
     * Option version method, write commander version string.
176
     *
177
     * @return void
178
     */
179
    public function optionVersion()
180
    {
181
        if (property_exists($this, 'commandVersion')) {
182
            if ( ! empty($this->commandVersion)) {
183
                // Show Name & Version Line
184
                output()->write(
0 ignored issues
show
Bug introduced by
The method write() does not exist on O2System\Kernel\Http\Output. ( Ignorable by Annotation )

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

184
                output()->/** @scrutinizer ignore-call */ write(

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
185
                    (new Format())
186
                        ->setContextualClass(Format::INFO)
187
                        ->setString(ucfirst($this->commandName) . ' v' . $this->commandVersion)
188
                        ->setNewLinesAfter(1)
189
                );
190
            }
191
        }
192
    }
193
194
    // ------------------------------------------------------------------------
195
196
    /**
197
     * AbstractCommander::__callOptions
198
     *
199
     * Options call executer.
200
     *
201
     * @return void
202
     */
203
    protected function __callOptions()
204
    {
205
        if(false !== ($options = input()->get())) {
206
            if(count($options)) {
207
                $command = new \ReflectionClass($this);
208
209
                foreach ($options as $method => $arguments) {
210
211
                    if (array_key_exists('-' . $method, $this->commandOptionsShortcuts)) {
212
                        $method = $this->commandOptionsShortcuts[ '-' . $method ];
213
                    }
214
215
                    $optionMethod = camelcase('option-' . $method);
216
217
                    if ($command->hasMethod($optionMethod)) {
218
219
                        $commandMethod = $command->getMethod($optionMethod);
220
221
                        if ($commandMethod->getNumberOfRequiredParameters() == 0) {
222
                            call_user_func_array([&$this, $optionMethod], [$arguments]);
223
                        } elseif ($commandMethod->getNumberOfRequiredParameters() > 0 and empty($arguments)) {
224
                            if (isset($this->commandOptions[ $method ][ 'help' ])) {
225
                                output()->write(
226
                                    (new Format())
227
                                        ->setContextualClass(Format::INFO)
228
                                        ->setString(language()->getLine('CLI_USAGE') . ':')
229
                                        ->setNewLinesBefore(1)
230
                                        ->setNewLinesAfter(1)
231
                                );
232
233
                                output()->write(
234
                                    (new Format())
235
                                        ->setContextualClass(Format::INFO)
236
                                        ->setString(language()->getLine($this->commandOptions[ $method ][ 'help' ]))
237
                                        ->setNewLinesAfter(2)
238
                                );
239
                            }
240
                        } else {
241
                            $optionArguments = is_array($arguments)
242
                                ? $arguments
243
                                : [$arguments];
244
245
                            call_user_func_array([&$this, $optionMethod], $optionArguments);
246
                        }
247
                    }
248
                }
249
            }
250
        }
251
    }
252
253
    // ------------------------------------------------------------------------
254
255
    /**
256
     * AbstractCommander::execute
257
     *
258
     * Default abstract commander execution to execute help option.
259
     *
260
     * @return void
261
     * @throws \ReflectionException
262
     */
263
    public function execute()
264
    {
265
        if (false !== ($options = input()->get())) {
0 ignored issues
show
Unused Code introduced by
The assignment to $options is dead and can be removed.
Loading history...
266
            $this->optionHelp();
267
        } else {
268
            $this->__callOptions();
269
        }
270
    }
271
272
    // ------------------------------------------------------------------------
273
274
    /**
275
     * AbstractCommander::optionHelp
276
     *
277
     * Option help method, write commander help.
278
     *
279
     * @return void
280
     * @throws \ReflectionException
281
     */
282
    final public function optionHelp()
283
    {
284
        // Show Usage
285
        output()->write(
286
            (new Format())
287
                ->setContextualClass(Format::INFO)
288
                ->setString(language()->getLine('CLI_USAGE') . ':')
289
                ->setNewLinesBefore(1)
290
                ->setNewLinesAfter(1)
291
        );
292
293
        // Show Actions
294
        $this->loadActions();
295
296
        if (count($this->actionsPool)) {
297
            output()->write(
298
                (new Format())
299
                    ->setContextualClass(Format::INFO)
300
                    ->setString($this->commandName . '/action --option=value')
301
            );
302
303
            output()->write(
304
                (new Format())
305
                    ->setString(language()->getLine('CLI_ACTIONS') . ':')
306
                    ->setNewLinesBefore(2)
307
                    ->setNewLinesAfter(1)
308
            );
309
310
            $table = new Table();
311
            $table->isShowBorder = false;
312
313
            foreach ($this->actionsPool as $action) {
314
315
                if ($action instanceof AbstractCommander) {
316
                    $table
317
                        ->addRow()
318
                        ->addColumn($action->getCommandName())
319
                        ->addColumn(language()->getLine($action->getCommandDescription()));
320
                }
321
            }
322
323
            output()->write(
324
                (new Format())
325
                    ->setString($table->render())
326
            );
327
        } else {
328
            output()->write(
329
                (new Format())
330
                    ->setContextualClass(Format::INFO)
331
                    ->setString($this->commandName . ' --option=value')
332
            );
333
        }
334
335
        // Show Options
336
        output()->write(
337
            (new Format())
338
                ->setString(language()->getLine('CLI_OPTIONS') . ':')
339
                ->setNewLinesBefore(2)
340
                ->setNewLinesAfter(1)
341
        );
342
343
        $table = new Table();
344
        $table->isShowBorder = false;
345
346
        foreach ($this->commandOptions as $optionCaller => $optionProps) {
347
            $table
348
                ->addRow()
349
                ->addColumn('--' . $optionCaller)
350
                ->addColumn($optionProps[ 'shortcut' ])
351
                ->addColumn(language()->getLine($optionProps[ 'description' ]));
352
        }
353
354
        output()->write(
355
            (new Format())
356
                ->setString($table->render())
357
                ->setNewLinesAfter(2)
358
        );
359
360
        exit(EXIT_SUCCESS);
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
361
    }
362
363
    // ------------------------------------------------------------------------
364
365
    /**
366
     * AbstractCommander::loadActions
367
     *
368
     * Load all actions.
369
     *
370
     * @param $namespace
371
     * @param $commandsPath
372
     *
373
     * @throws \ReflectionException
374
     */
375
    protected function loadActions()
376
    {
377
        $reflection = new \ReflectionClass($this);
378
        $actionNamespace = $reflection->name . '\\';
379
        $actionDirectory = get_class_name($reflection->name);
380
        $actionsPath = dirname($reflection->getFileName()) . DIRECTORY_SEPARATOR . $actionDirectory . DIRECTORY_SEPARATOR;
381
382
        foreach (glob($actionsPath . '*.php') as $filePath) {
383
            if (is_file($filePath)) {
384
                $commandClassName = $actionNamespace . pathinfo($filePath, PATHINFO_FILENAME);
385
                $this->addCommander(new $commandClassName);
386
            }
387
        }
388
    }
389
390
    // ------------------------------------------------------------------------
391
392
    /**
393
     * AbstractCommander::addCommander
394
     *
395
     * Add new commander to the pool.
396
     *
397
     * @param AbstractCommander $commander
398
     */
399
    public function addCommander(AbstractCommander $commander)
400
    {
401
        $this->actionsPool[ $commander->getCommandName() ] = $commander;
402
    }
403
404
    // ------------------------------------------------------------------------
405
406
    /**
407
     * AbstractCommander::getCommandName
408
     *
409
     * Gets command description.
410
     *
411
     * @return string
412
     */
413
    public function getCommandName()
414
    {
415
        return $this->commandName;
416
    }
417
418
    // ------------------------------------------------------------------------
419
420
    /**
421
     * AbstractCommander::getCommandDescription
422
     *
423
     * Gets command description.
424
     *
425
     * @return string
426
     */
427
    public function getCommandDescription()
428
    {
429
        return $this->commandDescription;
430
    }
431
432
    // ------------------------------------------------------------------------
433
434
    /**
435
     * AbstractCommander::setCommandDescription
436
     *
437
     * Sets command description.
438
     *
439
     * @param string $commandDescription
440
     *
441
     * @return static
442
     */
443
    public function setCommandDescription($commandDescription)
444
    {
445
        $this->commandDescription = trim($commandDescription);
446
447
        return $this;
448
    }
449
}