Column.php 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129
  1. <?php
  2. namespace Dcat\Admin\Layout;
  3. use Dcat\Admin\Grid;
  4. use Illuminate\Contracts\Support\Renderable;
  5. class Column implements Buildable
  6. {
  7. /**
  8. * grid system prefix width.
  9. *
  10. * @var array
  11. */
  12. protected $width = [];
  13. /**
  14. * @var array
  15. */
  16. protected $contents = [];
  17. /**
  18. * Column constructor.
  19. *
  20. * @param $content
  21. * @param int $width
  22. */
  23. public function __construct($content, $width = 12)
  24. {
  25. if ($content instanceof \Closure) {
  26. call_user_func($content, $this);
  27. } else {
  28. $this->append($content);
  29. }
  30. ///// set width.
  31. // if null, or $this->width is empty array, set as "md" => "12"
  32. if (is_null($width) || (is_array($width) && count($width) === 0)) {
  33. $this->width['md'] = 12;
  34. }
  35. // $this->width is number(old version), set as "md" => $width
  36. elseif (is_numeric($width)) {
  37. $this->width['md'] = $width;
  38. } else {
  39. $this->width = $width;
  40. }
  41. }
  42. /**
  43. * Append content to column.
  44. *
  45. * @param $content
  46. *
  47. * @return $this
  48. */
  49. public function append($content)
  50. {
  51. $this->contents[] = $content;
  52. return $this;
  53. }
  54. /**
  55. * Add a row for column.
  56. *
  57. * @param $content
  58. *
  59. * @return Column
  60. */
  61. public function row($content)
  62. {
  63. if (!$content instanceof \Closure) {
  64. $row = new Row($content);
  65. } else {
  66. $row = new Row();
  67. call_user_func($content, $row);
  68. }
  69. ob_start();
  70. $row->build();
  71. $contents = ob_get_contents();
  72. ob_end_clean();
  73. return $this->append($contents);
  74. }
  75. /**
  76. * Build column html.
  77. */
  78. public function build()
  79. {
  80. $this->startColumn();
  81. foreach ($this->contents as $content) {
  82. if ($content instanceof Renderable || $content instanceof Grid) {
  83. echo $content->render();
  84. } else {
  85. echo (string) $content;
  86. }
  87. }
  88. $this->endColumn();
  89. }
  90. /**
  91. * Start column.
  92. */
  93. protected function startColumn()
  94. {
  95. // get class name using width array
  96. $classnName = collect($this->width)->map(function ($value, $key) {
  97. return "col-$key-$value";
  98. })->implode(' ');
  99. echo "<div class=\"{$classnName}\">";
  100. }
  101. /**
  102. * End column.
  103. */
  104. protected function endColumn()
  105. {
  106. echo '</div>';
  107. }
  108. }