Last active
February 19, 2024 06:37
-
-
Save lyrixx/1be01bdfc65711dd03dbab5af3c6a028 to your computer and use it in GitHub Desktop.
How to call private command method in Symfony ?
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env php | |
<?php | |
require __DIR__ . '/../../vendor/autoload.php'; | |
use Castor\Console\Command\CompileCommand; | |
use Symfony\Component\Console\Application; | |
use Symfony\Component\Console\Command\Command; | |
// We extends the CompileCommand, to be able to remove the constructor, because | |
// it has some dependencies. We don't need them. So we don't want to pass them. | |
$command = (new class() extends CompileCommand { | |
public function __construct() { | |
// Don't call parent, cf above. But we need to call the Command | |
// constructor. | |
Command::__construct(); | |
}} | |
) | |
// Override the default `CompileCommand::execute()` | |
// see https://github.com/symfony/symfony/blob/7.1/src/Symfony/Component/Console/Command/Command.php#L312 | |
->setCode( | |
// We bind the closure to the CompileCommand class, to be able to use | |
// `$this` with `CompileCommand` scope. It means that we can use the | |
// private method `CompileCommand::generatePHPBuildCacheKey()` | |
Closure::bind( | |
fn($input) => | |
// We can use the private method in the closure | |
// `&& 0` is to force the return to be 0 (success) (otherwise it's the return of `print()` call) | |
(print $this->generatePHPBuildCacheKey($input)) && 0, | |
null, | |
CompileCommand::class, // The class where the closure is bound | |
) | |
) | |
; | |
// Regular Symfony Single Command Application But there is also a | |
// SingleCommandApplication, but PHP class cannot extends two classes. | |
(new Application()) | |
->add($command) | |
->getApplication() | |
->setDefaultCommand($command->getName(), true) | |
->run() | |
; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment