Model.php 15 KB

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