Model.php 14 KB

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