Model.php 13 KB

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