AbstractDisplayer.php 2.4 KB

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