AbstractDisplayer.php 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137
  1. <?php
  2. namespace Dcat\Admin\Grid\Displayers;
  3. use Dcat\Admin\Admin;
  4. use Dcat\Admin\Grid;
  5. use Dcat\Admin\Grid\Column;
  6. use Illuminate\Support\Fluent;
  7. abstract class AbstractDisplayer
  8. {
  9. /**
  10. * @var array
  11. */
  12. protected static $css = [];
  13. /**
  14. * @var array
  15. */
  16. protected static $js = [];
  17. /**
  18. * @var Grid
  19. */
  20. protected $grid;
  21. /**
  22. * @var Column
  23. */
  24. protected $column;
  25. /**
  26. * @var \Illuminate\Database\Eloquent\Model
  27. */
  28. public $row;
  29. /**
  30. * @var mixed
  31. */
  32. protected $value;
  33. /**
  34. * Create a new displayer instance.
  35. *
  36. * @param mixed $value
  37. * @param Grid $grid
  38. * @param Column $column
  39. * @param \stdClass $row
  40. */
  41. public function __construct($value, Grid $grid, Column $column, $row)
  42. {
  43. $this->value = $value;
  44. $this->grid = $grid;
  45. $this->column = $column;
  46. $this->setRow($row);
  47. $this->requireAssets();
  48. }
  49. protected function requireAssets()
  50. {
  51. if (static::$js) {
  52. Admin::js(static::$js);
  53. }
  54. if (static::$css) {
  55. Admin::css(static::$css);
  56. }
  57. }
  58. protected function setRow($row)
  59. {
  60. if (is_array($row)) {
  61. $row = new Fluent($row);
  62. }
  63. $this->row = $row;
  64. }
  65. /**
  66. * @return string
  67. */
  68. public function getElementName()
  69. {
  70. $name = explode('.', $this->column->getName());
  71. if (count($name) == 1) {
  72. return $name[0];
  73. }
  74. $html = array_shift($name);
  75. foreach ($name as $piece) {
  76. $html .= "[$piece]";
  77. }
  78. return $html;
  79. }
  80. /**
  81. * Get key of current row.
  82. *
  83. * @return mixed
  84. */
  85. public function getKey()
  86. {
  87. return $this->row->{$this->grid->getKeyName()};
  88. }
  89. /**
  90. * Get url path of current resource.
  91. *
  92. * @return string
  93. */
  94. public function resource()
  95. {
  96. return $this->grid->resource();
  97. }
  98. /**
  99. * Get translation.
  100. *
  101. * @param string $text
  102. *
  103. * @return string|\Symfony\Component\Translation\TranslatorInterface
  104. */
  105. protected function trans($text)
  106. {
  107. return trans("admin.$text");
  108. }
  109. /**
  110. * Display method.
  111. *
  112. * @return mixed
  113. */
  114. abstract public function display();
  115. }