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