Ejemplo de como implementar un filtro de selección que opera sobre un query string, petición de un API end point, basado en el diseño RHS (Right Hand Side)
Funciones y Clases
class FilterParam {
public string $fieldName = "", $operator = "asc";
public $value;
public function __construct(string $fieldName, string $operator, $value) {
$this->fieldName = $fieldName;
$this->operator = $operator;
$this->value = $value;
}
}
function isFilterParamRHS($field) {
return preg_match('/([[:word:]]+):\b(eq|lt)\b=([[:word:] :-]+)/', $field);
}
function getFieldRHS($s) {
preg_match('/([[:word:]]+):/', $s, $match);
return $match[1];
}
function getFilterOperatorRHS($s) {
preg_match('/:\b(eq|lt)\b/', $s, $match);
return $match[1];
}
function getValueRHS($s) {
preg_match('/=([[:word:] :-]+)/', $s, $match);
return $match[1];
}
function parserFilterRHS($s) {
$s_split = explode(',', $s);
$arr = [];
foreach ($s_split as $row) {
if (isFilterParamRHS($row)) {
$arr[] = new FilterParam(
getFieldRHS($row),
getFilterOperatorRHS($row),
getValueRHS($row)
);
}
}
return $arr;
}
Su uso
$s1 = "price:eq=200,date:lt=2022-11-04";
$s = $s1;
echo('sort_filter=' . $s . PHP_EOL);
$data = parserFilterRHS($s);
print_r($data);
Salida
sort_filter=price:eq=200,date:lt=2022-11-04
Array
(
[0] => FilterParam Object
(
[fieldName] => price
[operator] => eq
[value] => 200
)
[1] => FilterParam Object
(
[fieldName] => date
[operator] => lt
[value] => 2022-11-04
)
)
Banco de prueba online Filter Query String PHP