3
0
mirror of https://github.com/pragma-/pbot.git synced 2024-10-04 10:28:45 +02:00

ValidateString is now JSON-aware

This commit is contained in:
Pragmatic Software 2018-04-08 19:34:24 -07:00
parent c9d9322711
commit e033b5b837

View File

@ -1,17 +1,37 @@
package PBot::Utils::ValidateString; package PBot::Utils::ValidateString;
use 5.010; use warnings;
use warnings;
use strict;
require Exporter; require Exporter;
our @ISA = qw/Exporter/; our @ISA = qw/Exporter/;
our @EXPORT = qw/validate_string/; our @EXPORT = qw/validate_string/;
use JSON;
sub validate_string { sub validate_string {
my ($string, $max_length) = @_; my ($string, $max_length) = @_;
return $string if not defined $string or not length $string; return $string if not defined $string or not length $string;
$max_length = 2000 if not defined $max_length; $max_length = 1024 * 8 if not defined $max_length;
$string = substr $string, 0, $max_length unless $max_length <= 0;
eval {
my $h = decode_json($string);
foreach my $k (keys %$h) {
$h->{$k} = substr $h->{$k}, 0, $max_length unless $max_length <= 0;
}
$string = encode_json($h);
};
if ($@) {
# not a json string
$string = substr $string, 0, $max_length unless $max_length <= 0;
}
# $string =~ s/(\P{PosixGraph})/my $ch = $1; if ($ch =~ m{[\s\x03\x02\x1d\x1f\x16\x0f]}) { $ch } else { sprintf "\\x%02X", ord $ch }/ge; # $string =~ s/(\P{PosixGraph})/my $ch = $1; if ($ch =~ m{[\s\x03\x02\x1d\x1f\x16\x0f]}) { $ch } else { sprintf "\\x%02X", ord $ch }/ge;
# $string = substr $string, 0, $max_length unless $max_length <= 0; # $string = substr $string, 0, $max_length unless $max_length <= 0;
return $string; return $string;
} }