Grid.php 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978
  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. /**
  40. * The grid data model instance.
  41. *
  42. * @var \Dcat\Admin\Grid\Model
  43. */
  44. protected $model;
  45. /**
  46. * Collection of grid columns.
  47. *
  48. * @var \Illuminate\Support\Collection
  49. */
  50. protected $columns;
  51. /**
  52. * Collection of all grid columns.
  53. *
  54. * @var \Illuminate\Support\Collection
  55. */
  56. protected $allColumns;
  57. /**
  58. * Collection of all data rows.
  59. *
  60. * @var \Illuminate\Support\Collection
  61. */
  62. protected $rows;
  63. /**
  64. * @var array
  65. */
  66. protected $rowsCallbacks = [];
  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. * Resource path of the grid.
  87. *
  88. * @var
  89. */
  90. protected $resourcePath;
  91. /**
  92. * Default primary key name.
  93. *
  94. * @var string|array
  95. */
  96. protected $keyName;
  97. /**
  98. * View for grid to render.
  99. *
  100. * @var string
  101. */
  102. protected $view = 'admin::grid.table';
  103. /**
  104. * @var Closure[]
  105. */
  106. protected $header = [];
  107. /**
  108. * @var Closure[]
  109. */
  110. protected $footer = [];
  111. /**
  112. * @var Closure
  113. */
  114. protected $wrapper;
  115. /**
  116. * @var bool
  117. */
  118. protected $addNumberColumn = false;
  119. /**
  120. * @var string
  121. */
  122. protected $tableId = 'grid-table';
  123. /**
  124. * @var Grid\Tools\RowSelector
  125. */
  126. protected $rowSelector;
  127. /**
  128. * Options for grid.
  129. *
  130. * @var array
  131. */
  132. protected $options = [
  133. 'pagination' => true,
  134. 'filter' => true,
  135. 'actions' => true,
  136. 'quick_edit_button' => false,
  137. 'edit_button' => true,
  138. 'view_button' => true,
  139. 'delete_button' => true,
  140. 'row_selector' => true,
  141. 'create_button' => true,
  142. 'bordered' => false,
  143. 'table_collapse' => true,
  144. 'toolbar' => true,
  145. 'create_mode' => self::CREATE_MODE_DEFAULT,
  146. 'dialog_form_area' => ['700px', '670px'],
  147. 'table_class' => ['table', 'custom-data-table', 'data-table'],
  148. ];
  149. /**
  150. * @var \Illuminate\Http\Request
  151. */
  152. protected $request;
  153. /**
  154. * @var bool
  155. */
  156. protected $show = true;
  157. /**
  158. * Create a new grid instance.
  159. *
  160. * Grid constructor.
  161. *
  162. * @param Repository|\Illuminate\Database\Eloquent\Model|Builder|null $repository
  163. * @param null|\Closure $builder
  164. */
  165. public function __construct($repository = null, ?\Closure $builder = null, $request = null)
  166. {
  167. $this->model = new Model(request(), $repository);
  168. $this->columns = new Collection();
  169. $this->allColumns = new Collection();
  170. $this->rows = new Collection();
  171. $this->builder = $builder;
  172. $this->request = $request ?: request();
  173. $this->resourcePath = url($this->request->getPathInfo());
  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|array $name
  195. *
  196. * @return $this
  197. */
  198. public function setKeyName($name)
  199. {
  200. $this->keyName = $name;
  201. return $this;
  202. }
  203. /**
  204. * Get or set primary key name.
  205. *
  206. * @return string|array
  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['bordered']) {
  344. $this->addTableClass(['table-bordered', 'complex-headers', 'data-table']);
  345. }
  346. return implode(' ', array_unique((array) $this->options['table_class']));
  347. }
  348. /**
  349. * Build the grid.
  350. *
  351. * @return void
  352. */
  353. public function build()
  354. {
  355. if ($this->built) {
  356. return;
  357. }
  358. $collection = clone $this->processFilter();
  359. $this->prependRowSelectorColumn();
  360. $this->appendActionsColumn();
  361. Column::setOriginalGridModels($collection);
  362. $this->columns->map(function (Column $column) use (&$collection) {
  363. $column->fill($collection);
  364. $this->columnNames[] = $column->getName();
  365. });
  366. $this->buildRows($collection);
  367. $this->sortHeaders();
  368. }
  369. /**
  370. * @return void
  371. */
  372. public function callBuilder()
  373. {
  374. if ($this->builder && ! $this->built) {
  375. call_user_func($this->builder, $this);
  376. }
  377. $this->built = true;
  378. }
  379. /**
  380. * Build the grid rows.
  381. *
  382. * @param Collection $data
  383. *
  384. * @return void
  385. */
  386. protected function buildRows($data)
  387. {
  388. $this->rows = $data->map(function ($row) {
  389. return new Row($this, $row);
  390. });
  391. foreach ($this->rowsCallbacks as $callback) {
  392. $callback($this->rows);
  393. }
  394. }
  395. /**
  396. * Set grid row callback function.
  397. *
  398. * @return Collection|$this
  399. */
  400. public function rows(\Closure $callback = null)
  401. {
  402. if ($callback) {
  403. $this->rowsCallbacks[] = $callback;
  404. return $this;
  405. }
  406. return $this->rows;
  407. }
  408. /**
  409. * Get create url.
  410. *
  411. * @return string
  412. */
  413. public function getCreateUrl()
  414. {
  415. $queryString = '';
  416. if ($constraints = $this->model()->getConstraints()) {
  417. $queryString = http_build_query($constraints);
  418. }
  419. return sprintf(
  420. '%s/create%s',
  421. $this->resource(),
  422. $queryString ? ('?'.$queryString) : ''
  423. );
  424. }
  425. /**
  426. * @param string $key
  427. *
  428. * @return string
  429. */
  430. public function getEditUrl($key)
  431. {
  432. $url = "{$this->resource()}/{$key}/edit";
  433. $queryString = '';
  434. if ($constraints = $this->model()->getConstraints()) {
  435. $queryString = http_build_query($constraints);
  436. }
  437. return $url.($queryString ? ('?'.$queryString) : '');
  438. }
  439. /**
  440. * @param \Closure $closure
  441. *
  442. * @return Grid\Tools\RowSelector
  443. */
  444. public function rowSelector()
  445. {
  446. return $this->rowSelector ?: ($this->rowSelector = new Grid\Tools\RowSelector($this));
  447. }
  448. /**
  449. * Prepend checkbox column for grid.
  450. *
  451. * @return void
  452. */
  453. protected function prependRowSelectorColumn()
  454. {
  455. if (! $this->options['row_selector']) {
  456. return;
  457. }
  458. $rowSelector = $this->rowSelector();
  459. $keyName = $this->getKeyName();
  460. $this->prependColumn(
  461. Grid\Column::SELECT_COLUMN_NAME
  462. )->setLabel($rowSelector->renderHeader())->display(function () use ($rowSelector, $keyName) {
  463. return $rowSelector->renderColumn($this, $this->{$keyName});
  464. });
  465. }
  466. /**
  467. * @param string $width
  468. * @param string $height
  469. *
  470. * @return $this
  471. */
  472. public function setDialogFormDimensions(string $width, string $height)
  473. {
  474. $this->options['dialog_form_area'] = [$width, $height];
  475. return $this;
  476. }
  477. /**
  478. * Render create button for grid.
  479. *
  480. * @return string
  481. */
  482. public function renderCreateButton()
  483. {
  484. if (! $this->options['create_button']) {
  485. return '';
  486. }
  487. return (new Tools\CreateButton($this))->render();
  488. }
  489. /**
  490. * @param bool $value
  491. *
  492. * @return $this
  493. */
  494. public function withBorder(bool $value = true)
  495. {
  496. $this->options['bordered'] = $value;
  497. return $this;
  498. }
  499. /**
  500. * @param bool $value
  501. *
  502. * @return $this
  503. */
  504. public function tableCollapse(bool $value = true)
  505. {
  506. $this->options['table_collapse'] = $value;
  507. return $this;
  508. }
  509. /**
  510. * Set grid header.
  511. *
  512. * @param Closure|string|Renderable $content
  513. *
  514. * @return $this
  515. */
  516. public function header($content)
  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. return <<<HTML
  532. <div class="card-header clearfix" style="border-bottom: 0;background: transparent;padding: 0">{$this->renderHeaderOrFooter($this->header)}</div>
  533. HTML;
  534. }
  535. protected function renderHeaderOrFooter($callbacks)
  536. {
  537. $target = [$this->processFilter()];
  538. $content = [];
  539. foreach ($callbacks as $callback) {
  540. $content[] = Helper::render($callback, $target);
  541. }
  542. if (empty($content)) {
  543. return '';
  544. }
  545. return implode('<div class="mb-1 clearfix"></div>', $content);
  546. }
  547. /**
  548. * Set grid footer.
  549. *
  550. * @param Closure|string|Renderable $content
  551. *
  552. * @return $this
  553. */
  554. public function footer($content)
  555. {
  556. $this->footer[] = $content;
  557. return $this;
  558. }
  559. /**
  560. * Render grid footer.
  561. *
  562. * @return string
  563. */
  564. public function renderFooter()
  565. {
  566. if (! $this->footer) {
  567. return '';
  568. }
  569. return <<<HTML
  570. <div class="box-footer clearfix">{$this->renderHeaderOrFooter($this->footer)}</div>
  571. HTML;
  572. }
  573. /**
  574. * Get or set option for grid.
  575. *
  576. * @param string|array $key
  577. * @param mixed $value
  578. *
  579. * @return $this|mixed
  580. */
  581. public function option($key, $value = null)
  582. {
  583. if (is_null($value)) {
  584. return $this->options[$key] ?? null;
  585. }
  586. if (is_array($key)) {
  587. $this->options = array_merge($this->options, $key);
  588. } else {
  589. $this->options[$key] = $value;
  590. }
  591. return $this;
  592. }
  593. protected function setUpOptions()
  594. {
  595. if ($this->options['bordered']) {
  596. $this->tableCollapse(false);
  597. }
  598. }
  599. /**
  600. * Disable row selector.
  601. *
  602. * @return $this
  603. */
  604. public function disableRowSelector(bool $disable = true)
  605. {
  606. $this->tools->disableBatchActions($disable);
  607. return $this->option('row_selector', ! $disable);
  608. }
  609. /**
  610. * Show row selector.
  611. *
  612. * @return $this
  613. */
  614. public function showRowSelector(bool $val = true)
  615. {
  616. return $this->disableRowSelector(! $val);
  617. }
  618. /**
  619. * Remove create button on grid.
  620. *
  621. * @return $this
  622. */
  623. public function disableCreateButton(bool $disable = true)
  624. {
  625. return $this->option('create_button', ! $disable);
  626. }
  627. /**
  628. * Show create button.
  629. *
  630. * @return $this
  631. */
  632. public function showCreateButton(bool $val = true)
  633. {
  634. return $this->disableCreateButton(! $val);
  635. }
  636. /**
  637. * If allow creation.
  638. *
  639. * @return bool
  640. */
  641. public function allowCreateButton()
  642. {
  643. return $this->options['create_button'];
  644. }
  645. /**
  646. * @param string $mode
  647. *
  648. * @return $this
  649. */
  650. public function createMode(string $mode)
  651. {
  652. return $this->option('create_mode', $mode);
  653. }
  654. /**
  655. * @return $this
  656. */
  657. public function enableDialogCreate()
  658. {
  659. return $this->createMode(self::CREATE_MODE_DIALOG);
  660. }
  661. /**
  662. * Get or set resource path.
  663. *
  664. * @return string
  665. */
  666. public function resource()
  667. {
  668. return $this->resourcePath;
  669. }
  670. /**
  671. * Create a grid instance.
  672. *
  673. * @param mixed ...$params
  674. *
  675. * @return $this
  676. */
  677. public static function make(...$params)
  678. {
  679. return new static(...$params);
  680. }
  681. /**
  682. * @param Closure $closure
  683. *
  684. * @return $this;
  685. */
  686. public function wrap(\Closure $closure)
  687. {
  688. $this->wrapper = $closure;
  689. return $this;
  690. }
  691. /**
  692. * @return bool
  693. */
  694. public function hasWrapper()
  695. {
  696. return $this->wrapper ? true : false;
  697. }
  698. /**
  699. * Add variables to grid view.
  700. *
  701. * @param array $variables
  702. *
  703. * @return $this
  704. */
  705. public function with(array $variables)
  706. {
  707. $this->variables = $variables;
  708. return $this;
  709. }
  710. /**
  711. * Get all variables will used in grid view.
  712. *
  713. * @return array
  714. */
  715. protected function defaultVariables()
  716. {
  717. return [
  718. 'grid' => $this,
  719. 'tableId' => $this->getTableId(),
  720. ];
  721. }
  722. /**
  723. * Set a view to render.
  724. *
  725. * @param string $view
  726. *
  727. * @return $this
  728. */
  729. public function view($view)
  730. {
  731. $this->view = $view;
  732. return $this;
  733. }
  734. /**
  735. * Set grid title.
  736. *
  737. * @param string $title
  738. *
  739. * @return $this
  740. */
  741. public function title($title)
  742. {
  743. $this->variables['title'] = $title;
  744. return $this;
  745. }
  746. /**
  747. * Set grid description.
  748. *
  749. * @param string $description
  750. *
  751. * @return $this
  752. */
  753. public function description($description)
  754. {
  755. $this->variables['description'] = $description;
  756. return $this;
  757. }
  758. /**
  759. * Set resource path for grid.
  760. *
  761. * @param string $path
  762. *
  763. * @return $this
  764. */
  765. public function setResource($path)
  766. {
  767. $this->resourcePath = admin_url($path);
  768. return $this;
  769. }
  770. /**
  771. * 设置是否显示.
  772. *
  773. * @param bool $value
  774. *
  775. * @return $this
  776. */
  777. public function show(bool $value = true)
  778. {
  779. $this->show = $value;
  780. return $this;
  781. }
  782. /**
  783. * Get the string contents of the grid view.
  784. *
  785. * @return string
  786. */
  787. public function render()
  788. {
  789. $this->callComposing();
  790. $this->build();
  791. $this->applyFixColumns();
  792. $this->setUpOptions();
  793. return $this->doWrap();
  794. }
  795. /**
  796. * @return string
  797. */
  798. protected function doWrap()
  799. {
  800. if (! $this->show) {
  801. return;
  802. }
  803. $view = view($this->view, $this->variables());
  804. if (! $wrapper = $this->wrapper) {
  805. return $view->render();
  806. }
  807. return Helper::render($wrapper($view));
  808. }
  809. /**
  810. * Add column to grid.
  811. *
  812. * @param string $name
  813. *
  814. * @return Column
  815. */
  816. public function __get($name)
  817. {
  818. return $this->addColumn($name);
  819. }
  820. /**
  821. * Dynamically add columns to the grid view.
  822. *
  823. * @param $method
  824. * @param $arguments
  825. *
  826. * @return Column
  827. */
  828. public function __call($method, $arguments)
  829. {
  830. if (static::hasMacro($method)) {
  831. return $this->macroCall($method, $arguments);
  832. }
  833. return $this->addColumn($method, $arguments[0] ?? null);
  834. }
  835. }