View source
<?php
namespace Drupal\jsonapi\Query;
use Drupal\Core\Cache\CacheableMetadata;
use Drupal\Core\Http\Exception\CacheableBadRequestHttpException;
class EntityCondition {
const PATH_KEY = 'path';
const VALUE_KEY = 'value';
const OPERATOR_KEY = 'operator';
public static $allowedOperators = [
'=',
'<>',
'>',
'>=',
'<',
'<=',
'STARTS_WITH',
'CONTAINS',
'ENDS_WITH',
'IN',
'NOT IN',
'BETWEEN',
'NOT BETWEEN',
'IS NULL',
'IS NOT NULL',
];
protected $field;
protected $operator;
protected $value;
public function __construct($field, $value, $operator = NULL) {
$this->field = $field;
$this->value = $value;
$this->operator = $operator ? $operator : '=';
}
public function field() {
return $this->field;
}
public function operator() {
return $this->operator;
}
public function value() {
return $this->value;
}
public static function createFromQueryParameter($parameter) {
static::validate($parameter);
$field = $parameter[static::PATH_KEY];
$value = isset($parameter[static::VALUE_KEY]) ? $parameter[static::VALUE_KEY] : NULL;
$operator = isset($parameter[static::OPERATOR_KEY]) ? $parameter[static::OPERATOR_KEY] : NULL;
return new static($field, $value, $operator);
}
protected static function validate($parameter) {
$valid_key_combinations = [
[
static::PATH_KEY,
static::VALUE_KEY,
],
[
static::PATH_KEY,
static::OPERATOR_KEY,
],
[
static::PATH_KEY,
static::VALUE_KEY,
static::OPERATOR_KEY,
],
];
$given_keys = array_keys($parameter);
$valid_key_set = array_reduce($valid_key_combinations, function ($valid, $set) use ($given_keys) {
return $valid ? $valid : count(array_diff($set, $given_keys)) === 0;
}, FALSE);
$has_operator_key = isset($parameter[static::OPERATOR_KEY]);
$has_path_key = isset($parameter[static::PATH_KEY]);
$has_value_key = isset($parameter[static::VALUE_KEY]);
$cacheability = (new CacheableMetadata())
->addCacheContexts([
'url.query_args:filter',
]);
if (!$valid_key_set) {
if (!$has_operator_key) {
if (!$has_path_key) {
throw new CacheableBadRequestHttpException($cacheability, "Filter parameter is missing a '" . static::PATH_KEY . "' key.");
}
if (!$has_value_key) {
throw new CacheableBadRequestHttpException($cacheability, "Filter parameter is missing a '" . static::VALUE_KEY . "' key.");
}
}
$reason = "You must provide a valid filter condition. Check that you have set the required keys for your filter.";
throw new CacheableBadRequestHttpException($cacheability, $reason);
}
if ($has_operator_key) {
$operator = $parameter[static::OPERATOR_KEY];
if (!in_array($operator, static::$allowedOperators)) {
$reason = "The '" . $operator . "' operator is not allowed in a filter parameter.";
throw new CacheableBadRequestHttpException($cacheability, $reason);
}
if (in_array($operator, [
'IS NULL',
'IS NOT NULL',
]) && $has_value_key) {
$reason = "Filters using the '" . $operator . "' operator should not provide a value.";
throw new CacheableBadRequestHttpException($cacheability, $reason);
}
}
}
}