Relation.php 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121
  1. <?php
  2. namespace Dcat\Admin\Show;
  3. use Dcat\Admin\Grid;
  4. use Dcat\Admin\Show;
  5. use Dcat\Admin\Support\Helper;
  6. use Illuminate\Database\Eloquent\Model;
  7. use Illuminate\Support\Fluent;
  8. class Relation extends Field
  9. {
  10. /**
  11. * Relation name.
  12. *
  13. * @var string
  14. */
  15. protected $name;
  16. /**
  17. * Relation panel builder.
  18. *
  19. * @var \Closure
  20. */
  21. protected $builder;
  22. /**
  23. * Relation panel title.
  24. *
  25. * @var string
  26. */
  27. protected $title;
  28. /**
  29. * Parent model.
  30. *
  31. * @var Fluent
  32. */
  33. protected $model;
  34. /**
  35. * @var int
  36. */
  37. public $width = 12;
  38. /**
  39. * Relation constructor.
  40. *
  41. * @param string $name
  42. * @param \Closure $builder
  43. * @param string $title
  44. */
  45. public function __construct($name, $builder, $title = '')
  46. {
  47. $this->name = $name;
  48. $this->builder = $builder;
  49. $this->title = $this->formatLabel($title);
  50. }
  51. /**
  52. * Set parent model for relation.
  53. *
  54. * @param Fluent|Model $model
  55. *
  56. * @return $this|Fluent
  57. */
  58. public function model($model = null)
  59. {
  60. if ($model === null) {
  61. return $this->model;
  62. }
  63. $this->model = $model;
  64. return $this;
  65. }
  66. /**
  67. * @param int $width
  68. *
  69. * @return $this
  70. */
  71. public function width(int $width, int $_ = 2)
  72. {
  73. $this->width = $width;
  74. return $this;
  75. }
  76. protected function build()
  77. {
  78. $view = call_user_func($this->builder, $this->model);
  79. if ($view instanceof Show) {
  80. $view->panel()->title($this->title);
  81. return $view->render();
  82. }
  83. if ($view instanceof Grid) {
  84. return $view->setName($this->name)
  85. ->title($this->title)
  86. ->disableBatchDelete()
  87. ->render();
  88. }
  89. return Helper::render($view);
  90. }
  91. /**
  92. * Render this relation panel.
  93. *
  94. * @return string
  95. */
  96. public function render()
  97. {
  98. return <<<HTML
  99. <div class="mt-1-5">{$this->build()}</div>
  100. HTML;
  101. }
  102. }