Grid.php 19 KB

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