82 lines
1.6 KiB
Perl
82 lines
1.6 KiB
Perl
package utils::support::moo_sanitize;
|
|
|
|
use strict;
|
|
use warnings;
|
|
use Carp;
|
|
use Scalar::Util qw(blessed);
|
|
use utils::support::WhiteListSanitizer;
|
|
|
|
require Exporter;
|
|
our @ISA = qw(Exporter);
|
|
our @EXPORT = qw(sanitizes sanitize);
|
|
|
|
my %THINGS = ();
|
|
my $_sanitizer;
|
|
|
|
sub sanitizer {
|
|
return $_sanitizer //= WhiteListSanitizer->new;
|
|
}
|
|
|
|
sub sanitizes {
|
|
my ($fields, %args) = @_;
|
|
my $caller = caller;
|
|
|
|
my $thing = $THINGS{$caller};
|
|
$fields = [$fields] if ref($fields) ne 'ARRAY';
|
|
my $sanitize_options = %args ? \%args : 1;
|
|
|
|
foreach my $field (@$fields) {
|
|
$thing->{fields}->{$field} = $sanitize_options;
|
|
}
|
|
|
|
return;
|
|
}
|
|
|
|
sub sanitize {
|
|
my $self = shift;
|
|
my $class = blessed $self;
|
|
|
|
my $thing = $THINGS{$class};
|
|
while (my ($field, $options) = each %{$thing->{fields}}) {
|
|
my $value = $self->$field;
|
|
|
|
my %santize_options;
|
|
if (ref($options) eq "HASH") {
|
|
%santize_options = %$options;
|
|
}
|
|
|
|
$self->$field(sanitizer->sanitize($value, %santize_options));
|
|
}
|
|
|
|
return;
|
|
}
|
|
|
|
sub import {
|
|
my $class = shift;
|
|
my $caller = caller;
|
|
|
|
my $thing = $THINGS{$caller} = {
|
|
fields => {}
|
|
};
|
|
|
|
no strict 'refs';
|
|
no warnings 'redefine';
|
|
|
|
my $import = $caller->can('import');
|
|
|
|
*{"$caller\::import"} = sub {
|
|
foreach my $field (keys %{$thing->{fields}}) {
|
|
if (not $caller->can($field)) {
|
|
croak "Field: $field is not available on $caller";
|
|
}
|
|
}
|
|
|
|
if ($import) {
|
|
$import->(@_);
|
|
}
|
|
};
|
|
|
|
__PACKAGE__->export_to_level(1, @_);
|
|
}
|
|
|
|
1;
|