PaginatorHelper.php 44 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279
  1. <?php
  2. /**
  3. * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
  4. * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
  5. *
  6. * Licensed under The MIT License
  7. * For full copyright and license information, please see the LICENSE.txt
  8. * Redistributions of files must retain the above copyright notice.
  9. *
  10. * @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
  11. * @link https://cakephp.org CakePHP(tm) Project
  12. * @since 1.2.0
  13. * @license https://opensource.org/licenses/mit-license.php MIT License
  14. */
  15. namespace Cake\View\Helper;
  16. use Cake\Utility\Hash;
  17. use Cake\Utility\Inflector;
  18. use Cake\View\Helper;
  19. use Cake\View\StringTemplateTrait;
  20. use Cake\View\View;
  21. /**
  22. * Pagination Helper class for easy generation of pagination links.
  23. *
  24. * PaginationHelper encloses all methods needed when working with pagination.
  25. *
  26. * @property \Cake\View\Helper\UrlHelper $Url
  27. * @property \Cake\View\Helper\NumberHelper $Number
  28. * @property \Cake\View\Helper\HtmlHelper $Html
  29. * @property \Cake\View\Helper\FormHelper $Form
  30. * @link https://book.cakephp.org/3.0/en/views/helpers/paginator.html
  31. */
  32. class PaginatorHelper extends Helper
  33. {
  34. use StringTemplateTrait;
  35. /**
  36. * List of helpers used by this helper
  37. *
  38. * @var array
  39. */
  40. public $helpers = ['Url', 'Number', 'Html', 'Form'];
  41. /**
  42. * Default config for this class
  43. *
  44. * Options: Holds the default options for pagination links
  45. *
  46. * The values that may be specified are:
  47. *
  48. * - `url` Url of the action. See Router::url()
  49. * - `url['sort']` the key that the recordset is sorted.
  50. * - `url['direction']` Direction of the sorting (default: 'asc').
  51. * - `url['page']` Page number to use in links.
  52. * - `model` The name of the model.
  53. * - `escape` Defines if the title field for the link should be escaped (default: true).
  54. *
  55. * Templates: the templates used by this class
  56. *
  57. * @var array
  58. */
  59. protected $_defaultConfig = [
  60. 'options' => [],
  61. 'templates' => [
  62. 'nextActive' => '<li class="next"><a rel="next" href="{{url}}">{{text}}</a></li>',
  63. 'nextDisabled' => '<li class="next disabled"><a href="" onclick="return false;">{{text}}</a></li>',
  64. 'prevActive' => '<li class="prev"><a rel="prev" href="{{url}}">{{text}}</a></li>',
  65. 'prevDisabled' => '<li class="prev disabled"><a href="" onclick="return false;">{{text}}</a></li>',
  66. 'counterRange' => '{{start}} - {{end}} of {{count}}',
  67. 'counterPages' => '{{page}} of {{pages}}',
  68. 'first' => '<li class="first"><a href="{{url}}">{{text}}</a></li>',
  69. 'last' => '<li class="last"><a href="{{url}}">{{text}}</a></li>',
  70. 'number' => '<li><a href="{{url}}">{{text}}</a></li>',
  71. 'current' => '<li class="active"><a href="">{{text}}</a></li>',
  72. 'ellipsis' => '<li class="ellipsis">&hellip;</li>',
  73. 'sort' => '<a href="{{url}}">{{text}}</a>',
  74. 'sortAsc' => '<a class="asc" href="{{url}}">{{text}}</a>',
  75. 'sortDesc' => '<a class="desc" href="{{url}}">{{text}}</a>',
  76. 'sortAscLocked' => '<a class="asc locked" href="{{url}}">{{text}}</a>',
  77. 'sortDescLocked' => '<a class="desc locked" href="{{url}}">{{text}}</a>',
  78. ]
  79. ];
  80. /**
  81. * Default model of the paged sets
  82. *
  83. * @var string
  84. */
  85. protected $_defaultModel;
  86. /**
  87. * Constructor. Overridden to merge passed args with URL options.
  88. *
  89. * @param \Cake\View\View $View The View this helper is being attached to.
  90. * @param array $config Configuration settings for the helper.
  91. */
  92. public function __construct(View $View, array $config = [])
  93. {
  94. parent::__construct($View, $config);
  95. $query = $this->_View->getRequest()->getQueryParams();
  96. unset($query['page'], $query['limit'], $query['sort'], $query['direction']);
  97. $this->setConfig(
  98. 'options.url',
  99. array_merge($this->_View->getRequest()->getParam('pass', []), ['?' => $query])
  100. );
  101. }
  102. /**
  103. * Gets the current paging parameters from the resultset for the given model
  104. *
  105. * @param string|null $model Optional model name. Uses the default if none is specified.
  106. * @return array The array of paging parameters for the paginated resultset.
  107. */
  108. public function params($model = null)
  109. {
  110. $request = $this->_View->getRequest();
  111. if (empty($model)) {
  112. $model = $this->defaultModel();
  113. }
  114. if (!$request->getParam('paging') || !$request->getParam('paging.' . $model)) {
  115. return [];
  116. }
  117. return $request->getParam('paging.' . $model);
  118. }
  119. /**
  120. * Convenience access to any of the paginator params.
  121. *
  122. * @param string $key Key of the paginator params array to retrieve.
  123. * @param string|null $model Optional model name. Uses the default if none is specified.
  124. * @return mixed Content of the requested param.
  125. */
  126. public function param($key, $model = null)
  127. {
  128. $params = $this->params($model);
  129. if (!isset($params[$key])) {
  130. return null;
  131. }
  132. return $params[$key];
  133. }
  134. /**
  135. * Sets default options for all pagination links
  136. *
  137. * @param array $options Default options for pagination links.
  138. * See PaginatorHelper::$options for list of keys.
  139. * @return void
  140. */
  141. public function options(array $options = [])
  142. {
  143. $request = $this->_View->getRequest();
  144. if (!empty($options['paging'])) {
  145. $request = $request->withParam(
  146. 'paging',
  147. $options['paging'] + $request->getParam('paging', [])
  148. );
  149. unset($options['paging']);
  150. }
  151. $model = $this->defaultModel();
  152. if (!empty($options[$model])) {
  153. $request = $request->withParam(
  154. 'paging.' . $model,
  155. $options[$model] + (array)$request->getParam('paging.' . $model, [])
  156. );
  157. unset($options[$model]);
  158. }
  159. $this->_View->setRequest($request);
  160. $this->_config['options'] = array_filter($options + $this->_config['options']);
  161. if (empty($this->_config['options']['url'])) {
  162. $this->_config['options']['url'] = [];
  163. }
  164. if (!empty($this->_config['options']['model'])) {
  165. $this->defaultModel($this->_config['options']['model']);
  166. }
  167. }
  168. /**
  169. * Gets the current page of the recordset for the given model
  170. *
  171. * @param string|null $model Optional model name. Uses the default if none is specified.
  172. * @return int The current page number of the recordset.
  173. * @link https://book.cakephp.org/3.0/en/views/helpers/paginator.html#checking-the-pagination-state
  174. */
  175. public function current($model = null)
  176. {
  177. $params = $this->params($model);
  178. if (isset($params['page'])) {
  179. return $params['page'];
  180. }
  181. return 1;
  182. }
  183. /**
  184. * Gets the total number of pages in the recordset for the given model.
  185. *
  186. * @param string|null $model Optional model name. Uses the default if none is specified.
  187. * @return int The total pages for the recordset.
  188. */
  189. public function total($model = null)
  190. {
  191. $params = $this->params($model);
  192. if (isset($params['pageCount'])) {
  193. return $params['pageCount'];
  194. }
  195. return 0;
  196. }
  197. /**
  198. * Gets the current key by which the recordset is sorted
  199. *
  200. * @param string|null $model Optional model name. Uses the default if none is specified.
  201. * @param array $options Options for pagination links. See #options for list of keys.
  202. * @return string|null The name of the key by which the recordset is being sorted, or
  203. * null if the results are not currently sorted.
  204. * @link https://book.cakephp.org/3.0/en/views/helpers/paginator.html#creating-sort-links
  205. */
  206. public function sortKey($model = null, array $options = [])
  207. {
  208. if (empty($options)) {
  209. $options = $this->params($model);
  210. }
  211. if (!empty($options['sort'])) {
  212. return $options['sort'];
  213. }
  214. return null;
  215. }
  216. /**
  217. * Gets the current direction the recordset is sorted
  218. *
  219. * @param string|null $model Optional model name. Uses the default if none is specified.
  220. * @param array $options Options for pagination links. See #options for list of keys.
  221. * @return string The direction by which the recordset is being sorted, or
  222. * null if the results are not currently sorted.
  223. * @link https://book.cakephp.org/3.0/en/views/helpers/paginator.html#creating-sort-links
  224. */
  225. public function sortDir($model = null, array $options = [])
  226. {
  227. $dir = null;
  228. if (empty($options)) {
  229. $options = $this->params($model);
  230. }
  231. if (isset($options['direction'])) {
  232. $dir = strtolower($options['direction']);
  233. }
  234. if ($dir === 'desc') {
  235. return 'desc';
  236. }
  237. return 'asc';
  238. }
  239. /**
  240. * Generate an active/inactive link for next/prev methods.
  241. *
  242. * @param string|bool $text The enabled text for the link.
  243. * @param bool $enabled Whether or not the enabled/disabled version should be created.
  244. * @param array $options An array of options from the calling method.
  245. * @param array $templates An array of templates with the 'active' and 'disabled' keys.
  246. * @return string Generated HTML
  247. */
  248. protected function _toggledLink($text, $enabled, $options, $templates)
  249. {
  250. $template = $templates['active'];
  251. if (!$enabled) {
  252. $text = $options['disabledTitle'];
  253. $template = $templates['disabled'];
  254. }
  255. if (!$enabled && $text === false) {
  256. return '';
  257. }
  258. $text = $options['escape'] ? h($text) : $text;
  259. $templater = $this->templater();
  260. $newTemplates = !empty($options['templates']) ? $options['templates'] : false;
  261. if ($newTemplates) {
  262. $templater->push();
  263. $templateMethod = is_string($options['templates']) ? 'load' : 'add';
  264. $templater->{$templateMethod}($options['templates']);
  265. }
  266. if (!$enabled) {
  267. $out = $templater->format($template, [
  268. 'text' => $text,
  269. ]);
  270. if ($newTemplates) {
  271. $templater->pop();
  272. }
  273. return $out;
  274. }
  275. $paging = $this->params($options['model']);
  276. $url = array_merge(
  277. $options['url'],
  278. ['page' => $paging['page'] + $options['step']]
  279. );
  280. $url = $this->generateUrl($url, $options['model']);
  281. $out = $templater->format($template, [
  282. 'url' => $url,
  283. 'text' => $text,
  284. ]);
  285. if ($newTemplates) {
  286. $templater->pop();
  287. }
  288. return $out;
  289. }
  290. /**
  291. * Generates a "previous" link for a set of paged records
  292. *
  293. * ### Options:
  294. *
  295. * - `disabledTitle` The text to used when the link is disabled. This
  296. * defaults to the same text at the active link. Setting to false will cause
  297. * this method to return ''.
  298. * - `escape` Whether you want the contents html entity encoded, defaults to true
  299. * - `model` The model to use, defaults to PaginatorHelper::defaultModel()
  300. * - `url` An array of additional URL options to use for link generation.
  301. * - `templates` An array of templates, or template file name containing the
  302. * templates you'd like to use when generating the link for previous page.
  303. * The helper's original templates will be restored once prev() is done.
  304. *
  305. * @param string $title Title for the link. Defaults to '<< Previous'.
  306. * @param array $options Options for pagination link. See above for list of keys.
  307. * @return string A "previous" link or a disabled link.
  308. * @link https://book.cakephp.org/3.0/en/views/helpers/paginator.html#creating-jump-links
  309. */
  310. public function prev($title = '<< Previous', array $options = [])
  311. {
  312. $defaults = [
  313. 'url' => [],
  314. 'model' => $this->defaultModel(),
  315. 'disabledTitle' => $title,
  316. 'escape' => true,
  317. ];
  318. $options += $defaults;
  319. $options['step'] = -1;
  320. $enabled = $this->hasPrev($options['model']);
  321. $templates = [
  322. 'active' => 'prevActive',
  323. 'disabled' => 'prevDisabled'
  324. ];
  325. return $this->_toggledLink($title, $enabled, $options, $templates);
  326. }
  327. /**
  328. * Generates a "next" link for a set of paged records
  329. *
  330. * ### Options:
  331. *
  332. * - `disabledTitle` The text to used when the link is disabled. This
  333. * defaults to the same text at the active link. Setting to false will cause
  334. * this method to return ''.
  335. * - `escape` Whether you want the contents html entity encoded, defaults to true
  336. * - `model` The model to use, defaults to PaginatorHelper::defaultModel()
  337. * - `url` An array of additional URL options to use for link generation.
  338. * - `templates` An array of templates, or template file name containing the
  339. * templates you'd like to use when generating the link for next page.
  340. * The helper's original templates will be restored once next() is done.
  341. *
  342. * @param string $title Title for the link. Defaults to 'Next >>'.
  343. * @param array $options Options for pagination link. See above for list of keys.
  344. * @return string A "next" link or $disabledTitle text if the link is disabled.
  345. * @link https://book.cakephp.org/3.0/en/views/helpers/paginator.html#creating-jump-links
  346. */
  347. public function next($title = 'Next >>', array $options = [])
  348. {
  349. $defaults = [
  350. 'url' => [],
  351. 'model' => $this->defaultModel(),
  352. 'disabledTitle' => $title,
  353. 'escape' => true,
  354. ];
  355. $options += $defaults;
  356. $options['step'] = 1;
  357. $enabled = $this->hasNext($options['model']);
  358. $templates = [
  359. 'active' => 'nextActive',
  360. 'disabled' => 'nextDisabled'
  361. ];
  362. return $this->_toggledLink($title, $enabled, $options, $templates);
  363. }
  364. /**
  365. * Generates a sorting link. Sets named parameters for the sort and direction. Handles
  366. * direction switching automatically.
  367. *
  368. * ### Options:
  369. *
  370. * - `escape` Whether you want the contents html entity encoded, defaults to true.
  371. * - `model` The model to use, defaults to PaginatorHelper::defaultModel().
  372. * - `direction` The default direction to use when this link isn't active.
  373. * - `lock` Lock direction. Will only use the default direction then, defaults to false.
  374. *
  375. * @param string $key The name of the key that the recordset should be sorted.
  376. * @param string|null $title Title for the link. If $title is null $key will be used
  377. * for the title and will be generated by inflection.
  378. * @param array $options Options for sorting link. See above for list of keys.
  379. * @return string A link sorting default by 'asc'. If the resultset is sorted 'asc' by the specified
  380. * key the returned link will sort by 'desc'.
  381. * @link https://book.cakephp.org/3.0/en/views/helpers/paginator.html#creating-sort-links
  382. */
  383. public function sort($key, $title = null, array $options = [])
  384. {
  385. $options += ['url' => [], 'model' => null, 'escape' => true];
  386. $url = $options['url'];
  387. unset($options['url']);
  388. if (empty($title)) {
  389. $title = $key;
  390. if (strpos($title, '.') !== false) {
  391. $title = str_replace('.', ' ', $title);
  392. }
  393. $title = __(Inflector::humanize(preg_replace('/_id$/', '', $title)));
  394. }
  395. $defaultDir = isset($options['direction']) ? strtolower($options['direction']) : 'asc';
  396. unset($options['direction']);
  397. $locked = isset($options['lock']) ? $options['lock'] : false;
  398. unset($options['lock']);
  399. $sortKey = $this->sortKey($options['model']);
  400. $defaultModel = $this->defaultModel();
  401. $model = $options['model'] ?: $defaultModel;
  402. list($table, $field) = explode('.', $key . '.');
  403. if (!$field) {
  404. $field = $table;
  405. $table = $model;
  406. }
  407. $isSorted = (
  408. $sortKey === $table . '.' . $field ||
  409. $sortKey === $model . '.' . $key ||
  410. $table . '.' . $field === $model . '.' . $sortKey
  411. );
  412. $template = 'sort';
  413. $dir = $defaultDir;
  414. if ($isSorted) {
  415. if ($locked) {
  416. $template = $dir === 'asc' ? 'sortDescLocked' : 'sortAscLocked';
  417. } else {
  418. $dir = $this->sortDir($options['model']) === 'asc' ? 'desc' : 'asc';
  419. $template = $dir === 'asc' ? 'sortDesc' : 'sortAsc';
  420. }
  421. }
  422. if (is_array($title) && array_key_exists($dir, $title)) {
  423. $title = $title[$dir];
  424. }
  425. $url = array_merge(
  426. ['sort' => $key, 'direction' => $dir, 'page' => 1],
  427. $url,
  428. ['order' => null]
  429. );
  430. $vars = [
  431. 'text' => $options['escape'] ? h($title) : $title,
  432. 'url' => $this->generateUrl($url, $options['model']),
  433. ];
  434. return $this->templater()->format($template, $vars);
  435. }
  436. /**
  437. * Merges passed URL options with current pagination state to generate a pagination URL.
  438. *
  439. * ### Url options:
  440. *
  441. * - `escape`: If false, the URL will be returned unescaped, do only use if it is manually
  442. * escaped afterwards before being displayed.
  443. * - `fullBase`: If true, the full base URL will be prepended to the result
  444. *
  445. * @param array $options Pagination/URL options array
  446. * @param string|null $model Which model to paginate on
  447. * @param array $urlOptions Array of options
  448. * The bool version of this argument is *deprecated* and will be removed in 4.0.0
  449. * @return string By default, returns a full pagination URL string for use in non-standard contexts (i.e. JavaScript)
  450. * @link https://book.cakephp.org/3.0/en/views/helpers/paginator.html#generating-pagination-urls
  451. */
  452. public function generateUrl(array $options = [], $model = null, $urlOptions = [])
  453. {
  454. if (is_bool($urlOptions)) {
  455. $urlOptions = ['fullBase' => $urlOptions];
  456. deprecationWarning(
  457. 'Passing a boolean value as third argument into PaginatorHelper::generateUrl() is deprecated ' .
  458. 'and will be removed in 4.0.0 . ' .
  459. 'Pass an array instead.'
  460. );
  461. }
  462. $urlOptions += [
  463. 'escape' => true,
  464. 'fullBase' => false
  465. ];
  466. return $this->Url->build($this->generateUrlParams($options, $model), $urlOptions);
  467. }
  468. /**
  469. * Merges passed URL options with current pagination state to generate a pagination URL.
  470. *
  471. * @param array $options Pagination/URL options array
  472. * @param string|null $model Which model to paginate on
  473. * @return array An array of URL parameters
  474. */
  475. public function generateUrlParams(array $options = [], $model = null)
  476. {
  477. $paging = $this->params($model);
  478. $paging += ['page' => null, 'sort' => null, 'direction' => null, 'limit' => null];
  479. if (!empty($paging['sort']) && !empty($options['sort']) && strpos($options['sort'], '.') === false) {
  480. $paging['sort'] = $this->_removeAlias($paging['sort'], null);
  481. }
  482. if (!empty($paging['sortDefault']) && !empty($options['sort']) && strpos($options['sort'], '.') === false) {
  483. $paging['sortDefault'] = $this->_removeAlias($paging['sortDefault'], $model);
  484. }
  485. $url = [
  486. 'page' => $paging['page'],
  487. 'limit' => $paging['limit'],
  488. 'sort' => $paging['sort'],
  489. 'direction' => $paging['direction'],
  490. ];
  491. if (!empty($this->_config['options']['url'])) {
  492. $key = implode('.', array_filter(['options.url', Hash::get($paging, 'scope', null)]));
  493. $url = array_merge($url, Hash::get($this->_config, $key, []));
  494. }
  495. $url = array_filter($url, function ($value) {
  496. return ($value || is_numeric($value) || $value === false);
  497. });
  498. $url = array_merge($url, $options);
  499. if (!empty($url['page']) && $url['page'] == 1) {
  500. $url['page'] = false;
  501. }
  502. if (isset($paging['sortDefault'], $paging['directionDefault'], $url['sort'], $url['direction']) &&
  503. $url['sort'] === $paging['sortDefault'] &&
  504. strtolower($url['direction']) === strtolower($paging['directionDefault'])
  505. ) {
  506. $url['sort'] = $url['direction'] = null;
  507. }
  508. if (!empty($paging['scope'])) {
  509. $scope = $paging['scope'];
  510. $currentParams = $this->_config['options']['url'];
  511. if (isset($url['#'])) {
  512. $currentParams['#'] = $url['#'];
  513. unset($url['#']);
  514. }
  515. // Merge existing query parameters in the scope.
  516. if (isset($currentParams['?'][$scope]) && is_array($currentParams['?'][$scope])) {
  517. $url += $currentParams['?'][$scope];
  518. unset($currentParams['?'][$scope]);
  519. }
  520. $url = [$scope => $url] + $currentParams;
  521. if (empty($url[$scope]['page'])) {
  522. unset($url[$scope]['page']);
  523. }
  524. }
  525. return $url;
  526. }
  527. /**
  528. * Remove alias if needed.
  529. *
  530. * @param string $field Current field
  531. * @param string|null $model Current model alias
  532. * @return string Unaliased field if applicable
  533. */
  534. protected function _removeAlias($field, $model = null)
  535. {
  536. $currentModel = $model ?: $this->defaultModel();
  537. if (strpos($field, '.') === false) {
  538. return $field;
  539. }
  540. list ($alias, $currentField) = explode('.', $field);
  541. if ($alias === $currentModel) {
  542. return $currentField;
  543. }
  544. return $field;
  545. }
  546. /**
  547. * Returns true if the given result set is not at the first page
  548. *
  549. * @param string|null $model Optional model name. Uses the default if none is specified.
  550. * @return bool True if the result set is not at the first page.
  551. * @link https://book.cakephp.org/3.0/en/views/helpers/paginator.html#checking-the-pagination-state
  552. */
  553. public function hasPrev($model = null)
  554. {
  555. return $this->_hasPage($model, 'prev');
  556. }
  557. /**
  558. * Returns true if the given result set is not at the last page
  559. *
  560. * @param string|null $model Optional model name. Uses the default if none is specified.
  561. * @return bool True if the result set is not at the last page.
  562. * @link https://book.cakephp.org/3.0/en/views/helpers/paginator.html#checking-the-pagination-state
  563. */
  564. public function hasNext($model = null)
  565. {
  566. return $this->_hasPage($model, 'next');
  567. }
  568. /**
  569. * Returns true if the given result set has the page number given by $page
  570. *
  571. * @param string|null $model Optional model name. Uses the default if none is specified.
  572. * @param int $page The page number - if not set defaults to 1.
  573. * @return bool True if the given result set has the specified page number.
  574. * @link https://book.cakephp.org/3.0/en/views/helpers/paginator.html#checking-the-pagination-state
  575. */
  576. public function hasPage($model = null, $page = 1)
  577. {
  578. if (is_numeric($model)) {
  579. $page = $model;
  580. $model = null;
  581. }
  582. $paging = $this->params($model);
  583. if ($paging === []) {
  584. return false;
  585. }
  586. return $page <= $paging['pageCount'];
  587. }
  588. /**
  589. * Does $model have $page in its range?
  590. *
  591. * @param string $model Model name to get parameters for.
  592. * @param int $page Page number you are checking.
  593. * @return bool Whether model has $page
  594. */
  595. protected function _hasPage($model, $page)
  596. {
  597. $params = $this->params($model);
  598. return !empty($params) && $params[$page . 'Page'];
  599. }
  600. /**
  601. * Gets or sets the default model of the paged sets
  602. *
  603. * @param string|null $model Model name to set
  604. * @return string|null Model name or null if the pagination isn't initialized.
  605. */
  606. public function defaultModel($model = null)
  607. {
  608. if ($model !== null) {
  609. $this->_defaultModel = $model;
  610. }
  611. if ($this->_defaultModel) {
  612. return $this->_defaultModel;
  613. }
  614. if (!$this->_View->getRequest()->getParam('paging')) {
  615. return null;
  616. }
  617. list($this->_defaultModel) = array_keys($this->_View->getRequest()->getParam('paging'));
  618. return $this->_defaultModel;
  619. }
  620. /**
  621. * Returns a counter string for the paged result set
  622. *
  623. * ### Options
  624. *
  625. * - `model` The model to use, defaults to PaginatorHelper::defaultModel();
  626. * - `format` The format string you want to use, defaults to 'pages' Which generates output like '1 of 5'
  627. * set to 'range' to generate output like '1 - 3 of 13'. Can also be set to a custom string, containing
  628. * the following placeholders `{{page}}`, `{{pages}}`, `{{current}}`, `{{count}}`, `{{model}}`, `{{start}}`, `{{end}}` and any
  629. * custom content you would like.
  630. *
  631. * @param string|array $options Options for the counter string. See #options for list of keys.
  632. * If string it will be used as format.
  633. * @return string Counter string.
  634. * @link https://book.cakephp.org/3.0/en/views/helpers/paginator.html#creating-a-page-counter
  635. */
  636. public function counter($options = [])
  637. {
  638. if (is_string($options)) {
  639. $options = ['format' => $options];
  640. }
  641. $options += [
  642. 'model' => $this->defaultModel(),
  643. 'format' => 'pages',
  644. ];
  645. $paging = $this->params($options['model']);
  646. if (!$paging['pageCount']) {
  647. $paging['pageCount'] = 1;
  648. }
  649. switch ($options['format']) {
  650. case 'range':
  651. case 'pages':
  652. $template = 'counter' . ucfirst($options['format']);
  653. break;
  654. default:
  655. $template = 'counterCustom';
  656. $this->templater()->add([$template => $options['format']]);
  657. }
  658. $map = array_map([$this->Number, 'format'], [
  659. 'page' => $paging['page'],
  660. 'pages' => $paging['pageCount'],
  661. 'current' => $paging['current'],
  662. 'count' => $paging['count'],
  663. 'start' => $paging['start'],
  664. 'end' => $paging['end']
  665. ]);
  666. $map += [
  667. 'model' => strtolower(Inflector::humanize(Inflector::tableize($options['model'])))
  668. ];
  669. return $this->templater()->format($template, $map);
  670. }
  671. /**
  672. * Returns a set of numbers for the paged result set
  673. * uses a modulus to decide how many numbers to show on each side of the current page (default: 8).
  674. *
  675. * ```
  676. * $this->Paginator->numbers(['first' => 2, 'last' => 2]);
  677. * ```
  678. *
  679. * Using the first and last options you can create links to the beginning and end of the page set.
  680. *
  681. * ### Options
  682. *
  683. * - `before` Content to be inserted before the numbers, but after the first links.
  684. * - `after` Content to be inserted after the numbers, but before the last links.
  685. * - `model` Model to create numbers for, defaults to PaginatorHelper::defaultModel()
  686. * - `modulus` How many numbers to include on either side of the current page, defaults to 8.
  687. * Set to `false` to disable and to show all numbers.
  688. * - `first` Whether you want first links generated, set to an integer to define the number of 'first'
  689. * links to generate. If a string is set a link to the first page will be generated with the value
  690. * as the title.
  691. * - `last` Whether you want last links generated, set to an integer to define the number of 'last'
  692. * links to generate. If a string is set a link to the last page will be generated with the value
  693. * as the title.
  694. * - `templates` An array of templates, or template file name containing the templates you'd like to
  695. * use when generating the numbers. The helper's original templates will be restored once
  696. * numbers() is done.
  697. * - `url` An array of additional URL options to use for link generation.
  698. *
  699. * The generated number links will include the 'ellipsis' template when the `first` and `last` options
  700. * and the number of pages exceed the modulus. For example if you have 25 pages, and use the first/last
  701. * options and a modulus of 8, ellipsis content will be inserted after the first and last link sets.
  702. *
  703. * @param array $options Options for the numbers.
  704. * @return string|false Numbers string.
  705. * @link https://book.cakephp.org/3.0/en/views/helpers/paginator.html#creating-page-number-links
  706. */
  707. public function numbers(array $options = [])
  708. {
  709. $defaults = [
  710. 'before' => null, 'after' => null, 'model' => $this->defaultModel(),
  711. 'modulus' => 8, 'first' => null, 'last' => null, 'url' => []
  712. ];
  713. $options += $defaults;
  714. $params = (array)$this->params($options['model']) + ['page' => 1];
  715. if ($params['pageCount'] <= 1) {
  716. return false;
  717. }
  718. $templater = $this->templater();
  719. if (isset($options['templates'])) {
  720. $templater->push();
  721. $method = is_string($options['templates']) ? 'load' : 'add';
  722. $templater->{$method}($options['templates']);
  723. }
  724. if ($options['modulus'] !== false && $params['pageCount'] > $options['modulus']) {
  725. $out = $this->_modulusNumbers($templater, $params, $options);
  726. } else {
  727. $out = $this->_numbers($templater, $params, $options);
  728. }
  729. if (isset($options['templates'])) {
  730. $templater->pop();
  731. }
  732. return $out;
  733. }
  734. /**
  735. * Calculates the start and end for the pagination numbers.
  736. *
  737. * @param array $params Params from the numbers() method.
  738. * @param array $options Options from the numbers() method.
  739. * @return array An array with the start and end numbers.
  740. */
  741. protected function _getNumbersStartAndEnd($params, $options)
  742. {
  743. $half = (int)($options['modulus'] / 2);
  744. $end = max(1 + $options['modulus'], $params['page'] + $half);
  745. $start = min($params['pageCount'] - $options['modulus'], $params['page'] - $half - $options['modulus'] % 2);
  746. if ($options['first']) {
  747. $first = is_int($options['first']) ? $options['first'] : 1;
  748. if ($start <= $first + 2) {
  749. $start = 1;
  750. }
  751. }
  752. if ($options['last']) {
  753. $last = is_int($options['last']) ? $options['last'] : 1;
  754. if ($end >= $params['pageCount'] - $last - 1) {
  755. $end = $params['pageCount'];
  756. }
  757. }
  758. $end = min($params['pageCount'], $end);
  759. $start = max(1, $start);
  760. return [$start, $end];
  761. }
  762. /**
  763. * Formats a number for the paginator number output.
  764. *
  765. * @param \Cake\View\StringTemplate $templater StringTemplate instance.
  766. * @param array $options Options from the numbers() method.
  767. * @return string
  768. */
  769. protected function _formatNumber($templater, $options)
  770. {
  771. $url = array_merge($options['url'], ['page' => $options['page']]);
  772. $vars = [
  773. 'text' => $options['text'],
  774. 'url' => $this->generateUrl($url, $options['model']),
  775. ];
  776. return $templater->format('number', $vars);
  777. }
  778. /**
  779. * Generates the numbers for the paginator numbers() method.
  780. *
  781. * @param \Cake\View\StringTemplate $templater StringTemplate instance.
  782. * @param array $params Params from the numbers() method.
  783. * @param array $options Options from the numbers() method.
  784. * @return string Markup output.
  785. */
  786. protected function _modulusNumbers($templater, $params, $options)
  787. {
  788. $out = '';
  789. $ellipsis = $templater->format('ellipsis', []);
  790. list($start, $end) = $this->_getNumbersStartAndEnd($params, $options);
  791. $out .= $this->_firstNumber($ellipsis, $params, $start, $options);
  792. $out .= $options['before'];
  793. for ($i = $start; $i < $params['page']; $i++) {
  794. $out .= $this->_formatNumber($templater, [
  795. 'text' => $this->Number->format($i),
  796. 'page' => $i,
  797. 'model' => $options['model'],
  798. 'url' => $options['url'],
  799. ]);
  800. }
  801. $url = array_merge($options['url'], ['page' => $params['page']]);
  802. $out .= $templater->format('current', [
  803. 'text' => $this->Number->format($params['page']),
  804. 'url' => $this->generateUrl($url, $options['model']),
  805. ]);
  806. $start = $params['page'] + 1;
  807. $i = $start;
  808. while ($i < $end) {
  809. $out .= $this->_formatNumber($templater, [
  810. 'text' => $this->Number->format($i),
  811. 'page' => $i,
  812. 'model' => $options['model'],
  813. 'url' => $options['url'],
  814. ]);
  815. $i++;
  816. }
  817. if ($end != $params['page']) {
  818. $out .= $this->_formatNumber($templater, [
  819. 'text' => $this->Number->format($i),
  820. 'page' => $end,
  821. 'model' => $options['model'],
  822. 'url' => $options['url'],
  823. ]);
  824. }
  825. $out .= $options['after'];
  826. $out .= $this->_lastNumber($ellipsis, $params, $end, $options);
  827. return $out;
  828. }
  829. /**
  830. * Generates the first number for the paginator numbers() method.
  831. *
  832. * @param string $ellipsis Ellipsis character.
  833. * @param array $params Params from the numbers() method.
  834. * @param int $start Start number.
  835. * @param array $options Options from the numbers() method.
  836. * @return string Markup output.
  837. */
  838. protected function _firstNumber($ellipsis, $params, $start, $options)
  839. {
  840. $out = '';
  841. $first = is_int($options['first']) ? $options['first'] : 0;
  842. if ($options['first'] && $start > 1) {
  843. $offset = ($start <= $first) ? $start - 1 : $options['first'];
  844. $out .= $this->first($offset, $options);
  845. if ($first < $start - 1) {
  846. $out .= $ellipsis;
  847. }
  848. }
  849. return $out;
  850. }
  851. /**
  852. * Generates the last number for the paginator numbers() method.
  853. *
  854. * @param string $ellipsis Ellipsis character.
  855. * @param array $params Params from the numbers() method.
  856. * @param int $end End number.
  857. * @param array $options Options from the numbers() method.
  858. * @return string Markup output.
  859. */
  860. protected function _lastNumber($ellipsis, $params, $end, $options)
  861. {
  862. $out = '';
  863. $last = is_int($options['last']) ? $options['last'] : 0;
  864. if ($options['last'] && $end < $params['pageCount']) {
  865. $offset = ($params['pageCount'] < $end + $last) ? $params['pageCount'] - $end : $options['last'];
  866. if ($offset <= $options['last'] && $params['pageCount'] - $end > $last) {
  867. $out .= $ellipsis;
  868. }
  869. $out .= $this->last($offset, $options);
  870. }
  871. return $out;
  872. }
  873. /**
  874. * Generates the numbers for the paginator numbers() method.
  875. *
  876. * @param \Cake\View\StringTemplate $templater StringTemplate instance.
  877. * @param array $params Params from the numbers() method.
  878. * @param array $options Options from the numbers() method.
  879. * @return string Markup output.
  880. */
  881. protected function _numbers($templater, $params, $options)
  882. {
  883. $out = '';
  884. $out .= $options['before'];
  885. for ($i = 1; $i <= $params['pageCount']; $i++) {
  886. $url = array_merge($options['url'], ['page' => $i]);
  887. if ($i == $params['page']) {
  888. $out .= $templater->format('current', [
  889. 'text' => $this->Number->format($params['page']),
  890. 'url' => $this->generateUrl($url, $options['model']),
  891. ]);
  892. } else {
  893. $vars = [
  894. 'text' => $this->Number->format($i),
  895. 'url' => $this->generateUrl($url, $options['model']),
  896. ];
  897. $out .= $templater->format('number', $vars);
  898. }
  899. }
  900. $out .= $options['after'];
  901. return $out;
  902. }
  903. /**
  904. * Returns a first or set of numbers for the first pages.
  905. *
  906. * ```
  907. * echo $this->Paginator->first('< first');
  908. * ```
  909. *
  910. * Creates a single link for the first page. Will output nothing if you are on the first page.
  911. *
  912. * ```
  913. * echo $this->Paginator->first(3);
  914. * ```
  915. *
  916. * Will create links for the first 3 pages, once you get to the third or greater page. Prior to that
  917. * nothing will be output.
  918. *
  919. * ### Options:
  920. *
  921. * - `model` The model to use defaults to PaginatorHelper::defaultModel()
  922. * - `escape` Whether or not to HTML escape the text.
  923. * - `url` An array of additional URL options to use for link generation.
  924. *
  925. * @param string|int $first if string use as label for the link. If numeric, the number of page links
  926. * you want at the beginning of the range.
  927. * @param array $options An array of options.
  928. * @return string|false Numbers string.
  929. * @link https://book.cakephp.org/3.0/en/views/helpers/paginator.html#creating-jump-links
  930. */
  931. public function first($first = '<< first', array $options = [])
  932. {
  933. $options += [
  934. 'url' => [],
  935. 'model' => $this->defaultModel(),
  936. 'escape' => true
  937. ];
  938. $params = $this->params($options['model']);
  939. if ($params['pageCount'] <= 1) {
  940. return false;
  941. }
  942. $out = '';
  943. if (is_int($first) && $params['page'] >= $first) {
  944. for ($i = 1; $i <= $first; $i++) {
  945. $url = array_merge($options['url'], ['page' => $i]);
  946. $out .= $this->templater()->format('number', [
  947. 'url' => $this->generateUrl($url, $options['model']),
  948. 'text' => $this->Number->format($i)
  949. ]);
  950. }
  951. } elseif ($params['page'] > 1 && is_string($first)) {
  952. $first = $options['escape'] ? h($first) : $first;
  953. $out .= $this->templater()->format('first', [
  954. 'url' => $this->generateUrl(['page' => 1], $options['model']),
  955. 'text' => $first
  956. ]);
  957. }
  958. return $out;
  959. }
  960. /**
  961. * Returns a last or set of numbers for the last pages.
  962. *
  963. * ```
  964. * echo $this->Paginator->last('last >');
  965. * ```
  966. *
  967. * Creates a single link for the last page. Will output nothing if you are on the last page.
  968. *
  969. * ```
  970. * echo $this->Paginator->last(3);
  971. * ```
  972. *
  973. * Will create links for the last 3 pages. Once you enter the page range, no output will be created.
  974. *
  975. * ### Options:
  976. *
  977. * - `model` The model to use defaults to PaginatorHelper::defaultModel()
  978. * - `escape` Whether or not to HTML escape the text.
  979. * - `url` An array of additional URL options to use for link generation.
  980. *
  981. * @param string|int $last if string use as label for the link, if numeric print page numbers
  982. * @param array $options Array of options
  983. * @return string|false Numbers string.
  984. * @link https://book.cakephp.org/3.0/en/views/helpers/paginator.html#creating-jump-links
  985. */
  986. public function last($last = 'last >>', array $options = [])
  987. {
  988. $options += [
  989. 'model' => $this->defaultModel(),
  990. 'escape' => true,
  991. 'url' => []
  992. ];
  993. $params = $this->params($options['model']);
  994. if ($params['pageCount'] <= 1) {
  995. return false;
  996. }
  997. $out = '';
  998. $lower = (int)$params['pageCount'] - (int)$last + 1;
  999. if (is_int($last) && $params['page'] <= $lower) {
  1000. for ($i = $lower; $i <= $params['pageCount']; $i++) {
  1001. $url = array_merge($options['url'], ['page' => $i]);
  1002. $out .= $this->templater()->format('number', [
  1003. 'url' => $this->generateUrl($url, $options['model']),
  1004. 'text' => $this->Number->format($i)
  1005. ]);
  1006. }
  1007. } elseif ($params['page'] < $params['pageCount'] && is_string($last)) {
  1008. $last = $options['escape'] ? h($last) : $last;
  1009. $out .= $this->templater()->format('last', [
  1010. 'url' => $this->generateUrl(['page' => $params['pageCount']], $options['model']),
  1011. 'text' => $last
  1012. ]);
  1013. }
  1014. return $out;
  1015. }
  1016. /**
  1017. * Returns the meta-links for a paginated result set.
  1018. *
  1019. * ```
  1020. * echo $this->Paginator->meta();
  1021. * ```
  1022. *
  1023. * Echos the links directly, will output nothing if there is neither a previous nor next page.
  1024. *
  1025. * ```
  1026. * $this->Paginator->meta(['block' => true]);
  1027. * ```
  1028. *
  1029. * Will append the output of the meta function to the named block - if true is passed the "meta"
  1030. * block is used.
  1031. *
  1032. * ### Options:
  1033. *
  1034. * - `model` The model to use defaults to PaginatorHelper::defaultModel()
  1035. * - `block` The block name to append the output to, or false/absent to return as a string
  1036. * - `prev` (default True) True to generate meta for previous page
  1037. * - `next` (default True) True to generate meta for next page
  1038. * - `first` (default False) True to generate meta for first page
  1039. * - `last` (default False) True to generate meta for last page
  1040. *
  1041. * @param array $options Array of options
  1042. * @return string|null Meta links
  1043. */
  1044. public function meta(array $options = [])
  1045. {
  1046. $options += [
  1047. 'model' => null,
  1048. 'block' => false,
  1049. 'prev' => true,
  1050. 'next' => true,
  1051. 'first' => false,
  1052. 'last' => false
  1053. ];
  1054. $model = isset($options['model']) ? $options['model'] : null;
  1055. $params = $this->params($model);
  1056. $links = [];
  1057. if ($options['prev'] && $this->hasPrev()) {
  1058. $links[] = $this->Html->meta(
  1059. 'prev',
  1060. $this->generateUrl(['page' => $params['page'] - 1], null, ['escape' => false, 'fullBase' => true])
  1061. );
  1062. }
  1063. if ($options['next'] && $this->hasNext()) {
  1064. $links[] = $this->Html->meta(
  1065. 'next',
  1066. $this->generateUrl(['page' => $params['page'] + 1], null, ['escape' => false, 'fullBase' => true])
  1067. );
  1068. }
  1069. if ($options['first']) {
  1070. $links[] = $this->Html->meta(
  1071. 'first',
  1072. $this->generateUrl(['page' => 1], null, ['escape' => false, 'fullBase' => true])
  1073. );
  1074. }
  1075. if ($options['last']) {
  1076. $links[] = $this->Html->meta(
  1077. 'last',
  1078. $this->generateUrl(['page' => $params['pageCount']], null, ['escape' => false, 'fullBase' => true])
  1079. );
  1080. }
  1081. $out = implode($links);
  1082. if ($options['block'] === true) {
  1083. $options['block'] = __FUNCTION__;
  1084. }
  1085. if ($options['block']) {
  1086. $this->_View->append($options['block'], $out);
  1087. return null;
  1088. }
  1089. return $out;
  1090. }
  1091. /**
  1092. * Event listeners.
  1093. *
  1094. * @return array
  1095. */
  1096. public function implementedEvents()
  1097. {
  1098. return [];
  1099. }
  1100. /**
  1101. * Dropdown select for pagination limit.
  1102. * This will generate a wrapping form.
  1103. *
  1104. * @param array $limits The options array.
  1105. * @param int|null $default Default option for pagination limit. Defaults to `$this->param('perPage')`.
  1106. * @param array $options Options for Select tag attributes like class, id or event
  1107. * @return string html output.
  1108. */
  1109. public function limitControl(array $limits = [], $default = null, array $options = [])
  1110. {
  1111. $out = $this->Form->create(null, ['type' => 'get']);
  1112. if (empty($default) || !is_numeric($default)) {
  1113. $default = $this->param('perPage');
  1114. }
  1115. if (empty($limits)) {
  1116. $limits = [
  1117. '20' => '20',
  1118. '50' => '50',
  1119. '100' => '100'
  1120. ];
  1121. }
  1122. $out .= $this->Form->control('limit', $options + [
  1123. 'type' => 'select',
  1124. 'label' => __('View'),
  1125. 'value' => $default,
  1126. 'options' => $limits,
  1127. 'onChange' => 'this.form.submit()'
  1128. ]);
  1129. $out .= $this->Form->end();
  1130. return $out;
  1131. }
  1132. }