Grid.php 19 KB

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