Last active
June 6, 2021 13:58
-
-
Save sroze/3e8d45d0cdc301debfd2 to your computer and use it in GitHub Desktop.
Symfony Command that read file from file name or STDIN
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
<?php | |
namespace AmceBundle\Command; | |
class MyCommand | |
{ | |
// ... | |
protected function execute(InputInterface $input, OutputInterface $output) | |
{ | |
if ($filename = $input->getArgument('filename')) { | |
$contents = file_get_contents($filename); | |
} else if (0 === ftell(STDIN)) { | |
$contents = ''; | |
while (!feof(STDIN)) { | |
$contents .= fread(STDIN, 1024); | |
} | |
} else { | |
throw new \RuntimeException("Please provide a filename or pipe template content to STDIN."); | |
} | |
// Do whatever you want with `$contents` | |
} | |
} |
Or use stream_get_contents
@chalasr removed 😉
I found that the strategy of using ftell()
to identify if there was content to get from STDIN
was problematic when running PHPUnit via PHPStorm because ftell()
always returned 0
. I'm not sure what PHPStorm is doing with STDIN for this to happen.
So I found the following alternative strategy from PHP - detect STDIO input - Stack Overflow by dedee which appears to work in all cases.
$readStreams = [STDIN];
$writeStreams = [];
$exceptStreams = [];
$streamCount = stream_select($readStreams, $writeStreams, $exceptStreams, 0);
$hasStdIn = $streamCount === 1;
if ($hasStdIn) {
// Read content from STDIN ...
}
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This line should be removed:
- $filename = $input->getArgument('filename');
Thanks for sharing this.