Friends of Cake Search: Comparison filters and multiple comparison filters on the same field

I am wondering if it is possible to define multiple comparison filters, such as >= and <= on the same field. I am also wondering if there is a better way to accomplish some code I wrote. This code allows accepting filters like ?price=>= 200 or ?price=<=400. What I’ve come up with is re-usable when passed into a callback, but I feel like maybe I missed how to do this in the documentation.

    public static function comparisonFilter(Query $query, array $args, Base $filter)
    {
        $column = key($args);
        if (!is_string($column) || empty($column)) {
            throw new InternalErrorException('Comparison search key not found');
        }

        $value = trim($args[$column]);
        if (!isset($args[$column])) {
            throw new InternalErrorException('Comparison search index not found');
        }

        $search = explode(' ', $value);
        if (empty($search) || count($search) !== 2) {
            $query->where([$column => $value]);
            return true;
        }

        list($operator, $value) = $search;
        $operators = ['>', '>=', '<', '<='];
        if (!in_array($operator, $operators)) {
            throw new BadRequestException(
                'Comparison search operator must be one of ' . implode(', ', $operators)
            );
        }

        if (!is_numeric($value)) {
            throw new BadRequestException(
                'Comparison search value must be numeric'
            );
        }

        $query->where(["$column $operator" => $value]);

        return true;
    }
1 Like

I like the idea, to make it fully reusable, you would have to create a class extending BaseFilter see the example in the docs

Yeah you’re right, that was some pretty rudimentary code I threw together.