Model.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706
  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->queries = collect();
  121. }
  122. /**
  123. * @return Repository|null
  124. */
  125. public function repository()
  126. {
  127. return $this->repository;
  128. }
  129. /**
  130. * @return Collection
  131. */
  132. public function getQueries()
  133. {
  134. return $this->queries = $this->queries->unique();
  135. }
  136. /**
  137. * @param Collection $query
  138. *
  139. * @return void
  140. */
  141. public function setQueries(Collection $query)
  142. {
  143. $this->queries = $query;
  144. }
  145. /**
  146. * @return AbstractPaginator|LengthAwarePaginator
  147. */
  148. public function paginator(): AbstractPaginator
  149. {
  150. $this->buildData();
  151. return $this->paginator;
  152. }
  153. /**
  154. * @param int $total
  155. * @param Collection|array $data
  156. *
  157. * @return LengthAwarePaginator
  158. */
  159. public function makePaginator($total, $data, string $url = null)
  160. {
  161. $paginator = new LengthAwarePaginator(
  162. $data,
  163. $total,
  164. $this->getPerPage(), // 传入每页显示行数
  165. $this->getCurrentPage() // 传入当前页码
  166. );
  167. return $paginator->setPath(
  168. $url ?: url()->current()
  169. );
  170. }
  171. /**
  172. * Get primary key name of model.
  173. *
  174. * @return string
  175. */
  176. public function getKeyName()
  177. {
  178. return $this->grid->getKeyName();
  179. }
  180. /**
  181. * Enable or disable pagination.
  182. *
  183. * @param bool $use
  184. */
  185. public function usePaginate($use = true)
  186. {
  187. $this->usePaginate = $use;
  188. }
  189. /**
  190. * @return bool
  191. */
  192. public function allowPagination()
  193. {
  194. return $this->usePaginate;
  195. }
  196. /**
  197. * Get the query string variable used to store the per-page.
  198. *
  199. * @return string
  200. */
  201. public function getPerPageName()
  202. {
  203. return $this->perPageName;
  204. }
  205. /**
  206. * Set the query string variable used to store the per-page.
  207. *
  208. * @param string $name
  209. *
  210. * @return $this
  211. */
  212. public function setPerPageName($name)
  213. {
  214. $this->perPageName = $name;
  215. return $this;
  216. }
  217. /**
  218. * @param int $perPage
  219. */
  220. public function setPerPage(int $perPage)
  221. {
  222. $this->perPage = $perPage;
  223. return $this;
  224. }
  225. /**
  226. * @param string $pageName
  227. */
  228. public function setPageName(string $pageName)
  229. {
  230. $this->pageName = $pageName;
  231. return $this;
  232. }
  233. /**
  234. * @return string
  235. */
  236. public function getPageName()
  237. {
  238. return $this->pageName;
  239. }
  240. /**
  241. * Get the query string variable used to store the sort.
  242. *
  243. * @return string
  244. */
  245. public function getSortName()
  246. {
  247. return $this->sortName;
  248. }
  249. /**
  250. * Set the query string variable used to store the sort.
  251. *
  252. * @param string $name
  253. *
  254. * @return $this
  255. */
  256. public function setSortName($name)
  257. {
  258. $this->sortName = $name;
  259. return $this;
  260. }
  261. /**
  262. * Set parent grid instance.
  263. *
  264. * @param Grid $grid
  265. *
  266. * @return $this
  267. */
  268. public function setGrid(Grid $grid)
  269. {
  270. $this->grid = $grid;
  271. return $this;
  272. }
  273. /**
  274. * Get parent gird instance.
  275. *
  276. * @return Grid
  277. */
  278. public function grid()
  279. {
  280. return $this->grid;
  281. }
  282. /**
  283. * Get filter of Grid.
  284. *
  285. * @return Filter
  286. */
  287. public function filter()
  288. {
  289. return $this->grid->filter();
  290. }
  291. /**
  292. * Get constraints.
  293. *
  294. * @return array|bool
  295. */
  296. public function getConstraints()
  297. {
  298. return $this->constraints;
  299. }
  300. /**
  301. * @param array $constraints
  302. *
  303. * @return $this
  304. */
  305. public function setConstraints(array $constraints)
  306. {
  307. $this->constraints = $constraints;
  308. return $this;
  309. }
  310. /**
  311. * Set collection callback.
  312. *
  313. * @param callable $callback
  314. *
  315. * @return $this
  316. */
  317. public function collection(callable $callback = null)
  318. {
  319. $this->collectionCallback[] = $callback;
  320. return $this;
  321. }
  322. /**
  323. * Build.
  324. *
  325. * @param bool $toArray
  326. *
  327. * @return array|Collection|mixed
  328. */
  329. public function buildData(bool $toArray = false)
  330. {
  331. if (is_null($this->data)) {
  332. $this->setData($this->fetch());
  333. if ($this->collectionCallback) {
  334. $data = $this->data;
  335. foreach ($this->collectionCallback as $cb) {
  336. $data = call_user_func($cb, $data);
  337. }
  338. $this->setData($data);
  339. }
  340. }
  341. return $toArray ? $this->data->toArray() : $this->data;
  342. }
  343. /**
  344. * @param Collection|callable|array|AbstractPaginator $data
  345. *
  346. * @return $this
  347. */
  348. public function setData($data)
  349. {
  350. if (is_callable($data)) {
  351. $this->builder = $data;
  352. return $this;
  353. }
  354. if ($data instanceof AbstractPaginator) {
  355. $this->setPaginator($data);
  356. $data = $data->getCollection();
  357. } elseif (is_array($data)) {
  358. $data = collect($data);
  359. } elseif ($data instanceof Arrayable) {
  360. $data = collect($data->toArray());
  361. }
  362. if ($data instanceof Collection) {
  363. $this->data = $data;
  364. } else {
  365. $this->data = collect();
  366. }
  367. return $this;
  368. }
  369. /**
  370. * Add conditions to grid model.
  371. *
  372. * @param array $conditions
  373. *
  374. * @return $this
  375. */
  376. public function addConditions(array $conditions)
  377. {
  378. foreach ($conditions as $condition) {
  379. call_user_func_array([$this, key($condition)], current($condition));
  380. }
  381. return $this;
  382. }
  383. /**
  384. * @throws \Exception
  385. *
  386. * @return Collection|array
  387. */
  388. protected function fetch()
  389. {
  390. if ($this->paginator) {
  391. return $this->paginator->getCollection();
  392. }
  393. if ($this->builder && is_callable($this->builder)) {
  394. $results = call_user_func($this->builder, $this);
  395. } else {
  396. $results = $this->repository->get($this);
  397. }
  398. if (is_array($results) || $results instanceof Collection) {
  399. return $results;
  400. }
  401. if ($results instanceof AbstractPaginator) {
  402. $this->setPaginator($results);
  403. return $results->getCollection();
  404. }
  405. throw new \Exception('Grid query error');
  406. }
  407. /**
  408. * @param AbstractPaginator $paginator
  409. *
  410. * @return void
  411. */
  412. protected function setPaginator(AbstractPaginator $paginator)
  413. {
  414. $this->paginator = $paginator;
  415. $paginator->setPageName($this->pageName);
  416. }
  417. /**
  418. * If current page is greater than last page, then redirect to last page.
  419. *
  420. * @param LengthAwarePaginator $paginator
  421. *
  422. * @return void
  423. */
  424. protected function handleInvalidPage(LengthAwarePaginator $paginator)
  425. {
  426. if (
  427. $this->usePaginate
  428. && $paginator->lastPage()
  429. && $paginator->currentPage() > $paginator->lastPage()
  430. ) {
  431. $lastPageUrl = $this->request->fullUrlWithQuery([
  432. $paginator->getPageName() => $paginator->lastPage(),
  433. ]);
  434. Pjax::respond(redirect($lastPageUrl));
  435. }
  436. }
  437. /**
  438. * Get current page.
  439. *
  440. * @return int|null
  441. */
  442. public function getCurrentPage()
  443. {
  444. if (! $this->usePaginate) {
  445. return;
  446. }
  447. return $this->currentPage ?: ($this->currentPage = ($this->request->get($this->pageName) ?: 1));
  448. }
  449. /**
  450. * @param int $currentPage
  451. */
  452. public function setCurrentPage(int $currentPage)
  453. {
  454. $this->currentPage = $currentPage;
  455. return $this;
  456. }
  457. /**
  458. * Get items number of per page.
  459. *
  460. * @return int|null
  461. */
  462. public function getPerPage()
  463. {
  464. if (! $this->usePaginate) {
  465. return;
  466. }
  467. return $this->request->get($this->perPageName) ?: $this->perPage;
  468. }
  469. /**
  470. * Find query by method name.
  471. *
  472. * @param $method
  473. *
  474. * @return static
  475. */
  476. public function findQueryByMethod($method)
  477. {
  478. return $this->queries->first(function ($query) use ($method) {
  479. return $query['method'] == $method;
  480. });
  481. }
  482. /**
  483. * @param string|callable $method
  484. *
  485. * @return $this
  486. */
  487. public function filterQueryBy($method)
  488. {
  489. $this->queries = $this->queries->filter(function ($query, $k) use ($method) {
  490. if (
  491. (is_string($method) && $query['method'] === $method)
  492. || (is_array($method) && in_array($query['method'], $method, true))
  493. ) {
  494. return false;
  495. }
  496. if (is_callable($method)) {
  497. return call_user_func($method, $query, $k);
  498. }
  499. return true;
  500. });
  501. return $this;
  502. }
  503. /**
  504. * Get the grid sort.
  505. *
  506. * @return array exp: ['name', 'desc']
  507. */
  508. public function getSort()
  509. {
  510. if (empty($this->sort)) {
  511. $this->sort = $this->request->get($this->getSortName());
  512. }
  513. if (empty($this->sort['column']) || empty($this->sort['type'])) {
  514. return [null, null];
  515. }
  516. return [$this->sort['column'], $this->sort['type']];
  517. }
  518. /**
  519. * @param string|array $method
  520. *
  521. * @return void
  522. */
  523. public function rejectQuery($method)
  524. {
  525. $this->queries = $this->queries->reject(function ($query) use ($method) {
  526. if (is_callable($method)) {
  527. return call_user_func($method, $query);
  528. }
  529. return in_array($query['method'], (array) $method, true);
  530. });
  531. }
  532. /**
  533. * Reset orderBy query.
  534. *
  535. * @return void
  536. */
  537. public function resetOrderBy()
  538. {
  539. $this->rejectQuery(['orderBy', 'orderByDesc']);
  540. }
  541. /**
  542. * @param string $method
  543. * @param array $arguments
  544. *
  545. * @return $this
  546. */
  547. public function __call($method, $arguments)
  548. {
  549. return $this->addQuery($method, $arguments);
  550. }
  551. /**
  552. * @param string $method
  553. * @param array $arguments
  554. *
  555. * @return $this
  556. */
  557. public function addQuery(string $method, array $arguments = [])
  558. {
  559. $this->queries->push([
  560. 'method' => $method,
  561. 'arguments' => $arguments,
  562. ]);
  563. return $this;
  564. }
  565. /**
  566. * Set the relationships that should be eager loaded.
  567. *
  568. * @param mixed $relations
  569. *
  570. * @return $this|Model
  571. */
  572. public function with($relations)
  573. {
  574. if (is_array($relations)) {
  575. if (Arr::isAssoc($relations)) {
  576. $relations = array_keys($relations);
  577. }
  578. $this->eagerLoads = array_merge($this->eagerLoads, $relations);
  579. }
  580. if (is_string($relations)) {
  581. if (Str::contains($relations, '.')) {
  582. $relations = explode('.', $relations)[0];
  583. }
  584. if (Str::contains($relations, ':')) {
  585. $relations = explode(':', $relations)[0];
  586. }
  587. if (in_array($relations, $this->eagerLoads)) {
  588. return $this;
  589. }
  590. $this->eagerLoads[] = $relations;
  591. }
  592. return $this->addQuery('with', (array) $relations);
  593. }
  594. /**
  595. * @return void
  596. */
  597. public function reset()
  598. {
  599. $this->data = null;
  600. $this->model = null;
  601. }
  602. }