HasSelector.php 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. <?php
  2. namespace Dcat\Admin\Grid\Concerns;
  3. use Dcat\Admin\Grid;
  4. use Dcat\Admin\Grid\Tools\Selector;
  5. use Dcat\Admin\Support\Helper;
  6. /**
  7. * @mixin Grid
  8. */
  9. trait HasSelector
  10. {
  11. /**
  12. * @var Selector
  13. */
  14. protected $_selector;
  15. /**
  16. * @param \Closure $closure
  17. *
  18. * @return $this|Selector
  19. */
  20. public function selector(\Closure $closure = null)
  21. {
  22. if ($closure === null) {
  23. return $this->_selector;
  24. }
  25. $this->_selector = new Selector($this);
  26. call_user_func($closure, $this->_selector);
  27. $this->header(function () {
  28. return $this->renderSelector();
  29. });
  30. return $this;
  31. }
  32. /**
  33. * Apply selector query to grid model query.
  34. *
  35. * @return $this
  36. */
  37. protected function applySelectorQuery()
  38. {
  39. if (is_null($this->_selector)) {
  40. return $this;
  41. }
  42. $active = $this->_selector->parseSelected();
  43. $this->_selector->all()->each(function ($selector, $column) use ($active) {
  44. $key = $this->_selector->formatKey($column);
  45. if (! array_key_exists($key, $active)) {
  46. return;
  47. }
  48. $this->fireOnce(new Grid\Events\ApplySelector($this, [$active]));
  49. $values = $active[$key];
  50. if ($selector['type'] == 'one') {
  51. $values = current($values);
  52. }
  53. if ($selector['query']) {
  54. call_user_func($selector['query'], $this->model(), $values);
  55. return;
  56. }
  57. Helper::withQueryCondition(
  58. $this->model(),
  59. $column,
  60. is_array($values) ? 'whereIn' : 'where',
  61. [$values]
  62. );
  63. });
  64. return $this;
  65. }
  66. /**
  67. * Render grid selector.
  68. *
  69. * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View|string
  70. */
  71. public function renderSelector()
  72. {
  73. return $this->_selector->render();
  74. }
  75. }