FormMagick/TagMaker.pm untested

filter: Statementstmt 0.0% 0 / 123 Branchbran 0.0% 0 / 40 Conditioncond 0.0% 0 / 15 MC/DCmcdc 0.0% 0 / 9 Subroutinesub 0.0% 0 / 12 Podpod 0.0% 0 / 8 totaltotal 0.0% 0 / 207 CC 21 SCAR 38.5
CC
21
Cov
0%
make_html_tag
90.0
make_html_tag_group
72.0
AUTOLOAD
20.0
CRAP 47.0
1 =head1 NAME
2  
3 CGI::FormMagick::TagMaker - Generate HTML tags
4  
5 =cut
6  
7 package CGI::FormMagick::TagMaker;
8 require 5.004;
9  
10 use strict;
11 use vars qw($VERSION @ISA $AUTOLOAD);
12 $VERSION = '1.01';
13  
14 use Class::ParamParser;
15 @ISA = qw( Class::ParamParser );
16  
17 =head1 SYNOPSIS
18  
19 use CGI::FormMagick::TagMaker;
20  
21 my $html = CGI::FormMagick::TagMaker->new();
22 $html->input( type => 'submit' ),
23  
24 =head1 DESCRIPTION
25  
26 This Perl 5 object class can be used to generate any HTML tags in a format that
27 is consistent with the W3C HTML 4.0 standard. There are no restrictions on what
28 tags are named, however; you can ask for any new or unsupported tag that comes
29 along from Netscape or Microsoft, and it will be made. Additionally, you can
30 generate lists of said tags with one method call, or just parts of said tags (but
31 not both at once).
32  
33 In this implementation, "standard format" means that tags are made as pairs
34 (<TAG></TAG>) by default, unless they are known to be "no pair" tags. Tags that
35 I know to be "no pair" are [basefont, img, area, param, br, hr, input, option,
36 tbody, frame, comment, isindex, base, link, meta]. However, you can force any
37 tag to be "pair" or "start only" or "end only" by appropriately modifying your
38 call to the tag making method.
39  
40 Also, "standard format" means that tag modifiers are formatted as "key=value" by
41 default, unless they are known to be "no value" modifiers. Modifiers that I know
42 to be "no value" are [ismap, noshade, compact, checked, multiple, selected,
43 nowrap, noresize, param]. These are formatted simply as "key" because their very
44 presence indicates positive assertion, while their absense means otherwise. For
45 modifiers with values, the values will always become bounded by quotes, which
46 ensures they work with both string and numerical quantities (eg: key="value").
47  
48 Note that this class is a subclass of Class::ParamParser, and inherits
49 all of its methods, "params_to_hash()" and "params_to_array()".
50  
51 =for testing
52 TODO: {
53 local $TODO = "Write tests for TagMaker!";
54 ok(0, "Fake test just to keep 'make test' happy");
55 }
56  
57 =cut
58  
59  
60 # Names of properties for objects of this class are declared here:
61 my $KEY_AUTO_GROUP = 'auto_group'; # do we make tag groups by default?
62 my $KEY_AUTO_POSIT = 'auto_posit'; # with methods whose parameters
63 # could be either named or positional, when we aren't sure what we
64 # are given, do we guess positional? Default is named.
65  
66 # These extra tag properties work only with AUTOLOAD:
67 my $PARAM_TEXT = 'text'; #tag pair is wrapped around this
68 my $PARAM_LIST = 'list'; #force tag groups to be returned in ARRAY ref
69  
70 # Constant values used in this class go here:
71  
72 my $TAG_GROUP = 'group'; # values that "what_to_make" can have
73 my $TAG_PAIR = 'pair';
74 my $TAG_START = 'start';
75 my $TAG_END = 'end';
76  
77 my %NO_PAIR_TAGS = ( # comments correspond to Bare Bones sections
78 basefont => 1, # PRESENTATION FORMATTING
79 img => 1, # LINKS, GRAPHICS, AND SOUNDS
80 area => 1, # LINKS, GRAPHICS, AND SOUNDS
81 param => 1, # LINKS, GRAPHICS, AND SOUNDS
82 br => 1, # DIVIDERS
83 hr => 1, # DIVIDERS
84 input => 1, # FORMS
85 option => 1, # FORMS
86 tbody => 1, # TABLES
87 frame => 1, # FRAMES
88 comment => 1, # MISCELLANEOUS
89 isindex => 1, # MISCELLANEOUS
90 base => 1, # MISCELLANEOUS
91 'link' => 1, # MISCELLANEOUS
92 meta => 1, # MISCELLANEOUS
93 );
94  
95 my %NO_VALUE_PARAMS = ( # comments correspond to Bare Bones sections
96 ismap => 1, # LINKS, GRAPHICS, AND SOUNDS
97 noshade => 1, # DIVIDERS
98 compact => 1, # LISTS
99 checked => 1, # FORMS
100 multiple => 1, # FORMS
101 selected => 1, # FORMS
102 nowrap => 1, # TABLES
103 noresize => 1, # FRAMES
104 param => 1, # SCRIPTS AND JAVA
105 );
106  
107 my %PARAMS_PRECEDENCE = ( # larger number means goes first; undef last
108 method => 190,
109 action => 185,
110 type => 180,
111 name => 175,
112 width => 170,
113 height => 165,
114 rows => 160,
115 cols => 155,
116 border => 150,
117 cellspacing => 145,
118 cellpadding => 140,
119 multiple => 135,
120 checked => 130,
121 selected => 125,
122 value => 120,
123 target => 115,
124 rev => 113,
125 rel => 112,
126 href => 110,
127 src => 105,
128 alt => 100,
129 );
130  
131 =head1 SYNTAX
132  
133 Through the magic of autoloading, this class can make any html tag by calling a
134 class method with the same name as the tag you want. For examples, use "hr()" to
135 make a "<HR>" tag, or "p('text')" to make "<P>text</P>". This also means that if
136 you mis-spell any method name, it will still make a new tag with the mis-spelled
137 name. For autoloaded methods only, the method names are case-insensitive.
138  
139 If you call a class method whose name ends in either of ['_start', '_end',
140 '_pair'], this will be interpreted as an instruction to make just part of one tag
141 whose name are the part of the method name preceeding that suffix. For example,
142 calling "p_start( 'text' )" results in "<P>text" rather than "<P>text</P>".
143 Similarly, calling "p_end()" will generate a "</P>" only. Using the '_pair'
144 suffix will force tags to be made as a pair, whether or not they would do so
145 naturally. For example, calling "br_pair" would produce a "<BR></BR>" rather
146 than the normal "<BR>". When using either of ['_start','_pair'], the arguments
147 you pass the method are exactly the same as the unmodified method would use, and
148 there are no other symantec differences. However, when using the '_end' suffix,
149 any arguments are ignored, as the latter member of a tag pair never carries any
150 attributes anyway.
151  
152 If you call a class method whose name ends in "_group", this will be interpreted
153 as an instruction to make a list of tags whose name are the part of the method
154 name preceeding the "_group". For example, calling "td_group(
155 ['here','we','are'] )" results in "<TD>here</TD><TD>we</TD><TD>are</TD>" being
156 generated. The arguments that you call this method are exactly the same as for
157 calling a method to make a single tag of the same name, except that the extra
158 optional parameter "list" can be used to force an ARRAY ref of the new tags to be
159 returned instead of a scalar. The symantec difference is that any arguments
160 whose values are ARRAY refs are interpreted as a list of values where each one is
161 used in a separate tag; for a single tag, the literal ARRAY ref itself would be
162 used. The number of tags produced is equal to the length of the longest ARRAY
163 ref passed as an argument. For any other arguments who have fewer than this
164 count, their last value is replicated and appended enough times as necessary to
165 make them the same length. The value of a scalar argument is used for all the
166 tags. For example, calling "input_group( type => checkbox, name => 'letters',
167 value => ['a','b','c'] )" produces '<INPUT TYPE="checkbox" NAME="letters"
168 VALUE="a"><INPUT TYPE="checkbox" NAME="letters" VALUE="b"><INPUT TYPE="checkbox"
169 NAME="letters" VALUE="c">'.
170  
171 All autoloaded methods require their parameters to be in named format. These
172 names and values correspond to attribute names and values for the new tags.
173 Since "no value" attributes are essentially booleans, they can have any true or
174 false value associated with them in the parameter list, which won't be printed.
175 If an autoloaded method is passed exactly one parameter, it will be interpreted
176 as the "text" that goes between the tag pair (<TAG>text</TAG>) or after "start
177 tags" (<TAG>text). The same result can be had explicitely by passing the named
178 parameter "text". Most static (non-autoloaded) methods require positional
179 parameters, except for start_html(), which can take either format. The names of
180 any named parameters can optionally start with a "-".
181  
182 =cut
183  
184 # All HTML tags have a method of this class associated with them.
185  
186 sub AUTOLOAD {
187 my $self = shift( @_ );
188 $AUTOLOAD =~ m/([^:]*)$/; # we don't need fully qualified name
189 my $called_sub_name = $1;
190  
191 my ($tag_name, $what_to_make) = split( '_', $called_sub_name, 2 );
192 unless( lc($what_to_make) =~
193 /^($TAG_GROUP|$TAG_PAIR|$TAG_START|$TAG_END)$/ ) {
194 if( $self->{$KEY_AUTO_GROUP} ) {
195 $what_to_make = $TAG_GROUP;
196 } else {
197 $what_to_make = undef;
198 }
199 }
200  
201 my $rh_params = $self->params_to_hash( \@_, 0, $PARAM_TEXT,
202 {}, $PARAM_TEXT );
203 my $ra_text = delete( $rh_params->{$PARAM_TEXT} );
204 my $force_list = delete( $rh_params->{$PARAM_LIST} );
205  
206 if( lc($what_to_make) eq $TAG_GROUP ) {
207 return( $self->make_html_tag_group(
208 $tag_name, $rh_params, $ra_text, $force_list ) );
209 }
210  
211 return( $self->make_html_tag(
212 $tag_name, $rh_params, $ra_text, $what_to_make ) );
213 }
214  
215 # This is provided so AUTOLOAD isn't called instead.
216 sub DESTROY {
217 }
218  
219 sub by_params_precedence {
220 local $PARAMS_PRECEDENCE{$a} ||= 0;
221 local $PARAMS_PRECEDENCE{$b} ||= 0;
222 return $PARAMS_PRECEDENCE{$a} <=> $PARAMS_PRECEDENCE{$b};
223 }
224  
225 =head1 FUNCTIONS AND METHODS
226  
227 Note that all the methods defined below are static, so information specific to
228 autoloaded methods won't likely apply to them. All of these methods take
229 positional arguments unless otherwise specified.
230  
231 =head2 new()
232  
233 This function creates a new HTML::TagMaker object (or subclass thereof) and
234 returns it.
235  
236 =for testing
237 BEGIN: {
238 use_ok('CGI::FormMagick::TagMaker');
239 }
240 my $t = CGI::FormMagick::TagMaker->new();
241 isa_ok($t, 'CGI::FormMagick::TagMaker');
242  
243 =cut
244  
245 sub new {
246 my $class = shift( @_ );
247 my $self = bless( {}, ref($class) || $class );
248 $self->{$KEY_AUTO_GROUP} = 0;
249 $self->{$KEY_AUTO_POSIT} = 0;
250 return( $self );
251 }
252  
253 =head2 groups_by_default([ VALUE ])
254  
255 This method is an accessor for the boolean "automatic grouping" property of this
256 object, which it returns. If VALUE is defined, this property is set to it. In
257 cases where we aren't told explicitely that autoloaded methods are making a
258 single or multiple tags (using ['_start', '_end', '_pair'] and '_group'
259 respectively), we look to this property to determine what operation we guess.
260 The default is "single". When this property is true, we can make both single and
261 groups of tags by using a suffix-less method name; however, making single tags
262 this way is slower than when this property is false. Also, be aware that when we
263 are making a "group", arguments that are ARRAY refs are always flattened, and
264 when we are making a "single", ARRAY ref arguments are always used literally.
265  
266 =cut
267  
268 sub groups_by_default {
269 my $self = shift( @_ );
270 if( defined( my $new_value = shift( @_ ) ) ) {
271 $self->{$KEY_AUTO_GROUP} = $new_value;
272 }
273 return( $self->{$KEY_AUTO_GROUP} );
274 }
275  
276 =head2 positional_by_default([ VALUE ])
277  
278 This method is an accessor for the boolean "positional arguments" property of
279 this object, which it returns. If VALUE is defined, this property is set to it.
280 With methods whose parameters could be either named or positional, when we aren't
281 sure what we are given, do we guess positional? Default is named.
282  
283 =cut
284  
285 sub positional_by_default {
286 my $self = shift( @_ );
287 if( defined( my $new_value = shift( @_ ) ) ) {
288 $self->{$KEY_AUTO_POSIT} = $new_value;
289 }
290 return( $self->{$KEY_AUTO_POSIT} );
291 }
292  
293 =head2 make_html_tag( NAME[, PARAMS[, TEXT[, PART]]] )
294  
295 This method is used internally to do the actual construction of single html tags.
296 You can call it directly when you want faster code and/or more control over how
297 tags are made. The first argument, NAME, is a scalar that defines the actual
298 name of the tag we are making (eg: 'br'); it is case-insensitive. The optional
299 second argument, PARAMS, is a HASH ref containing attribute names and values for
300 the new tag; the names (keys) are case-insensitive. The attribute values are all
301 printed literally, so they should be scalars. The optional third argument, TEXT,
302 is a scalar containing the text that goes between the tag pairs; it is not a tag
303 attribute. The optional fourth argument, PART, is a scalar which indicates we
304 should make just a certain part of the tag; acceptable values are ['pair',
305 'start', 'end'], and it is case-insensitive. This method knows which HTML tags
306 are normally paired or not, which tag attributes take specified values or not,
307 and acts accordingly.
308  
309 =cut
310  
311 sub make_html_tag {
312 my ($self, $tag_name, $rh_params, $text, $what_to_make) = @_;
313 $tag_name = lc($tag_name);
314 $what_to_make = lc($what_to_make);
315 $text = $text || '';
316  
317 my %tag_params = map { ( lc($_) => $rh_params->{$_} ) }
318 (ref($rh_params) eq 'HASH') ? (keys %{$rh_params}) : ();
319  
320 unless( $what_to_make =~ /^($TAG_PAIR|$TAG_START|$TAG_END)$/ ) {
321 $what_to_make =
322 $NO_PAIR_TAGS{$tag_name} ? $TAG_START : $TAG_PAIR;
323 }
324
325 my $tag_name_uc = uc($tag_name);
326
327 if( $what_to_make eq $TAG_END ) {
328 return( "\n</$tag_name_uc>" );
329 }
330
331 my $param_str = '';
332 foreach my $param ( sort by_params_precedence keys %tag_params ) {
333 next if( $NO_VALUE_PARAMS{$param} and !$tag_params{$param} );
334 $param_str .= ' '.uc( $param );
335 unless( $NO_VALUE_PARAMS{$param} ) {
336 if ($tag_params{$param}) {
337 $param_str .= "=\"$tag_params{$param}\"";
338 }
339 }
340 }
341  
342 if( $what_to_make eq $TAG_START ) {
343 return( "\n<$tag_name_uc$param_str>$text" );
344 }
345
346 return( "\n<$tag_name_uc$param_str>$text</$tag_name_uc>" );
347 }
348  
349 =head2 make_html_tag_group( NAME[, PARAMS[, TEXT[, LIST]]] )
350  
351 This method is used internally to do the actual construction of html tag groups.
352 You can call it directly when you want faster code and/or more control over how
353 tags are made. The first argument, NAME, is a scalar that defines the actual
354 name of the tag we are making (eg: 'br'); it is case-insensitive. The optional
355 second argument, PARAMS, is a HASH ref containing attribute names and values for
356 the new tag; the names (keys) are case-insensitive. Any attribute values which
357 are ARRAY refs are flattened, and the number of tags made is determined by the
358 length of the longest one. The optional third argument, TEXT, is a HASH ref (or
359 scalar) containing the text that goes between the tag pairs; it is not a tag
360 attribute, but if its an ARRAY ref then its length will influence the number of
361 tags that are made as the length of tag attribute arrays do. The optional fourth
362 argument, LIST, is a boolean/scalar which indicates whether this method returns
363 the new tags in an ARRAY ref (one tag per element) or as a scalar (tags are
364 concatenated together); a true value forces an ARRAY ref, scalar is the default.
365 This method knows which HTML tags are normally paired or not, which tag
366 attributes take specified values or not, and acts accordingly.
367  
368 =cut
369  
370 sub make_html_tag_group {
371 my $self = shift( @_ );
372 my $tag_name = lc(shift( @_ ));
373 my $rh_params = shift( @_ );
374 my $text_in = shift( @_ );
375 my $force_list = shift( @_ );
376  
377 my %tag_params = map { ( lc($_) => $rh_params->{$_} ) }
378 (ref($rh_params) eq 'HASH') ? (keys %{$rh_params}) : ();
379  
380 $tag_params{$PARAM_TEXT} = $text_in;
381  
382 my $max_tag_ind = 0;
383 foreach my $key (keys %tag_params) {
384 my $ra_values = $tag_params{$key};
385 unless( ref($ra_values) eq 'ARRAY' ) {
386 $tag_params{$key} = [$ra_values];
387 next;
388 }
389 if( $#{$ra_values} > $max_tag_ind ) {
390 $max_tag_ind = $#{$ra_values};
391 }
392 }
393  
394 foreach my $ra_values (values %tag_params) {
395 my $last_value = $ra_values->[-1];
396 push( @{$ra_values},
397 map { $last_value } (($#{$ra_values} + 1)..$max_tag_ind) );
398 }
399
400 my $tag_name_uc = uc($tag_name);
401 my $ra_text = delete( $tag_params{$PARAM_TEXT} );
402 my @param_seq = sort by_params_precedence keys %tag_params;
403 my @new_tags = ();
404  
405 foreach my $index (0..$max_tag_ind) {
406 my $param_str = '';
407 foreach my $param ( @param_seq ) {
408 next if( $NO_VALUE_PARAMS{$param} and
409 !$tag_params{$param}->[$index] );
410 $param_str .= ' '.uc( $param );
411 unless( $NO_VALUE_PARAMS{$param} ) {
412 $param_str .= "=\"$tag_params{$param}->[$index]\"";
413 }
414 }
415 my $text = $ra_text->[$index];
416 if( $NO_PAIR_TAGS{$tag_name} ) {
417 push( @new_tags, "\n<$tag_name_uc$param_str>$text" );
418 } else {
419 push( @new_tags,
420 "\n<$tag_name_uc$param_str>$text</$tag_name_uc>" );
421 }
422 }
423  
424 return( $force_list ? \@new_tags : join( '', @new_tags ) );
425 }
426  
427 1;
428  
429  
430 =head1 COMPATABILITY WITH OTHER MODULES
431  
432 The methods of this class and their parameters are designed to be compatible with
433 any same-named methods in the popular CGI.pm class. This class will produce
434 identical or browser-compatible HTML from such methods, and this class can accept
435 all the same argument formats. Exceptions to this include:
436  
437 =over 4
438  
439 =item 0
440  
441 None of our methods are exported and must be called using indirect
442 notation, whereas CGI.pm can export any of it's methods.
443  
444 =item 0
445  
446 start_html() doesn't support all the same arguments, but those that do have
447 the same names. However, the effects of the missing arguments can be easily
448 replicated by making the appropriate tags explicitely and handing them in via
449 either the "head" or "body" arguments, where appropriate. The common arguments
450 are ['title', 'author', 'meta', 'style', 'head', 'body'], in that order.
451  
452 =item 0
453  
454 Our textarea() method is autoloaded, and doesn't have the special symantecs
455 that CGI.pm's textarea() does. However, any module who subclasses from this one
456 can override textarea() with one that matches CGI.pm's symantecs. The
457 "HTML::FormMaker" module does this.
458  
459 =item 0
460  
461 Autoloaded methods do not use the presence or absense of arguments to
462 decide whether to make the new tag as a pair or as "start only".
463  
464 =item 0
465  
466 Autoloaded methods that make html tags won't concatenate their arguments
467 into a single argument under any circumstances, but in some cases the "shortcuts"
468 of CGI.pm will do so.
469  
470 =item 0
471  
472 Currently we don't html-escape any argument values passed to our tag making
473 functions, whereas CGI.pm sometimes does. While we expect our caller to do the
474 escaping themselves where necessary, we may do it later in an update.
475  
476 =item 0
477  
478 We go further to make the generated HTML human-readable by: 1. having each
479 new tag start on a new line; 2. making all tag and attribute names uppercase; 3.
480 ensuring that about 20 often-used tag attributes always appear in the same order
481 (eg: 'type' is before 'name' is before 'value'), and before any others.
482  
483 =back
484  
485  
486 =head1 COPYING
487  
488 Copyright (c) 2000-2001, Kirrily "Skud" Robert <skud@cpan.org>
489  
490 This module is free software; you can redistribute it and/or modify it
491 under the same terms and Perl itself.
492  
493 This module is based on Darren Duncan's HTML::TagMaker, the copyright
494 notice for which appears below:
495  
496 Copyright (c) 1999-2000, Darren R. Duncan. All rights reserved.
497  
498 This module is free software; you can redistribute it and/or modify it under
499 the same terms as Perl itself. However, I do request that this copyright information
500 remain attached to the file. If you modify this module and redistribute a changed
501 version then please attach a note listing the modifications.
502  
503 =head1 SEE ALSO
504  
505 L<CGI::FormMagick>
506  
507  
508 =cut