view-components / grids

MIT License
86 stars 17 forks source link

FilterOperation::OPERATOR_LIKE and ArrayDataProvider error #27

Closed peacemaker96 closed 7 years ago

peacemaker96 commented 7 years ago

It turns out that if we use ArrayDataProvider, and add a filter with the parameter "FilterOperation :: OPERATOR_LIKE" error occurs "Method ViewComponents\Grids\Grid::__toString() must not throw an exception". I corrected, added the missing parameter in the file "FilterProcessor.php":

    protected function checkValue($testedValue, $operator, $argument)
    {
        switch ($operator) {
            //New code
            case FilterOperation::OPERATOR_LIKE:
                return mb_stripos($testedValue, $argument)!== false;
            // /New code
            case FilterOperation::OPERATOR_EQ:
                return $testedValue == $argument;
            case FilterOperation::OPERATOR_GT:
Nayjest commented 7 years ago

Hi! Little advice: don't use $grid->__toString if you want to debug view-components without pain: Replace calls like

echo $grid;

or

<?= $grid ?>

to

echo $grid->render();

or

<?= $grid->render() ?>

and you will see Exception("Unsupported operator LIKE").

Tanks for your contribution, it would be great to apply OPERATOR_LIKE to arrays. But this operator means possibility to specify template with special characters like "%" or "?", currently it works only for data providers that reads from database.

Your implementation actually does case FilterOperation::OPERATOR_STR_CONTAINS. See similar code on line 57.

Currently FilterOperation::OPERATOR_LIKE is absent for arrays by design because of non-trivial implementation.

Good news: You can just use FilterOperation::OPERATOR_STR_CONTAINS for both querying php arrays and database. Data Providers that works with database will add LIKE "%$value%" to SQL query if you will use FilterOperation::OPERATOR_STR_CONTAINS.

FilterOperation::OPERATOR_LIKE may be useful just in case when you want to allow users to specify template for LIKE operation with "%" and "?" characters directly in form input.

If you need this feature for arrays, you can contribute to view-components/view-components with your implementation that will support special characters used in SQL LIKE.

But considering your current impl. looks like you need just replace FilterOperation::OPERATOR_LIKE to FilterOperation::OPERATOR_STR_CONTAINS in your code.

peacemaker96 commented 7 years ago

Thanks tovarisch)