Grid.php 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962
  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
  96. */
  97. protected $keyName = 'id';
  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 $name
  196. *
  197. * @return $this
  198. */
  199. public function setKeyName(string $name)
  200. {
  201. $this->keyName = $name;
  202. return $this;
  203. }
  204. /**
  205. * Get or set primary key name.
  206. *
  207. * @return string|void
  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 = $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 \Closure $closure
  428. *
  429. * @return Grid\Tools\RowSelector
  430. */
  431. public function rowSelector()
  432. {
  433. return $this->rowSelector ?: ($this->rowSelector = new Grid\Tools\RowSelector($this));
  434. }
  435. /**
  436. * Prepend checkbox column for grid.
  437. *
  438. * @return void
  439. */
  440. protected function prependRowSelectorColumn()
  441. {
  442. if (! $this->options['show_row_selector']) {
  443. return;
  444. }
  445. $rowSelector = $this->rowSelector();
  446. $keyName = $this->getKeyName();
  447. $this->prependColumn(
  448. Grid\Column::SELECT_COLUMN_NAME
  449. )->setLabel($rowSelector->renderHeader())->display(function () use ($rowSelector, $keyName) {
  450. return $rowSelector->renderColumn($this, $this->{$keyName});
  451. });
  452. }
  453. /**
  454. * @param string $width
  455. * @param string $height
  456. *
  457. * @return $this
  458. */
  459. public function setDialogFormDimensions(string $width, string $height)
  460. {
  461. $this->options['dialog_form_area'] = [$width, $height];
  462. return $this;
  463. }
  464. /**
  465. * Render create button for grid.
  466. *
  467. * @return string
  468. */
  469. public function renderCreateButton()
  470. {
  471. if (! $this->options['show_create_button']) {
  472. return '';
  473. }
  474. return (new Tools\CreateButton($this))->render();
  475. }
  476. /**
  477. * @param bool $value
  478. *
  479. * @return $this
  480. */
  481. public function withBorder(bool $value = true)
  482. {
  483. $this->options['show_bordered'] = $value;
  484. return $this;
  485. }
  486. /**
  487. * @param bool $value
  488. *
  489. * @return $this
  490. */
  491. public function tableCollapse(bool $value = true)
  492. {
  493. $this->options['table_collapse'] = $value;
  494. return $this;
  495. }
  496. /**
  497. * Set grid header.
  498. *
  499. * @param Closure|string|Renderable $content
  500. *
  501. * @return $this
  502. */
  503. public function header($content)
  504. {
  505. $this->header[] = $content;
  506. return $this;
  507. }
  508. /**
  509. * Render grid header.
  510. *
  511. * @return string
  512. */
  513. public function renderHeader()
  514. {
  515. if (! $this->header) {
  516. return '';
  517. }
  518. return <<<HTML
  519. <div class="card-header clearfix" style="border-bottom: 0;background: transparent;padding: 0">{$this->renderHeaderOrFooter($this->header)}</div>
  520. HTML;
  521. }
  522. protected function renderHeaderOrFooter($callbacks)
  523. {
  524. $target = [$this->processFilter()];
  525. $content = [];
  526. foreach ($callbacks as $callback) {
  527. $content[] = Helper::render($callback, $target);
  528. }
  529. if (empty($content)) {
  530. return '';
  531. }
  532. return implode('<div class="mb-1 clearfix"></div>', $content);
  533. }
  534. /**
  535. * Set grid footer.
  536. *
  537. * @param Closure|string|Renderable $content
  538. *
  539. * @return $this
  540. */
  541. public function footer($content)
  542. {
  543. $this->footer[] = $content;
  544. return $this;
  545. }
  546. /**
  547. * Render grid footer.
  548. *
  549. * @return string
  550. */
  551. public function renderFooter()
  552. {
  553. if (! $this->footer) {
  554. return '';
  555. }
  556. return <<<HTML
  557. <div class="box-footer clearfix">{$this->renderHeaderOrFooter($this->footer)}</div>
  558. HTML;
  559. }
  560. /**
  561. * Get or set option for grid.
  562. *
  563. * @param string|array $key
  564. * @param mixed $value
  565. *
  566. * @return $this|mixed
  567. */
  568. public function option($key, $value = null)
  569. {
  570. if (is_null($value)) {
  571. return $this->options[$key] ?? null;
  572. }
  573. if (is_array($key)) {
  574. $this->options = array_merge($this->options, $key);
  575. } else {
  576. $this->options[$key] = $value;
  577. }
  578. return $this;
  579. }
  580. protected function setUpOptions()
  581. {
  582. if ($this->options['show_bordered']) {
  583. $this->tableCollapse(false);
  584. }
  585. }
  586. /**
  587. * Disable row selector.
  588. *
  589. * @return $this
  590. */
  591. public function disableRowSelector(bool $disable = true)
  592. {
  593. $this->tools->disableBatchActions($disable);
  594. return $this->option('show_row_selector', ! $disable);
  595. }
  596. /**
  597. * Show row selector.
  598. *
  599. * @return $this
  600. */
  601. public function showRowSelector(bool $val = true)
  602. {
  603. return $this->disableRowSelector(! $val);
  604. }
  605. /**
  606. * Remove create button on grid.
  607. *
  608. * @return $this
  609. */
  610. public function disableCreateButton(bool $disable = true)
  611. {
  612. return $this->option('show_create_button', ! $disable);
  613. }
  614. /**
  615. * Show create button.
  616. *
  617. * @return $this
  618. */
  619. public function showCreateButton(bool $val = true)
  620. {
  621. return $this->disableCreateButton(! $val);
  622. }
  623. /**
  624. * If allow creation.
  625. *
  626. * @return bool
  627. */
  628. public function allowCreateButton()
  629. {
  630. return $this->options['show_create_button'];
  631. }
  632. /**
  633. * @param string $mode
  634. *
  635. * @return $this
  636. */
  637. public function createMode(string $mode)
  638. {
  639. return $this->option('create_mode', $mode);
  640. }
  641. /**
  642. * @return $this
  643. */
  644. public function enableDialogCreate()
  645. {
  646. return $this->createMode(self::CREATE_MODE_DIALOG);
  647. }
  648. /**
  649. * Get or set resource path.
  650. *
  651. * @return string
  652. */
  653. public function resource()
  654. {
  655. return $this->resourcePath;
  656. }
  657. /**
  658. * Create a grid instance.
  659. *
  660. * @param mixed ...$params
  661. *
  662. * @return $this
  663. */
  664. public static function make(...$params)
  665. {
  666. return new static(...$params);
  667. }
  668. /**
  669. * @param Closure $closure
  670. *
  671. * @return $this;
  672. */
  673. public function wrap(\Closure $closure)
  674. {
  675. $this->wrapper = $closure;
  676. return $this;
  677. }
  678. /**
  679. * @return bool
  680. */
  681. public function hasWrapper()
  682. {
  683. return $this->wrapper ? true : false;
  684. }
  685. /**
  686. * Add variables to grid view.
  687. *
  688. * @param array $variables
  689. *
  690. * @return $this
  691. */
  692. public function with(array $variables)
  693. {
  694. $this->variables = $variables;
  695. return $this;
  696. }
  697. /**
  698. * Get all variables will used in grid view.
  699. *
  700. * @return array
  701. */
  702. protected function defaultVariables()
  703. {
  704. return [
  705. 'grid' => $this,
  706. 'tableId' => $this->getTableId(),
  707. ];
  708. }
  709. /**
  710. * Set a view to render.
  711. *
  712. * @param string $view
  713. *
  714. * @return $this
  715. */
  716. public function view($view)
  717. {
  718. $this->view = $view;
  719. return $this;
  720. }
  721. /**
  722. * Set grid title.
  723. *
  724. * @param string $title
  725. *
  726. * @return $this
  727. */
  728. public function title($title)
  729. {
  730. $this->variables['title'] = $title;
  731. return $this;
  732. }
  733. /**
  734. * Set grid description.
  735. *
  736. * @param string $description
  737. *
  738. * @return $this
  739. */
  740. public function description($description)
  741. {
  742. $this->variables['description'] = $description;
  743. return $this;
  744. }
  745. /**
  746. * Set resource path for grid.
  747. *
  748. * @param string $path
  749. *
  750. * @return $this
  751. */
  752. public function setResource($path)
  753. {
  754. $this->resourcePath = admin_url($path);
  755. return $this;
  756. }
  757. /**
  758. * 设置是否显示.
  759. *
  760. * @param bool $value
  761. *
  762. * @return $this
  763. */
  764. public function show(bool $value = true)
  765. {
  766. $this->show = $value;
  767. return $this;
  768. }
  769. /**
  770. * Get the string contents of the grid view.
  771. *
  772. * @return string
  773. */
  774. public function render()
  775. {
  776. $this->callComposing();
  777. $this->build();
  778. $this->applyFixColumns();
  779. $this->setUpOptions();
  780. return $this->doWrap();
  781. }
  782. /**
  783. * @return string
  784. */
  785. protected function doWrap()
  786. {
  787. if (! $this->show) {
  788. return;
  789. }
  790. $view = view($this->view, $this->variables());
  791. if (! $wrapper = $this->wrapper) {
  792. return $view->render();
  793. }
  794. return Helper::render($wrapper($view));
  795. }
  796. /**
  797. * Add column to grid.
  798. *
  799. * @param string $name
  800. *
  801. * @return Column
  802. */
  803. public function __get($name)
  804. {
  805. return $this->addColumn($name);
  806. }
  807. /**
  808. * Dynamically add columns to the grid view.
  809. *
  810. * @param $method
  811. * @param $arguments
  812. *
  813. * @return Column
  814. */
  815. public function __call($method, $arguments)
  816. {
  817. if (static::hasMacro($method)) {
  818. return $this->macroCall($method, $arguments);
  819. }
  820. return $this->addColumn($method, $arguments[0] ?? null);
  821. }
  822. }