3 namespace Drupal\Core\Database\Query;
5 use Drupal\Core\Database\Connection;
8 * Query extender class for tablesort queries.
10 class TableSortExtender extends SelectExtender {
13 * The array of fields that can be sorted by.
15 protected $header = [];
17 public function __construct(SelectInterface $query, Connection $connection) {
18 parent::__construct($query, $connection);
20 // Add convenience tag to mark that this is an extended query. We have to
21 // do this in the constructor to ensure that it is set before preExecute()
23 $this->addTag('tablesort');
27 * Order the query based on a header array.
29 * @param array $header
32 * @return \Drupal\Core\Database\Query\SelectInterface
35 * @see table.html.twig
37 public function orderByHeader(array $header) {
38 $this->header = $header;
40 if (!empty($ts['sql'])) {
41 // Based on code from db_escape_table(), but this can also contain a dot.
42 $field = preg_replace('/[^A-Za-z0-9_.]+/', '', $ts['sql']);
44 // orderBy() will ensure that only ASC/DESC values are accepted, so we
45 // don't need to sanitize that here.
46 $this->orderBy($field, $ts['sort']);
52 * Initialize the table sort context.
54 protected function init() {
56 $ts['sort'] = $this->getSort();
57 $ts['query'] = $this->getQueryParameters();
62 * Determine the current sort direction.
65 * The current sort direction ("asc" or "desc").
67 * @see tablesort_get_sort()
69 protected function getSort() {
70 return tablesort_get_sort($this->header);
74 * Compose a URL query parameter array to append to table sorting requests.
77 * A URL query parameter array that consists of all components of the current
78 * page request except for those pertaining to table sorting.
80 * @see tablesort_get_query_parameters()
82 protected function getQueryParameters() {
83 return tablesort_get_query_parameters();
87 * Determine the current sort criterion.
90 * An associative array describing the criterion, containing the keys:
91 * - "name": The localized title of the table column.
92 * - "sql": The name of the database field to sort on.
94 * @see tablesort_get_order()
96 protected function order() {
97 return tablesort_get_order($this->header);