HTML::Util: Short circuit ohne $value. Behebt gleichzeitig eine Warnung.
[kivitendo-erp.git] / SL / HTML / Util.pm
1 package SL::HTML::Util;
2
3 use strict;
4 use warnings;
5
6 use HTML::Parser;
7
8 my %stripper;
9 my %entities = (
10   'lt'  => '<',
11   'gt'  => '>',
12   'amp' => '&',
13 );
14
15 sub strip {
16   my ($class_or_value) = @_;
17
18   my $value = !ref($class_or_value) && (($class_or_value // '') eq 'SL::HTML::Util') ? $_[1] : $class_or_value;
19
20   return '' unless $value;
21
22   if (!%stripper) {
23     %stripper = ( parser => HTML::Parser->new );
24
25     $stripper{parser}->handler(text => sub { $stripper{text} .= $_[1]; });
26   }
27
28   $stripper{text} = '';
29   $stripper{parser}->parse($value);
30   $stripper{parser}->eof;
31
32   $stripper{text} =~ s{\&([^;]+);}{ $entities{$1} || "\&$1;" }eg;
33
34   return delete $stripper{text};
35 }
36
37 1;
38 __END__
39
40 =pod
41
42 =encoding utf8
43
44 =head1 NAME
45
46 SL::HTML::Util - Utility functions dealing with HTML
47
48 =head1 SYNOPSIS
49
50   my $plain_text = SL::HTML::Util->strip('<h1>Hello World</h1>');
51
52 =head1 FUNCTIONS
53
54 =over 4
55
56 =item C<strip $html_content>
57
58 Removes all HTML elements and tags from C<$html_content> and returns
59 the remaining plain text.
60
61 =back
62
63 =head1 BUGS
64
65 Nothing here yet.
66
67 =head1 AUTHOR
68
69 Moritz Bunkus E<lt>m.bunkus@linet-services.deE<gt>
70
71 =cut