TrimmedBufferOutput.php 1.8 KB

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