LabelCall.php 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. <?php
  2. namespace UCore\DcatAdmin\Grid\Displayers;
  3. use Dcat\Admin\Admin;
  4. use Dcat\Admin\Grid;
  5. use Dcat\Admin\Grid\Column;
  6. use Dcat\Admin\Grid\Displayers\AbstractDisplayer;
  7. use Dcat\Admin\Support\Helper;
  8. class LabelCall extends AbstractDisplayer
  9. {
  10. protected $baseClass = 'label';
  11. protected $call;
  12. public function __construct($value, Grid $grid, Column $column, $row)
  13. {
  14. parent::__construct($value, $grid, $column, $row);
  15. return $this;
  16. }
  17. public function call(callable $call)
  18. {
  19. $this->call = $call;
  20. return $this;
  21. }
  22. public function display($style = 'primary', $max = null)
  23. {
  24. if (!$value = $this->value($max)) {
  25. return;
  26. }
  27. $original = $this->column->getOriginal();
  28. $defaultStyle = is_array($style) ? ($style['default'] ?? 'default') : 'default';
  29. $background = $this->formatStyle(
  30. is_array($style) ?
  31. (is_scalar($original) ? ($style[$original] ?? $defaultStyle) : current($style))
  32. : $style
  33. );
  34. return collect($value)->map(function ($name) use ($background) {
  35. return "<span class='{$this->baseClass}' {$background}>$name</span>";
  36. })->implode(' ');
  37. }
  38. protected function formatStyle($style)
  39. {
  40. $background = 'style="background:#d2d6de;color: #555"';
  41. if ($style !== 'default') {
  42. $style = Admin::color()->get($style, $style);
  43. $background = "style='background:{$style}'";
  44. }
  45. return $background;
  46. }
  47. protected function value($max)
  48. {
  49. $values = Helper::array($this->value);
  50. if ($max && count($values) > $max) {
  51. $values = array_slice($values, 0, $max);
  52. $values[] = '...';
  53. }
  54. return $values;
  55. }
  56. }