add sanitize sub
Matt S Trout [Wed, 21 Oct 2009 18:06:09 +0000 (14:06 -0400)]
lib/XML/Tags.pm
t/tags.t

index 1b2729c..4acc852 100644 (file)
@@ -5,8 +5,6 @@ use warnings FATAL => 'all';
 
 use File::Glob ();
 
-
-
 my $IN_SCOPE = 0;
 
 sub import {
@@ -22,6 +20,16 @@ sub import {
   $IN_SCOPE = 1;
 }
 
+sub sanitize {
+  map { # string == text -> HTML, scalarref == raw HTML, other == passthrough
+    ref($_)
+      ? (ref $_ eq 'SCALAR' ? $$_ : $_)
+      : do { local $_ = $_; # copy
+          s/&/&amp;/g; s/"/&quot/g; s/</&lt;/g; s/>/&gt;/g; $_;
+        }
+  } @_
+}
+
 sub _find_tags { shift; @_ }
 
 sub _find_target {
index e80d2b7..fa53f80 100644 (file)
--- a/t/tags.t
+++ b/t/tags.t
@@ -22,12 +22,12 @@ use Test::More qw(no_plan);
 
   sub quux {
     use HTML::Tags;
-    <html>, <body id="spoon">, \"YAY", </body>, </html>;
+    <html>, <body id="spoon">, "YAY", </body>, </html>;
   }
 }
 
 is(
-  join(', ', map ${$_}, Foo::foo()),
+  join(', ', XML::Tags::sanitize Foo::foo()),
   '<one>, <two>, <three>',
   'open tags ok'
 );
@@ -35,13 +35,13 @@ is(
 ok(!eval { Foo::bar(); 1 }, 'Death on use of unimported tag');
 
 is(
-  join(', ', map ${$_}, Foo::baz()),
+  join(', ', XML::Tags::sanitize Foo::baz()),
   '</bar>',
   'close tag ok'
 );
 
 is(
-  join('', map ${$_}, Foo::quux),
+  join('', XML::Tags::sanitize Foo::quux),
   '<html><body id="spoon">YAY</body></html>',
   'HTML tags ok'
 );