Relation.php 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119
  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. * @return $this|Fluent
  56. */
  57. public function model($model = null)
  58. {
  59. if ($model === null) {
  60. return $this->model;
  61. }
  62. $this->model = $model;
  63. return $this;
  64. }
  65. /**
  66. * @param int $width
  67. * @return $this
  68. */
  69. public function width(int $width, int $_ = 2)
  70. {
  71. $this->width = $width;
  72. return $this;
  73. }
  74. protected function build()
  75. {
  76. $view = call_user_func($this->builder, $this->model);
  77. if ($view instanceof Show) {
  78. $view->panel()->title($this->title);
  79. return $view->render();
  80. }
  81. if ($view instanceof Grid) {
  82. return $view->setName($this->name)
  83. ->title($this->title)
  84. ->disableBatchDelete()
  85. ->render();
  86. }
  87. return Helper::render($view);
  88. }
  89. /**
  90. * Render this relation panel.
  91. *
  92. * @return string
  93. */
  94. public function render()
  95. {
  96. return <<<HTML
  97. <div class="mt-1-5">{$this->build()}</div>
  98. HTML;
  99. }
  100. }