Completed
Push — master ( 9573eb...833af1 )
by Amine
11s
created

InteractiveCommand::readSimple()   B

Complexity

Conditions 5
Paths 13

Size

Total Lines 34
Code Lines 27

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 34
rs 8.439
c 0
b 0
f 0
cc 5
eloc 27
nc 13
nop 1
1
<?php namespace Tarsana\Command\Commands;
2
3
use Tarsana\Command\Helpers\SyntaxHelper;
4
use Tarsana\Command\SubCommand;
5
use Tarsana\Syntax\ArraySyntax;
6
use Tarsana\Syntax\Factory as S;
7
use Tarsana\Syntax\ObjectSyntax;
8
use Tarsana\Syntax\OptionalSyntax;
9
use Tarsana\Syntax\Syntax;
10
11
class InteractiveCommand extends SubCommand {
12
13
    const KEYS = [
14
        10  => 'enter',
15
        127 => 'backspace',
16
        65  => 'up',
17
        66  => 'down',
18
        67  => 'right',
19
        68  => 'left',
20
        9   => 'tab'
21
    ];
22
23
    protected $helper;
24
    protected $confirmSyntax;
25
26
    protected function init()
27
    {
28
        $this->name('Interactive')
29
             ->description('Reads the command arguments and options interactively.');
30
        $this->helper = SyntaxHelper::instance();
31
        $this->confirmSyntax = S::optional(S::boolean(), false);
32
    }
33
34
    protected function execute()
35
    {
36
        $parent = $this->parent;
37
        $syntax = $parent->syntax();
38
        $this->console->out('<save>');
39
40
        if ($syntax) {
41
            $args = $this->read($syntax);
42
            $parent->args($args);
43
        }
44
45
        $options = array_keys($parent->options());
46
        $chosen = [];
47
        foreach($options as $option) {
48
            $bool = $this->read($this->confirmSyntax, $option, true);
49
            $parent->options[$option] = $bool;
50
            if ($bool) {
51
                $chosen[] = $option;
52
            }
53
        }
54
55
        $options = implode(' ', $chosen) . ' ';
56
        $args = $syntax ? $syntax->dump($args) : '';
0 ignored issues
show
Bug introduced by
The variable $args 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...
57
58
        $this->console->out('<load><clearAfter>');
59
        $this->console->line("> {$options}{$args}<br>");
60
61
        return $this->parent->fire();
62
    }
63
64
    protected function read(Syntax $syntax, string $prefix = '', bool $display = false)
65
    {
66
        if ($display) {
67
            $this->display($syntax, $prefix);
68
        }
69
70
        $type = $this->helper->type($syntax);
71
        $result = null;
0 ignored issues
show
Unused Code introduced by
$result is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
72
        switch ($type) {
73
            case 'object':
74
                $result = $this->readObject($syntax, $prefix);
0 ignored issues
show
Compatibility introduced by
$syntax of type object<Tarsana\Syntax\Syntax> is not a sub-type of object<Tarsana\Syntax\ObjectSyntax>. It seems like you assume a child class of the class Tarsana\Syntax\Syntax to be always present.

This check looks for parameters that are defined as one type in their type hint or doc comment but seem to be used as a narrower type, i.e an implementation of an interface or a subclass.

Consider changing the type of the parameter or doing an instanceof check before assuming your parameter is of the expected type.

Loading history...
75
            break;
76
            case 'array':
77
                $result = $this->readArray($syntax, $prefix);
0 ignored issues
show
Compatibility introduced by
$syntax of type object<Tarsana\Syntax\Syntax> is not a sub-type of object<Tarsana\Syntax\ArraySyntax>. It seems like you assume a child class of the class Tarsana\Syntax\Syntax to be always present.

This check looks for parameters that are defined as one type in their type hint or doc comment but seem to be used as a narrower type, i.e an implementation of an interface or a subclass.

Consider changing the type of the parameter or doing an instanceof check before assuming your parameter is of the expected type.

Loading history...
78
            break;
79
            case 'optional':
80
                $result = $this->readOptional($syntax, $prefix);
0 ignored issues
show
Compatibility introduced by
$syntax of type object<Tarsana\Syntax\Syntax> is not a sub-type of object<Tarsana\Syntax\OptionalSyntax>. It seems like you assume a child class of the class Tarsana\Syntax\Syntax to be always present.

This check looks for parameters that are defined as one type in their type hint or doc comment but seem to be used as a narrower type, i.e an implementation of an interface or a subclass.

Consider changing the type of the parameter or doing an instanceof check before assuming your parameter is of the expected type.

Loading history...
81
            break;
82
            default:
83
                $result = $this->readSimple($syntax);
84
            break;
85
        }
86
87
        return $result;
88
    }
89
90
    protected function display(Syntax $syntax, string $name)
91
    {
92
        $text = $this->helper->asString($syntax);
93
        $default = '';
94
        if ($syntax instanceof OptionalSyntax) {
95
            $default = '(default: ' . json_encode($syntax->getDefault()) . ')';
96
        }
97
        $description = $this->parent->describe($name);
98
        $this->console->out(
99
            "<success>{$name}</success> <warn>{$text}</warn>"
100
          . " {$description} <warn>{$default}</warn><br>"
101
        );
102
    }
103
104
    protected function readObject(ObjectSyntax $syntax, string $prefix)
105
    {
106
        $result = [];
107
        if ($prefix != '')
108
            $prefix .= '.';
109
        foreach ($syntax->fields() as $name => $s) {
0 ignored issues
show
Bug introduced by
The expression $syntax->fields() of type array|object<Tarsana\Syntax\ObjectSyntax> is not guaranteed to be traversable. How about adding an additional type check?

There are different options of fixing this problem.

  1. If you want to be on the safe side, you can add an additional type-check:

    $collection = json_decode($data, true);
    if ( ! is_array($collection)) {
        throw new \RuntimeException('$collection must be an array.');
    }
    
    foreach ($collection as $item) { /** ... */ }
    
  2. If you are sure that the expression is traversable, you might want to add a doc comment cast to improve IDE auto-completion and static analysis:

    /** @var array $collection */
    $collection = json_decode($data, true);
    
    foreach ($collection as $item) { /** .. */ }
    
  3. Mark the issue as a false-positive: Just hover the remove button, in the top-right corner of this issue for more options.

Loading history...
110
            $fullname = $prefix . $name;
111
            $result[$name] = $this->read($s, $fullname, true);
112
        }
113
        return (object) $result;
114
    }
115
116
    protected function readArray(ArraySyntax $syntax, string $prefix)
117
    {
118
        $result = [];
119
        $repeat = true;
120
        while ($repeat) {
121
            $result[] = $this->read($syntax->syntax(), $prefix);
122
            $this->console->out("Add new item to <success>{$prefix}</success>?<br>");
123
            $repeat = $this->readOptional($this->confirmSyntax, '');
124
            $this->clearLines(3);
125
        }
126
        return $result;
127
    }
128
129
    protected function readOptional(OptionalSyntax $syntax, string $prefix)
130
    {
131
        $default = $syntax->syntax()->dump($syntax->getDefault());
132
        $this->console->out("<color:252>{$default}<column:1><reset>");
133
        $n = ord($this->console->char());
134
        $this->console->out('<column:1><clearLine>');
135
        if (array_key_exists($n, static::KEYS) && static::KEYS[$n] == 'enter')
136
            return $syntax->getDefault();
137
        return $this->read($syntax->syntax(), $prefix);
138
    }
139
140
    protected function readSimple(Syntax $syntax)
141
    {
142
        $this->console->out('<column:1>> ');
143
        $done = false;
144
        $text = '';
145
        $result = null;
146
        while (! $done) {
147
            $c = $this->readChar();
148
            switch($c) {
149
                case 'enter':
150
                    $done = true;
151
                break;
152
                case 'backspace':
153
                    $text = substr($text, 0, -1);
154
                break;
155
                default:
156
                    $text .= $c;
157
                break;
158
            }
159
160
            try {
161
                $result = $syntax->parse($text);
162
                $this->clearLines(1);
163
                $this->console->out("> {$text}");
164
            } catch (\Exception $e) {
165
                $this->clearLines(1);
166
                $this->console->out("> <warn>{$text}</warn>");
167
                $done = false;
168
            }
169
        }
170
        $this->console->out('<br>');
171
172
        return $result;
173
    }
174
175
    protected function readChar() : string
176
    {
177
        $c = $this->console->char();
178
        if (ctype_print($c))
179
            return $c;
180
        $n = ord($c);
181
        if (
182
            array_key_exists($n, static::KEYS)
183
            && in_array(static::KEYS[$n], ['enter', 'backspace'])
184
        ) {
185
            return static::KEYS[$n];
186
        }
187
        return '';
188
    }
189
190
    protected function clearLines(int $number)
191
    {
192
        $text = '<clearLine>'
193
            . str_repeat('<prevLine><clearLine>', $number - 1)
194
            . '<column:1>';
195
        $this->console->out($text);
196
    }
197
}
198