TrimmedBufferOutput.php 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  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 $maxLength;
  21. private $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. * @return string
  34. */
  35. public function fetch()
  36. {
  37. $content = $this->buffer;
  38. $this->buffer = '';
  39. return $content;
  40. }
  41. /**
  42. * {@inheritdoc}
  43. */
  44. protected function doWrite(string $message, bool $newline)
  45. {
  46. $this->buffer .= $message;
  47. if ($newline) {
  48. $this->buffer .= \PHP_EOL;
  49. }
  50. $this->buffer = substr($this->buffer, 0 - $this->maxLength);
  51. }
  52. }