TableSort.php 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183
  1. <?php
  2. namespace Drupal\Core\Utility;
  3. use Drupal\Component\Render\FormattableMarkup;
  4. use Drupal\Component\Utility\UrlHelper;
  5. use Drupal\Core\Link;
  6. use Drupal\Core\StringTranslation\TranslatableMarkup;
  7. use Symfony\Component\HttpFoundation\Request;
  8. /**
  9. * Provides a class for table sorting processing and rendering.
  10. */
  11. class TableSort {
  12. const ASC = 'asc';
  13. const DESC = 'desc';
  14. /**
  15. * Initializes the table sort context.
  16. *
  17. * @param array $headers
  18. * An array of column headers in the format described in '#type' => 'table'.
  19. * @param \Symfony\Component\HttpFoundation\Request $request
  20. * A current request.
  21. *
  22. * @return array
  23. * The current table sort context.
  24. */
  25. public static function getContextFromRequest(array $headers, Request $request) {
  26. $context = static::getOrder($headers, $request);
  27. $context['sort'] = static::getSort($headers, $request);
  28. $context['query'] = static::getQueryParameters($request);
  29. return $context;
  30. }
  31. /**
  32. * Formats a column header.
  33. *
  34. * If the cell in question is the column header for the current sort
  35. * criterion, it gets special formatting. All possible sort criteria become
  36. * links.
  37. *
  38. * @param string $cell_content
  39. * The cell content to format. Passed by reference.
  40. * @param array $cell_attributes
  41. * The cell attributes. Passed by reference.
  42. * @param array $header
  43. * An array of column headers in the format described in '#type' => 'table'.
  44. * @param array $context
  45. * The current table sort context as returned from
  46. * TableSort::getContextFromRequest() method.
  47. *
  48. * @throws \Exception
  49. *
  50. * @see getContextFromRequest()
  51. */
  52. public static function header(&$cell_content, array &$cell_attributes, array $header, array $context) {
  53. // Special formatting for the currently sorted column header.
  54. if (isset($cell_attributes['field'])) {
  55. $title = new TranslatableMarkup('sort by @s', ['@s' => $cell_content]);
  56. if ($cell_content == $context['name']) {
  57. // aria-sort is a WAI-ARIA property that indicates if items in a table
  58. // or grid are sorted in ascending or descending order. See
  59. // http://www.w3.org/TR/wai-aria/states_and_properties#aria-sort
  60. $cell_attributes['aria-sort'] = ($context['sort'] == self::ASC) ? 'ascending' : 'descending';
  61. $context['sort'] = (($context['sort'] == self::ASC) ? self::DESC : self::ASC);
  62. $cell_attributes['class'][] = 'is-active';
  63. $tablesort_indicator = [
  64. '#theme' => 'tablesort_indicator',
  65. '#style' => $context['sort'],
  66. ];
  67. $image = \Drupal::service('renderer')->render($tablesort_indicator);
  68. }
  69. else {
  70. // This determines the sort order when the column gets first clicked by
  71. // the user. It is "asc" by default but the sort can be changed if
  72. // $cell['initial_click_sort'] is defined. The possible values are "asc"
  73. // or "desc".
  74. $context['sort'] = $cell_attributes['initial_click_sort'] ?? self::ASC;
  75. $image = '';
  76. }
  77. $cell_content = Link::createFromRoute(new FormattableMarkup('@cell_content@image', ['@cell_content' => $cell_content, '@image' => $image]), '<current>', [], [
  78. 'attributes' => ['title' => $title, 'rel' => 'nofollow'],
  79. 'query' => array_merge($context['query'], [
  80. 'sort' => $context['sort'],
  81. 'order' => $cell_content,
  82. ]),
  83. ]);
  84. unset($cell_attributes['field'], $cell_attributes['sort'], $cell_attributes['initial_click_sort']);
  85. }
  86. }
  87. /**
  88. * Determines the current sort criterion.
  89. *
  90. * @param array $headers
  91. * An array of column headers in the format described in '#type' => 'table'.
  92. * @param \Symfony\Component\HttpFoundation\Request $request
  93. * A current request.
  94. *
  95. * @return array
  96. * An associative array describing the criterion, containing the keys:
  97. * - "name": The localized title of the table column.
  98. * - "sql": The name of the database field to sort on.
  99. */
  100. public static function getOrder(array $headers, Request $request) {
  101. $order = $request->query->get('order', '');
  102. foreach ($headers as $header) {
  103. if (is_array($header)) {
  104. if (isset($header['data']) && $order == $header['data']) {
  105. $default = $header;
  106. break;
  107. }
  108. if (empty($default) && isset($header['sort']) && in_array($header['sort'], [self::ASC, self::DESC])) {
  109. $default = $header;
  110. }
  111. }
  112. }
  113. if (!isset($default)) {
  114. $default = reset($headers);
  115. if (!is_array($default)) {
  116. $default = ['data' => $default];
  117. }
  118. }
  119. $default += ['data' => NULL, 'field' => NULL];
  120. return ['name' => $default['data'], 'sql' => $default['field']];
  121. }
  122. /**
  123. * Determines the current sort direction.
  124. *
  125. * @param array $headers
  126. * An array of column headers in the format described in '#type' => 'table'.
  127. * @param \Symfony\Component\HttpFoundation\Request|null $request
  128. * A current request.
  129. *
  130. * @return string
  131. * The current sort direction ("asc" or "desc").
  132. */
  133. public static function getSort(array $headers, Request $request) {
  134. $query = $request->query;
  135. if ($query->has('sort')) {
  136. return (strtolower($query->get('sort')) == self::DESC) ? self::DESC : self::ASC;
  137. }
  138. // The user has not specified a sort. Use the default for the currently
  139. // sorted header if specified; otherwise use "asc".
  140. // Find out which header is currently being sorted.
  141. $order = static::getOrder($headers, $request);
  142. foreach ($headers as $header) {
  143. if (is_array($header) && isset($header['data']) && $header['data'] == $order['name']) {
  144. if (isset($header['sort'])) {
  145. return $header['sort'];
  146. }
  147. if (isset($header['initial_click_sort'])) {
  148. return $header['initial_click_sort'];
  149. }
  150. }
  151. }
  152. return self::ASC;
  153. }
  154. /**
  155. * Composes a URL query parameter array for table sorting links.
  156. *
  157. * @param \Symfony\Component\HttpFoundation\Request|null $request
  158. * A current request.
  159. *
  160. * @return array
  161. * A URL query parameter array that consists of all components of the
  162. * current page request except for those pertaining to table sorting.
  163. *
  164. * @internal
  165. */
  166. public static function getQueryParameters(Request $request) {
  167. return UrlHelper::filterQueryParameters($request->query->all(), ['sort', 'order']);
  168. }
  169. }