Same filename and directory in other branches
- 8.9.x core/modules/jsonapi/src/Query/Sort.php
- 9 core/modules/jsonapi/src/Query/Sort.php
Namespace
Drupal\jsonapi\Query
File
core/modules/jsonapi/src/Query/Sort.php
View source
<?php
namespace Drupal\jsonapi\Query;
use Drupal\Core\Cache\CacheableMetadata;
use Drupal\Core\Http\Exception\CacheableBadRequestHttpException;
class Sort {
const KEY_NAME = 'sort';
const PATH_KEY = 'path';
const DIRECTION_KEY = 'direction';
const LANGUAGE_KEY = 'langcode';
protected $fields;
public function __construct(array $fields) {
$this->fields = $fields;
}
public function fields() {
return $this->fields;
}
public static function createFromQueryParameter($parameter) {
if (empty($parameter)) {
$cacheability = (new CacheableMetadata())
->addCacheContexts([
'url.query_args:sort',
]);
throw new CacheableBadRequestHttpException($cacheability, 'You need to provide a value for the sort parameter.');
}
if (is_string($parameter)) {
$parameter = static::expandFieldString($parameter);
}
$expanded = [];
foreach ($parameter as $sort_index => $sort_item) {
$expanded[$sort_index] = static::expandItem($sort_item);
}
return new static($expanded);
}
protected static function expandFieldString($fields) {
return array_map(function ($field) {
$sort = [];
if ($field[0] == '-') {
$sort[static::DIRECTION_KEY] = 'DESC';
$sort[static::PATH_KEY] = substr($field, 1);
}
else {
$sort[static::DIRECTION_KEY] = 'ASC';
$sort[static::PATH_KEY] = $field;
}
return $sort;
}, explode(',', $fields));
}
protected static function expandItem(array $sort_item) {
$cacheability = (new CacheableMetadata())
->addCacheContexts([
'url.query_args:sort',
]);
$defaults = [
static::DIRECTION_KEY => 'ASC',
static::LANGUAGE_KEY => NULL,
];
if (!isset($sort_item[static::PATH_KEY])) {
throw new CacheableBadRequestHttpException($cacheability, 'You need to provide a field name for the sort parameter.');
}
$expected_keys = [
static::PATH_KEY,
static::DIRECTION_KEY,
static::LANGUAGE_KEY,
];
$expanded = array_merge($defaults, $sort_item);
if (count(array_diff($expected_keys, array_keys($expanded))) > 0) {
throw new CacheableBadRequestHttpException($cacheability, 'You have provided an invalid set of sort keys.');
}
return $expanded;
}
}
Classes
Name |
Description |
Sort |
Gathers information about the sort parameter. |