Grid.php 20 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003
  1. <?php
  2. namespace Dcat\Admin;
  3. use Closure;
  4. use Dcat\Admin\Contracts\Repository;
  5. use Dcat\Admin\Grid\Column;
  6. use Dcat\Admin\Grid\Concerns;
  7. use Dcat\Admin\Grid\Model;
  8. use Dcat\Admin\Grid\Responsive;
  9. use Dcat\Admin\Grid\Row;
  10. use Dcat\Admin\Grid\Tools;
  11. use Dcat\Admin\Support\Helper;
  12. use Dcat\Admin\Traits\HasBuilderEvents;
  13. use Illuminate\Contracts\Support\Renderable;
  14. use Illuminate\Database\Eloquent\Builder;
  15. use Illuminate\Support\Collection;
  16. use Illuminate\Support\Traits\Macroable;
  17. class Grid
  18. {
  19. use HasBuilderEvents;
  20. use Concerns\HasNames;
  21. use Concerns\HasFilter;
  22. use Concerns\HasTools;
  23. use Concerns\HasActions;
  24. use Concerns\HasPaginator;
  25. use Concerns\HasExporter;
  26. use Concerns\HasComplexHeaders;
  27. use Concerns\HasSelector;
  28. use Concerns\HasQuickCreate;
  29. use Concerns\HasQuickSearch;
  30. use Concerns\CanFixColumns;
  31. use Macroable {
  32. __call as macroCall;
  33. }
  34. const CREATE_MODE_DEFAULT = 'default';
  35. const CREATE_MODE_DIALOG = 'dialog';
  36. const IFRAME_QUERY_NAME = '_grid_iframe_';
  37. /**
  38. * The grid data model instance.
  39. *
  40. * @var \Dcat\Admin\Grid\Model
  41. */
  42. protected $model;
  43. /**
  44. * Collection of grid columns.
  45. *
  46. * @var \Illuminate\Support\Collection
  47. */
  48. protected $columns;
  49. /**
  50. * Collection of all grid columns.
  51. *
  52. * @var \Illuminate\Support\Collection
  53. */
  54. protected $allColumns;
  55. /**
  56. * Collection of all data rows.
  57. *
  58. * @var \Illuminate\Support\Collection
  59. */
  60. protected $rows;
  61. /**
  62. * Rows callable fucntion.
  63. *
  64. * @var \Closure[]
  65. */
  66. protected $rowsCallback = [];
  67. /**
  68. * All column names of the grid.
  69. *
  70. * @var array
  71. */
  72. protected $columnNames = [];
  73. /**
  74. * Grid builder.
  75. *
  76. * @var \Closure
  77. */
  78. protected $builder;
  79. /**
  80. * Mark if the grid is built.
  81. *
  82. * @var bool
  83. */
  84. protected $built = false;
  85. /**
  86. * All variables in grid view.
  87. *
  88. * @var array
  89. */
  90. protected $variables = [];
  91. /**
  92. * Resource path of the grid.
  93. *
  94. * @var
  95. */
  96. protected $resourcePath;
  97. /**
  98. * Default primary key name.
  99. *
  100. * @var string
  101. */
  102. protected $keyName = 'id';
  103. /**
  104. * View for grid to render.
  105. *
  106. * @var string
  107. */
  108. protected $view = 'admin::grid.table';
  109. /**
  110. * @var Closure
  111. */
  112. protected $header;
  113. /**
  114. * @var Closure
  115. */
  116. protected $footer;
  117. /**
  118. * @var Closure
  119. */
  120. protected $wrapper;
  121. /**
  122. * @var Responsive
  123. */
  124. protected $responsive;
  125. /**
  126. * @var bool
  127. */
  128. protected $addNumberColumn = false;
  129. /**
  130. * @var string
  131. */
  132. protected $tableId = 'grid-table';
  133. /**
  134. * @var Grid\Tools\RowSelector
  135. */
  136. protected $rowSelector;
  137. /**
  138. * Options for grid.
  139. *
  140. * @var array
  141. */
  142. protected $options = [
  143. 'show_pagination' => true,
  144. 'show_filter' => true,
  145. 'show_actions' => true,
  146. 'show_quick_edit_button' => false,
  147. 'show_edit_button' => true,
  148. 'show_view_button' => true,
  149. 'show_delete_button' => true,
  150. 'show_row_selector' => true,
  151. 'show_create_button' => true,
  152. 'show_bordered' => false,
  153. 'table_collapse' => true,
  154. 'show_toolbar' => true,
  155. 'create_mode' => self::CREATE_MODE_DEFAULT,
  156. 'dialog_form_area' => ['700px', '670px'],
  157. 'table_class' => ['table', 'dt-checkboxes-select'],
  158. ];
  159. /**
  160. * Create a new grid instance.
  161. *
  162. * Grid constructor.
  163. *
  164. * @param Repository|\Illuminate\Database\Eloquent\Model|Builder|null $repository
  165. * @param null|\Closure $builder
  166. */
  167. public function __construct($repository = null, ?\Closure $builder = null)
  168. {
  169. $this->model = new Model(request(), $repository);
  170. $this->columns = new Collection();
  171. $this->allColumns = new Collection();
  172. $this->rows = new Collection();
  173. $this->builder = $builder;
  174. if ($repository = $this->model->repository()) {
  175. $this->setKeyName($repository->getKeyName());
  176. }
  177. $this->model->setGrid($this);
  178. $this->setupTools();
  179. $this->setupFilter();
  180. $this->callResolving();
  181. }
  182. /**
  183. * Get table ID.
  184. *
  185. * @return string
  186. */
  187. public function getTableId()
  188. {
  189. return $this->tableId;
  190. }
  191. /**
  192. * Set primary key name.
  193. *
  194. * @param string $name
  195. *
  196. * @return $this
  197. */
  198. public function setKeyName(string $name)
  199. {
  200. $this->keyName = $name;
  201. return $this;
  202. }
  203. /**
  204. * Get or set primary key name.
  205. *
  206. * @return string|void
  207. */
  208. public function getKeyName()
  209. {
  210. return $this->keyName ?: 'id';
  211. }
  212. /**
  213. * Add column to Grid.
  214. *
  215. * @param string $name
  216. * @param string $label
  217. *
  218. * @return Column
  219. */
  220. public function column($name, $label = '')
  221. {
  222. return $this->addColumn($name, $label);
  223. }
  224. /**
  225. * Add number column.
  226. *
  227. * @param null|string $label
  228. *
  229. * @return Column
  230. */
  231. public function number(?string $label = null)
  232. {
  233. return $this->addColumn('#', $label ?: '#');
  234. }
  235. /**
  236. * Batch add column to grid.
  237. *
  238. * @example
  239. * 1.$grid->columns(['name' => 'Name', 'email' => 'Email' ...]);
  240. * 2.$grid->columns('name', 'email' ...)
  241. *
  242. * @param array $columns
  243. *
  244. * @return Collection|Column[]|void
  245. */
  246. public function columns($columns = null)
  247. {
  248. if ($columns === null) {
  249. return $this->columns;
  250. }
  251. if (func_num_args() == 1 && is_array($columns)) {
  252. foreach ($columns as $column => $label) {
  253. $this->column($column, $label);
  254. }
  255. return;
  256. }
  257. foreach (func_get_args() as $column) {
  258. $this->column($column);
  259. }
  260. }
  261. /**
  262. * @return Collection|Column[]
  263. */
  264. public function allColumns()
  265. {
  266. return $this->allColumns;
  267. }
  268. /**
  269. * Add column to grid.
  270. *
  271. * @param string $field
  272. * @param string $label
  273. *
  274. * @return Column
  275. */
  276. protected function addColumn($field = '', $label = '')
  277. {
  278. $column = $this->newColumn($field, $label);
  279. $this->columns->put($field, $column);
  280. $this->allColumns->put($field, $column);
  281. return $column;
  282. }
  283. /**
  284. * @param string $field
  285. * @param string $label
  286. *
  287. * @return Column
  288. */
  289. public function prependColumn($field = '', $label = '')
  290. {
  291. $column = $this->newColumn($field, $label);
  292. $this->columns->prepend($column, $field);
  293. $this->allColumns->prepend($column, $field);
  294. return $column;
  295. }
  296. /**
  297. * @param string $field
  298. * @param string $label
  299. *
  300. * @return Column
  301. */
  302. public function newColumn($field = '', $label = '')
  303. {
  304. $column = new Column($field, $label);
  305. $column->setGrid($this);
  306. return $column;
  307. }
  308. /**
  309. * Get Grid model.
  310. *
  311. * @return Model
  312. */
  313. public function model()
  314. {
  315. return $this->model;
  316. }
  317. /**
  318. * @return array
  319. */
  320. public function getColumnNames()
  321. {
  322. return $this->columnNames;
  323. }
  324. /**
  325. * Apply column filter to grid query.
  326. */
  327. protected function applyColumnFilter()
  328. {
  329. $this->columns->each->bindFilterQuery($this->model());
  330. }
  331. /**
  332. * @param string|array $class
  333. *
  334. * @return $this
  335. */
  336. public function addTableClass($class)
  337. {
  338. $this->options['table_class'] = array_merge((array) $this->options['table_class'], (array) $class);
  339. return $this;
  340. }
  341. public function formatTableClass()
  342. {
  343. if ($this->options['show_bordered']) {
  344. $this->addTableClass(['table-bordered', 'complex-headers', 'dataTable']);
  345. }
  346. if ($this->getComplexHeaders()) {
  347. $this->addTableClass('table-text-center');
  348. }
  349. return implode(' ', array_unique((array) $this->options['table_class']));
  350. }
  351. /**
  352. * Build the grid.
  353. *
  354. * @return void
  355. */
  356. public function build()
  357. {
  358. if ($this->built) {
  359. return;
  360. }
  361. $collection = $this->processFilter(false);
  362. $data = $collection->toArray();
  363. $this->prependRowSelectorColumn();
  364. $this->appendActionsColumn();
  365. Column::setOriginalGridModels($collection);
  366. $this->columns->map(function (Column $column) use (&$data) {
  367. $column->fill($data);
  368. $this->columnNames[] = $column->getName();
  369. });
  370. $this->buildRows($data);
  371. if ($data && $this->responsive) {
  372. $this->responsive->build();
  373. }
  374. $this->sortHeaders();
  375. }
  376. /**
  377. * @return void
  378. */
  379. public function callBuilder()
  380. {
  381. if ($this->builder && ! $this->built) {
  382. call_user_func($this->builder, $this);
  383. }
  384. $this->built = true;
  385. }
  386. /**
  387. * Build the grid rows.
  388. *
  389. * @param array $data
  390. *
  391. * @return void
  392. */
  393. protected function buildRows(array $data)
  394. {
  395. $this->rows = collect($data)->map(function ($model) {
  396. return new Row($this, $model);
  397. });
  398. if ($this->rowsCallback) {
  399. foreach ($this->rowsCallback as $value) {
  400. $value($this->rows);
  401. }
  402. }
  403. }
  404. /**
  405. * Set grid row callback function.
  406. *
  407. * @param Closure $callable
  408. *
  409. * @return Collection|void
  410. */
  411. public function rows(Closure $callable = null)
  412. {
  413. if (is_null($callable)) {
  414. return $this->rows;
  415. }
  416. $this->rowsCallback[] = $callable;
  417. }
  418. /**
  419. * Get create url.
  420. *
  421. * @return string
  422. */
  423. public function getCreateUrl()
  424. {
  425. $queryString = '';
  426. if ($constraints = $this->model()->getConstraints()) {
  427. $queryString = http_build_query($constraints);
  428. }
  429. return sprintf(
  430. '%s/create%s',
  431. $this->resource(),
  432. $queryString ? ('?'.$queryString) : ''
  433. );
  434. }
  435. /**
  436. * @param \Closure $closure
  437. *
  438. * @return Grid\Tools\RowSelector
  439. */
  440. public function rowSelector()
  441. {
  442. return $this->rowSelector ?: ($this->rowSelector = new Grid\Tools\RowSelector($this));
  443. }
  444. /**
  445. * Prepend checkbox column for grid.
  446. *
  447. * @return void
  448. */
  449. protected function prependRowSelectorColumn()
  450. {
  451. if (! $this->options['show_row_selector']) {
  452. return;
  453. }
  454. $rowSelector = $this->rowSelector();
  455. $keyName = $this->getKeyName();
  456. $this->prependColumn(
  457. Grid\Column::SELECT_COLUMN_NAME,
  458. $rowSelector->renderHeader()
  459. )->display(function () use ($rowSelector, $keyName) {
  460. return $rowSelector->renderColumn($this, $this->{$keyName});
  461. });
  462. }
  463. /**
  464. * @param string $width
  465. * @param string $height
  466. *
  467. * @return $this
  468. */
  469. public function setDialogFormDimensions(string $width, string $height)
  470. {
  471. $this->options['dialog_form_area'] = [$width, $height];
  472. return $this;
  473. }
  474. /**
  475. * Render create button for grid.
  476. *
  477. * @return string
  478. */
  479. public function renderCreateButton()
  480. {
  481. if (! $this->options['show_create_button']) {
  482. return '';
  483. }
  484. return (new Tools\CreateButton($this))->render();
  485. }
  486. /**
  487. * @param bool $value
  488. *
  489. * @return $this
  490. */
  491. public function withBorder(bool $value = true)
  492. {
  493. $this->options['show_bordered'] = $value;
  494. return $this;
  495. }
  496. /**
  497. * @param bool $value
  498. *
  499. * @return $this
  500. */
  501. public function tableCollapse(bool $value = true)
  502. {
  503. $this->options['table_collapse'] = $value;
  504. return $this;
  505. }
  506. /**
  507. * Set grid header.
  508. *
  509. * @param Closure|string|Renderable $content
  510. *
  511. * @return $this|Closure
  512. */
  513. public function header($content = null)
  514. {
  515. if (! $content) {
  516. return $this->header;
  517. }
  518. $this->header = $content;
  519. return $this;
  520. }
  521. /**
  522. * Render grid header.
  523. *
  524. * @return string
  525. */
  526. public function renderHeader()
  527. {
  528. if (! $this->header) {
  529. return '';
  530. }
  531. $content = Helper::render($this->header, [$this->processFilter(false)]);
  532. if (empty($content)) {
  533. return '';
  534. }
  535. return <<<HTML
  536. <div class="card-header clearfix" style="border-bottom: 0;background: transparent;padding: 0">{$content}</div>
  537. HTML;
  538. }
  539. /**
  540. * Set grid footer.
  541. *
  542. * @param Closure|string|Renderable $content
  543. *
  544. * @return $this|Closure
  545. */
  546. public function footer($content = null)
  547. {
  548. if (! $content) {
  549. return $this->footer;
  550. }
  551. $this->footer = $content;
  552. return $this;
  553. }
  554. /**
  555. * Render grid footer.
  556. *
  557. * @return string
  558. */
  559. public function renderFooter()
  560. {
  561. if (! $this->footer) {
  562. return '';
  563. }
  564. $content = Helper::render($this->footer, [$this->processFilter(false)]);
  565. if (empty($content)) {
  566. return '';
  567. }
  568. return <<<HTML
  569. <div class="box-footer clearfix">{$content}</div>
  570. HTML;
  571. }
  572. /**
  573. * Get or set option for grid.
  574. *
  575. * @param string $key
  576. * @param mixed $value
  577. *
  578. * @return $this|mixed
  579. */
  580. public function option($key, $value = null)
  581. {
  582. if (is_null($value)) {
  583. return $this->options[$key] ?? null;
  584. }
  585. $this->options[$key] = $value;
  586. return $this;
  587. }
  588. protected function setUpOptions()
  589. {
  590. if ($this->options['show_bordered']) {
  591. $this->tableCollapse(false);
  592. }
  593. }
  594. /**
  595. * Disable row selector.
  596. *
  597. * @return $this
  598. */
  599. public function disableRowSelector(bool $disable = true)
  600. {
  601. $this->tools->disableBatchActions($disable);
  602. return $this->option('show_row_selector', ! $disable);
  603. }
  604. /**
  605. * Show row selector.
  606. *
  607. * @return $this
  608. */
  609. public function showRowSelector(bool $val = true)
  610. {
  611. return $this->disableRowSelector(! $val);
  612. }
  613. /**
  614. * Remove create button on grid.
  615. *
  616. * @return $this
  617. */
  618. public function disableCreateButton(bool $disable = true)
  619. {
  620. return $this->option('show_create_button', ! $disable);
  621. }
  622. /**
  623. * Show create button.
  624. *
  625. * @return $this
  626. */
  627. public function showCreateButton(bool $val = true)
  628. {
  629. return $this->disableCreateButton(! $val);
  630. }
  631. /**
  632. * If allow creation.
  633. *
  634. * @return bool
  635. */
  636. public function allowCreateButton()
  637. {
  638. return $this->options['show_create_button'];
  639. }
  640. /**
  641. * @param string $mode
  642. *
  643. * @return $this
  644. */
  645. public function createMode(string $mode)
  646. {
  647. return $this->option('create_mode', $mode);
  648. }
  649. /**
  650. * @return $this
  651. */
  652. public function enableDialogCreate()
  653. {
  654. return $this->createMode(self::CREATE_MODE_DIALOG);
  655. }
  656. /**
  657. * Get or set resource path.
  658. *
  659. * @param string $path
  660. *
  661. * @return $this|string
  662. */
  663. public function resource(string $path = null)
  664. {
  665. if ($path === null) {
  666. return $this->resourcePath ?: (
  667. $this->resourcePath = url(app('request')->getPathInfo())
  668. );
  669. }
  670. if (! empty($path)) {
  671. $this->resourcePath = admin_url($path);
  672. }
  673. return $this;
  674. }
  675. /**
  676. * Create a grid instance.
  677. *
  678. * @param mixed ...$params
  679. *
  680. * @return $this
  681. */
  682. public static function make(...$params)
  683. {
  684. return new static(...$params);
  685. }
  686. /**
  687. * Enable responsive tables.
  688. *
  689. * @see https://github.com/nadangergeo/RWD-Table-Patterns
  690. *
  691. * @return Responsive
  692. *
  693. * @deprecated 即将在2.0版本中废弃
  694. */
  695. public function responsive()
  696. {
  697. if (! $this->responsive) {
  698. $this->responsive = new Responsive($this);
  699. }
  700. return $this->responsive;
  701. }
  702. /**
  703. * @return bool
  704. */
  705. public function allowResponsive()
  706. {
  707. return $this->responsive ? true : false;
  708. }
  709. /**
  710. * @param Closure $closure
  711. *
  712. * @return $this;
  713. */
  714. public function wrap(\Closure $closure)
  715. {
  716. $this->wrapper = $closure;
  717. return $this;
  718. }
  719. /**
  720. * @return bool
  721. */
  722. public function hasWrapper()
  723. {
  724. return $this->wrapper ? true : false;
  725. }
  726. /**
  727. * Add variables to grid view.
  728. *
  729. * @param array $variables
  730. *
  731. * @return $this
  732. */
  733. public function with($variables = [])
  734. {
  735. $this->variables = $variables;
  736. return $this;
  737. }
  738. /**
  739. * Get all variables will used in grid view.
  740. *
  741. * @return array
  742. */
  743. protected function variables()
  744. {
  745. $this->variables['grid'] = $this;
  746. $this->variables['tableId'] = $this->getTableId();
  747. return $this->variables;
  748. }
  749. /**
  750. * Set a view to render.
  751. *
  752. * @param string $view
  753. * @param array $variables
  754. */
  755. public function view($view, $variables = [])
  756. {
  757. if (! empty($variables)) {
  758. $this->with($variables);
  759. }
  760. $this->view = $view;
  761. }
  762. /**
  763. * Set grid title.
  764. *
  765. * @param string $title
  766. *
  767. * @return $this
  768. */
  769. public function title($title)
  770. {
  771. $this->variables['title'] = $title;
  772. return $this;
  773. }
  774. /**
  775. * Set grid description.
  776. *
  777. * @param string $description
  778. *
  779. * @return $this
  780. */
  781. public function description($description)
  782. {
  783. $this->variables['description'] = $description;
  784. return $this;
  785. }
  786. /**
  787. * Set resource path for grid.
  788. *
  789. * @param string $path
  790. *
  791. * @return $this
  792. */
  793. public function setResource($path)
  794. {
  795. $this->resourcePath = $path;
  796. return $this;
  797. }
  798. /**
  799. * Get the string contents of the grid view.
  800. *
  801. * @return string
  802. */
  803. public function render()
  804. {
  805. try {
  806. $this->callComposing();
  807. $this->build();
  808. $this->applyFixColumns();
  809. $this->setUpOptions();
  810. } catch (\Throwable $e) {
  811. return $this->handleException($e);
  812. }
  813. return $this->doWrap();
  814. }
  815. /**
  816. * @return string
  817. */
  818. protected function doWrap()
  819. {
  820. $view = view($this->view, $this->variables());
  821. if (! $wrapper = $this->wrapper) {
  822. return $view->render();
  823. }
  824. return $wrapper($view);
  825. }
  826. protected function handleException(\Throwable $e)
  827. {
  828. return Admin::makeExceptionHandler()->handle($e);
  829. }
  830. /**
  831. * Add column to grid.
  832. *
  833. * @param string $name
  834. *
  835. * @return Column
  836. */
  837. public function __get($name)
  838. {
  839. return $this->addColumn($name);
  840. }
  841. /**
  842. * Dynamically add columns to the grid view.
  843. *
  844. * @param $method
  845. * @param $arguments
  846. *
  847. * @return Column
  848. */
  849. public function __call($method, $arguments)
  850. {
  851. if (static::hasMacro($method)) {
  852. return $this->macroCall($method, $arguments);
  853. }
  854. return $this->addColumn($method, $arguments[0] ?? null);
  855. }
  856. }