Model.php 14 KB

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