From 18d426871e8854123063ff56dc3046fe1bd365ca Mon Sep 17 00:00:00 2001 From: Thomas Calvet Date: Fri, 22 Jan 2021 09:23:15 +0100 Subject: [PATCH] [Console][Command] Fix Closure code binding when it is a static anonymous function --- src/Symfony/Component/Console/Command/Command.php | 9 ++++++++- .../Component/Console/Tests/Command/CommandTest.php | 12 ++++++++++++ 2 files changed, 20 insertions(+), 1 deletion(-) diff --git a/src/Symfony/Component/Console/Command/Command.php b/src/Symfony/Component/Console/Command/Command.php index c2b1f4c7e9..71ad4a49e9 100644 --- a/src/Symfony/Component/Console/Command/Command.php +++ b/src/Symfony/Component/Console/Command/Command.php @@ -281,7 +281,14 @@ class Command if ($code instanceof \Closure) { $r = new \ReflectionFunction($code); if (null === $r->getClosureThis()) { - $code = \Closure::bind($code, $this); + set_error_handler(static function () {}); + try { + if ($c = \Closure::bind($code, $this)) { + $code = $c; + } + } finally { + restore_error_handler(); + } } } diff --git a/src/Symfony/Component/Console/Tests/Command/CommandTest.php b/src/Symfony/Component/Console/Tests/Command/CommandTest.php index 34156f7b52..9e1ae05eb1 100644 --- a/src/Symfony/Component/Console/Tests/Command/CommandTest.php +++ b/src/Symfony/Component/Console/Tests/Command/CommandTest.php @@ -398,6 +398,18 @@ class CommandTest extends TestCase { $output->writeln('from the code...'); } + + public function testSetCodeWithStaticAnonymousFunction() + { + $command = new \TestCommand(); + $command->setCode(static function (InputInterface $input, OutputInterface $output) { + $output->writeln(isset($this) ? 'bound' : 'not bound'); + }); + $tester = new CommandTester($command); + $tester->execute([]); + + $this->assertEquals('interact called'.\PHP_EOL.'not bound'.\PHP_EOL, $tester->getDisplay()); + } } // In order to get an unbound closure, we should create it outside a class