8000 Ensure overriding Command::execute() keep priority over __invoke · symfony/symfony@f77c403 · GitHub
[go: up one dir, main page]

Skip to content

Commit f77c403

Browse files
committed
Ensure overriding Command::execute() keep priority over __invoke
1 parent 7379bfb commit f77c403

File tree

2 files changed

+42
-1
lines changed

2 files changed

+42
-1
lines changed

src/Symfony/Component/Console/Command/Command.php

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -134,7 +134,7 @@ public function __construct(?string $name = null)
134134
$this->setHelp($attribute?->help ?? '');
135135
}
136136

137-
if (\is_callable($this)) {
137+
if (\is_callable($this) && (new \ReflectionMethod($this, 'execute'))->getDeclaringClass()->name === self::class) {
138138
$this->code = new InvokableCommand($this, $this(...));
139139
}
140140

src/Symfony/Component/Console/Tests/Command/InvokableCommandTest.php

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,9 @@
2121
use Symfony\Component\Console\Exception\InvalidOptionException;
2222
use Symfony\Component\Console\Exception\LogicException;
2323
use Symfony\Component\Console\Input\ArrayInput;
24+
use Symfony\Component\Console\Input\InputInterface;
2425
use Symfony\Component\Console\Output\NullOutput;
26+
use Symfony\Component\Console\Output\OutputInterface;
2527

2628
class InvokableCommandTest extends TestCase
2729
{
@@ -142,6 +144,45 @@ public function testInvalidOptionType()
142144
$command->getDefinition();
143145
}
144146

147+
public function testExecuteHasPriorityOverInvokeMethod()
148+
{
149+
$command = new class extends Command {
150+
public string $called;
151+
protected function execute(InputInterface $input, OutputInterface $output): int
152+
{
153+
$this->called = __FUNCTION__;
154+
155+
return 0;
156+
}
157+
158+
public function __invoke(): int
159+
{
160+
$this->called = __FUNCTION__;
161+
162+
return 0;
163+
}
164+
};
165+
166+
$command->run(new ArrayInput([]), new NullOutput());
167+
$this->assertSame('execute', $command->called);
168+
}
169+
170+
public function testCallInvokeMethodWhenExtendingCommandClass()
171+
{
172+
$command = new class extends Command {
173+
public string $called;
174+
public function __invoke(): int
175+
{
176+
$this->called = __FUNCTION__;
177+
178+
return 0;
179+
}
180+
};
181+
182+
$command->run(new ArrayInput([]), new NullOutput());
183+
$this->assertSame('__invoke', $command->called);
184+
}
185+
145186
public function testInvalidReturnType()
146187
{
147188
$command = new Command('foo');

0 commit comments

Comments
 (0)
0