Stack.php 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116
  1. <?php
  2. // +----------------------------------------------------------------------
  3. // | ThinkPHP [ WE CAN DO IT JUST THINK ]
  4. // +----------------------------------------------------------------------
  5. // | Copyright (c) 2006~2015 http://thinkphp.cn All rights reserved.
  6. // +----------------------------------------------------------------------
  7. // | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
  8. // +----------------------------------------------------------------------
  9. // | Author: yunwuxin <448901948@qq.com>
  10. // +----------------------------------------------------------------------
  11. namespace think\console\output\formatter;
  12. class Stack
  13. {
  14. /**
  15. * @var Style[]
  16. */
  17. private $styles;
  18. /**
  19. * @var Style
  20. */
  21. private $emptyStyle;
  22. /**
  23. * 构造方法
  24. * @param Style|null $emptyStyle
  25. */
  26. public function __construct(Style $emptyStyle = null)
  27. {
  28. $this->emptyStyle = $emptyStyle ?: new Style();
  29. $this->reset();
  30. }
  31. /**
  32. * 重置堆栈
  33. */
  34. public function reset()
  35. {
  36. $this->styles = [];
  37. }
  38. /**
  39. * 推一个样式进入堆栈
  40. * @param Style $style
  41. */
  42. public function push(Style $style)
  43. {
  44. $this->styles[] = $style;
  45. }
  46. /**
  47. * 从堆栈中弹出一个样式
  48. * @param Style|null $style
  49. * @return Style
  50. * @throws \InvalidArgumentException
  51. */
  52. public function pop(Style $style = null)
  53. {
  54. if (empty($this->styles)) {
  55. return $this->emptyStyle;
  56. }
  57. if (null === $style) {
  58. return array_pop($this->styles);
  59. }
  60. /**
  61. * @var int $index
  62. * @var Style $stackedStyle
  63. */
  64. foreach (array_reverse($this->styles, true) as $index => $stackedStyle) {
  65. if ($style->apply('') === $stackedStyle->apply('')) {
  66. $this->styles = array_slice($this->styles, 0, $index);
  67. return $stackedStyle;
  68. }
  69. }
  70. throw new \InvalidArgumentException('Incorrectly nested style tag found.');
  71. }
  72. /**
  73. * 计算堆栈的当前样式。
  74. * @return Style
  75. */
  76. public function getCurrent()
  77. {
  78. if (empty($this->styles)) {
  79. return $this->emptyStyle;
  80. }
  81. return $this->styles[count($this->styles) - 1];
  82. }
  83. /**
  84. * @param Style $emptyStyle
  85. * @return Stack
  86. */
  87. public function setEmptyStyle(Style $emptyStyle)
  88. {
  89. $this->emptyStyle = $emptyStyle;
  90. return $this;
  91. }
  92. /**
  93. * @return Style
  94. */
  95. public function getEmptyStyle()
  96. {
  97. return $this->emptyStyle;
  98. }
  99. }