Model.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733
  1. <?php
  2. namespace Dcat\Admin\Grid;
  3. use Dcat\Admin\Admin;
  4. use Dcat\Admin\Grid;
  5. use Dcat\Admin\Middleware\Pjax;
  6. use Dcat\Admin\Repositories\Repository;
  7. use Illuminate\Contracts\Support\Arrayable;
  8. use Illuminate\Database\Eloquent\Relations\Relation;
  9. use Illuminate\Database\Query\Builder;
  10. use Illuminate\Http\Request;
  11. use Illuminate\Pagination\AbstractPaginator;
  12. use Illuminate\Pagination\LengthAwarePaginator;
  13. use Illuminate\Support\Arr;
  14. use Illuminate\Support\Collection;
  15. use Illuminate\Support\Str;
  16. /**
  17. * @mixin Builder
  18. */
  19. class Model
  20. {
  21. use Grid\Concerns\HasTree;
  22. /**
  23. * @var Request
  24. */
  25. protected $request;
  26. /**
  27. * @var Repository
  28. */
  29. protected $repository;
  30. /**
  31. * @var AbstractPaginator
  32. */
  33. protected $paginator;
  34. /**
  35. * Array of queries of the model.
  36. *
  37. * @var \Illuminate\Support\Collection
  38. */
  39. protected $queries;
  40. /**
  41. * Sort parameters of the model.
  42. *
  43. * @var array
  44. */
  45. protected $sort;
  46. /**
  47. * @var Collection
  48. */
  49. protected $data;
  50. /**
  51. * @var callable
  52. */
  53. protected $builder;
  54. /*
  55. * 20 items per page as default.
  56. *
  57. * @var int
  58. */
  59. protected $perPage = 20;
  60. /**
  61. * @var string
  62. */
  63. protected $pageName = 'page';
  64. /**
  65. * @var int
  66. */
  67. protected $currentPage;
  68. /**
  69. * If the model use pagination.
  70. *
  71. * @var bool
  72. */
  73. protected $usePaginate = true;
  74. /**
  75. * The query string variable used to store the per-page.
  76. *
  77. * @var string
  78. */
  79. protected $perPageName = 'per_page';
  80. /**
  81. * The query string variable used to store the sort.
  82. *
  83. * @var string
  84. */
  85. protected $sortName = '_sort';
  86. /**
  87. * Collection callback.
  88. *
  89. * @var callable[]
  90. */
  91. protected $collectionCallback = [];
  92. /**
  93. * @var Grid
  94. */
  95. protected $grid;
  96. /**
  97. * @var Relation
  98. */
  99. protected $relation;
  100. /**
  101. * @var array
  102. */
  103. protected $eagerLoads = [];
  104. /**
  105. * @var array
  106. */
  107. protected $constraints = [];
  108. /**
  109. * Create a new grid model instance.
  110. *
  111. * @param Repository|\Illuminate\Database\Eloquent\Model $repository
  112. * @param Request $request
  113. */
  114. public function __construct(Request $request, $repository = null)
  115. {
  116. if ($repository) {
  117. $this->repository = Admin::repository($repository);
  118. }
  119. $this->request = $request;
  120. $this->initQueries();
  121. }
  122. /**
  123. * @return void
  124. */
  125. protected function initQueries()
  126. {
  127. $this->queries = new Collection();
  128. }
  129. /**
  130. * @return Repository|null
  131. */
  132. public function repository()
  133. {
  134. return $this->repository;
  135. }
  136. /**
  137. * @return Collection
  138. */
  139. public function getQueries()
  140. {
  141. return $this->queries = $this->queries->unique();
  142. }
  143. /**
  144. * @param Collection $query
  145. *
  146. * @return void
  147. */
  148. public function setQueries(Collection $query)
  149. {
  150. $this->queries = $query;
  151. }
  152. /**
  153. * @return AbstractPaginator|LengthAwarePaginator
  154. */
  155. public function paginator(): AbstractPaginator
  156. {
  157. $this->buildData();
  158. return $this->paginator;
  159. }
  160. /**
  161. * @param int $total
  162. * @param Collection|array $data
  163. *
  164. * @return LengthAwarePaginator
  165. */
  166. public function makePaginator($total, $data, string $url = null)
  167. {
  168. $paginator = new LengthAwarePaginator(
  169. $data,
  170. $total,
  171. $this->getPerPage(), // 传入每页显示行数
  172. $this->getCurrentPage() // 传入当前页码
  173. );
  174. return $paginator->setPath(
  175. $url ?: url()->current()
  176. );
  177. }
  178. /**
  179. * Get primary key name of model.
  180. *
  181. * @return string
  182. */
  183. public function getKeyName()
  184. {
  185. return $this->grid->getKeyName();
  186. }
  187. /**
  188. * Enable or disable pagination.
  189. *
  190. * @param bool $use
  191. */
  192. public function usePaginate($use = true)
  193. {
  194. $this->usePaginate = $use;
  195. }
  196. /**
  197. * @return bool
  198. */
  199. public function allowPagination()
  200. {
  201. return $this->usePaginate;
  202. }
  203. /**
  204. * Get the query string variable used to store the per-page.
  205. *
  206. * @return string
  207. */
  208. public function getPerPageName()
  209. {
  210. return $this->perPageName;
  211. }
  212. /**
  213. * Set the query string variable used to store the per-page.
  214. *
  215. * @param string $name
  216. *
  217. * @return $this
  218. */
  219. public function setPerPageName($name)
  220. {
  221. $this->perPageName = $name;
  222. return $this;
  223. }
  224. /**
  225. * @param int $perPage
  226. */
  227. public function setPerPage(int $perPage)
  228. {
  229. $this->perPage = $perPage;
  230. return $this;
  231. }
  232. /**
  233. * @param string $pageName
  234. */
  235. public function setPageName(string $pageName)
  236. {
  237. $this->pageName = $pageName;
  238. return $this;
  239. }
  240. /**
  241. * @return string
  242. */
  243. public function getPageName()
  244. {
  245. return $this->pageName;
  246. }
  247. /**
  248. * Get the query string variable used to store the sort.
  249. *
  250. * @return string
  251. */
  252. public function getSortName()
  253. {
  254. return $this->sortName;
  255. }
  256. /**
  257. * Set the query string variable used to store the sort.
  258. *
  259. * @param string $name
  260. *
  261. * @return $this
  262. */
  263. public function setSortName($name)
  264. {
  265. $this->sortName = $name;
  266. return $this;
  267. }
  268. /**
  269. * Set parent grid instance.
  270. *
  271. * @param Grid $grid
  272. *
  273. * @return $this
  274. */
  275. public function setGrid(Grid $grid)
  276. {
  277. $this->grid = $grid;
  278. return $this;
  279. }
  280. /**
  281. * Get parent gird instance.
  282. *
  283. * @return Grid
  284. */
  285. public function grid()
  286. {
  287. return $this->grid;
  288. }
  289. /**
  290. * Get filter of Grid.
  291. *
  292. * @return Filter
  293. */
  294. public function filter()
  295. {
  296. return $this->grid->filter();
  297. }
  298. /**
  299. * Get constraints.
  300. *
  301. * @return array|bool
  302. */
  303. public function getConstraints()
  304. {
  305. return $this->constraints;
  306. }
  307. /**
  308. * @param array $constraints
  309. *
  310. * @return $this
  311. */
  312. public function setConstraints(array $constraints)
  313. {
  314. $this->constraints = $constraints;
  315. return $this;
  316. }
  317. /**
  318. * Set collection callback.
  319. *
  320. * @param callable $callback
  321. *
  322. * @return $this
  323. */
  324. public function collection(callable $callback = null)
  325. {
  326. $this->collectionCallback[] = $callback;
  327. return $this;
  328. }
  329. /**
  330. * Build.
  331. *
  332. * @param bool $toArray
  333. *
  334. * @return array|Collection|mixed
  335. */
  336. public function buildData(bool $toArray = false)
  337. {
  338. if (is_null($this->data)) {
  339. $this->setData($this->fetch());
  340. if ($this->collectionCallback) {
  341. $data = $this->data;
  342. foreach ($this->collectionCallback as $cb) {
  343. $data = call_user_func($cb, $data);
  344. }
  345. $this->setData($data);
  346. }
  347. }
  348. return $toArray ? $this->data->toArray() : $this->data;
  349. }
  350. /**
  351. * @param Collection|callable|array|AbstractPaginator $data
  352. *
  353. * @return $this
  354. */
  355. public function setData($data)
  356. {
  357. if (is_callable($data)) {
  358. $this->builder = $data;
  359. return $this;
  360. }
  361. if ($data instanceof AbstractPaginator) {
  362. $this->setPaginator($data);
  363. $data = $data->getCollection();
  364. } elseif (is_array($data)) {
  365. $data = collect($data);
  366. } elseif ($data instanceof Arrayable) {
  367. $data = collect($data->toArray());
  368. }
  369. if ($data instanceof Collection) {
  370. $this->data = $data;
  371. } else {
  372. $this->data = collect();
  373. }
  374. $this->stdObjToArray($this->data);
  375. return $this;
  376. }
  377. /**
  378. * Add conditions to grid model.
  379. *
  380. * @param array $conditions
  381. *
  382. * @return $this
  383. */
  384. public function addConditions(array $conditions)
  385. {
  386. foreach ($conditions as $condition) {
  387. call_user_func_array([$this, key($condition)], current($condition));
  388. }
  389. return $this;
  390. }
  391. /**
  392. * @throws \Exception
  393. *
  394. * @return Collection|array
  395. */
  396. protected function fetch()
  397. {
  398. if ($this->paginator) {
  399. return $this->paginator->getCollection();
  400. }
  401. if ($this->builder && is_callable($this->builder)) {
  402. $results = call_user_func($this->builder, $this);
  403. } else {
  404. $results = $this->repository->get($this);
  405. }
  406. if (is_array($results) || $results instanceof Collection) {
  407. return $results;
  408. }
  409. if ($results instanceof AbstractPaginator) {
  410. $this->setPaginator($results);
  411. return $results->getCollection();
  412. }
  413. throw new \Exception('Grid query error');
  414. }
  415. /**
  416. * @param AbstractPaginator $paginator
  417. *
  418. * @return void
  419. */
  420. protected function setPaginator(AbstractPaginator $paginator)
  421. {
  422. $this->paginator = $paginator;
  423. $paginator->setPageName($this->pageName);
  424. }
  425. /**
  426. * @param Collection $collection
  427. *
  428. * @return Collection
  429. */
  430. protected function stdObjToArray(Collection $collection)
  431. {
  432. return $collection->transform(function ($item) {
  433. if ($item instanceof \stdClass) {
  434. return (array) $item;
  435. }
  436. return $item;
  437. });
  438. }
  439. /**
  440. * If current page is greater than last page, then redirect to last page.
  441. *
  442. * @param LengthAwarePaginator $paginator
  443. *
  444. * @return void
  445. */
  446. protected function handleInvalidPage(LengthAwarePaginator $paginator)
  447. {
  448. if (
  449. $this->usePaginate
  450. && $paginator->lastPage()
  451. && $paginator->currentPage() > $paginator->lastPage()
  452. ) {
  453. $lastPageUrl = $this->request->fullUrlWithQuery([
  454. $paginator->getPageName() => $paginator->lastPage(),
  455. ]);
  456. Pjax::respond(redirect($lastPageUrl));
  457. }
  458. }
  459. /**
  460. * Get current page.
  461. *
  462. * @return int|null
  463. */
  464. public function getCurrentPage()
  465. {
  466. if (! $this->usePaginate) {
  467. return;
  468. }
  469. return $this->currentPage ?: ($this->currentPage = ($this->request->get($this->pageName) ?: 1));
  470. }
  471. /**
  472. * @param int $currentPage
  473. */
  474. public function setCurrentPage(int $currentPage)
  475. {
  476. $this->currentPage = $currentPage;
  477. return $this;
  478. }
  479. /**
  480. * Get items number of per page.
  481. *
  482. * @return int|null
  483. */
  484. public function getPerPage()
  485. {
  486. if (! $this->usePaginate) {
  487. return;
  488. }
  489. return $this->request->get($this->perPageName) ?: $this->perPage;
  490. }
  491. /**
  492. * Find query by method name.
  493. *
  494. * @param $method
  495. *
  496. * @return static
  497. */
  498. public function findQueryByMethod($method)
  499. {
  500. return $this->queries->first(function ($query) use ($method) {
  501. return $query['method'] == $method;
  502. });
  503. }
  504. /**
  505. * @param string|callable $method
  506. *
  507. * @return $this
  508. */
  509. public function filterQueryBy($method)
  510. {
  511. $this->queries = $this->queries->filter(function ($query, $k) use ($method) {
  512. if (
  513. (is_string($method) && $query['method'] === $method)
  514. || (is_array($method) && in_array($query['method'], $method, true))
  515. ) {
  516. return false;
  517. }
  518. if (is_callable($method)) {
  519. return call_user_func($method, $query, $k);
  520. }
  521. return true;
  522. });
  523. return $this;
  524. }
  525. /**
  526. * Get the grid sort.
  527. *
  528. * @return array exp: ['name', 'desc']
  529. */
  530. public function getSort()
  531. {
  532. if (empty($this->sort)) {
  533. $this->sort = $this->request->get($this->getSortName());
  534. }
  535. if (empty($this->sort['column']) || empty($this->sort['type'])) {
  536. return [null, null];
  537. }
  538. return [$this->sort['column'], $this->sort['type']];
  539. }
  540. /**
  541. * @param string|array $method
  542. *
  543. * @return void
  544. */
  545. public function rejectQuery($method)
  546. {
  547. $this->queries = $this->queries->reject(function ($query) use ($method) {
  548. if (is_callable($method)) {
  549. return call_user_func($method, $query);
  550. }
  551. return in_array($query['method'], (array) $method, true);
  552. });
  553. }
  554. /**
  555. * Reset orderBy query.
  556. *
  557. * @return void
  558. */
  559. public function resetOrderBy()
  560. {
  561. $this->rejectQuery(['orderBy', 'orderByDesc']);
  562. }
  563. /**
  564. * @param string $method
  565. * @param array $arguments
  566. *
  567. * @return $this
  568. */
  569. public function __call($method, $arguments)
  570. {
  571. return $this->addQuery($method, $arguments);
  572. }
  573. /**
  574. * @param string $method
  575. * @param array $arguments
  576. *
  577. * @return $this
  578. */
  579. public function addQuery(string $method, array $arguments = [])
  580. {
  581. $this->queries->push([
  582. 'method' => $method,
  583. 'arguments' => $arguments,
  584. ]);
  585. return $this;
  586. }
  587. /**
  588. * Set the relationships that should be eager loaded.
  589. *
  590. * @param mixed $relations
  591. *
  592. * @return $this|Model
  593. */
  594. public function with($relations)
  595. {
  596. if (is_array($relations)) {
  597. if (Arr::isAssoc($relations)) {
  598. $relations = array_keys($relations);
  599. }
  600. $this->eagerLoads = array_merge($this->eagerLoads, $relations);
  601. }
  602. if (is_string($relations)) {
  603. if (Str::contains($relations, '.')) {
  604. $relations = explode('.', $relations)[0];
  605. }
  606. if (Str::contains($relations, ':')) {
  607. $relations = explode(':', $relations)[0];
  608. }
  609. if (in_array($relations, $this->eagerLoads)) {
  610. return $this;
  611. }
  612. $this->eagerLoads[] = $relations;
  613. }
  614. return $this->addQuery('with', (array) $relations);
  615. }
  616. /**
  617. * @return void
  618. */
  619. public function reset()
  620. {
  621. $this->data = null;
  622. $this->model = null;
  623. $this->initQueries();
  624. }
  625. }