Model.php 14 KB

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