Grid.php 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945
  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|Closure
  499. */
  500. public function header($content = null)
  501. {
  502. if (! $content) {
  503. return $this->header;
  504. }
  505. $this->header = $content;
  506. return $this;
  507. }
  508. /**
  509. * Render grid header.
  510. *
  511. * @return string
  512. */
  513. public function renderHeader()
  514. {
  515. if (! $this->header) {
  516. return '';
  517. }
  518. $content = Helper::render($this->header, [$this->processFilter(false)]);
  519. if (empty($content)) {
  520. return '';
  521. }
  522. return <<<HTML
  523. <div class="card-header clearfix" style="border-bottom: 0;background: transparent;padding: 0">{$content}</div>
  524. HTML;
  525. }
  526. /**
  527. * Set grid footer.
  528. *
  529. * @param Closure|string|Renderable $content
  530. *
  531. * @return $this|Closure
  532. */
  533. public function footer($content = null)
  534. {
  535. if (! $content) {
  536. return $this->footer;
  537. }
  538. $this->footer = $content;
  539. return $this;
  540. }
  541. /**
  542. * Render grid footer.
  543. *
  544. * @return string
  545. */
  546. public function renderFooter()
  547. {
  548. if (! $this->footer) {
  549. return '';
  550. }
  551. $content = Helper::render($this->footer, [$this->processFilter(false)]);
  552. if (empty($content)) {
  553. return '';
  554. }
  555. return <<<HTML
  556. <div class="box-footer clearfix">{$content}</div>
  557. HTML;
  558. }
  559. /**
  560. * Get or set option for grid.
  561. *
  562. * @param string|array $key
  563. * @param mixed $value
  564. *
  565. * @return $this|mixed
  566. */
  567. public function option($key, $value = null)
  568. {
  569. if (is_null($value)) {
  570. return $this->options[$key] ?? null;
  571. }
  572. if (is_array($key)) {
  573. $this->options = array_merge($this->options, $key);
  574. } else {
  575. $this->options[$key] = $value;
  576. }
  577. return $this;
  578. }
  579. protected function setUpOptions()
  580. {
  581. if ($this->options['show_bordered']) {
  582. $this->tableCollapse(false);
  583. }
  584. }
  585. /**
  586. * Disable row selector.
  587. *
  588. * @return $this
  589. */
  590. public function disableRowSelector(bool $disable = true)
  591. {
  592. $this->tools->disableBatchActions($disable);
  593. return $this->option('show_row_selector', ! $disable);
  594. }
  595. /**
  596. * Show row selector.
  597. *
  598. * @return $this
  599. */
  600. public function showRowSelector(bool $val = true)
  601. {
  602. return $this->disableRowSelector(! $val);
  603. }
  604. /**
  605. * Remove create button on grid.
  606. *
  607. * @return $this
  608. */
  609. public function disableCreateButton(bool $disable = true)
  610. {
  611. return $this->option('show_create_button', ! $disable);
  612. }
  613. /**
  614. * Show create button.
  615. *
  616. * @return $this
  617. */
  618. public function showCreateButton(bool $val = true)
  619. {
  620. return $this->disableCreateButton(! $val);
  621. }
  622. /**
  623. * If allow creation.
  624. *
  625. * @return bool
  626. */
  627. public function allowCreateButton()
  628. {
  629. return $this->options['show_create_button'];
  630. }
  631. /**
  632. * @param string $mode
  633. *
  634. * @return $this
  635. */
  636. public function createMode(string $mode)
  637. {
  638. return $this->option('create_mode', $mode);
  639. }
  640. /**
  641. * @return $this
  642. */
  643. public function enableDialogCreate()
  644. {
  645. return $this->createMode(self::CREATE_MODE_DIALOG);
  646. }
  647. /**
  648. * Get or set resource path.
  649. *
  650. * @return string
  651. */
  652. public function resource()
  653. {
  654. return $this->resourcePath;
  655. }
  656. /**
  657. * Create a grid instance.
  658. *
  659. * @param mixed ...$params
  660. *
  661. * @return $this
  662. */
  663. public static function make(...$params)
  664. {
  665. return new static(...$params);
  666. }
  667. /**
  668. * @param Closure $closure
  669. *
  670. * @return $this;
  671. */
  672. public function wrap(\Closure $closure)
  673. {
  674. $this->wrapper = $closure;
  675. return $this;
  676. }
  677. /**
  678. * @return bool
  679. */
  680. public function hasWrapper()
  681. {
  682. return $this->wrapper ? true : false;
  683. }
  684. /**
  685. * Add variables to grid view.
  686. *
  687. * @param array $variables
  688. *
  689. * @return $this
  690. */
  691. public function with(array $variables)
  692. {
  693. $this->variables = $variables;
  694. return $this;
  695. }
  696. /**
  697. * Get all variables will used in grid view.
  698. *
  699. * @return array
  700. */
  701. protected function defaultVariables()
  702. {
  703. return [
  704. 'grid' => $this,
  705. 'tableId' => $this->getTableId(),
  706. ];
  707. }
  708. /**
  709. * Set a view to render.
  710. *
  711. * @param string $view
  712. *
  713. * @return $this
  714. */
  715. public function view($view)
  716. {
  717. $this->view = $view;
  718. return $this;
  719. }
  720. /**
  721. * Set grid title.
  722. *
  723. * @param string $title
  724. *
  725. * @return $this
  726. */
  727. public function title($title)
  728. {
  729. $this->variables['title'] = $title;
  730. return $this;
  731. }
  732. /**
  733. * Set grid description.
  734. *
  735. * @param string $description
  736. *
  737. * @return $this
  738. */
  739. public function description($description)
  740. {
  741. $this->variables['description'] = $description;
  742. return $this;
  743. }
  744. /**
  745. * Set resource path for grid.
  746. *
  747. * @param string $path
  748. *
  749. * @return $this
  750. */
  751. public function setResource($path)
  752. {
  753. $this->resourcePath = admin_url($path);
  754. return $this;
  755. }
  756. /**
  757. * Get the string contents of the grid view.
  758. *
  759. * @return string
  760. */
  761. public function render()
  762. {
  763. $this->callComposing();
  764. $this->build();
  765. $this->applyFixColumns();
  766. $this->setUpOptions();
  767. return $this->doWrap();
  768. }
  769. /**
  770. * @return string
  771. */
  772. protected function doWrap()
  773. {
  774. $view = view($this->view, $this->variables());
  775. if (! $wrapper = $this->wrapper) {
  776. return $view->render();
  777. }
  778. return Helper::render($wrapper($view));
  779. }
  780. /**
  781. * Add column to grid.
  782. *
  783. * @param string $name
  784. *
  785. * @return Column
  786. */
  787. public function __get($name)
  788. {
  789. return $this->addColumn($name);
  790. }
  791. /**
  792. * Dynamically add columns to the grid view.
  793. *
  794. * @param $method
  795. * @param $arguments
  796. *
  797. * @return Column
  798. */
  799. public function __call($method, $arguments)
  800. {
  801. if (static::hasMacro($method)) {
  802. return $this->macroCall($method, $arguments);
  803. }
  804. return $this->addColumn($method, $arguments[0] ?? null);
  805. }
  806. }