annotate core/includes/pager.inc @ 19:fa3358dc1485 tip

Add ndrum files
author Chris Cannam
date Wed, 28 Aug 2019 13:14:47 +0100
parents af1871eacc83
children
rev   line source
Chris@0 1 <?php
Chris@0 2
Chris@0 3 /**
Chris@0 4 * @file
Chris@0 5 * Functions to aid in presenting database results as a set of pages.
Chris@0 6 */
Chris@0 7
Chris@18 8 use Drupal\Core\Url;
Chris@0 9 use Drupal\Component\Utility\UrlHelper;
Chris@18 10 use Drupal\Component\Utility\Html;
Chris@0 11
Chris@0 12 /**
Chris@0 13 * Returns the current page being requested for display within a pager.
Chris@0 14 *
Chris@0 15 * @param int $element
Chris@0 16 * (optional) An integer to distinguish between multiple pagers on one page.
Chris@0 17 *
Chris@0 18 * @return int
Chris@0 19 * The number of the current requested page, within the pager represented by
Chris@0 20 * $element. This is determined from the URL query parameter
Chris@0 21 * \Drupal::request()->query->get('page'), or 0 by default. Note that this
Chris@0 22 * number may differ from the actual page being displayed. For example, if a
Chris@0 23 * search for "example text" brings up three pages of results, but a user
Chris@0 24 * visits search/node/example+text?page=10, this function will return 10,
Chris@0 25 * even though the default pager implementation adjusts for this and still
Chris@0 26 * displays the third page of search results at that URL.
Chris@0 27 *
Chris@0 28 * @see pager_default_initialize()
Chris@0 29 */
Chris@0 30 function pager_find_page($element = 0) {
Chris@0 31 $page = \Drupal::request()->query->get('page', '');
Chris@0 32 $page_array = explode(',', $page);
Chris@0 33 if (!isset($page_array[$element])) {
Chris@0 34 $page_array[$element] = 0;
Chris@0 35 }
Chris@0 36 return (int) $page_array[$element];
Chris@0 37 }
Chris@0 38
Chris@0 39 /**
Chris@0 40 * Initializes a pager.
Chris@0 41 *
Chris@0 42 * This function sets up the necessary global variables so that the render
Chris@0 43 * system will correctly process #type 'pager' render arrays to output pagers
Chris@0 44 * that correspond to the items being displayed.
Chris@0 45 *
Chris@0 46 * If the items being displayed result from a database query performed using
Chris@0 47 * Drupal's database API, and if you have control over the construction of the
Chris@0 48 * database query, you do not need to call this function directly; instead, you
Chris@0 49 * can simply extend the query object with the 'PagerSelectExtender' extender
Chris@0 50 * before executing it. For example:
Chris@0 51 * @code
Chris@0 52 * $query = db_select('some_table')
Chris@0 53 * ->extend('Drupal\Core\Database\Query\PagerSelectExtender');
Chris@0 54 * @endcode
Chris@0 55 *
Chris@0 56 * However, if you are using a different method for generating the items to be
Chris@0 57 * paged through, then you should call this function in preparation.
Chris@0 58 *
Chris@0 59 * The following example shows how this function can be used in a controller
Chris@0 60 * that invokes an external datastore with an SQL-like syntax:
Chris@0 61 * @code
Chris@0 62 * // First find the total number of items and initialize the pager.
Chris@0 63 * $where = "status = 1";
Chris@0 64 * $total = mymodule_select("SELECT COUNT(*) FROM data " . $where)->result();
Chris@0 65 * $num_per_page = \Drupal::config('mymodule.settings')->get('num_per_page');
Chris@0 66 * $page = pager_default_initialize($total, $num_per_page);
Chris@0 67 *
Chris@0 68 * // Next, retrieve the items for the current page and put them into a
Chris@0 69 * // render array.
Chris@0 70 * $offset = $num_per_page * $page;
Chris@0 71 * $result = mymodule_select("SELECT * FROM data " . $where . " LIMIT %d, %d", $offset, $num_per_page)->fetchAll();
Chris@0 72 * $render = [];
Chris@0 73 * $render[] = [
Chris@0 74 * '#theme' => 'mymodule_results',
Chris@0 75 * '#result' => $result,
Chris@0 76 * ];
Chris@0 77 *
Chris@0 78 * // Finally, add the pager to the render array, and return.
Chris@0 79 * $render[] = ['#type' => 'pager'];
Chris@0 80 * return $render;
Chris@0 81 * @endcode
Chris@0 82 *
Chris@0 83 * A second example involves a controller that invokes an external search
Chris@0 84 * service where the total number of matching results is provided as part of
Chris@0 85 * the returned set (so that we do not need a separate query in order to obtain
Chris@0 86 * this information). Here, we call pager_find_page() to calculate the desired
Chris@0 87 * offset before the search is invoked:
Chris@0 88 * @code
Chris@0 89 * // Perform the query, using the requested offset from pager_find_page().
Chris@0 90 * // This comes from a URL parameter, so here we are assuming that the URL
Chris@0 91 * // parameter corresponds to an actual page of results that will exist
Chris@0 92 * // within the set.
Chris@0 93 * $page = pager_find_page();
Chris@0 94 * $num_per_page = \Drupal::config('mymodule.settings')->get('num_per_page');
Chris@0 95 * $offset = $num_per_page * $page;
Chris@0 96 * $result = mymodule_remote_search($keywords, $offset, $num_per_page);
Chris@0 97 *
Chris@0 98 * // Now that we have the total number of results, initialize the pager.
Chris@0 99 * pager_default_initialize($result->total, $num_per_page);
Chris@0 100 *
Chris@0 101 * // Create a render array with the search results.
Chris@0 102 * $render = [];
Chris@0 103 * $render[] = [
Chris@0 104 * '#theme' => 'search_results',
Chris@0 105 * '#results' => $result->data,
Chris@0 106 * '#type' => 'remote',
Chris@0 107 * ];
Chris@0 108 *
Chris@0 109 * // Finally, add the pager to the render array, and return.
Chris@0 110 * $render[] = ['#type' => 'pager'];
Chris@0 111 * return $render;
Chris@0 112 * @endcode
Chris@0 113 *
Chris@0 114 * @param int $total
Chris@0 115 * The total number of items to be paged.
Chris@0 116 * @param int $limit
Chris@0 117 * The number of items the calling code will display per page.
Chris@0 118 * @param int $element
Chris@0 119 * (optional) An integer to distinguish between multiple pagers on one page.
Chris@0 120 *
Chris@0 121 * @return int
Chris@0 122 * The number of the current page, within the pager represented by $element.
Chris@0 123 * This is determined from the URL query parameter
Chris@0 124 * \Drupal::request()->query->get('page), or 0 by default. However, if a page
Chris@0 125 * that does not correspond to the actual range of the result set was
Chris@0 126 * requested, this function will return the closest page actually within the
Chris@0 127 * result set.
Chris@0 128 */
Chris@0 129 function pager_default_initialize($total, $limit, $element = 0) {
Chris@0 130 global $pager_page_array, $pager_total, $pager_total_items, $pager_limits;
Chris@0 131
Chris@0 132 $page = pager_find_page($element);
Chris@0 133
Chris@0 134 // We calculate the total of pages as ceil(items / limit).
Chris@0 135 $pager_total_items[$element] = $total;
Chris@0 136 $pager_total[$element] = ceil($pager_total_items[$element] / $limit);
Chris@0 137 $pager_page_array[$element] = max(0, min($page, ((int) $pager_total[$element]) - 1));
Chris@0 138 $pager_limits[$element] = $limit;
Chris@0 139 return $pager_page_array[$element];
Chris@0 140 }
Chris@0 141
Chris@0 142 /**
Chris@0 143 * Compose a URL query parameter array for pager links.
Chris@0 144 *
Chris@0 145 * @return array
Chris@0 146 * A URL query parameter array that consists of all components of the current
Chris@0 147 * page request except for those pertaining to paging.
Chris@0 148 */
Chris@0 149 function pager_get_query_parameters() {
Chris@0 150 $query = &drupal_static(__FUNCTION__);
Chris@0 151 if (!isset($query)) {
Chris@0 152 $query = UrlHelper::filterQueryParameters(\Drupal::request()->query->all(), ['page']);
Chris@0 153 }
Chris@0 154 return $query;
Chris@0 155 }
Chris@0 156
Chris@0 157 /**
Chris@0 158 * Prepares variables for pager templates.
Chris@0 159 *
Chris@0 160 * Default template: pager.html.twig.
Chris@0 161 *
Chris@0 162 * Menu callbacks that display paged query results should use #type => pager
Chris@0 163 * to retrieve a pager control so that users can view other results. Format a
Chris@0 164 * list of nearby pages with additional query results.
Chris@0 165 *
Chris@0 166 * @param array $variables
Chris@0 167 * An associative array containing:
Chris@0 168 * - pager: A render element containing:
Chris@0 169 * - #tags: An array of labels for the controls in the pager.
Chris@0 170 * - #element: An optional integer to distinguish between multiple pagers on
Chris@0 171 * one page.
Chris@0 172 * - #parameters: An associative array of query string parameters to append
Chris@0 173 * to the pager links.
Chris@0 174 * - #route_parameters: An associative array of the route parameters.
Chris@0 175 * - #quantity: The number of pages in the list.
Chris@0 176 */
Chris@0 177 function template_preprocess_pager(&$variables) {
Chris@0 178 $element = $variables['pager']['#element'];
Chris@0 179 $parameters = $variables['pager']['#parameters'];
Chris@0 180 $quantity = $variables['pager']['#quantity'];
Chris@0 181 $route_name = $variables['pager']['#route_name'];
Chris@0 182 $route_parameters = isset($variables['pager']['#route_parameters']) ? $variables['pager']['#route_parameters'] : [];
Chris@0 183 global $pager_page_array, $pager_total;
Chris@0 184
Chris@0 185 // Nothing to do if there is only one page.
Chris@0 186 if ($pager_total[$element] <= 1) {
Chris@0 187 return;
Chris@0 188 }
Chris@0 189
Chris@0 190 $tags = $variables['pager']['#tags'];
Chris@0 191
Chris@0 192 // Calculate various markers within this pager piece:
Chris@0 193 // Middle is used to "center" pages around the current page.
Chris@0 194 $pager_middle = ceil($quantity / 2);
Chris@0 195 // current is the page we are currently paged to.
Chris@0 196 $pager_current = $pager_page_array[$element] + 1;
Chris@0 197 // first is the first page listed by this pager piece (re quantity).
Chris@0 198 $pager_first = $pager_current - $pager_middle + 1;
Chris@0 199 // last is the last page listed by this pager piece (re quantity).
Chris@0 200 $pager_last = $pager_current + $quantity - $pager_middle;
Chris@0 201 // max is the maximum page number.
Chris@0 202 $pager_max = $pager_total[$element];
Chris@0 203 // End of marker calculations.
Chris@0 204
Chris@0 205 // Prepare for generation loop.
Chris@0 206 $i = $pager_first;
Chris@0 207 if ($pager_last > $pager_max) {
Chris@0 208 // Adjust "center" if at end of query.
Chris@0 209 $i = $i + ($pager_max - $pager_last);
Chris@0 210 $pager_last = $pager_max;
Chris@0 211 }
Chris@0 212 if ($i <= 0) {
Chris@0 213 // Adjust "center" if at start of query.
Chris@0 214 $pager_last = $pager_last + (1 - $i);
Chris@0 215 $i = 1;
Chris@0 216 }
Chris@0 217 // End of generation loop preparation.
Chris@0 218
Chris@0 219 // Create the "first" and "previous" links if we are not on the first page.
Chris@0 220 if ($pager_page_array[$element] > 0) {
Chris@0 221 $items['first'] = [];
Chris@0 222 $options = [
Chris@0 223 'query' => pager_query_add_page($parameters, $element, 0),
Chris@0 224 ];
Chris@18 225 $items['first']['href'] = Url::fromRoute($route_name, $route_parameters, $options)->toString();
Chris@0 226 if (isset($tags[0])) {
Chris@0 227 $items['first']['text'] = $tags[0];
Chris@0 228 }
Chris@0 229
Chris@0 230 $items['previous'] = [];
Chris@0 231 $options = [
Chris@0 232 'query' => pager_query_add_page($parameters, $element, $pager_page_array[$element] - 1),
Chris@0 233 ];
Chris@18 234 $items['previous']['href'] = Url::fromRoute($route_name, $route_parameters, $options)->toString();
Chris@0 235 if (isset($tags[1])) {
Chris@0 236 $items['previous']['text'] = $tags[1];
Chris@0 237 }
Chris@0 238 }
Chris@0 239
Chris@0 240 if ($i != $pager_max) {
Chris@0 241 // Add an ellipsis if there are further previous pages.
Chris@0 242 if ($i > 1) {
Chris@0 243 $variables['ellipses']['previous'] = TRUE;
Chris@0 244 }
Chris@0 245 // Now generate the actual pager piece.
Chris@0 246 for (; $i <= $pager_last && $i <= $pager_max; $i++) {
Chris@0 247 $options = [
Chris@0 248 'query' => pager_query_add_page($parameters, $element, $i - 1),
Chris@0 249 ];
Chris@18 250 $items['pages'][$i]['href'] = Url::fromRoute($route_name, $route_parameters, $options)->toString();
Chris@0 251 if ($i == $pager_current) {
Chris@0 252 $variables['current'] = $i;
Chris@0 253 }
Chris@0 254 }
Chris@0 255 // Add an ellipsis if there are further next pages.
Chris@0 256 if ($i < $pager_max + 1) {
Chris@0 257 $variables['ellipses']['next'] = TRUE;
Chris@0 258 }
Chris@0 259 }
Chris@0 260
Chris@0 261 // Create the "next" and "last" links if we are not on the last page.
Chris@0 262 if ($pager_page_array[$element] < ($pager_max - 1)) {
Chris@0 263 $items['next'] = [];
Chris@0 264 $options = [
Chris@0 265 'query' => pager_query_add_page($parameters, $element, $pager_page_array[$element] + 1),
Chris@0 266 ];
Chris@18 267 $items['next']['href'] = Url::fromRoute($route_name, $route_parameters, $options)->toString();
Chris@0 268 if (isset($tags[3])) {
Chris@0 269 $items['next']['text'] = $tags[3];
Chris@0 270 }
Chris@0 271
Chris@0 272 $items['last'] = [];
Chris@0 273 $options = [
Chris@0 274 'query' => pager_query_add_page($parameters, $element, $pager_max - 1),
Chris@0 275 ];
Chris@18 276 $items['last']['href'] = Url::fromRoute($route_name, $route_parameters, $options)->toString();
Chris@0 277 if (isset($tags[4])) {
Chris@0 278 $items['last']['text'] = $tags[4];
Chris@0 279 }
Chris@0 280 }
Chris@0 281
Chris@0 282 $variables['items'] = $items;
Chris@18 283 $variables['heading_id'] = Html::getUniqueId('pagination-heading');
Chris@0 284
Chris@0 285 // The rendered link needs to play well with any other query parameter used
Chris@0 286 // on the page, like exposed filters, so for the cacheability all query
Chris@0 287 // parameters matter.
Chris@0 288 $variables['#cache']['contexts'][] = 'url.query_args';
Chris@0 289 }
Chris@0 290
Chris@0 291 /**
Chris@0 292 * Gets the URL query parameter array of a pager link.
Chris@0 293 *
Chris@0 294 * Adds to or adjusts the 'page' URL query parameter so that if you follow the
Chris@0 295 * link, you'll get page $index for pager $element on the page.
Chris@0 296 *
Chris@0 297 * The 'page' URL query parameter is a comma-delimited string, where each value
Chris@0 298 * is the target content page for the corresponding pager $element. For
Chris@0 299 * instance, if we have 5 pagers on a single page, and we want to have a link
Chris@0 300 * to a page that should display the 6th content page for the 3rd pager, and
Chris@0 301 * the 1st content page for all the other pagers, then the URL query will look
Chris@0 302 * like this: ?page=0,0,5,0,0 (page numbering starts at zero).
Chris@0 303 *
Chris@0 304 * @param array $query
Chris@0 305 * An associative array of URL query parameters to add to.
Chris@0 306 * @param int $element
Chris@0 307 * An integer to distinguish between multiple pagers on one page.
Chris@0 308 * @param int $index
Chris@0 309 * The index of the target page, for the given element, in the pager array.
Chris@0 310 *
Chris@0 311 * @return array
Chris@0 312 * The altered $query parameter array.
Chris@0 313 */
Chris@0 314 function pager_query_add_page(array $query, $element, $index) {
Chris@0 315 global $pager_page_array;
Chris@0 316
Chris@0 317 // Build the 'page' query parameter. This is built based on the current
Chris@0 318 // page of each pager element (or NULL if the pager is not set), with the
Chris@0 319 // exception of the requested page index for the current element.
Chris@0 320 $max_element = max(array_keys($pager_page_array));
Chris@0 321 $element_pages = [];
Chris@0 322 for ($i = 0; $i <= $max_element; $i++) {
Chris@0 323 $element_pages[] = ($i == $element) ? $index : (isset($pager_page_array[$i]) ? $pager_page_array[$i] : NULL);
Chris@0 324 }
Chris@0 325 $query['page'] = implode(',', $element_pages);
Chris@0 326
Chris@0 327 // Merge the query parameters passed to this function with the parameters
Chris@0 328 // from the current request. In case of collision, the parameters passed into
Chris@0 329 // this function take precedence.
Chris@0 330 if ($current_request_query = pager_get_query_parameters()) {
Chris@0 331 $query = array_merge($current_request_query, $query);
Chris@0 332 }
Chris@0 333 return $query;
Chris@0 334 }