Grid.php 18 KB

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