Filter.php 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811
  1. <?php
  2. namespace Dcat\Admin\Grid;
  3. use Dcat\Admin\Admin;
  4. use Dcat\Admin\Exception\RuntimeException;
  5. use Dcat\Admin\Grid\Events\ApplyFilter;
  6. use Dcat\Admin\Grid\Events\Fetched;
  7. use Dcat\Admin\Grid\Events\Fetching;
  8. use Dcat\Admin\Grid\Filter\AbstractFilter;
  9. use Dcat\Admin\Grid\Filter\Between;
  10. use Dcat\Admin\Grid\Filter\Date;
  11. use Dcat\Admin\Grid\Filter\Day;
  12. use Dcat\Admin\Grid\Filter\EndWith;
  13. use Dcat\Admin\Grid\Filter\Equal;
  14. use Dcat\Admin\Grid\Filter\FindInSet;
  15. use Dcat\Admin\Grid\Filter\Group;
  16. use Dcat\Admin\Grid\Filter\Gt;
  17. use Dcat\Admin\Grid\Filter\Hidden;
  18. use Dcat\Admin\Grid\Filter\Ilike;
  19. use Dcat\Admin\Grid\Filter\In;
  20. use Dcat\Admin\Grid\Filter\Layout\Layout;
  21. use Dcat\Admin\Grid\Filter\Like;
  22. use Dcat\Admin\Grid\Filter\Lt;
  23. use Dcat\Admin\Grid\Filter\Month;
  24. use Dcat\Admin\Grid\Filter\Newline;
  25. use Dcat\Admin\Grid\Filter\Ngt;
  26. use Dcat\Admin\Grid\Filter\Nlt;
  27. use Dcat\Admin\Grid\Filter\NotEqual;
  28. use Dcat\Admin\Grid\Filter\NotIn;
  29. use Dcat\Admin\Grid\Filter\Scope;
  30. use Dcat\Admin\Grid\Filter\StartWith;
  31. use Dcat\Admin\Grid\Filter\Where;
  32. use Dcat\Admin\Grid\Filter\WhereBetween;
  33. use Dcat\Admin\Grid\Filter\Year;
  34. use Dcat\Admin\Support\Helper;
  35. use Dcat\Admin\Traits\HasBuilderEvents;
  36. use Dcat\Admin\Traits\HasVariables;
  37. use Illuminate\Contracts\Support\Renderable;
  38. use Illuminate\Support\Arr;
  39. use Illuminate\Support\Collection;
  40. use Illuminate\Support\Str;
  41. use Illuminate\Support\Traits\Macroable;
  42. /**
  43. * Class Filter.
  44. *
  45. * @method Equal equal($column, $label = '')
  46. * @method NotEqual notEqual($column, $label = '')
  47. * @method Like like($column, $label = '')
  48. * @method Ilike ilike($column, $label = '')
  49. * @method StartWith startWith($column, $label = '')
  50. * @method EndWith endWith($column, $label = '')
  51. * @method Gt gt($column, $label = '')
  52. * @method Lt lt($column, $label = '')
  53. * @method Ngt ngt($column, $label = '')
  54. * @method Nlt nlt($column, $label = '')
  55. * @method Between between($column, $label = '')
  56. * @method In in($column, $label = '')
  57. * @method NotIn notIn($column, $label = '')
  58. * @method Where where($colum, $callback, $label = '')
  59. * @method WhereBetween whereBetween($colum, $callback, $label = '')
  60. * @method Date date($column, $label = '')
  61. * @method Day day($column, $label = '')
  62. * @method Month month($column, $label = '')
  63. * @method Year year($column, $label = '')
  64. * @method Hidden hidden($name, $value)
  65. * @method Group group($column, $builder = null, $label = '')
  66. * @method Newline newline()
  67. * @method FindInSet findInSet($column, $label = '')
  68. */
  69. class Filter implements Renderable
  70. {
  71. use HasBuilderEvents;
  72. use Macroable;
  73. use HasVariables;
  74. const MODE_RIGHT_SIDE = 'right-side';
  75. const MODE_PANEL = 'panel';
  76. /**
  77. * @var array
  78. */
  79. protected static $supports = [];
  80. /**
  81. * @var array
  82. */
  83. protected static $defaultFilters = [
  84. 'equal' => Equal::class,
  85. 'notEqual' => NotEqual::class,
  86. 'ilike' => Ilike::class,
  87. 'like' => Like::class,
  88. 'startWith' => StartWith::class,
  89. 'endWith' => EndWith::class,
  90. 'gt' => Gt::class,
  91. 'lt' => Lt::class,
  92. 'ngt' => Ngt::class,
  93. 'nlt' => Nlt::class,
  94. 'between' => Between::class,
  95. 'group' => Group::class,
  96. 'where' => Where::class,
  97. 'whereBetween' => WhereBetween::class,
  98. 'in' => In::class,
  99. 'notIn' => NotIn::class,
  100. 'date' => Date::class,
  101. 'day' => Day::class,
  102. 'month' => Month::class,
  103. 'year' => Year::class,
  104. 'hidden' => Hidden::class,
  105. 'newline' => Newline::class,
  106. 'findInSet' => FindInSet::class,
  107. ];
  108. /**
  109. * @var Model
  110. */
  111. protected $model;
  112. /**
  113. * @var AbstractFilter[]
  114. */
  115. protected $filters = [];
  116. /**
  117. * Action of search form.
  118. *
  119. * @var string
  120. */
  121. protected $action;
  122. /**
  123. * @var string
  124. */
  125. protected $view;
  126. /**
  127. * @var string
  128. */
  129. protected $filterID;
  130. /**
  131. * @var string
  132. */
  133. protected $name = '';
  134. /**
  135. * @var bool
  136. */
  137. public $expand;
  138. /**
  139. * @var Collection
  140. */
  141. protected $scopes;
  142. /**
  143. * @var Layout
  144. */
  145. protected $layout;
  146. /**
  147. * Primary key of giving model.
  148. *
  149. * @var mixed
  150. */
  151. protected $primaryKey;
  152. /**
  153. * @var string
  154. */
  155. protected $style = 'padding:0';
  156. /**
  157. * @var bool
  158. */
  159. protected $disableResetButton = false;
  160. /**
  161. * @var string
  162. */
  163. protected $border = 'border-top:1px solid #f4f4f4;';
  164. /**
  165. * @var string
  166. */
  167. protected $containerClass = '';
  168. /**
  169. * @var bool
  170. */
  171. protected $disableCollapse = false;
  172. /**
  173. * @var array
  174. */
  175. protected $inputs;
  176. /**
  177. * @var string
  178. */
  179. protected $mode = self::MODE_RIGHT_SIDE;
  180. protected $conditions;
  181. /**
  182. * Create a new filter instance.
  183. *
  184. * @param Model $model
  185. */
  186. public function __construct(Model $model)
  187. {
  188. $this->model = $model;
  189. $this->primaryKey = $model->getKeyName();
  190. $this->filterID = $this->formatFilterId();
  191. $this->initLayout();
  192. $this->scopes = new Collection();
  193. $this->callResolving();
  194. }
  195. /**
  196. * Initialize filter layout.
  197. */
  198. protected function initLayout()
  199. {
  200. $this->layout = new Filter\Layout\Layout($this);
  201. }
  202. /**
  203. * @return string
  204. */
  205. protected function formatFilterId()
  206. {
  207. return 'filter-box'.Str::random(8);
  208. }
  209. /**
  210. * Set action of search form.
  211. *
  212. * @param string $action
  213. * @return $this
  214. */
  215. public function setAction($action)
  216. {
  217. $this->action = $action;
  218. return $this;
  219. }
  220. /**
  221. * @return $this
  222. */
  223. public function withoutInputBorder()
  224. {
  225. $this->containerClass = 'input-no-border';
  226. return $this;
  227. }
  228. /**
  229. * @param bool $disabled
  230. * @return $this
  231. */
  232. public function disableCollapse(bool $disabled = true)
  233. {
  234. $this->disableCollapse = $disabled;
  235. return $this;
  236. }
  237. /**
  238. * @param bool $disabled
  239. * @return $this
  240. */
  241. public function disableResetButton(bool $disabled = true)
  242. {
  243. $this->disableResetButton = $disabled;
  244. return $this;
  245. }
  246. /**
  247. * Get input data.
  248. *
  249. * @param string $key
  250. * @param null $value
  251. * @return array|mixed
  252. */
  253. public function input($key = null, $default = null)
  254. {
  255. $inputs = $this->inputs();
  256. if ($key === null) {
  257. return $inputs;
  258. }
  259. return Arr::get($inputs, $key, $default);
  260. }
  261. /**
  262. * Get grid model.
  263. *
  264. * @return Model
  265. */
  266. public function model()
  267. {
  268. return $this->model;
  269. }
  270. /**
  271. * Get grid.
  272. *
  273. * @return \Dcat\Admin\Grid
  274. */
  275. public function grid()
  276. {
  277. return $this->model->grid();
  278. }
  279. /**
  280. * Set ID of search form.
  281. *
  282. * @param string $filterID
  283. * @return $this
  284. */
  285. public function setFilterID($filterID)
  286. {
  287. $this->filterID = $filterID;
  288. return $this;
  289. }
  290. /**
  291. * @return $this
  292. */
  293. public function panel()
  294. {
  295. return $this->mode(static::MODE_PANEL);
  296. }
  297. /**
  298. * @return $this
  299. */
  300. public function rightSide()
  301. {
  302. return $this->mode(static::MODE_RIGHT_SIDE);
  303. }
  304. /**
  305. * @param string|null $mode
  306. * @return $this|string
  307. */
  308. public function mode(string $mode = null)
  309. {
  310. if ($mode === null) {
  311. return $this->mode;
  312. }
  313. $this->mode = $mode;
  314. return $this;
  315. }
  316. /**
  317. * Get filter ID.
  318. *
  319. * @return string
  320. */
  321. public function filterID()
  322. {
  323. return $this->filterID;
  324. }
  325. /**
  326. * @return $this
  327. */
  328. public function withoutBorder()
  329. {
  330. return $this->withBorder('');
  331. }
  332. /**
  333. * @return $this
  334. */
  335. public function withBorder($border = null)
  336. {
  337. $this->border = is_null($border) ? 'border-top:1px solid #f4f4f4;' : $border;
  338. return $this;
  339. }
  340. /**
  341. * Remove filter by column.
  342. *
  343. * @param string|array $column
  344. */
  345. public function removeFilter($column)
  346. {
  347. $this->filters = array_filter($this->filters, function (AbstractFilter $filter) use (&$column) {
  348. if (is_array($column)) {
  349. return ! in_array($filter->column(), $column);
  350. }
  351. return $filter->column() != $column;
  352. });
  353. }
  354. /**
  355. * @return array
  356. */
  357. public function inputs()
  358. {
  359. if (! is_null($this->inputs)) {
  360. return $this->inputs;
  361. }
  362. $this->inputs = Arr::dot(request()->all());
  363. $this->inputs = array_filter($this->inputs, function ($input) {
  364. return $input !== '' && ! is_null($input);
  365. });
  366. $this->sanitizeInputs($this->inputs);
  367. return $this->inputs;
  368. }
  369. /**
  370. * Get all conditions of the filters.
  371. *
  372. * @return array
  373. */
  374. public function getConditions()
  375. {
  376. $inputs = $this->inputs();
  377. if (empty($inputs)) {
  378. return [];
  379. }
  380. if ($this->conditions !== null) {
  381. return $this->conditions;
  382. }
  383. $params = [];
  384. foreach ($inputs as $key => $value) {
  385. Arr::set($params, $key, $value);
  386. }
  387. $conditions = [];
  388. foreach ($this->filters() as $filter) {
  389. $conditions[] = $filter->condition($params);
  390. }
  391. return tap(array_filter($conditions), function ($conditions) {
  392. if (! empty($conditions)) {
  393. if ($this->expand === null || $this->mode !== static::MODE_RIGHT_SIDE) {
  394. $this->expand();
  395. }
  396. $this->grid()->fireOnce(new ApplyFilter([$conditions]));
  397. $this->grid()->model()->disableBindTreeQuery();
  398. }
  399. $this->conditions = $conditions;
  400. });
  401. }
  402. /**
  403. * @param array $inputs
  404. * @return void
  405. */
  406. protected function sanitizeInputs(&$inputs)
  407. {
  408. if (! $prefix = $this->grid()->getNamePrefix()) {
  409. return;
  410. }
  411. $inputs = collect($inputs)->filter(function ($input, $key) use ($prefix) {
  412. return Str::startsWith($key, $prefix);
  413. })->mapWithKeys(function ($val, $key) use ($prefix) {
  414. $key = str_replace($prefix, '', $key);
  415. return [$key => $val];
  416. })->toArray();
  417. }
  418. /**
  419. * Add a filter to grid.
  420. *
  421. * @param AbstractFilter $filter
  422. * @return AbstractFilter
  423. */
  424. protected function addFilter(AbstractFilter $filter)
  425. {
  426. $this->layout->addFilter($filter);
  427. $filter->setParent($this);
  428. return $this->filters[] = $filter;
  429. }
  430. /**
  431. * Use a custom filter.
  432. *
  433. * @param AbstractFilter $filter
  434. * @return AbstractFilter
  435. */
  436. public function use(AbstractFilter $filter)
  437. {
  438. return $this->addFilter($filter);
  439. }
  440. /**
  441. * Get all filters.
  442. *
  443. * @return AbstractFilter[]
  444. */
  445. public function filters()
  446. {
  447. return $this->filters;
  448. }
  449. /**
  450. * 统计查询条件的数量.
  451. *
  452. * @return int
  453. */
  454. public function countConditions()
  455. {
  456. return $this->mode() === Filter::MODE_RIGHT_SIDE
  457. ? count($this->getConditions()) : 0;
  458. }
  459. /**
  460. * @param string $key
  461. * @param string $label
  462. * @return Scope
  463. */
  464. public function scope($key, $label = '')
  465. {
  466. $scope = new Scope($this, $key, $label);
  467. $this->scopes->push($scope);
  468. return $scope;
  469. }
  470. /**
  471. * @return string
  472. */
  473. public function getScopeQueryName()
  474. {
  475. return $this->grid()->makeName('_scope_');
  476. }
  477. /**
  478. * Get all filter scopes.
  479. *
  480. * @return Collection
  481. */
  482. public function scopes()
  483. {
  484. return $this->scopes;
  485. }
  486. /**
  487. * Get current scope.
  488. *
  489. * @return Scope|null
  490. */
  491. public function getCurrentScope()
  492. {
  493. $key = $this->getCurrentScopeName();
  494. return $this->scopes->first(function ($scope) use ($key) {
  495. return $scope->key == $key;
  496. });
  497. }
  498. /**
  499. * Get the name of current scope.
  500. *
  501. * @return string
  502. */
  503. public function getCurrentScopeName()
  504. {
  505. return request($this->getScopeQueryName());
  506. }
  507. /**
  508. * Get scope conditions.
  509. *
  510. * @return array
  511. */
  512. protected function getScopeConditions()
  513. {
  514. if ($scope = $this->getCurrentScope()) {
  515. return $scope->condition();
  516. }
  517. return [];
  518. }
  519. /**
  520. * Expand filter container.
  521. *
  522. * @param bool $value
  523. * @return $this
  524. */
  525. public function expand(bool $value = true)
  526. {
  527. $this->expand = $value;
  528. return $this;
  529. }
  530. /**
  531. * Execute the filter with conditions.
  532. *
  533. * @return Collection|mixed
  534. */
  535. public function execute()
  536. {
  537. $conditions = array_merge(
  538. $this->getConditions(),
  539. $this->getScopeConditions()
  540. );
  541. $this->model->addConditions($conditions);
  542. $this->grid()->fireOnce(new Fetching());
  543. $data = $this->model->buildData();
  544. $this->grid()->fireOnce(new Fetched([&$data]));
  545. return $data;
  546. }
  547. /**
  548. * @param string $top
  549. * @param string $right
  550. * @param string $bottom
  551. * @param string $left
  552. * @return Filter
  553. */
  554. public function padding($top = '15px', $right = '15px', $bottom = '5px', $left = '')
  555. {
  556. return $this->style("padding:$top $right $bottom $left");
  557. }
  558. /**
  559. * @param string $style
  560. * @return $this
  561. */
  562. public function style(?string $style)
  563. {
  564. $this->style = $style;
  565. return $this;
  566. }
  567. /**
  568. * @return $this
  569. */
  570. public function noPadding()
  571. {
  572. return $this->style('padding:0;left:-4px;');
  573. }
  574. /**
  575. * @return $this
  576. */
  577. public function hiddenResetButtonText()
  578. {
  579. Admin::style(".{$this->containerClass} a.reset .d-none d-sm-inline{display:none}");
  580. return $this;
  581. }
  582. public function view(string $view)
  583. {
  584. $this->view = $view;
  585. return $this;
  586. }
  587. /**
  588. * Get the string contents of the filter view.
  589. *
  590. * @return \Illuminate\View\View|string
  591. */
  592. public function render()
  593. {
  594. $this->grid()->callBuilder();
  595. if (empty($this->filters)) {
  596. return '';
  597. }
  598. $this->callComposing();
  599. if (! $this->view) {
  600. $this->view = $this->mode === static::MODE_RIGHT_SIDE ? 'admin::filter.right-side-container' : 'admin::filter.container';
  601. }
  602. return view($this->view)->with($this->variables())->render();
  603. }
  604. protected function defaultVariables()
  605. {
  606. return [
  607. 'action' => $this->action ?: $this->urlWithoutFilters(),
  608. 'layout' => $this->layout,
  609. 'filterID' => $this->disableCollapse ? '' : $this->filterID,
  610. 'expand' => $this->expand,
  611. 'style' => $this->style,
  612. 'border' => $this->border,
  613. 'containerClass' => $this->containerClass,
  614. 'disableResetButton' => $this->disableResetButton,
  615. ];
  616. }
  617. /**
  618. * Get url without filter queryString.
  619. *
  620. * @return string
  621. */
  622. public function urlWithoutFilters()
  623. {
  624. $filters = collect($this->filters);
  625. /** @var Collection $columns */
  626. $columns = $filters->map->getElementName()->flatten();
  627. $columns->push(
  628. $this->grid()->model()->getPageName()
  629. );
  630. $groupNames = $filters->filter(function ($filter) {
  631. return $filter instanceof Group;
  632. })->map(function (AbstractFilter $filter) {
  633. return "{$filter->getId()}_group";
  634. });
  635. return Helper::fullUrlWithoutQuery(
  636. $columns->merge($groupNames)
  637. );
  638. }
  639. /**
  640. * Get url without scope queryString.
  641. *
  642. * @return string
  643. */
  644. public function urlWithoutScopes()
  645. {
  646. return Helper::fullUrlWithoutQuery($this->getScopeQueryName());
  647. }
  648. /**
  649. * Generate a filter object and add to grid.
  650. *
  651. * @param string $method
  652. * @param array $arguments
  653. * @return AbstractFilter|$this
  654. */
  655. public function __call($method, $arguments)
  656. {
  657. if (! empty(static::$supports[$method])) {
  658. $class = static::$supports[$method];
  659. if (! is_subclass_of($class, AbstractFilter::class)) {
  660. throw new RuntimeException("The class [{$class}] must be a type of ".AbstractFilter::class.'.');
  661. }
  662. return $this->addFilter(new $class(...$arguments));
  663. }
  664. if (isset(static::$defaultFilters[$method])) {
  665. return $this->addFilter(new static::$defaultFilters[$method](...$arguments));
  666. }
  667. return $this;
  668. }
  669. /**
  670. * @param string $name
  671. * @param string $filterClass
  672. */
  673. public static function extend($name, $filterClass)
  674. {
  675. static::$supports[$name] = $filterClass;
  676. }
  677. /**
  678. * @return array
  679. */
  680. public static function extensions()
  681. {
  682. return static::$supports;
  683. }
  684. }