Sorter.php 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  1. <?php
  2. namespace Dcat\Admin\Grid\Column;
  3. use Illuminate\Contracts\Support\Renderable;
  4. class Sorter implements Renderable
  5. {
  6. /**
  7. * Sort arguments.
  8. *
  9. * @var array
  10. */
  11. protected $sort;
  12. /**
  13. * Cast Name.
  14. *
  15. * @var array
  16. */
  17. protected $cast;
  18. /**
  19. * @var string
  20. */
  21. protected $sortName;
  22. /**
  23. * @var string
  24. */
  25. protected $columnName;
  26. /**
  27. * Sorter constructor.
  28. *
  29. * @param string $sortName
  30. * @param string $columnName
  31. * @param string $cast
  32. */
  33. public function __construct($sortName, $columnName, $cast)
  34. {
  35. $this->sortName = $sortName;
  36. $this->columnName = $columnName;
  37. $this->cast = $cast;
  38. }
  39. /**
  40. * Determine if this column is currently sorted.
  41. *
  42. * @return bool
  43. */
  44. protected function isSorted()
  45. {
  46. $this->sort = app('request')->get($this->sortName);
  47. if (empty($this->sort)) {
  48. return false;
  49. }
  50. return isset($this->sort['column']) && $this->sort['column'] == $this->columnName;
  51. }
  52. /**
  53. * @return string
  54. */
  55. public function render()
  56. {
  57. $icon = '';
  58. $color = '';
  59. $type = 'desc';
  60. if ($this->isSorted()) {
  61. $type = $this->sort['type'] == 'desc' ? 'asc' : 'desc';
  62. if ($this->sort['type']) {
  63. $icon .= $this->sort['type'] == 'desc' ? '-by-attributes-alt' : '-by-attributes';
  64. $color = '';
  65. }
  66. }
  67. $sort = ['column' => $this->columnName, 'type' => $type];
  68. if ($this->cast) {
  69. $sort['cast'] = $this->cast;
  70. }
  71. if (! $this->isSorted() || $this->sort['type'] != 'asc') {
  72. $url = request()->fullUrlWithQuery([
  73. $this->sortName => $sort,
  74. ]);
  75. } else {
  76. $url = request()->fullUrlWithQuery([
  77. $this->sortName => [],
  78. ]);
  79. }
  80. if ($icon) {
  81. $icon .= ' active';
  82. }
  83. return " <a class=' glyphicon glyphicon-sort{$icon} $color' href='$url'></a>";
  84. }
  85. }