Filter.php 17 KB

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