Completed
Push — master ( d21e4b...25fd19 )
by Nikolas
03:46
created

CliApplication::printResult()   D

Complexity

Conditions 9
Paths 8

Size

Total Lines 32
Code Lines 27

Duplication

Lines 0
Ratio 0 %

Importance

Changes 3
Bugs 0 Features 0
Metric Value
c 3
b 0
f 0
dl 0
loc 32
rs 4.9091
cc 9
eloc 27
nc 8
nop 2
1
<?php
2
namespace rtens\domin\delivery\cli;
3
4
use rtens\domin\Action;
5
use rtens\domin\ActionRegistry;
6
use rtens\domin\delivery\cli\fields\ArrayField;
7
use rtens\domin\delivery\cli\fields\BooleanField;
8
use rtens\domin\delivery\cli\fields\DateIntervalField;
9
use rtens\domin\delivery\cli\fields\DateTimeField;
10
use rtens\domin\delivery\cli\fields\EnumerationField;
11
use rtens\domin\delivery\cli\fields\FileField;
12
use rtens\domin\delivery\cli\fields\HtmlField;
13
use rtens\domin\delivery\cli\fields\IdentifierField;
14
use rtens\domin\delivery\cli\fields\MultiField;
15
use rtens\domin\delivery\cli\fields\NullableField;
16
use rtens\domin\delivery\cli\fields\ObjectField;
17
use rtens\domin\delivery\cli\fields\PrimitiveField;
18
use rtens\domin\delivery\cli\fields\RangeField;
19
use rtens\domin\delivery\cli\renderers\ArrayRenderer;
20
use rtens\domin\delivery\cli\renderers\BooleanRenderer;
21
use rtens\domin\delivery\cli\renderers\ChartRenderer;
22
use rtens\domin\delivery\cli\renderers\DateIntervalRenderer;
23
use rtens\domin\delivery\cli\renderers\DateTimeRenderer;
24
use rtens\domin\delivery\cli\renderers\DelayedOutputRenderer;
25
use rtens\domin\delivery\cli\renderers\FileRenderer;
26
use rtens\domin\delivery\cli\renderers\HtmlRenderer;
27
use rtens\domin\delivery\cli\renderers\IdentifierRenderer;
28
use rtens\domin\delivery\cli\renderers\ObjectRenderer;
29
use rtens\domin\delivery\cli\renderers\PrimitiveRenderer;
30
use rtens\domin\delivery\cli\renderers\tables\DataTableRenderer;
31
use rtens\domin\delivery\cli\renderers\tables\ObjectTableRenderer;
32
use rtens\domin\delivery\cli\renderers\tables\TableRenderer;
33
use rtens\domin\delivery\FieldRegistry;
34
use rtens\domin\delivery\ParameterReader;
35
use rtens\domin\delivery\RendererRegistry;
36
use rtens\domin\execution\ExecutionResult;
37
use rtens\domin\execution\FailedResult;
38
use rtens\domin\execution\MissingParametersResult;
39
use rtens\domin\execution\NoResult;
40
use rtens\domin\execution\NotPermittedResult;
41
use rtens\domin\execution\RedirectResult;
42
use rtens\domin\execution\ValueResult;
43
use rtens\domin\Executor;
44
use rtens\domin\reflection\CommentParser;
45
use rtens\domin\reflection\types\TypeFactory;
46
use watoki\factory\Factory;
47
use watoki\reflect\ValuePrinter;
48
49
class CliApplication {
50
51
    const OK = 0;
52
    const ERROR = 1;
53
54
    /** @var Factory */
55
    public $factory;
56
57
    /** @var ActionRegistry */
58
    public $actions;
59
60
    /** @var FieldRegistry */
61
    public $fields;
62
63
    /** @var RendererRegistry */
64
    public $renderers;
65
66
    /** @var TypeFactory */
67
    public $types;
68
69
    /** @var CommentParser */
70
    public $parser;
71
72
    /**
73
     * @param Factory $factory <-
74
     * @param ActionRegistry $actions <-
75
     * @param FieldRegistry $fields <-
76
     * @param RendererRegistry $renderers <-
77
     * @param TypeFactory $types <-
78
     * @param CommentParser $parser <-
79
     */
80
    public function __construct(Factory $factory, ActionRegistry $actions, FieldRegistry $fields,
81
                                RendererRegistry $renderers, TypeFactory $types, CommentParser $parser) {
82
        $this->factory = $factory;
83
84
        $this->actions = $actions;
85
        $this->fields = $fields;
86
        $this->renderers = $renderers;
87
        $this->types = $types;
88
        $this->parser = $parser;
89
    }
90
91
    /**
92
     * @param callable $callback Receives the CliApplication instance
93
     * @param null|Factory $factory
94
     * @return Factory
95
     */
96
    public static function init(callable $callback, Factory $factory = null) {
97
        $factory = $factory ?: new Factory();
98
        $callback($factory->setSingleton($factory->getInstance(self::class)));
99
        return $factory;
100
    }
101
102
    public static function run(Factory $factory, Console $console = null) {
103
        global $argv;
0 ignored issues
show
Compatibility Best Practice introduced by
Use of global functionality is not recommended; it makes your code harder to test, and less reusable.

Instead of relying on global state, we recommend one of these alternatives:

1. Pass all data via parameters

function myFunction($a, $b) {
    // Do something
}

2. Create a class that maintains your state

class MyClass {
    private $a;
    private $b;

    public function __construct($a, $b) {
        $this->a = $a;
        $this->b = $b;
    }

    public function myFunction() {
        // Do something
    }
}
Loading history...
104
105
        /** @var self $app */
106
        $app = $factory->getInstance(self::class);
107
        return $app->doRun($console ?: new Console($argv));
108
    }
109
110
    private function doRun(Console $console) {
111
        if ($console->getArguments()) {
112
            if ($console->getArguments()[0] == '!') {
113
                $actionId = $this->selectAction($console);
114
                $reader = new InteractiveCliParameterReader($this->fields, $console);
115
116
                $this->printActionHeader($console, $actionId);
117
            } else {
118
                $actionId = $console->getArguments()[0];
119
                $reader = new CliParameterReader($console);
120
            }
121
        } else {
122
            $this->printUsage($console);
123
            $this->printActions($console);
124
            return self::OK;
125
        }
126
127
        $this->registerFields($reader);
128
        $this->registerRenderers();
129
130
        $executor = new Executor($this->actions, $this->fields, $reader);
131
        return $this->printResult($console, $executor->execute($actionId));
132
    }
133
134
    private function printResult(Console $console, ExecutionResult $result) {
135
        if ($result instanceof ValueResult) {
136
            $value = $result->getValue();
137
            $console->writeLine((string)$this->renderers->getRenderer($value)->render($value));
138
            return self::OK;
139
        } else if ($result instanceof MissingParametersResult) {
140
            $console->writeLine();
141
            $console->writeLine("Missing parameters!");
142
            foreach ($result->getMissingNames() as $missing) {
143
                $console->writeLine('  ' . $missing . ': ' . $result->getException($missing)->getMessage());
144
            }
145
            return self::ERROR;
146
        } else if ($result instanceof NotPermittedResult) {
147
            $console->writeLine('Permission denied');
148
            return self::ERROR;
149
        } else if ($result instanceof FailedResult) {
150
            $console->writeLine("Error: " . $result->getMessage());
151
152
            $exception = $result->getException();
153
            $console->error(
154
                get_class($exception) . ': ' . $exception->getMessage() . ' ' .
155
                '[' . $exception->getFile() . ':' . $exception->getLine() . ']' . "\n" .
156
                $exception->getTraceAsString()
157
            );
158
            return $exception->getCode() ?: self::ERROR;
159
        } else if ($result instanceof NoResult || $result instanceof RedirectResult) {
160
            return self::OK;
161
        } else {
162
            $console->writeLine('Cannot print [' . (new \ReflectionClass($result))->getShortName() . ']');
163
            return self::OK;
164
        }
165
    }
166
167
    private function selectAction(Console $console) {
168
        $console->writeLine();
169
        $console->writeLine('Available Actions');
170
        $console->writeLine('~~~~~~~~~~~~~~~~~');
171
172
        $i = 1;
173
        $actionIds = [];
174 View Code Duplication
        foreach ($this->actions->getAllActions() as $id => $action) {
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...
175
            $console->writeLine($i++ . " - " . $action->caption() . $this->shortDescription($action));
176
            $actionIds[] = $id;
177
        }
178
179
        $console->writeLine();
180
        $actionIndex = $console->read('Action: ');
181
182
        return $actionIds[$actionIndex - 1];
183
    }
184
185
    private function printActionHeader(Console $console, $actionId) {
186
        $action = $this->actions->getAction($actionId);
187
        $console->writeLine();
188
        $console->writeLine($action->caption());
189
        $console->writeLine(str_repeat('~', strlen($action->caption())));
190
        $console->writeLine();
191
192
        if ($action->description()) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $action->description() of type string|null is loosely compared to true; this is ambiguous if the string can be empty. You might want to explicitly use !== null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
193
            $console->writeLine($action->description());
194
            $console->writeLine();
195
        }
196
    }
