Skip to content

Commit

Permalink
Inject $input and $output into the command instance if it is set up t…
Browse files Browse the repository at this point in the history
…o receive them.
  • Loading branch information
greg-1-anderson committed Aug 26, 2020
1 parent 5452eb5 commit b28007e
Show file tree
Hide file tree
Showing 2 changed files with 66 additions and 0 deletions.
47 changes: 47 additions & 0 deletions src/CommandProcessor.php
Original file line number Diff line number Diff line change
Expand Up @@ -253,6 +253,7 @@ protected function runCommandCallback($commandCallback, CommandData $commandData
{
$result = false;
try {
$this->injectIntoCommandInstance($commandCallback, $commandData);
$args = $this->parameterInjection()->args($commandData);
$result = call_user_func_array($commandCallback, $args);
} catch (\Exception $e) {
Expand All @@ -261,8 +262,54 @@ protected function runCommandCallback($commandCallback, CommandData $commandData
return $result;
}

/**
* Use the parameter injection manager to provide injected classes to command data.
*
* @param CommandData $commandData
* @param array $injectedClasses
*/
public function injectIntoCommandData($commandData, $injectedClasses)
{
$this->parameterInjection()->injectIntoCommandData($commandData, $injectedClasses);
}

/**
* Inject $input and $output into the command instance if it is set up to receive them.
*
* @param callable $commandCallback
* @param CommandData $commandData
*/
protected function injectIntoCommandInstance($commandCallback, CommandData $commandData)
{
$commandInstance = $this->recoverObject($commandCallback);
if (!$commandInstance) {
return;
}

if ($commandInstance instanceof InputAwareInterface) {
$commandInstance->setInput($commandData->input());
}
if ($commandInstance instanceof OutputAwareInterface) {
$commandInstance->setInput($commandData->output());
}
}

/**
* If the command callback is a method of an object, return the object.
*
* @param callable $commandCallback
* @return object|bool
*/
protected function recoverObject($commandCallback)
{
if (!is_array($commandCallback)) {
return false;
}

if (!is_object($commandCallback[0])) {
return false;
}

return $commandCallback[0];
}
}
19 changes: 19 additions & 0 deletions src/Output/OutputAwareInterface.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
<?php

/**
* Provide OutputAwareInterface, not present in Symfony Console
*/

namespace Consolidation\AnnotatedCommand\Output;

use Symfony\Component\Console\Output\OutputInterface;

interface OutputAwareInterface
{
/**
* Sets the Console Output.
*
* @param \Symfony\Component\Console\Output\OutputInterface $output
*/
public function setOutput(OutputInterface $output);
}

0 comments on commit b28007e

Please sign in to comment.