Valiant/JSON/Util.pm

filter: Statementstmt 100% 22 / 22 Branchbran 50.0% 1 / 2 Conditioncond n/a MC/DCmcdc n/a Subroutinesub 100% 4 / 4 Podpod 100% 1 / 1 totaltotal 96.5% 28 / 29 CC 2 SCAR 3.4
CC
2
Cov
96%
escape_javascript
2.0
BEGIN
1.0
BEGIN
1.0
CRAP 1.4
« Valiant/Filter/Upper.pm ↑ Summary Valiant/Filter/Numberize.pm »
1 package Valiant::JSON::Util;
2  
3 1 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 1 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
5 1 ▶use Exporter 'import';
Subroutine BEGIN: called CC=1 SCAR=0.0
6
7  
8 1 our @EXPORT_OK = qw(escape_javascript);
9 1 our %EXPORT_TAGS = (all => \@EXPORT_OK);
10  
11 1 my %JS_ESCAPE_MAP = (
12 '\\' => '\\\\',
13 '</' => '<\/',
14 "\r\n" => '\n',
15 "\3342\2200\2250" => '\x{3342}\x{2200}\x{2250}',
16 "\3342\2200\2251" => '\x{3342}\x{2200}\x{2251}',
17 "\n" => '\n',
18 "\r" => '\n',
19 '"' => '\"',
20 "'" => "\\'"
21 );
22  
23 1 ▶sub escape_javascript {
Subroutine escape_javascript: called CC=2 SCAR=6.9
Pod documented
24 1 my ($javascript) = @_;
25 1 ▶ return "" unless $javascript;
Branch: 1 branch
BranchTrueFalseTotal
unless $javascript 0 1 1
26  
27 # Longest-first to avoid partial matches shadowing longer ones
28 my $pattern = join '|',
29 9 map { quotemeta }
30 1 sort { length($b) <=> length($a) } keys %JS_ESCAPE_MAP;
31  
32 1 my $result = $javascript; # make a copy (since 5.10 lacks /r)
33 1 $result =~ s/($pattern)/$JS_ESCAPE_MAP{$1}/eg;
34 1 return $result;
35 }
36  
37 1 1;
38  
39 =head1 NAME
40  
41 Valiant::JSON::Util - Importable utility methods
42  
43 =head1 SYNOPSIS
44  
45 use Valiant::JSON::Util 'escape_javascript';
46  
47 =head1 DESCRIPTION
48  
49 Just a place to stick various utility functions that are cross cutting concerns.
50  
51 =head1 SUBROUTINES
52  
53 This package has the following subroutines for EXPORT
54  
55 =head2 escape_javascript
56  
57 escape_javascript($string);
58  
59 Escapes a string so it can be used inside a javascript string: escapes ' and " and \
60 and newlines and a few other characters so that you can use a string as a javascript
61 value. Helps with injection attacks (but isn't everything you need).
62  
63 =head1 SEE ALSO
64
65 L<Valiant>
66  
67 =head1 AUTHOR
68
69 See L<Valiant>
70  
71 =head1 COPYRIGHT & LICENSE
72
73 See L<Valiant>
74  
75 =cut
« Valiant/Filter/Upper.pm ↑ Summary Valiant/Filter/Numberize.pm »