TrimmedBufferOutput.php 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. <?php
  2. /*
  3. * This file is part of the Symfony package.
  4. *
  5. * (c) Fabien Potencier <fabien@symfony.com>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace Symfony\Component\Console\Output;
  11. use Symfony\Component\Console\Exception\InvalidArgumentException;
  12. use Symfony\Component\Console\Formatter\OutputFormatterInterface;
  13. /**
  14. * A BufferedOutput that keeps only the last N chars.
  15. *
  16. * @author Jérémy Derussé <jeremy@derusse.com>
  17. */
  18. class TrimmedBufferOutput extends Output
  19. {
  20. private int $maxLength;
  21. private string $buffer = '';
  22. public function __construct(int $maxLength, ?int $verbosity = self::VERBOSITY_NORMAL, bool $decorated = false, ?OutputFormatterInterface $formatter = null)
  23. {
  24. if ($maxLength <= 0) {
  25. throw new InvalidArgumentException(sprintf('"%s()" expects a strictly positive maxLength. Got %d.', __METHOD__, $maxLength));
  26. }
  27. parent::__construct($verbosity, $decorated, $formatter);
  28. $this->maxLength = $maxLength;
  29. }
  30. /**
  31. * Empties buffer and returns its content.
  32. */
  33. public function fetch(): string
  34. {
  35. $content = $this->buffer;
  36. $this->buffer = '';
  37. return $content;
  38. }
  39. /**
  40. * @return void
  41. */
  42. protected function doWrite(string $message, bool $newline)
  43. {
  44. $this->buffer .= $message;
  45. if ($newline) {
  46. $this->buffer .= \PHP_EOL;
  47. }
  48. $this->buffer = substr($this->buffer, 0 - $this->maxLength);
  49. }
  50. }