Column.php 2.6 KB

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