HasHeader.php 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120
  1. <?php
  2. namespace Dcat\Admin\Grid\Column;
  3. use Dcat\Admin\Grid;
  4. use Dcat\Admin\Grid\Column;
  5. use Dcat\Admin\Grid\Model;
  6. use Illuminate\Contracts\Support\Htmlable;
  7. use Illuminate\Contracts\Support\Renderable;
  8. /**
  9. * @property Grid $grid
  10. */
  11. trait HasHeader
  12. {
  13. /**
  14. * @var Filter
  15. */
  16. public $filter;
  17. /**
  18. * @var array
  19. */
  20. protected $headers = [];
  21. /**
  22. * Add contents to column header.
  23. *
  24. * @param string|Renderable|Htmlable $header
  25. *
  26. * @return $this
  27. */
  28. public function addHeader($header)
  29. {
  30. if ($header instanceof Filter) {
  31. $header->setParent($this);
  32. $this->filter = $header;
  33. }
  34. $this->headers[] = $header;
  35. return $this;
  36. }
  37. /**
  38. * Add a column sortable to column header.
  39. *
  40. * @param string $cast
  41. *
  42. * @return $this
  43. */
  44. protected function addSorter($cast = null)
  45. {
  46. $sortName = $this->grid->model()->getSortName();
  47. $sorter = new Sorter($sortName, $this->getName(), $cast);
  48. return $this->addHeader($sorter);
  49. }
  50. /**
  51. * Add a help tooltip to column header.
  52. *
  53. * @param string|\Closure $message
  54. * @param null|string $style 'green', 'blue', 'red', 'purple'
  55. * @param null|string $placement 'bottom', 'left', 'right', 'top'
  56. *
  57. * @return $this
  58. */
  59. protected function addHelp($message, ?string $style = null, ?string $placement = 'bottom')
  60. {
  61. return $this->addHeader(new Help($message, $style, $placement));
  62. }
  63. /**
  64. * Add a filter to column header.
  65. *
  66. * @param \Closure $builder
  67. *
  68. * @return $this
  69. */
  70. protected function addFilter(Filter $filter)
  71. {
  72. return $this->addHeader($filter);
  73. }
  74. /**
  75. * Add a binding based on filter to the model query.
  76. *
  77. * @param Model $model
  78. */
  79. public function bindFilterQuery(Model $model)
  80. {
  81. if ($this->filter) {
  82. $this->filter->addBinding($this->filter->value(), $model);
  83. }
  84. }
  85. /**
  86. * Render Column header.
  87. *
  88. * @return string
  89. */
  90. public function renderHeader()
  91. {
  92. $headers = collect($this->headers)->map(function ($item) {
  93. if ($item instanceof Renderable) {
  94. return $item->render();
  95. }
  96. if ($item instanceof Htmlable) {
  97. return $item->toHtml();
  98. }
  99. return (string) $item;
  100. })->implode('');
  101. return "<span class='grid-column-header'>$headers</span>";
  102. }
  103. }