Grid.php 18 KB

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