diff --git a/src/Symfony/Component/Console/Command/Command.php b/src/Symfony/Component/Console/Command/Command.php index 02e207eac775c..0b968809938d3 100644 --- a/src/Symfony/Component/Console/Command/Command.php +++ b/src/Symfony/Component/Console/Command/Command.php @@ -284,6 +284,13 @@ public function setCode($code) throw new \InvalidArgumentException('Invalid callable provided to Command::setCode.'); } + if (PHP_VERSION_ID >= 50400 && $code instanceof \Closure) { + $r = new \ReflectionFunction($code); + if (null === $r->getClosureThis()) { + $code = \Closure::bind($code, $this); + } + } + $this->code = $code; return $this; diff --git a/src/Symfony/Component/Console/Tests/Command/CommandTest.php b/src/Symfony/Component/Console/Tests/Command/CommandTest.php index 08761163eb2d8..42b2944ba77bb 100644 --- a/src/Symfony/Component/Console/Tests/Command/CommandTest.php +++ b/src/Symfony/Component/Console/Tests/Command/CommandTest.php @@ -293,6 +293,33 @@ public function testSetCode() $this->assertEquals('interact called'.PHP_EOL.'from the code...'.PHP_EOL, $tester->getDisplay()); } + public function getSetCodeBindToClosureTests() + { + return array( + array(true, 'not bound to the command'), + array(false, 'bound to the command'), + ); + } + + /** @dataProvider getSetCodeBindToClosureTests */ + public function testSetCodeBindToClosure($previouslyBound, $expected) + { + if (PHP_VERSION_ID < 50400) { + $this->markTestSkipped('Test skipped, for PHP 5.4+ only.'); + } + + $code = createClosure(); + if ($previouslyBound) { + $code = $code->bindTo($this); + } + + $command = new \TestCommand(); + $command->setCode($code); + $tester = new CommandTester($command); + $tester->execute(array()); + $this->assertEquals('interact called'.PHP_EOL.$expected.PHP_EOL, $tester->getDisplay()); + } + public function testSetCodeWithNonClosureCallable() { $command = new \TestCommand(); @@ -346,3 +373,13 @@ public function testLegacyAsXml() $this->assertXmlStringEqualsXmlFile(self::$fixturesPath.'/command_asxml.txt', $command->asXml(), '->asXml() returns an XML representation of the command'); } } + +// In order to get an unbound closure, we should create it outside a class +// scope. +function createClosure() +{ + return function(InputInterface $input, OutputInterface $output) + { + $output->writeln($this instanceof Command ? 'bound to the command' : 'not bound to the command'); + }; +}
Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.
Alternative Proxies: