Sorter.php 2.1 KB

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