Model.php 15 KB

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