TableSortExtender.php 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. <?php
  2. namespace Drupal\Core\Database\Query;
  3. use Drupal\Core\Database\Connection;
  4. use Drupal\Core\Utility\TableSort;
  5. /**
  6. * Query extender class for tablesort queries.
  7. */
  8. class TableSortExtender extends SelectExtender {
  9. /**
  10. * {@inheritdoc}
  11. */
  12. public function __construct(SelectInterface $query, Connection $connection) {
  13. parent::__construct($query, $connection);
  14. // Add convenience tag to mark that this is an extended query. We have to
  15. // do this in the constructor to ensure that it is set before preExecute()
  16. // gets called.
  17. $this->addTag('tablesort');
  18. }
  19. /**
  20. * Order the query based on a header array.
  21. *
  22. * @param array $header
  23. * Table header array.
  24. *
  25. * @return \Drupal\Core\Database\Query\SelectInterface
  26. * The called object.
  27. *
  28. * @see table.html.twig
  29. */
  30. public function orderByHeader(array $header) {
  31. $context = TableSort::getContextFromRequest($header, \Drupal::request());
  32. if (!empty($context['sql'])) {
  33. // Based on code from \Drupal\Core\Database\Connection::escapeTable(),
  34. // but this can also contain a dot.
  35. $field = preg_replace('/[^A-Za-z0-9_.]+/', '', $context['sql']);
  36. // orderBy() will ensure that only ASC/DESC values are accepted, so we
  37. // don't need to sanitize that here.
  38. $this->orderBy($field, $context['sort']);
  39. }
  40. return $this;
  41. }
  42. }