merged branch igorw/callable-set-code (PR #6179)

This PR was submitted for the 2.1 branch but it was merged into the master branch instead (closes #6179).

Commits
-------

31911c2 [Console] Allow any callable to be passed to Command::setCode

Discussion
----------

[Console] Allow any callable to be passed to Command::setCode

Bug fix: no
Feature addition: kinda
Backwards compatibility break: no
Symfony2 tests pass: yes
License of the code: MIT
This commit is contained in:
Fabien Potencier 2012-12-03 23:00:56 +01:00
commit 6ded77566b
2 changed files with 31 additions and 2 deletions

View File

@ -247,7 +247,7 @@ class Command
* If this method is used, it overrides the code defined
* in the execute() method.
*
* @param \Closure $code A \Closure
* @param callable $code A callable(InputInterface $input, OutputInterface $output)
*
* @return Command The current instance
*
@ -255,8 +255,12 @@ class Command
*
* @api
*/
public function setCode(\Closure $code)
public function setCode($code)
{
if (!is_callable($code)) {
throw new \InvalidArgumentException('Invalid callable provided to Command::setCode.');
}
$this->code = $code;
return $this;

View File

@ -240,6 +240,31 @@ class CommandTest extends \PHPUnit_Framework_TestCase
$this->assertEquals('interact called'.PHP_EOL.'from the code...'.PHP_EOL, $tester->getDisplay());
}
public function testSetCodeWithNonClosureCallable()
{
$command = new \TestCommand();
$ret = $command->setCode(array($this, 'callableMethodCommand'));
$this->assertEquals($command, $ret, '->setCode() implements a fluent interface');
$tester = new CommandTester($command);
$tester->execute(array());
$this->assertEquals('interact called'.PHP_EOL.'from the code...'.PHP_EOL, $tester->getDisplay());
}
/**
* @expectedException InvalidArgumentException
* @expectedExceptionMessage Invalid callable provided to Command::setCode.
*/
public function testSetCodeWithNonCallable()
{
$command = new \TestCommand();
$command->setCode(array($this, 'nonExistentMethod'));
}
public function callableMethodCommand(InputInterface $input, OutputInterface $output)
{
$output->writeln('from the code...');
}
public function testAsText()
{
$command = new \TestCommand();