Skip to content

Commit

Permalink
Add output handler to command utility
Browse files Browse the repository at this point in the history
  • Loading branch information
leomarquine committed Oct 27, 2017
1 parent 60e1536 commit 7812256
Show file tree
Hide file tree
Showing 2 changed files with 72 additions and 8 deletions.
44 changes: 37 additions & 7 deletions src/Utilities/Command.php
Original file line number Diff line number Diff line change
Expand Up @@ -12,11 +12,11 @@ class Command extends Utility
public $command;

/**
* List of commands to run.
* Command output handler.
*
* @var array
* @var callable
*/
public $commands = [];
public $handler;

/**
* Run the utility.
Expand All @@ -25,12 +25,42 @@ class Command extends Utility
*/
public function run()
{
if ($this->command) {
shell_exec($this->command);
if (is_string($this->command)) {
$output = $this->runCommand();
}

if (is_array($this->command)) {
$output = $this->runCommands();
}

if (is_callable($this->handler)) {
call_user_func($this->handler, $output);
}
}

/**
* Execute a single command.
*
* @return string
*/
protected function runCommand()
{
return shell_exec($this->command);
}

foreach ($this->commands as $command) {
shell_exec($command);
/**
* Execute multiple commands.
*
* @return array
*/
protected function runCommands()
{
$output = [];

foreach ($this->command as $command) {
$output[] = shell_exec($command);
}

return $output;
}
}
36 changes: 35 additions & 1 deletion tests/Utilities/CommandTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ public function execute_multiple_commands()
{
$utility = new Command;

$utility->commands = [
$utility->command = [
"touch {$this->path('file.txt')}",
"mv {$this->path('file.txt')} {$this->path('new.txt')}",
];
Expand All @@ -59,4 +59,38 @@ public function execute_multiple_commands()

$this->assertFileExists($this->path('new.txt'));
}

/** @test */
public function handle_output_of_a_single_command()
{
$utility = new Command;

$result;

$utility->command = 'echo foobar';
$utility->handler = function ($output) use (&$result) {
$result = $output;
};

$utility->run();

$this->assertEquals('foobar', trim($result));
}

/** @test */
public function handle_output_of_multiple_commands()
{
$utility = new Command;

$result;

$utility->command = ['echo foo', 'echo bar'];
$utility->handler = function ($output) use (&$result) {
$result = $output;
};

$utility->run();

$this->assertEquals(['foo', 'bar'], array_map('trim', $result));
}
}

0 comments on commit 7812256

Please sign in to comment.