Model.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724
  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. $this->stdObjToArray($this->data);
  368. return $this;
  369. }
  370. /**
  371. * Add conditions to grid model.
  372. *
  373. * @param array $conditions
  374. *
  375. * @return $this
  376. */
  377. public function addConditions(array $conditions)
  378. {
  379. foreach ($conditions as $condition) {
  380. call_user_func_array([$this, key($condition)], current($condition));
  381. }
  382. return $this;
  383. }
  384. /**
  385. * @throws \Exception
  386. *
  387. * @return Collection|array
  388. */
  389. protected function fetch()
  390. {
  391. if ($this->paginator) {
  392. return $this->paginator->getCollection();
  393. }
  394. if ($this->builder && is_callable($this->builder)) {
  395. $results = call_user_func($this->builder, $this);
  396. } else {
  397. $results = $this->repository->get($this);
  398. }
  399. if (is_array($results) || $results instanceof Collection) {
  400. return $results;
  401. }
  402. if ($results instanceof AbstractPaginator) {
  403. $this->setPaginator($results);
  404. return $results->getCollection();
  405. }
  406. throw new \Exception('Grid query error');
  407. }
  408. /**
  409. * @param AbstractPaginator $paginator
  410. *
  411. * @return void
  412. */
  413. protected function setPaginator(AbstractPaginator $paginator)
  414. {
  415. $this->paginator = $paginator;
  416. $paginator->setPageName($this->pageName);
  417. }
  418. /**
  419. * @param Collection $collection
  420. *
  421. * @return Collection
  422. */
  423. protected function stdObjToArray(Collection $collection)
  424. {
  425. return $collection->transform(function ($item) {
  426. if ($item instanceof \stdClass) {
  427. return (array) $item;
  428. }
  429. return $item;
  430. });
  431. }
  432. /**
  433. * If current page is greater than last page, then redirect to last page.
  434. *
  435. * @param LengthAwarePaginator $paginator
  436. *
  437. * @return void
  438. */
  439. protected function handleInvalidPage(LengthAwarePaginator $paginator)
  440. {
  441. if (
  442. $this->usePaginate
  443. && $paginator->lastPage()
  444. && $paginator->currentPage() > $paginator->lastPage()
  445. ) {
  446. $lastPageUrl = $this->request->fullUrlWithQuery([
  447. $paginator->getPageName() => $paginator->lastPage(),
  448. ]);
  449. Pjax::respond(redirect($lastPageUrl));
  450. }
  451. }
  452. /**
  453. * Get current page.
  454. *
  455. * @return int|null
  456. */
  457. public function getCurrentPage()
  458. {
  459. if (! $this->usePaginate) {
  460. return;
  461. }
  462. return $this->currentPage ?: ($this->currentPage = ($this->request->get($this->pageName) ?: 1));
  463. }
  464. /**
  465. * @param int $currentPage
  466. */
  467. public function setCurrentPage(int $currentPage)
  468. {
  469. $this->currentPage = $currentPage;
  470. return $this;
  471. }
  472. /**
  473. * Get items number of per page.
  474. *
  475. * @return int|null
  476. */
  477. public function getPerPage()
  478. {
  479. if (! $this->usePaginate) {
  480. return;
  481. }
  482. return $this->request->get($this->perPageName) ?: $this->perPage;
  483. }
  484. /**
  485. * Find query by method name.
  486. *
  487. * @param $method
  488. *
  489. * @return static
  490. */
  491. public function findQueryByMethod($method)
  492. {
  493. return $this->queries->first(function ($query) use ($method) {
  494. return $query['method'] == $method;
  495. });
  496. }
  497. /**
  498. * @param string|callable $method
  499. *
  500. * @return $this
  501. */
  502. public function filterQueryBy($method)
  503. {
  504. $this->queries = $this->queries->filter(function ($query, $k) use ($method) {
  505. if (
  506. (is_string($method) && $query['method'] === $method)
  507. || (is_array($method) && in_array($query['method'], $method, true))
  508. ) {
  509. return false;
  510. }
  511. if (is_callable($method)) {
  512. return call_user_func($method, $query, $k);
  513. }
  514. return true;
  515. });
  516. return $this;
  517. }
  518. /**
  519. * Get the grid sort.
  520. *
  521. * @return array exp: ['name', 'desc']
  522. */
  523. public function getSort()
  524. {
  525. if (empty($this->sort)) {
  526. $this->sort = $this->request->get($this->getSortName());
  527. }
  528. if (empty($this->sort['column']) || empty($this->sort['type'])) {
  529. return [null, null];
  530. }
  531. return [$this->sort['column'], $this->sort['type']];
  532. }
  533. /**
  534. * @param string|array $method
  535. *
  536. * @return void
  537. */
  538. public function rejectQuery($method)
  539. {
  540. $this->queries = $this->queries->reject(function ($query) use ($method) {
  541. if (is_callable($method)) {
  542. return call_user_func($method, $query);
  543. }
  544. return in_array($query['method'], (array) $method, true);
  545. });
  546. }
  547. /**
  548. * Reset orderBy query.
  549. *
  550. * @return void
  551. */
  552. public function resetOrderBy()
  553. {
  554. $this->rejectQuery(['orderBy', 'orderByDesc']);
  555. }
  556. /**
  557. * @param string $method
  558. * @param array $arguments
  559. *
  560. * @return $this
  561. */
  562. public function __call($method, $arguments)
  563. {
  564. return $this->addQuery($method, $arguments);
  565. }
  566. /**
  567. * @param string $method
  568. * @param array $arguments
  569. *
  570. * @return $this
  571. */
  572. public function addQuery(string $method, array $arguments = [])
  573. {
  574. $this->queries->push([
  575. 'method' => $method,
  576. 'arguments' => $arguments,
  577. ]);
  578. return $this;
  579. }
  580. /**
  581. * Set the relationships that should be eager loaded.
  582. *
  583. * @param mixed $relations
  584. *
  585. * @return $this|Model
  586. */
  587. public function with($relations)
  588. {
  589. if (is_array($relations)) {
  590. if (Arr::isAssoc($relations)) {
  591. $relations = array_keys($relations);
  592. }
  593. $this->eagerLoads = array_merge($this->eagerLoads, $relations);
  594. }
  595. if (is_string($relations)) {
  596. if (Str::contains($relations, '.')) {
  597. $relations = explode('.', $relations)[0];
  598. }
  599. if (Str::contains($relations, ':')) {
  600. $relations = explode(':', $relations)[0];
  601. }
  602. if (in_array($relations, $this->eagerLoads)) {
  603. return $this;
  604. }
  605. $this->eagerLoads[] = $relations;
  606. }
  607. return $this->addQuery('with', (array) $relations);
  608. }
  609. /**
  610. * @return void
  611. */
  612. public function reset()
  613. {
  614. $this->data = null;
  615. $this->model = null;
  616. }
  617. }