Grid.php 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998
  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. Concerns\HasNames,
  21. Concerns\HasFilter,
  22. Concerns\HasTools,
  23. Concerns\HasActions,
  24. Concerns\HasPaginator,
  25. Concerns\HasExporter,
  26. Concerns\HasComplexHeaders,
  27. Concerns\HasSelector,
  28. Concerns\HasQuickCreate,
  29. Concerns\HasQuickSearch,
  30. Concerns\CanFixColumns,
  31. 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.data-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 Admin::makeExceptionHandler()->handle($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. /**
  827. * Add column to grid.
  828. *
  829. * @param string $name
  830. *
  831. * @return Column
  832. */
  833. public function __get($name)
  834. {
  835. return $this->addColumn($name);
  836. }
  837. /**
  838. * Dynamically add columns to the grid view.
  839. *
  840. * @param $method
  841. * @param $arguments
  842. *
  843. * @return Column
  844. */
  845. public function __call($method, $arguments)
  846. {
  847. if (static::hasMacro($method)) {
  848. return $this->macroCall($method, $arguments);
  849. }
  850. return $this->addColumn($method, $arguments[0] ?? null);
  851. }
  852. }