Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Using custom filters alongside default filters on array properties #31

Open
ZeroGodForce opened this issue Apr 5, 2023 · 0 comments
Open

Comments

@ZeroGodForce
Copy link

I've written a custom filter based on filter_var_array() and inspired by the FilterVars::class to allow an array of repeating arrays (e.g. order lines) to be validated on a per-element level. For example:

<?php

namespace App\Filters;

use ArondeParon\RequestSanitizer\Contracts\Sanitizer;

class FilterRepeatingVarArray implements Sanitizer
{
    protected array $fields;

    public function __construct($fields = [])
    {
        $this->fields = $fields;
    }

    /**
     * Sanitize the nested array using the native PHP function: filter_var_array()
     * @param $input
     * @return array|null
     * @see https://www.php.net/manual/en/function.filter-var-array.php
     */
    public function sanitize($input): ?array
    {
        if (is_null($input)) {
            return $input;
        }

        $sanitized = [];
        foreach ($input as $item) {
            $sanitized[] = filter_var_array($item, $this->fields);
        }

        return $sanitized;
    }
}

Then in the form request it's defined like this:

    protected array $sanitizers = [
        ...
        'order_line' => [
            FilterRepeatingVarArray::class => [
                'fields' => [
                    'quantity' => [
                        'filter' => FILTER_VALIDATE_INT,
                    ],
                    'price' => [
                        'filter' => FILTER_SANITIZE_NUMBER_FLOAT,
                        'flags' => FILTER_FLAG_ALLOW_FRACTION,
                        'options' => null,
                    ],
                ],
            ],
        ],
        ...
    ];

This appears to be working fine, but I'm not actually sure how I can apply any of the package's default filters to this kind of 2D array. Ironically, it's brought me back to the original reason I wrote this custom filter; I'm not sure how (or if it's currently possible) to run filter classes on nested array elements?

Thanks for the library, it's ace!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant