Output.php 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. <?php
  2. namespace Michel\Console;
  3. use RuntimeException;
  4. use const PHP_EOL;
  5. final class Output implements OutputInterface
  6. {
  7. /**
  8. * @var callable
  9. */
  10. private $output;
  11. public function __construct(callable $output = null)
  12. {
  13. if ($output === null) {
  14. $output = function ($message, $error = false) {
  15. if ($error) {
  16. fwrite(STDERR, $message);
  17. return;
  18. }
  19. fwrite(STDOUT, $message);
  20. };
  21. }
  22. $this->output = $output;
  23. }
  24. /**
  25. * @var bool
  26. */
  27. private bool $verbose = false;
  28. public function error(string $message): void
  29. {
  30. $output = $this->output;
  31. $output($message, true);
  32. }
  33. public function write(string $message): void
  34. {
  35. $output = $this->output;
  36. $output($message);
  37. }
  38. public function writeln(string $message): void
  39. {
  40. $this->write($message);
  41. $this->write(PHP_EOL);
  42. }
  43. public function setVerbose(bool $verbose): void
  44. {
  45. $this->verbose = $verbose;
  46. }
  47. public function isVerbose(): bool
  48. {
  49. return $this->verbose;
  50. }
  51. }