Skip to content

[Console] Support reading from stdin directly #61384

@alex-dev

Description

@alex-dev

Description

Using pipes and redirection in terminal allows to create more flexible CLI tools. Symfony doesn't offer a standard way to deal with this.

Example

Here is a simple implementation that does most of the job.

function readStdin(InputInterface $input): string {
  $stdin = $input instanceof StreamableInputInterface ? $input->getStream() : null;
  $stdin ??= fopen('php://stdin', 'r');
  
  $reads = [$stdin];
  $writes = [];
  $excepts = [];
  
  if (!stream_select($reads, $writes, $excepts, seconds: 0)) {
    return '';
  }
  
  return stream_get_contents($stdin) ?: '';
}

This implementation is impossible to test correctly under Symfony standard facilities: stdin will block if it is empty, a memory based stream is not even selectable.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions