Grid.php 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981
  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\Str;
  17. use Illuminate\Support\Traits\Macroable;
  18. class Grid
  19. {
  20. use HasBuilderEvents,
  21. Concerns\HasNames,
  22. Concerns\HasFilter,
  23. Concerns\HasTools,
  24. Concerns\HasActions,
  25. Concerns\HasPaginator,
  26. Concerns\HasExporter,
  27. Concerns\HasComplexHeaders,
  28. Concerns\HasSelector,
  29. Concerns\HasQuickCreate,
  30. Concerns\HasQuickSearch,
  31. Concerns\CanFixColumns,
  32. Macroable {
  33. __call as macroCall;
  34. }
  35. const CREATE_MODE_DEFAULT = 'default';
  36. const CREATE_MODE_DIALOG = 'dialog';
  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. '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. if (mb_strpos($name, '.') !== false) {
  222. [$relationName, $relationColumn] = explode('.', $name);
  223. $name = Str::snake($relationName).'.'.$relationColumn;
  224. }
  225. return $this->addColumn($name, $label);
  226. }
  227. /**
  228. * Add number column.
  229. *
  230. * @param null|string $label
  231. *
  232. * @return Column
  233. */
  234. public function number(?string $label = null)
  235. {
  236. return $this->addColumn('#', $label ?: '#');
  237. }
  238. /**
  239. * Batch add column to grid.
  240. *
  241. * @example
  242. * 1.$grid->columns(['name' => 'Name', 'email' => 'Email' ...]);
  243. * 2.$grid->columns('name', 'email' ...)
  244. *
  245. * @param array $columns
  246. *
  247. * @return Collection|Column[]|void
  248. */
  249. public function columns($columns = null)
  250. {
  251. if ($columns === null) {
  252. return $this->columns;
  253. }
  254. if (func_num_args() == 1 && is_array($columns)) {
  255. foreach ($columns as $column => $label) {
  256. $this->column($column, $label);
  257. }
  258. return;
  259. }
  260. foreach (func_get_args() as $column) {
  261. $this->column($column);
  262. }
  263. }
  264. /**
  265. * @return Collection|Column[]
  266. */
  267. public function allColumns()
  268. {
  269. return $this->allColumns;
  270. }
  271. /**
  272. * Add column to grid.
  273. *
  274. * @param string $field
  275. * @param string $label
  276. *
  277. * @return Column
  278. */
  279. protected function addColumn($field = '', $label = '')
  280. {
  281. $column = $this->newColumn($field, $label);
  282. $this->columns->put($field, $column);
  283. $this->allColumns->put($field, $column);
  284. return $column;
  285. }
  286. /**
  287. * @param string $field
  288. * @param string $label
  289. *
  290. * @return Column
  291. */
  292. public function prependColumn($field = '', $label = '')
  293. {
  294. $column = $this->newColumn($field, $label);
  295. $this->columns->prepend($column, $field);
  296. $this->allColumns->prepend($column, $field);
  297. return $column;
  298. }
  299. /**
  300. * @param string $field
  301. * @param string $label
  302. *
  303. * @return Column
  304. */
  305. public function newColumn($field = '', $label = '')
  306. {
  307. $column = new Column($field, $label);
  308. $column->setGrid($this);
  309. return $column;
  310. }
  311. /**
  312. * Get Grid model.
  313. *
  314. * @return Model
  315. */
  316. public function model()
  317. {
  318. return $this->model;
  319. }
  320. /**
  321. * @return array
  322. */
  323. public function getColumnNames()
  324. {
  325. return $this->columnNames;
  326. }
  327. /**
  328. * Apply column filter to grid query.
  329. */
  330. protected function applyColumnFilter()
  331. {
  332. $this->columns->each->bindFilterQuery($this->model());
  333. }
  334. /**
  335. * @param string|array $class
  336. *
  337. * @return $this
  338. */
  339. public function addTableClass($class)
  340. {
  341. $this->options['table_class'] = array_merge((array) $this->options['table_class'], (array) $class);
  342. return $this;
  343. }
  344. public function formatTableClass()
  345. {
  346. if ($this->options['show_bordered']) {
  347. $this->addTableClass(['table-bordered', 'complex-headers', 'dataTable']);
  348. }
  349. if ($this->getComplexHeaders()) {
  350. $this->addTableClass('table-text-center');
  351. }
  352. return implode(' ', array_unique((array) $this->options['table_class']));
  353. }
  354. /**
  355. * Build the grid.
  356. *
  357. * @return void
  358. */
  359. public function build()
  360. {
  361. if ($this->built) {
  362. return;
  363. }
  364. $collection = $this->processFilter(false);
  365. $data = $collection->toArray();
  366. $this->prependRowSelectorColumn();
  367. $this->appendActionsColumn();
  368. Column::setOriginalGridModels($collection);
  369. $this->columns->map(function (Column $column) use (&$data) {
  370. $column->fill($data);
  371. $this->columnNames[] = $column->getName();
  372. });
  373. $this->buildRows($data);
  374. if ($data && $this->responsive) {
  375. $this->responsive->build();
  376. }
  377. $this->sortHeaders();
  378. }
  379. /**
  380. * @return void
  381. */
  382. public function callBuilder()
  383. {
  384. if ($this->builder && ! $this->built) {
  385. call_user_func($this->builder, $this);
  386. }
  387. $this->built = true;
  388. }
  389. /**
  390. * Build the grid rows.
  391. *
  392. * @param array $data
  393. *
  394. * @return void
  395. */
  396. protected function buildRows(array $data)
  397. {
  398. $this->rows = collect($data)->map(function ($model) {
  399. return new Row($this, $model);
  400. });
  401. if ($this->rowsCallback) {
  402. foreach ($this->rowsCallback as $value) {
  403. $value($this->rows);
  404. }
  405. }
  406. }
  407. /**
  408. * Set grid row callback function.
  409. *
  410. * @param Closure $callable
  411. *
  412. * @return Collection|void
  413. */
  414. public function rows(Closure $callable = null)
  415. {
  416. if (is_null($callable)) {
  417. return $this->rows;
  418. }
  419. $this->rowsCallback[] = $callable;
  420. }
  421. /**
  422. * Get create url.
  423. *
  424. * @return string
  425. */
  426. public function getCreateUrl()
  427. {
  428. $queryString = '';
  429. if ($constraints = $this->model()->getConstraints()) {
  430. $queryString = http_build_query($constraints);
  431. }
  432. return sprintf(
  433. '%s/create%s',
  434. $this->resource(),
  435. $queryString ? ('?'.$queryString) : ''
  436. );
  437. }
  438. /**
  439. * @param \Closure $closure
  440. *
  441. * @return Grid\Tools\RowSelector
  442. */
  443. public function rowSelector()
  444. {
  445. return $this->rowSelector ?: ($this->rowSelector = new Grid\Tools\RowSelector($this));
  446. }
  447. /**
  448. * Prepend checkbox column for grid.
  449. *
  450. * @return void
  451. */
  452. protected function prependRowSelectorColumn()
  453. {
  454. if (! $this->options['show_row_selector']) {
  455. return;
  456. }
  457. $rowSelector = $this->rowSelector();
  458. $keyName = $this->getKeyName();
  459. $this->prependColumn(
  460. Grid\Column::SELECT_COLUMN_NAME,
  461. $rowSelector->renderHeader()
  462. )->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['show_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['show_bordered'] = $value;
  497. return $this;
  498. }
  499. /**
  500. * Set grid header.
  501. *
  502. * @param Closure|string|Renderable $content
  503. *
  504. * @return $this|Closure
  505. */
  506. public function header($content = null)
  507. {
  508. if (! $content) {
  509. return $this->header;
  510. }
  511. $this->header = $content;
  512. return $this;
  513. }
  514. /**
  515. * Render grid header.
  516. *
  517. * @return string
  518. */
  519. public function renderHeader()
  520. {
  521. if (! $this->header) {
  522. return '';
  523. }
  524. $content = Helper::render($this->header, [$this->processFilter(false)]);
  525. if (empty($content)) {
  526. return '';
  527. }
  528. return <<<HTML
  529. <div class="card-header clearfix" style="border-bottom: 0;background: transparent;padding: 0">{$content}</div>
  530. HTML;
  531. }
  532. /**
  533. * Set grid footer.
  534. *
  535. * @param Closure|string|Renderable $content
  536. *
  537. * @return $this|Closure
  538. */
  539. public function footer($content = null)
  540. {
  541. if (! $content) {
  542. return $this->footer;
  543. }
  544. $this->footer = $content;
  545. return $this;
  546. }
  547. /**
  548. * Render grid footer.
  549. *
  550. * @return string
  551. */
  552. public function renderFooter()
  553. {
  554. if (! $this->footer) {
  555. return '';
  556. }
  557. $content = Helper::render($this->footer, [$this->processFilter(false)]);
  558. if (empty($content)) {
  559. return '';
  560. }
  561. return <<<HTML
  562. <div class="box-footer clearfix">{$content}</div>
  563. HTML;
  564. }
  565. /**
  566. * Get or set option for grid.
  567. *
  568. * @param string $key
  569. * @param mixed $value
  570. *
  571. * @return $this|mixed
  572. */
  573. public function option($key, $value = null)
  574. {
  575. if (is_null($value)) {
  576. return $this->options[$key];
  577. }
  578. $this->options[$key] = $value;
  579. return $this;
  580. }
  581. /**
  582. * Disable row selector.
  583. *
  584. * @return $this
  585. */
  586. public function disableRowSelector(bool $disable = true)
  587. {
  588. $this->tools->disableBatchActions($disable);
  589. return $this->option('show_row_selector', ! $disable);
  590. }
  591. /**
  592. * Show row selector.
  593. *
  594. * @return $this
  595. */
  596. public function showRowSelector(bool $val = true)
  597. {
  598. return $this->disableRowSelector(! $val);
  599. }
  600. /**
  601. * Remove create button on grid.
  602. *
  603. * @return $this
  604. */
  605. public function disableCreateButton(bool $disable = true)
  606. {
  607. return $this->option('show_create_button', ! $disable);
  608. }
  609. /**
  610. * Show create button.
  611. *
  612. * @return $this
  613. */
  614. public function showCreateButton(bool $val = true)
  615. {
  616. return $this->disableCreateButton(! $val);
  617. }
  618. /**
  619. * If allow creation.
  620. *
  621. * @return bool
  622. */
  623. public function allowCreateButton()
  624. {
  625. return $this->options['show_create_button'];
  626. }
  627. /**
  628. * @param string $mode
  629. *
  630. * @return $this
  631. */
  632. public function createMode(string $mode)
  633. {
  634. return $this->option('create_mode', $mode);
  635. }
  636. /**
  637. * @return $this
  638. */
  639. public function enableDialogCreate()
  640. {
  641. return $this->createMode(self::CREATE_MODE_DIALOG);
  642. }
  643. /**
  644. * Get or set resource path.
  645. *
  646. * @param string $path
  647. *
  648. * @return $this|string
  649. */
  650. public function resource(string $path = null)
  651. {
  652. if ($path === null) {
  653. return $this->resourcePath ?: (
  654. $this->resourcePath = url(app('request')->getPathInfo())
  655. );
  656. }
  657. if (! empty($path)) {
  658. $this->resourcePath = admin_url($path);
  659. }
  660. return $this;
  661. }
  662. /**
  663. * Create a grid instance.
  664. *
  665. * @param mixed ...$params
  666. *
  667. * @return $this
  668. */
  669. public static function make(...$params)
  670. {
  671. return new static(...$params);
  672. }
  673. /**
  674. * Enable responsive tables.
  675. *
  676. * @see https://github.com/nadangergeo/RWD-Table-Patterns
  677. *
  678. * @return Responsive
  679. */
  680. public function responsive()
  681. {
  682. if (! $this->responsive) {
  683. $this->responsive = new Responsive($this);
  684. }
  685. return $this->responsive;
  686. }
  687. /**
  688. * @return bool
  689. */
  690. public function allowResponsive()
  691. {
  692. return $this->responsive ? true : false;
  693. }
  694. /**
  695. * @param Closure $closure
  696. *
  697. * @return $this;
  698. */
  699. public function wrap(\Closure $closure)
  700. {
  701. $this->wrapper = $closure;
  702. return $this;
  703. }
  704. /**
  705. * @return bool
  706. */
  707. public function hasWrapper()
  708. {
  709. return $this->wrapper ? true : false;
  710. }
  711. /**
  712. * Add variables to grid view.
  713. *
  714. * @param array $variables
  715. *
  716. * @return $this
  717. */
  718. public function with($variables = [])
  719. {
  720. $this->variables = $variables;
  721. return $this;
  722. }
  723. /**
  724. * Get all variables will used in grid view.
  725. *
  726. * @return array
  727. */
  728. protected function variables()
  729. {
  730. $this->variables['grid'] = $this;
  731. $this->variables['tableId'] = $this->getTableId();
  732. return $this->variables;
  733. }
  734. /**
  735. * Set a view to render.
  736. *
  737. * @param string $view
  738. * @param array $variables
  739. */
  740. public function view($view, $variables = [])
  741. {
  742. if (! empty($variables)) {
  743. $this->with($variables);
  744. }
  745. $this->view = $view;
  746. }
  747. /**
  748. * Set grid title.
  749. *
  750. * @param string $title
  751. *
  752. * @return $this
  753. */
  754. public function title($title)
  755. {
  756. $this->variables['title'] = $title;
  757. return $this;
  758. }
  759. /**
  760. * Set grid description.
  761. *
  762. * @param string $description
  763. *
  764. * @return $this
  765. */
  766. public function description($description)
  767. {
  768. $this->variables['description'] = $description;
  769. return $this;
  770. }
  771. /**
  772. * Set resource path for grid.
  773. *
  774. * @param string $path
  775. *
  776. * @return $this
  777. */
  778. public function setResource($path)
  779. {
  780. $this->resourcePath = $path;
  781. return $this;
  782. }
  783. /**
  784. * Get the string contents of the grid view.
  785. *
  786. * @return string
  787. */
  788. public function render()
  789. {
  790. $this->handleExportRequest();
  791. try {
  792. $this->callComposing();
  793. $this->build();
  794. $this->applyFixColumns();
  795. } catch (\Throwable $e) {
  796. return Admin::makeExceptionHandler()->handle($e);
  797. }
  798. return $this->doWrap();
  799. }
  800. /**
  801. * @return string
  802. */
  803. protected function doWrap()
  804. {
  805. $view = view($this->view, $this->variables());
  806. if (! $wrapper = $this->wrapper) {
  807. return $view->render();
  808. }
  809. return $wrapper($view);
  810. }
  811. /**
  812. * Add column to grid.
  813. *
  814. * @param string $name
  815. *
  816. * @return Column
  817. */
  818. public function __get($name)
  819. {
  820. return $this->addColumn($name);
  821. }
  822. /**
  823. * Dynamically add columns to the grid view.
  824. *
  825. * @param $method
  826. * @param $arguments
  827. *
  828. * @return Column
  829. */
  830. public function __call($method, $arguments)
  831. {
  832. if (static::hasMacro($method)) {
  833. return $this->macroCall($method, $arguments);
  834. }
  835. return $this->addColumn($method, $arguments[0] ?? null);
  836. }
  837. }