public
Last active

  • Download Gist
lib/Template/AutoFilter.pm
Perl
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
use strict;
use warnings;
 
package Template::AutoFilter;
 
use base 'Template';
 
use lib '..';
use Template::AutoFilter::Parser;
 
sub new {
my $class = shift;
 
my $params = defined($_[0]) && ref($_[0]) eq 'HASH' ? shift : {@_};
$params->{FILTERS}{none} ||= sub { $_[0] };
 
$params->{PARSER} ||= Template::AutoFilter::Parser->new( $params );
 
return $class->SUPER::new( $params );
}
 
1;
lib/Template/AutoFilter/Parser.pm
Perl
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
use strict;
use warnings;
 
package Template::AutoFilter::Parser;
 
use base 'Template::Parser';
 
sub new {
my ( $class, $params ) = @_;
 
my $self = $class->SUPER::new( $params );
$self->{AUTO_FILTER} = $params->{AUTO_FILTER} || 'html';
 
return $self;
}
 
sub split_text {
my ( $self, @args ) = @_;
my $tokens = $self->SUPER::split_text( @args ) or return;
 
for my $token ( @{$tokens} ) {
next if !ref $token;
 
my %fields = @{$token->[2]};
next if $fields{FILTER};
 
push @{$token->[2]}, qw( FILTER | IDENT ), $self->{AUTO_FILTER};
}
 
return $tokens;
}
 
1;
t/autofilter.t
Perl
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69
#!/usr/bin/perl
 
use strict;
use warnings;
 
package autofilter;
 
use lib 'lib';
use lib '../lib';
 
use Test::Most;
 
run_tests();
done_testing;
 
exit;
 
sub tests {(
{
name => 'plain text remains unfiltered',
tmpl => '<a>',
expect => '<a>',
},
{
name => 'excluded tokens remain unfiltered',
tmpl => '[% test | none %]',
expect => '<a>',
},
{
name => 'unfiltered tokens get filtered',
tmpl => '[% test %]',
expect => '&lt;a&gt;',
},
{
name => 'specifically filtered tokens get filtered',
tmpl => '[% test | html %]',
expect => '&lt;a&gt;',
},
{
name => 'other filters are applied without the autofilter',
tmpl => '[% test | upper %]',
expect => '<A>',
},
)}
 
sub run_tests {
use_ok "Template::AutoFilter";
 
run_test($_) for tests();
 
return;
}
 
sub run_test {
my ( $test ) = @_;
$test->{params} ||= {};
 
my $tt = Template::AutoFilter->new( $test->{params} );
my $out;
my $res = $tt->process( \$test->{tmpl}, { test => '<a>' }, \$out );
 
subtest $test->{name} => sub {
cmp_deeply( [ $tt->error, $res ], [ '', 1 ], 'no template errors' );
 
is( $out, $test->{expect}, 'output is correct' );
};
 
return;
}

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.