OutputFormatterStyleStack.php 2.4KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110
  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\Formatter;
  11. use Symfony\Component\Console\Exception\InvalidArgumentException;
  12. /**
  13. * @author Jean-François Simon <contact@jfsimon.fr>
  14. */
  15. class OutputFormatterStyleStack
  16. {
  17. /**
  18. * @var OutputFormatterStyleInterface[]
  19. */
  20. private $styles;
  21. private $emptyStyle;
  22. public function __construct(OutputFormatterStyleInterface $emptyStyle = null)
  23. {
  24. $this->emptyStyle = $emptyStyle ?: new OutputFormatterStyle();
  25. $this->reset();
  26. }
  27. /**
  28. * Resets stack (ie. empty internal arrays).
  29. */
  30. public function reset()
  31. {
  32. $this->styles = array();
  33. }
  34. /**
  35. * Pushes a style in the stack.
  36. */
  37. public function push(OutputFormatterStyleInterface $style)
  38. {
  39. $this->styles[] = $style;
  40. }
  41. /**
  42. * Pops a style from the stack.
  43. *
  44. * @return OutputFormatterStyleInterface
  45. *
  46. * @throws InvalidArgumentException When style tags incorrectly nested
  47. */
  48. public function pop(OutputFormatterStyleInterface $style = null)
  49. {
  50. if (empty($this->styles)) {
  51. return $this->emptyStyle;
  52. }
  53. if (null === $style) {
  54. return array_pop($this->styles);
  55. }
  56. foreach (array_reverse($this->styles, true) as $index => $stackedStyle) {
  57. if ($style->apply('') === $stackedStyle->apply('')) {
  58. $this->styles = array_slice($this->styles, 0, $index);
  59. return $stackedStyle;
  60. }
  61. }
  62. throw new InvalidArgumentException('Incorrectly nested style tag found.');
  63. }
  64. /**
  65. * Computes current style with stacks top codes.
  66. *
  67. * @return OutputFormatterStyle
  68. */
  69. public function getCurrent()
  70. {
  71. if (empty($this->styles)) {
  72. return $this->emptyStyle;
  73. }
  74. return $this->styles[count($this->styles) - 1];
  75. }
  76. /**
  77. * @return $this
  78. */
  79. public function setEmptyStyle(OutputFormatterStyleInterface $emptyStyle)
  80. {
  81. $this->emptyStyle = $emptyStyle;
  82. return $this;
  83. }
  84. /**
  85. * @return OutputFormatterStyleInterface
  86. */
  87. public function getEmptyStyle()
  88. {
  89. return $this->emptyStyle;
  90. }
  91. }