Completed
Pull Request — master (#179)
by Greg
01:41
created

CommandProcessor::getInstanceToInject()   A

Complexity

Conditions 3
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 3
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
        // A little messy, for backwards compatibility: if the result implements
198
        // ExitCodeInterface, then use that as the exit code. If a status code
199
        // dispatcher returns a non-zero result, then we will never print a
200
        // result.
201
        if ($result instanceof ExitCodeInterface) {
202
            $status = $result->getExitCode();
203
        } else {
204
            $status = $statusCodeDispatcher->determineStatusCode($result);
205
            if (isset($status) && ($status != 0)) {
206
                return $status;
207
            }
208
        }
209
        // If the result is an integer and no separate status code was provided, then use the result as the status and do no output.
210
        if (is_integer($result) && !isset($status)) {
211
            return $result;
212
        }
213
        $status = $this->interpretStatusCode($status);
214
215
        // Get the structured output, the output stream and the formatter
216
        $extractDispatcher = new ExtracterHookDispatcher($this->hookManager(), $names);
217
        $structuredOutput = $extractDispatcher->extractOutput($result);
218
        if (($status != 0) && is_string($structuredOutput)) {
219
            $output = $this->chooseOutputStream($output, $status);
220
            return $this->writeErrorMessage($output, $status, $structuredOutput, $result);
221
        }
222
        if ($this->dataCanBeFormatted($structuredOutput) && isset($this->formatterManager)) {
223
            return $this->writeUsingFormatter($output, $structuredOutput, $commandData, $status);
224
        }
225
        return $this->writeCommandOutput($output, $structuredOutput, $status);
226
    }
227
228
    protected function dataCanBeFormatted($structuredOutput)
229
    {
230
        if (!isset($this->formatterManager)) {
231
            return false;
232
        }
233
        return
234
            is_object($structuredOutput) ||
235
            is_array($structuredOutput);
236
    }
237
238
    /**
239
     * Run the main command callback
240
     */
241
    protected function runCommandCallback($commandCallback, CommandData $commandData)
242
    {
243
        $result = false;
244
        try {
245
            $args = array_merge(
246
                $commandData->injectedInstances(),
247
                $commandData->getArgsAndOptions()
248
            );
249
            $result = call_user_func_array($commandCallback, $args);
250
        } catch (\Exception $e) {
251
            $result = $this->commandErrorForException($e);
252
        }
253
        return $result;
254
    }
255
256
    public function injectIntoCommandData($commandData, $injectedClasses)
257
    {
258
        foreach ($injectedClasses as $injectedClass) {
259
            $injectedInstance = $this->getInstanceToInject($commandData, $injectedClass);
260
            $commandData->injectInstance($injectedInstance);
261
        }
262
    }
263
264
    protected function getInstanceToInject(CommandData $commandData, $injectedClass)
265
    {
266
        switch ($injectedClass) {
267
            case 'Symfony\Component\Console\Input\InputInterface':
268
                return $commandData->input();
269
            case 'Symfony\Component\Console\Output\OutputInterface':
270
                return $commandData->output();
271
        }
272
273
        return null;
274
    }
275
276
    /**
277
     * Determine the formatter that should be used to render
278
     * output.
279
     *
280
     * If the user specified a format via the --format option,
281
     * then always return that.  Otherwise, return the default
282
     * format, unless --pipe was specified, in which case
283
     * return the default pipe format, format-pipe.
284
     *
285
     * n.b. --pipe is a handy option introduced in Drush 2
286
     * (or perhaps even Drush 1) that indicates that the command
287
     * should select the output format that is most appropriate
288
     * for use in scripts (e.g. to pipe to another command).
289
     *
290
     * @return string
291
     */
292
    protected function getFormat(FormatterOptions $options)
293
    {
294
        // In Symfony Console, there is no way for us to differentiate
295
        // between the user specifying '--format=table', and the user
296
        // not specifying --format when the default value is 'table'.
297
        // Therefore, we must make --field always override --format; it
298
        // cannot become the default value for --format.
299
        if ($options->get('field')) {
300
            return 'string';
301
        }
302
        $defaults = [];
303
        if ($options->get('pipe')) {
304
            return $options->get('pipe-format', [], 'tsv');
305
        }
306
        return $options->getFormat($defaults);
307
    }
308
309
    /**
310
     * Determine whether we should use stdout or stderr.
311
     */
312
    protected function chooseOutputStream(OutputInterface $output, $status)
313
    {
314
        // If the status code indicates an error, then print the
315
        // result to stderr rather than stdout
316
        if ($status && ($output instanceof ConsoleOutputInterface)) {
317
            return $output->getErrorOutput();
318
        }
319
        return $output;
320
    }
321
322
    /**
323
     * Call the formatter to output the provided data.
324
     */
325
    protected function writeUsingFormatter(OutputInterface $output, $structuredOutput, CommandData $commandData, $status = 0)
326
    {
327
        $formatterOptions = $this->createFormatterOptions($commandData);
328
        $format = $this->getFormat($formatterOptions);
329
        $this->formatterManager->write(
330
            $output,
331
            $format,
332
            $structuredOutput,
333
            $formatterOptions
334
        );
335
        return $status;
336
    }
337
338
    /**
339
     * Create a FormatterOptions object for use in writing the formatted output.
340
     * @param CommandData $commandData
341
     * @return FormatterOptions
342
     */
343
    protected function createFormatterOptions($commandData)
344
    {
345
        $options = $commandData->input()->getOptions();
346
        $formatterOptions = new FormatterOptions($commandData->annotationData()->getArrayCopy(), $options);
347
        foreach ($this->prepareOptionsList as $preparer) {
348
            $preparer->prepare($commandData, $formatterOptions);
349
        }
350
        return $formatterOptions;
351
    }
352
353
    /**
354
     * Description
355
     * @param OutputInterface $output
356
     * @param int $status
357
     * @param string $structuredOutput
358
     * @param mixed $originalResult
359
     * @return type
360
     */
361
    protected function writeErrorMessage($output, $status, $structuredOutput, $originalResult)
362
    {
363
        if (isset($this->displayErrorFunction)) {
364
            call_user_func($this->displayErrorFunction, $output, $structuredOutput, $status, $originalResult);
365
        } else {
366
            $this->writeCommandOutput($output, $structuredOutput);
367
        }
368
        return $status;
369
    }
370
371
    /**
372
     * If the result object is a string, then print it.
373
     */
374
    protected function writeCommandOutput(
375
        OutputInterface $output,
376
        $structuredOutput,
377
        $status = 0
378
    ) {
379
        // If there is no formatter, we will print strings,
380
        // but can do no more than that.
381
        if (is_string($structuredOutput)) {
382
            $output->writeln($structuredOutput);
383
        }
384
        return $status;
385
    }
386
387
    /**
388
     * If a status code was set, then return it; otherwise,
389
     * presume success.
390
     */
391
    protected function interpretStatusCode($status)
392
    {
393
        if (isset($status)) {
394
            return $status;
395
        }
396
        return 0;
397
    }
398
}
399