TrimmedBufferOutput.php 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  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(
  23. int $maxLength,
  24. ?int $verbosity = self::VERBOSITY_NORMAL,
  25. bool $decorated = false,
  26. OutputFormatterInterface $formatter = null
  27. ) {
  28. if ($maxLength <= 0) {
  29. throw new InvalidArgumentException(sprintf('"%s()" expects a strictly positive maxLength. Got %d.', __METHOD__, $maxLength));
  30. }
  31. parent::__construct($verbosity, $decorated, $formatter);
  32. $this->maxLength = $maxLength;
  33. }
  34. /**
  35. * Empties buffer and returns its content.
  36. *
  37. * @return string
  38. */
  39. public function fetch()
  40. {
  41. $content = $this->buffer;
  42. $this->buffer = '';
  43. return $content;
  44. }
  45. /**
  46. * {@inheritdoc}
  47. */
  48. protected function doWrite($message, $newline)
  49. {
  50. $this->buffer .= $message;
  51. if ($newline) {
  52. $this->buffer .= \PHP_EOL;
  53. }
  54. $this->buffer = substr($this->buffer, 0 - $this->maxLength);
  55. }
  56. }