OutputFormatterStyleStack.php 2.5 KB

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