Completed
Pull Request — master (#163)
by Greg
07:30
created

CommandProcessor::runCommandCallback()   A

Complexity

Conditions 2
Paths 3

Size

Total Lines 11

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 11
rs 9.9
c 0
b 0
f 0
cc 2
nc 3
nop 2
1
<?php
2
namespace Consolidation\AnnotatedCommand;
3
4
use Consolidation\AnnotatedCommand\Hooks\Dispatchers\ReplaceCommandHookDispatcher;
5
use Psr\Log\LoggerAwareInterface;
6
use Psr\Log\LoggerAwareTrait;
7
use Symfony\Component\Console\Input\InputInterface;
8
use Symfony\Component\Console\Output\OutputInterface;
9
use Symfony\Component\Console\Output\ConsoleOutputInterface;
10
11
use Consolidation\OutputFormatters\FormatterManager;
12
use Consolidation\OutputFormatters\Options\FormatterOptions;
13
use Consolidation\AnnotatedCommand\Hooks\HookManager;
14
use Consolidation\AnnotatedCommand\Options\PrepareFormatter;
15
16
use Consolidation\AnnotatedCommand\Hooks\Dispatchers\InitializeHookDispatcher;
17
use Consolidation\AnnotatedCommand\Hooks\Dispatchers\OptionsHookDispatcher;
18
use Consolidation\AnnotatedCommand\Hooks\Dispatchers\InteractHookDispatcher;
19
use Consolidation\AnnotatedCommand\Hooks\Dispatchers\ValidateHookDispatcher;
20
use Consolidation\AnnotatedCommand\Hooks\Dispatchers\ProcessResultHookDispatcher;
21
use Consolidation\AnnotatedCommand\Hooks\Dispatchers\StatusDeterminerHookDispatcher;
22
use Consolidation\AnnotatedCommand\Hooks\Dispatchers\ExtracterHookDispatcher;
23
24
/**
25
 * Process a command, including hooks and other callbacks.
26
 * There should only be one command processor per application.
27
 * Provide your command processor to the AnnotatedCommandFactory
28
 * via AnnotatedCommandFactory::setCommandProcessor().
29
 */
30
class CommandProcessor implements LoggerAwareInterface
31
{
32
    use LoggerAwareTrait;
33
34
    /** var HookManager */
35
    protected $hookManager;
36
    /** var FormatterManager */
37
    protected $formatterManager;
38
    /** var callable */
39
    protected $displayErrorFunction;
40
    /** var PrepareFormatterOptions[] */
41
    protected $prepareOptionsList = [];
42
    /** var boolean */
43
    protected $passExceptions;
44
45
    public function __construct(HookManager $hookManager)
46
    {
47
        $this->hookManager = $hookManager;
48
    }
49
50
    /**
51
     * Return the hook manager
52
     * @return HookManager
53
     */
54
    public function hookManager()
55
    {
56
        return $this->hookManager;
57
    }
58
59
    public function addPrepareFormatter(PrepareFormatter $preparer)
60
    {
61
        $this->prepareOptionsList[] = $preparer;
62
    }
63
64
    public function setFormatterManager(FormatterManager $formatterManager)
65
    {
66
        $this->formatterManager = $formatterManager;
67
        return $this;
68
    }
69
70
    public function setDisplayErrorFunction(callable $fn)
71
    {
72
        $this->displayErrorFunction = $fn;
73
        return $this;
74
    }
75
76
    /**
77
     * Set a mode to make the annotated command library re-throw
78
     * any exception that it catches while processing a command.
79
     *
80
     * The default behavior in the current (2.x) branch is to catch
81
     * the exception and replace it with a CommandError object that
82
     * may be processed by the normal output processing passthrough.
83
     *
84
     * In the 3.x branch, exceptions will never be caught; they will
85
     * be passed through, as if setPassExceptions(true) were called.
86
     * This is the recommended behavior.
87
     */
88
    public function setPassExceptions($passExceptions)
89
    {
90
        $this->passExceptions = $passExceptions;
91
        return $this;
92
    }
93
94
    public function commandErrorForException(\Exception $e)
95
    {
96
        if ($this->passExceptions) {
97
            throw $e;
98
        }
99
        return new CommandError($e->getMessage(), $e->getCode());
100
    }
101
102
    /**
103
     * Return the formatter manager
104
     * @return FormatterManager
105
     */
106
    public function formatterManager()
107
    {
108
        return $this->formatterManager;
109
    }
110
111
    public function initializeHook(
112
        InputInterface $input,
113
        $names,
114
        AnnotationData $annotationData
115
    ) {
116
        $initializeDispatcher = new InitializeHookDispatcher($this->hookManager(), $names);
117
        return $initializeDispatcher->initialize($input, $annotationData);
118
    }
119
120
    public function optionsHook(
121
        AnnotatedCommand $command,
122
        $names,
123
        AnnotationData $annotationData
124
    ) {
125
        $optionsDispatcher = new OptionsHookDispatcher($this->hookManager(), $names);
126
        $optionsDispatcher->getOptions($command, $annotationData);
127
    }
128
129
    public function interact(
130
        InputInterface $input,
131
        OutputInterface $output,
132
        $names,
133
        AnnotationData $annotationData
134
    ) {
135
        $interactDispatcher = new InteractHookDispatcher($this->hookManager(), $names);
136
        return $interactDispatcher->interact($input, $output, $annotationData);
137
    }
138
139
    public function process(
140
        OutputInterface $output,
141
        $names,
142
        $commandCallback,
143
        CommandData $commandData
144
    ) {
145
        $result = [];
146
        try {
147
            $result = $this->validateRunAndAlter(
148
                $names,
149
                $commandCallback,
150
                $commandData
151
            );
152
            return $this->handleResults($output, $names, $result, $commandData);
153
        } catch (\Exception $e) {
154
            $result = $this->commandErrorForException($e);
155
            return $this->handleResults($output, $names, $result, $commandData);
156
        }
157
    }
158
159
    public function validateRunAndAlter(
160
        $names,
161
        $commandCallback,
162
        CommandData $commandData
163
    ) {
164
        // Validators return any object to signal a validation error;
165
        // if the return an array, it replaces the arguments.
166
        $validateDispatcher = new ValidateHookDispatcher($this->hookManager(), $names);
167
        $validated = $validateDispatcher->validate($commandData);
168
        if (is_object($validated)) {
169
            return $validated;
170
        }
171
172
        $replaceDispatcher = new ReplaceCommandHookDispatcher($this->hookManager(), $names);
173
        if ($this->logger) {
174
            $replaceDispatcher->setLogger($this->logger);
175
        }
176
        if ($replaceDispatcher->hasReplaceCommandHook()) {
177
            $commandCallback = $replaceDispatcher->getReplacementCommand($commandData);
178
        }
179
180
        // Run the command, alter the results, and then handle output and status
181
        $result = $this->runCommandCallback($commandCallback, $commandData);
182
        return $this->processResults($names, $result, $commandData);
183
    }
184
185
    public function processResults($names, $result, CommandData $commandData)
186
    {
187
        $processDispatcher = new ProcessResultHookDispatcher($this->hookManager(), $names);
188
        return $processDispatcher->process($result, $commandData);
189
    }
190
191
    /**
192
     * Handle the result output and status code calculation.
193
     */
194
    public function handleResults(OutputInterface $output, $names, $result, CommandData $commandData)
195
    {
196
        $statusCodeDispatcher = new StatusDeterminerHookDispatcher($this->hookManager(), $names);
197
        $status = $statusCodeDispatcher->determineStatusCode($result);
198
        // If the result is an integer and no separate status code was provided, then use the result as the status and do no output.
199
        if (is_integer($result) && !isset($status)) {
200
            return $result;
201
        }
202
        $status = $this->interpretStatusCode($status);
203
204
        // Get the structured output, the output stream and the formatter
205
        $extractDispatcher = new ExtracterHookDispatcher($this->hookManager(), $names);
206
        $structuredOutput = $extractDispatcher->extractOutput($result);
207
        $output = $this->chooseOutputStream($output, $status);
208
        if ($status != 0) {
209
            return $this->writeErrorMessage($output, $status, $structuredOutput, $result);
210
        }
211
        if (isset($this->formatterManager)) {
212
            return $this->writeUsingFormatter($output, $structuredOutput, $commandData);
213
        }
214
        return $this->writeCommandOutput($output, $structuredOutput);
215
    }
216
217
    /**
218
     * Run the main command callback
219
     */
220
    protected function runCommandCallback($commandCallback, CommandData $commandData)
221
    {
222
        $result = false;
223
        try {
224
            $args = $commandData->getArgsAndOptions();
225
            $result = call_user_func_array($commandCallback, $args);
226
        } catch (\Exception $e) {
227
            $result = $this->commandErrorForException($e);
228
        }
229
        return $result;
230
    }
231
232
    /**
233
     * Determine the formatter that should be used to render
234
     * output.
235
     *
236
     * If the user specified a format via the --format option,
237
     * then always return that.  Otherwise, return the default
238
     * format, unless --pipe was specified, in which case
239
     * return the default pipe format, format-pipe.
240
     *
241
     * n.b. --pipe is a handy option introduced in Drush 2
242
     * (or perhaps even Drush 1) that indicates that the command
243
     * should select the output format that is most appropriate
244
     * for use in scripts (e.g. to pipe to another command).
245
     *
246
     * @return string
247
     */
248
    protected function getFormat(FormatterOptions $options)
249
    {
250
        // In Symfony Console, there is no way for us to differentiate
251
        // between the user specifying '--format=table', and the user
252
        // not specifying --format when the default value is 'table'.
253
        // Therefore, we must make --field always override --format; it
254
        // cannot become the default value for --format.
255
        if ($options->get('field')) {
256
            return 'string';
257
        }
258
        $defaults = [];
259
        if ($options->get('pipe')) {
260
            return $options->get('pipe-format', [], 'tsv');
261
        }
262
        return $options->getFormat($defaults);
263
    }
264
265
    /**
266
     * Determine whether we should use stdout or stderr.
267
     */
268
    protected function chooseOutputStream(OutputInterface $output, $status)
269
    {
270
        // If the status code indicates an error, then print the
271
        // result to stderr rather than stdout
272
        if ($status && ($output instanceof ConsoleOutputInterface)) {
273
            return $output->getErrorOutput();
274
        }
275
        return $output;
276
    }
277
278
    /**
279
     * Call the formatter to output the provided data.
280
     */
281
    protected function writeUsingFormatter(OutputInterface $output, $structuredOutput, CommandData $commandData)
282
    {
283
        $formatterOptions = $this->createFormatterOptions($commandData);
284
        $format = $this->getFormat($formatterOptions);
285
        $this->formatterManager->write(
286
            $output,
287
            $format,
288
            $structuredOutput,
289
            $formatterOptions
290
        );
291
        return 0;
292
    }
293
294
    /**
295
     * Create a FormatterOptions object for use in writing the formatted output.
296
     * @param CommandData $commandData
297
     * @return FormatterOptions
298
     */
299
    protected function createFormatterOptions($commandData)
300
    {
301
        $options = $commandData->input()->getOptions();
302
        $formatterOptions = new FormatterOptions($commandData->annotationData()->getArrayCopy(), $options);
303
        foreach ($this->prepareOptionsList as $preparer) {
304
            $preparer->prepare($commandData, $formatterOptions);
305
        }
306
        return $formatterOptions;
307
    }
308
309
    /**
310
     * Description
311
     * @param OutputInterface $output
312
     * @param int $status
313
     * @param string $structuredOutput
314
     * @param mixed $originalResult
315
     * @return type
316
     */
317
    protected function writeErrorMessage($output, $status, $structuredOutput, $originalResult)
318
    {
319
        if (isset($this->displayErrorFunction)) {
320
            call_user_func($this->displayErrorFunction, $output, $structuredOutput, $status, $originalResult);
321
        } else {
322
            $this->writeCommandOutput($output, $structuredOutput);
323
        }
324
        return $status;
325
    }
326
327
    /**
328
     * If the result object is a string, then print it.
329
     */
330
    protected function writeCommandOutput(
331
        OutputInterface $output,
332
        $structuredOutput
333
    ) {
334
        // If there is no formatter, we will print strings,
335
        // but can do no more than that.
336
        if (is_string($structuredOutput)) {
337
            $output->writeln($structuredOutput);
338
        }
339
        return 0;
340
    }
341
342
    /**
343
     * If a status code was set, then return it; otherwise,
344
     * presume success.
345
     */
346
    protected function interpretStatusCode($status)
347
    {
348
        if (isset($status)) {
349
            return $status;
350
        }
351
        return 0;
352
    }
353
}
354