ComplexHeader.php 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128
  1. <?php
  2. namespace Dcat\Admin\Grid;
  3. use Dcat\Admin\Grid;
  4. use Dcat\Admin\Grid\Column\Help;
  5. use Dcat\Admin\Widgets\Widget;
  6. use Illuminate\Support\Collection;
  7. class ComplexHeader extends Widget
  8. {
  9. /**
  10. * @var Grid
  11. */
  12. protected $grid;
  13. /**
  14. * @var string
  15. */
  16. protected $column;
  17. /**
  18. * @var string
  19. */
  20. protected $label;
  21. /**
  22. * @var array
  23. */
  24. protected $columnNames = [];
  25. /**
  26. * @var array
  27. */
  28. protected $html = [];
  29. public function __construct(Grid $grid, ?string $column, array $columnNames, ?string $label = null)
  30. {
  31. $this->grid = $grid;
  32. $this->column = $column;
  33. $this->label = $label ?: admin_trans_field($column);
  34. $this->columnNames = collect($columnNames);
  35. $this->addDefaultAttributes();
  36. }
  37. /**
  38. * @return Collection
  39. */
  40. public function getColumnNames()
  41. {
  42. return $this->columnNames;
  43. }
  44. /**
  45. * @return Collection
  46. */
  47. public function columns()
  48. {
  49. return $this->columnNames->map(function ($name) {
  50. return $this->grid->allColumns()->get($name);
  51. })->filter();
  52. }
  53. /**
  54. * 默认隐藏字段
  55. *
  56. * @return $this
  57. */
  58. public function hide()
  59. {
  60. $this->grid->hideColumns($this->column);
  61. return $this;
  62. }
  63. public function getName()
  64. {
  65. return $this->column;
  66. }
  67. public function getLabel()
  68. {
  69. return $this->label;
  70. }
  71. /**
  72. * @param string $html
  73. *
  74. * @return $this
  75. */
  76. public function append($html)
  77. {
  78. $this->html[] = $html;
  79. return $this;
  80. }
  81. /**
  82. * @param string|\Closure $message
  83. * @param null|string $style 'green', 'blue', 'red', 'purple'
  84. * @param null|string $placement 'bottom', 'left', 'right', 'top'
  85. *
  86. * @return $this
  87. */
  88. public function help($message, ?string $style = null, ?string $placement = null)
  89. {
  90. return $this->append((new Help($message, $style, $placement))->render());
  91. }
  92. protected function addDefaultAttributes()
  93. {
  94. $count = $this->columnNames->count();
  95. if ($count == 1) {
  96. $this->htmlAttributes['rowspan'] = 2;
  97. } else {
  98. $this->htmlAttributes['colspan'] = $count;
  99. }
  100. }
  101. public function render()
  102. {
  103. $headers = implode(' ', $this->html);
  104. return "<th {$this->formatHtmlAttributes()}>{$this->label}<span class='grid-column-header'>{$headers}</span></th>";
  105. }
  106. }