PaginatorHelper.php 42 KB

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