auraphp / Aura.Filter

Validate and sanitize arrays and objects.
MIT License
159 stars 33 forks source link

Sanitize to Field If Blank? #119

Closed jakejohns closed 2 years ago

jakejohns commented 8 years ago

Often I wish to set a field (ie. slug) to the value of another field (ie. title) if the former is blank, then sanitize it further. I think I can accomplish this now with some magic strings like this:

$filter->sanitize('slug')->useBlankValue('FIELD_IS_BLANK');
$filter->sanitize('slug')->to('callback', function ($subject, $field) {
    if ($subject->$field == 'FIELD_IS_BLANK') {
        $subject->$field = $subject->title;
    }
    return true;
});
$filter->sanitize('slug')->to('uppercase');

$data = [
    'slug' => '',
    'title' => 'some thing here'
];

var_dump($filter->apply($data));
var_dump($data);

But that's kind of awkward/magical/weird.

Any suggestions? Think we need a PR?

I was thinking about patching the SanatizeSpec to be able to pass a callable to useBlankValue that would take the subject as an arg, but i don't actually think that's the way.

ie.:

    //  SanitizeSpec::__invoke
    public function __invoke($subject)
    {
        if (! $this->subjectFieldIsBlank($subject)) {
            return parent::__invoke($subject);
        }

        if (! $this->allow_blank) {
            return false;
        }

        $blank = $this->blank_value;

        if (is_callable($blank)) {
            $blank = $blank($subject, $this->field);
        }

        $field = $this->field;
        $subject->$field = $blank;
        return true;
    }

// filter
$filter->sanitize('slug')->useBlankValue(
    function ($subject, $field) {
        return $subject->title;
    }
);

Maybe what I want isn't really a "blank" value, but a "defaultTo" or something? and should encompass a new set of logic?

//  SanitizeSpec::__invoke
    public function __invoke($subject)
    {
        if (! $this->subjectFieldIsBlank($subject)) {
            return parent::__invoke($subject);
        }
        if ($defaultField = $this->defaultTo) {
            $subject->$field = $subject->$default;
            return parent::__invoke($subject);
        }
        // ...
    }

Thoughts?

pmjones commented 8 years ago

I was thinking about patching the SanatizeSpec to be able to pass a callable to useBlankValue that would take the subject as an arg, but i don't actually think that's the way.

I wonder if an added method useBlankField() (or something like that) would be useful here, to indicate "if blank, use the value from this field".

pmjones commented 7 years ago

@jakejohns Any further thoughts here?