197
198
    private function printUsage(Console $console) {
199
        $console->writeLine();
200
201
        $console->writeLine("Interactive mode: php {$console->getScriptName()} !");
202
        $console->writeLine("Execute Action:   php {$console->getScriptName()} <actionId> --<parameterName> <parameterValue> ...");
203
        $console->writeLine();
204
    }
205
206
    private function printActions(Console $console) {
207
        $console->writeLine('Available Actions');
208
        $console->writeLine('~~~~~~~~~~~~~~~~~');
209
210 View Code Duplication
        foreach ($this->actions->getAllActions() as $id => $action) {
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...
211
            $console->writeLine($id . ' - ' . $action->caption() . $this->shortDescription($action));
212
        }
213
    }
214
215
    private function registerFields(ParameterReader $reader) {
216
        $this->fields->add(new PrimitiveField());
217
        $this->fields->add(new RangeField());
218
        $this->fields->add(new BooleanField());
219
        $this->fields->add(new FileField());
220
        $this->fields->add(new HtmlField($reader));
221
        $this->fields->add(new DateTimeField());
222
        $this->fields->add(new DateIntervalField());
223
        $this->fields->add(new ArrayField($this->fields, $reader));
224
        $this->fields->add(new NullableField($this->fields, $reader));
225
        $this->fields->add(new ObjectField($this->types, $this->fields, $reader));
226
        $this->fields->add(new MultiField($this->fields, $reader));
227
        $this->fields->add(new IdentifierField($this->fields));
228
        $this->fields->add(new EnumerationField($this->fields));
229
    }
230
231
    private function registerRenderers() {
232
        $this->renderers->add(new BooleanRenderer());
233
        $this->renderers->add(new PrimitiveRenderer());
234
        $this->renderers->add(new DateTimeRenderer());
235
        $this->renderers->add(new DateIntervalRenderer());
236
        $this->renderers->add(new HtmlRenderer());
237
        $this->renderers->add(new IdentifierRenderer());
238
        $this->renderers->add(new FileRenderer(''));
239
        $this->renderers->add(new DelayedOutputRenderer());
240
        $this->renderers->add(new ObjectTableRenderer($this->renderers));
241
        $this->renderers->add(new DataTableRenderer($this->renderers));
242
        $this->renderers->add(new TableRenderer($this->renderers));
243
        $this->renderers->add(new ChartRenderer($this->renderers));
244
        $this->renderers->add(new ArrayRenderer($this->renderers));
245
        $this->renderers->add(new ObjectRenderer($this->renderers, $this->types));
246
    }
247
248
    private function shortDescription(Action $action) {
249
        $description = $this->parser->shorten($action->description());
250
        return $description ? " ($description)" : '';
251
    }
252
}
253