Scope.php 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. <?php
  2. namespace Dcat\Admin\Grid\Filter;
  3. use Dcat\Admin\Grid\Filter;
  4. use Illuminate\Contracts\Support\Renderable;
  5. use Illuminate\Database\Query\Builder;
  6. use Illuminate\Support\Collection;
  7. use Illuminate\Support\Traits\Macroable;
  8. /**
  9. * @mixin Builder
  10. */
  11. class Scope implements Renderable
  12. {
  13. use Macroable;
  14. /**
  15. * @var Filter
  16. */
  17. protected $filter;
  18. /**
  19. * @var string
  20. */
  21. public $key = '';
  22. /**
  23. * @var string
  24. */
  25. protected $label = '';
  26. /**
  27. * @var Collection
  28. */
  29. protected $queries;
  30. /**
  31. * Scope constructor.
  32. *
  33. * @param Filter $filter
  34. * @param string $key
  35. * @param string $label
  36. */
  37. public function __construct(Filter $filter, $key, $label = '')
  38. {
  39. $this->filter = $filter;
  40. $this->key = $key;
  41. $this->label = $label ?: admin_trans_field($key);
  42. $this->queries = new Collection();
  43. }
  44. /**
  45. * Get label.
  46. *
  47. * @return string
  48. */
  49. public function getLabel()
  50. {
  51. return $this->label;
  52. }
  53. /**
  54. * Get model query conditions.
  55. *
  56. * @return array
  57. */
  58. public function condition()
  59. {
  60. return $this->queries->map(function ($query) {
  61. return [$query['method'] => $query['arguments']];
  62. })->toArray();
  63. }
  64. /**
  65. * @return string
  66. */
  67. public function render()
  68. {
  69. $url = request()->fullUrlWithQuery([
  70. $this->filter->getScopeQueryName() => $this->key,
  71. $this->filter->grid()->model()->getPageName() => null,
  72. ]);
  73. return "<li class='dropdown-item'><a href=\"{$url}\">{$this->label}</a></li>";
  74. }
  75. /**
  76. * @param string $method
  77. * @param array $arguments
  78. *
  79. * @return $this
  80. */
  81. public function __call($method, $arguments)
  82. {
  83. $this->queries->push(compact('method', 'arguments'));
  84. return $this;
  85. }
  86. }