Skip to content

Instantly share code, notes, and snippets.

@sroze
Last active June 6, 2021 13:58
Show Gist options
  • Star 11 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save sroze/3e8d45d0cdc301debfd2 to your computer and use it in GitHub Desktop.
Save sroze/3e8d45d0cdc301debfd2 to your computer and use it in GitHub Desktop.
Symfony Command that read file from file name or STDIN
<?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`
}
}
@chalasr
Copy link

chalasr commented Jun 21, 2016

This line should be removed:

- $filename = $input->getArgument('filename');

Thanks for sharing this.

@Cosmologist
Copy link

Or use stream_get_contents

@sroze
Copy link
Author

sroze commented Oct 3, 2017

@chalasr removed 😉

@courtney-miles
Copy link

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