c8c78a092f7084b1ed88db8348ab3919e721c8e9
[kivitendo-erp.git] / SL / Presenter / EscapedText.pm
1 package SL::Presenter::EscapedText;
2
3 use strict;
4
5 use JSON ();
6
7 use overload '""' => \&escaped;
8
9 sub new {
10   my ($class, %params) = @_;
11
12   return $params{text} if ref($params{text}) eq $class;
13
14   my $self      = bless {}, $class;
15   $self->{text} = $params{is_escaped} ? $params{text} : $::locale->quote_special_chars('HTML', $params{text});
16
17   return $self;
18 }
19
20 sub escaped {
21   my ($self) = @_;
22   return $self->{text};
23 }
24
25 sub TO_JSON {
26   goto &escaped;
27 }
28
29 1;
30 __END__
31
32 =pod
33
34 =encoding utf8
35
36 =head1 NAME
37
38 SL::Presenter::EscapedText - Thin proxy object around HTML-escaped strings
39
40 =head1 SYNOPSIS
41
42   use SL::Presenter::EscapedText;
43
44   sub blackbox {
45     my ($text) = @_;
46     return SL::Presenter::EscapedText->new(text => $text);
47   }
48
49   sub build_output {
50     my $output_of_other_component = blackbox('Hello & Goodbye');
51
52     # The following is safe, text will not be escaped twice:
53     return SL::Presenter::EscapedText->new(text => $output_of_other_component);
54   }
55
56   my $output = build_output();
57   print "Yeah: $output\n";
58
59 =head1 OVERVIEW
60
61 Sometimes it's nice to let a sub-component build its own
62 representation. However, you always have to be very careful about
63 whose responsibility escaping is. Only the building function knows
64 enough about the structure to be able to HTML escape properly.
65
66 But higher functions should not have to care if the output is already
67 escaped -- they should be able to simply escape it again. Without
68 producing stuff like '&'.
69
70 Stringification is overloaded. It will return the same as L<escaped>.
71
72 This works together with the template plugin
73 L<SL::Template::Plugin::P> and its C<escape> method.
74
75 =head1 FUNCTIONS
76
77 =over 4
78
79 =item C<new %params>
80
81 Creates an instance of C<EscapedText>.
82
83 The parameter C<text> is the text to escape. If it is already an
84 instance of C<EscapedText> then C<$params{text}> is returned
85 unmodified.
86
87 Otherwise C<text> is HTML-escaped and stored in the new instance. This
88 can be overridden by setting C<$params{is_escaped}> to a trueish
89 value.
90
91 =item C<escaped>
92
93 Returns the escaped string (not an instance of C<EscapedText> but an
94 actual string).
95
96 =back
97
98 =head1 BUGS
99
100 Nothing here yet.
101
102 =head1 AUTHOR
103
104 Moritz Bunkus E<lt>m.bunkus@linet-services.deE<gt>
105
106 =cut