Grid.php 19 KB

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