Tab.php 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126
  1. <?php
  2. namespace Dcat\Admin\Form;
  3. use Dcat\Admin\Form;
  4. use Illuminate\Support\Collection;
  5. class Tab
  6. {
  7. /**
  8. * @var Form
  9. */
  10. protected $form;
  11. /**
  12. * @var Collection
  13. */
  14. protected $tabs;
  15. /**
  16. * @var int
  17. */
  18. protected $offset = 0;
  19. /**
  20. * Tab constructor.
  21. *
  22. * @param Form $form
  23. */
  24. public function __construct(Form $form)
  25. {
  26. $this->form = $form;
  27. $this->tabs = new Collection();
  28. }
  29. /**
  30. * Append a tab section.
  31. *
  32. * @param string $title
  33. * @param \Closure $content
  34. * @param bool $active
  35. *
  36. * @return $this
  37. */
  38. public function append($title, \Closure $content, $active = false)
  39. {
  40. $fields = $this->collectFields($content);
  41. $id = 'tab-form-'.($this->tabs->count() + 1).'-'.mt_rand(0, 9999);
  42. $this->tabs->push(compact('id', 'title', 'fields', 'active'));
  43. return $this;
  44. }
  45. /**
  46. * Collect fields under current tab.
  47. *
  48. * @param \Closure $content
  49. *
  50. * @return Collection
  51. */
  52. protected function collectFields(\Closure $content)
  53. {
  54. call_user_func($content, $this->form);
  55. $fields = clone $this->form->builder()->fields();
  56. $all = $fields->toArray();
  57. foreach ($this->form->rows() as $row) {
  58. $rowFields = array_map(function ($field) {
  59. return $field['element'];
  60. }, $row->getFields());
  61. $match = false;
  62. foreach ($rowFields as $field) {
  63. if (($index = array_search($field, $all)) !== false) {
  64. if (! $match) {
  65. $fields->put($index, $row);
  66. } else {
  67. $fields->pull($index);
  68. }
  69. $match = true;
  70. }
  71. }
  72. }
  73. $fields = $fields->slice($this->offset);
  74. $this->offset += $fields->count();
  75. return $fields;
  76. }
  77. /**
  78. * Get all tabs.
  79. *
  80. * @return Collection
  81. */
  82. public function getTabs()
  83. {
  84. // If there is no active tab, then active the first.
  85. if ($this->tabs->filter(function ($tab) {
  86. return $tab['active'];
  87. })->isEmpty()) {
  88. $first = $this->tabs->first();
  89. $first['active'] = true;
  90. $this->tabs->offsetSet(0, $first);
  91. }
  92. return $this->tabs;
  93. }
  94. /**
  95. * @return bool
  96. */
  97. public function isEmpty()
  98. {
  99. return $this->tabs->isEmpty();
  100. }
  101. }