MetaText/Factory.pm

filter: Statementstmt 89.0% 89 / 100 Branchbran 70.5% 24 / 34 Conditioncond 36.0% 9 / 25 MC/DCmcdc 6.6% 1 / 15 Subroutinesub 83.3% 10 / 12 Podpod 0.0% 0 / 4 totaltotal 70.0% 133 / 190 CC 28 SCAR 22.9
CC
28
Cov
77%
create_directive
18.2
_split_text
7.0
error
6.0
CRAP 9.9
« MetaText.pm ↑ Summary MetaText/Directive.pm »
1 #============================================================================
2 #
3 # Text::MetaText::Factory
4 #
5 # DESCRIPTION
6 # Objects of the the MetaText Factory class (Text::MetaText::Factory)
7 # are used to instantiate objects of the MetaText Directive class
8 # (Text::MetaText::Directive) or sub-classes. The default factory
9 # is responsible for parsing the contents of a directive string and
10 # creating from that a specifically configured Directive object. The
11 # MetaText object class (Text::MetaText) uses a factory instance (which
12 # may be user-supplied at run-time) in constructing a parsed ("compiled")
13 # representation of a document. The Factory and Directive classes can
14 # easily be sub-classed to derive more specific objects that can then be
15 # used in the standard MetaText framework.
16 #
17 # AUTHOR
18 # Andy Wardley <abw@kfs.org>
19 #
20 # COPYRIGHT
21 # Copyright (C) 1996-1998 Andy Wardley. All Rights Reserved.
22 #
23 # This module is free software; you can redistribute it and/or
24 # modify it under the terms of the Perl Artistic Licence.
25 #
26 #----------------------------------------------------------------------------
27 #
28 # $Id: Factory.pm,v 0.2 1998/09/01 12:59:45 abw Exp abw $
29 #
30 #============================================================================
31
32 package Text::MetaText::Factory;
33  
34 9 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
35 9 ▶use vars qw( $VERSION $DIRECTIVE $ERROR $CONTROL );
Subroutine BEGIN: called CC=1 SCAR=0.0
36  
37 9 ▶use Text::MetaText::Directive;
Subroutine BEGIN: called CC=1 SCAR=0.0
38  
39 9 require 5.004;
40  
41  
42  
43 #========================================================================
44 # ----- CONFIGURATION -----
45 #========================================================================
46
47 9 $VERSION = sprintf("%d.%02d", q$Revision: 0.2 $ =~ /(\d+)\.(\d+)/);
48 9 $DIRECTIVE = 'Text::MetaText::Directive'; # default directive type
49  
50 # define the control parameters valid for each directive type
51 $CONTROL = {
52 18 DEFINE => { map { $_ => 1 } qw( IF UNLESS ) },
53 36 SUBST => { map { $_ => 1 } qw( IF UNLESS FORMAT FILTER ) },
54 36 INCLUDE => { map { $_ => 1 } qw( IF UNLESS FORMAT FILTER ) },
55 9 BLOCK => { map { $_ => 1 } qw( PRINT TRIM ) },
56 };
57  
58  
59  
60 #========================================================================
61 # ----- PUBLIC METHODS -----
62 #========================================================================
63
64 #========================================================================
65 #
66 # new(\%cfg)
67 #
68 # Object constructor. A reference to a hash array of configuration
69 # options may be passed which is then delegated to _configure() to
70 # process.
71 #
72 # Returns a reference to a newly created Text::MetaText::Factory object.
73 #
74 #========================================================================
75  
76 14 ▶sub new {
Subroutine new: called CC=5 SCAR=17.6
Pod undocumented
77 14 my $self = shift;
78 14 ▶ my $class = ref($self) || $self;
Condition33%1/3
ref $self || $self
l!l&&r!l&&!r
0140
MC/DC0%0/2
ref $self || $self
ref $self $self
Truth table33%1/3
A || B
A= ref $selfB= $self
ABresult
1X1
011
000
79 14 my $cfg = shift;
80  
81  
82 # make me an object
83 14 $self = bless { }, $class;
84  
85 # the configuration hash, $cfg, may contain an entry $cfg->{ DIRECTIVE }
86 # which names the directive class which the factory is expected to
87 # instantiate. If this is undefined, the $DIRECTIVE variable in the
88 # class package (which may be a sub-class) and in the current (base-
89 # class) package are checked, in that order, and used if defined.
90 {
91 # turn off strict reference checking for this block so that we can
92 # construct a variable name in the calling package without warning
93 9 ▶ no strict 'refs';
Subroutine BEGIN: called CC=1 SCAR=0.0
94  
95 $self->{ DIRECTIVE } = # specified in...
96 $cfg->{ DIRECTIVE } # ...the $cfg hashref
97 14 ▶ || ${ "$class\::DIRECTIVE" } # ...the calling package, $class
Condition33%2/6
$cfg->{'DIRECTIVE'} || ${"${class}::DIRECTIVE";} || $Text::MetaText::Factory::DIRECTIVE
l!l&&r!l&&!r
1400
$cfg->{"DIRECTIVE"} or ${"${class}::DIRECTIVE";}
l!l&&r!l&&!r
0140
MC/DC0%0/3
$cfg->{'DIRECTIVE'} || ${"${class}::DIRECTIVE";} || $Text::MetaText::Factory::DIRECTIVE
$cfg->{"DIRECTIVE"} ${"${class}::DIRECTIVE";} $Text::MetaText::Factory::DIRECTIVE
Truth table25%1/4
A or B || C
A= $cfg->{"DIRECTIVE"}B= ${"${class}::DIRECTIVE";}C= $Text::MetaText::Factory::DIRECTIVE
ABCresult
1XX1
01X1
0011
0000
98 || $DIRECTIVE; # ...the current (base) package
99 }
100  
101 # we call _configure() which in this base class does very little but
102 # acts as a convenient hook for sub-classes. The return value of
103 # _configure() indicates if the constructor should return a $self
104 # reference to indicate success (any true value) or undef to indicate
105 # failure (any false value)
106 14 ▶ $self->_configure($cfg)
Branch: 1 branch
BranchTrueFalseTotal
$self->_configure($cfg) ? : 14 0 14
107 ? $self
108 : undef;
109 }
110  
111  
112  
113 #========================================================================
114 #
115 # create_directive($text)
116 #
117 # The public method create_directive() is called by Text::MetaText when
118 # is has identified a text string enclosed in the MetaText magic marker
119 # tokens (default: '%%' ... '%%') which it needs converting to a
120 # Directive object. The text string to be converted is passed in the
121 # only parameter, $text.
122 #
123 # Returns a reference to a newly created Text::MetaText::Directive
124 # object, or derivative. On error, undef is returned and an appropriate
125 # error message will be stored internally, available through the public
126 # error() method.
127 #
128 #========================================================================
129  
130 230 ▶sub create_directive {
Subroutine create_directive: called CC=15 SCAR=29.0
Pod undocumented
131 230 my $self = shift;
132 230 my $text = shift;
133  
134 230 my $directive = { };
135 230 my ($type, $ident);
136 230 my ($tokens, $token);
137 230 my ($name, $value);
138 230 my ($ucname, $uctype);
139  
140  
141 # save the original parameter text string
142 230 $directive->{ PARAMSTR } = $text;
143  
144 # split the text string into lexical tokens
145 230 $tokens = $self->_split_text($text);
146  
147 # identify the type (first token) in the parameter string
148 230 ▶ unless (defined($type = shift @$tokens) && ! ref($type)) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined($type = shift @$tokens) and not ref $type) 0 230 230
Condition33%1/3
defined($type = shift @$tokens) and not ref $type
!ll&&!rl&&r
00230
MC/DC0%0/2
defined($type = shift @$tokens) and not ref $type
defined($type = shift @$tokens) not ref $type
Truth table33%1/3
A and not(B)
A= defined($type = shift @$tokens)B= not ref $type
ABresult
0X0
100
111
149 0 $self->_error("Missing directive keyword");
150 0 return undef;
151 }
152  
153 # keep an UPPER CASE $type to avoid using case insensitive regexen
154 230 $uctype = uc $type;
155  
156  
157 # parse the directive parameters according to the directive type
158 TYPE: {
159
160 # END(BLOCK|IF)? directive ignores everything
161 230 ▶ $uctype =~ /^END(BLOCK|IF)?$/o && do {
Branch: 1 branch
BranchTrueFalseTotal
$uctype =~ /^END(BLOCK|IF)?$/o and do { $ident = ""; last TYPE } 19 211 230
162 19 $ident = '';
163 19 last TYPE;
164 };
165  
166 # DEFINE directive has optional identifier and params
167 211 ▶ $uctype =~ /^DEFINE$/o && do {
Branch: 1 branch
BranchTrueFalseTotal
$uctype =~ /^DEFINE$/o and do { $ident = @$tokens && !ref($tokens->[0]) ? shift @$tokens : ""; last TYPE } 37 174 211
168  
169 # identifier must be a simple variable
170 37 ▶ $ident = (@$tokens && !ref($tokens->[0]))
Branch: 1 branch
BranchTrueFalseTotal
@$tokens && !ref($tokens->[0]) ? : 0 37 37
Condition33%1/3
@$tokens and not ref $tokens->[0]
!ll&&!rl&&r
0370
MC/DC0%0/2
@$tokens and not ref $tokens->[0]
@$tokens not ref $tokens->[0]
Truth table33%1/3
A and not(B)
A= @$tokensB= not ref $tokens->[0]
ABresult
0X0
100
111
171 ? shift(@$tokens)
172 : '';
173 37 last TYPE;
174 };
175
176 # INCLUDE/SUBST/BLOCK have mandatory identifier and
177 # optional params
178 174 ▶ $uctype =~ /^(INCLUDE|SUBST|BLOCK)$/o && do {
Branch: 1 branch
BranchTrueFalseTotal
$uctype =~ /^(INCLUDE|SUBST|BLOCK)$/o and do { unless (@$tokens and not ref $tokens->[0]) { $self->_error("No identifier in $type directive"); return undef; } ; $ident = shift @$tokens; last TYPE } 97 77 174
179  
180 # check there is a simple text identifier
181 97 ▶ unless (@$tokens && !ref($tokens->[0])) {
Branch: 1 branch
BranchTrueFalseTotal
unless (@$tokens and not ref $tokens->[0]) 0 97 97
Condition33%1/3
@$tokens and not ref $tokens->[0]
!ll&&!rl&&r
0097
MC/DC0%0/2
@$tokens and not ref $tokens->[0]
@$tokens not ref $tokens->[0]
Truth table33%1/3
A and not(B)
A= @$tokensB= not ref $tokens->[0]
ABresult
0X0
100
111
182 0 $self->_error("No identifier in $type directive");
183 0 return undef;
184 };
185 97 $ident = shift(@$tokens);
186 97 last TYPE;
187 };
188  
189 # if the type isn't recognised, we assume it's a basic SUBST
190 77 $ident = $type;
191 77 $type = $uctype = 'SUBST';
192 }
193  
194 # save identifier (as is) and keyword (in upper case)
195 230 $directive->{ TYPE } = $uctype;
196 230 $directive->{ IDENTIFIER } = $ident;
197  
198 # initialise parameter hash
199 230 $directive->{ PARAMS } = {};
200  
201 # examine, process and store the additional directive parameters
202 230 foreach $token (@$tokens) {
203
204 # extract/create a name, value pair from token (array or scalar)
205 178 ▶ ($name, $value) = ref($token) eq 'ARRAY'
Branch: 1 branch
BranchTrueFalseTotal
ref $token eq 'ARRAY' ? : 169 9 178
206 ? @$token
207 : ($token, 0);
208  
209 # un-escape any escaped characters in the value
210 178 $value =~ s/\\(.)/$1/go;
211  
212 # keep an UPPER CASE copy of the name
213 178 $ucname = uc $name;
214  
215 # is this a "control" parameter?
216 178 ▶ if (defined $CONTROL->{ $uctype }->{ $ucname }) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $Text::MetaText::Factory::CONTROL->{$uctype}{$ucname}) { } 58 120 178
217 # control params are forced to upper case
218 58 $directive->{ $ucname } = $value;
219 }
220 # otherwise, it's a normal variable parameter
221 else {
222 120 $directive->{ PARAMS }->{ $name } = $value;
223 }
224 }
225  
226  
227 # create a new Directive and check everything worked OK
228 230 ▶ unless (defined($directive = $self->{ DIRECTIVE }->new($directive))) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined($directive = $self->{"DIRECTIVE"}->new($directive))) 0 230 230
229 # we need to construct a soft reference to the error function in
230 # the Directive base class
231 9 ▶ no strict 'refs';
Subroutine BEGIN: called CC=1 SCAR=0.0
232  
233 $self->_error("Directive constructor failed: %s",
234 0 ▶ &{ $self->{ DIRECTIVE } . "\::error" } || '<unreported error>');
Condition0%0/2
&{$self->{'DIRECTIVE'} . '::error';} || '<unreported error>'
l!l
00
MC/DC0%0/1
&{$self->{'DIRECTIVE'} . '::error';} || '<unreported error>'
&{$self->{'DIRECTIVE'} . '::error';}
Truth table0%0/2
A
A= &{$self->{'DIRECTIVE'} . '::error';}
Aresult
11
00
235 }
236  
237 # return undef or reference to newly constructed directive
238 230 $directive;
239 }
240  
241  
242  
243 #========================================================================
244 #
245 # directive_type()
246 #
247 # Public method used by calling objects to determine the class type of
248 # the directives that the Factory creates via the create_directive()
249 # method.
250 #
251 # Returns a string containing the class name.
252 #
253 #========================================================================
254  
255 85 ▶sub directive_type {
Subroutine directive_type: called CC=1 SCAR=0.0
Pod undocumented
256 85 my $self = shift;
257  
258 85 $self->{ DIRECTIVE };
259 }
260  
261  
262  
263 #========================================================================
264 #
265 # error()
266 #
267 # Returns the current object error message, stored internally in
268 # $self->{ ERROR } or undef if no error condition is recorded. If the
269 # first (implicit) parameter isn't an object reference, then this must
270 # have been called as a package function rather than an object method.
271 # In this case, the contents of the package variable, $ERROR, is
272 # returned. e.g.
273 #
274 # $factory->error(); # returns $self->{ ERROR }
275 # Text::MetaText::Factory::error(); # returns $ERROR
276 #
277 # Returns an error string or undef if no error condition is currently
278 # raised.
279 #
280 #========================================================================
281  
282 0 ▶sub error {
Subroutine error: not called CC=2 SCAR=17.9
Pod undocumented
283 0 my $self = shift;
284  
285 defined $self
286 ? $self->{ ERROR }
287 0 ▶ : $ERROR;
Branch: 1 branch
BranchTrueFalseTotal
defined $self ? : 0 0 0
288 }
289  
290  
291  
292 #========================================================================
293 # ----- PRIVATE METHODS -----
294 #========================================================================
295
296 #========================================================================
297 #
298 # _configure(\%cfg)
299 #
300 # Private initialisation method called by the new() constructor.
301 # This acts as a hook method for derived classes who may wish to do
302 # specific initialisation. Errors can be reported in the _configure()
303 # method by calling $self->_error(...)
304 #
305 # Returns 1 on success, undef on failure. Derived methods must follow
306 # this protocol if they utilise the base class constructor, new(), and
307 # return a true/undef value to indicate if the method was successful or
308 # not. This affects whether or not the constructor returns a new object
309 # or undef to indicate failure.
310 #
311 #========================================================================
312  
313 14 ▶sub _configure {
Subroutine _configure: called CC=2 SCAR=7.1
314 14 my $self = shift;
315 14 ▶ my $cfg = shift || { };
Condition50%1/2
shift() || {}
l!l
140
MC/DC0%0/1
shift() || {}
shift()
Truth table50%1/2
A
A= shift()
Aresult
11
00
316  
317  
318 # do nothing - just return success
319 14 1;
320 }
321  
322  
323  
324 #========================================================================
325 #
326 # _split_text($text)
327 #
328 # Utility routine to split the input text, $text, into lexical tokens.
329 # The tokens are identified as single words which are pushed directly
330 # onto a "@tokens" list, or "<variable> = <value>" pairs which are
331 # coerced into a two-element array ([0] => variable, [1] => value) which
332 # is then stored in the list by reference.
333 #
334 # A reference to the list of tokens is returned. On error, undef is
335 # returned and the internal ERROR string will be set.
336 #
337 #========================================================================
338  
339 230 ▶sub _split_text {
Subroutine _split_text: called CC=7 SCAR=19.5
340 230 my $self = shift;
341 230 my $text = shift;
342 230 my @tokens = ();
343  
344  
345 # some simple definitions of elements we use in the regex
346 230 my $word = q((\S+)); # a word
347 230 my $space = q(\s*); # optional space
348 230 my $quote = q("); # single or double quote characters
349 230 my $escape = "\\\\"; # an escape \\ (both '\' escaped)
350 230 my $anyquote = "[$quote]"; # class for quote chars
351 230 my $equals = "$space=$space"; # '=', with optional whitespace
352  
353 # within a quoted phrase we might find escaped quotes, e.g.
354 # name = "James \"Charlie\" Brown"; to detect this, we scan
355 # for sequences of legal characters (not quotes or escapes) up until
356 # the first quote or escape; if we find an escape, we jump past the
357 # next character (possible a quote) and repeat the process, and repeat
358 # the process, and so on until we *don't* find an escape as the next
359 # character; that implies it's an unescaped quote and the string ends.
360 # (don't worry if that slipped you by - just think of it as magic)
361  
362 230 my $okchars = "[^$quote$escape]*";
363 230 my $qphrase = "$anyquote ( $okchars ($escape.$okchars)* ) $anyquote";
364  
365  
366 # split directive parameters; note that our definitions from
367 # above have embedded substrings ( ) so we need to be a little
368 # careful about counting backreferences accurately...
369 230 ▶ while ($text =~
Branch: 1 branch
BranchTrueFalseTotal
if ($text =~ / $word $equals $qphrase # $1 = $2 (NB: $2 contains $3) | # e.g. (foo) = "(bar baz)" $word $equals $word # $4 = $5 | # e.g. (foo) = (bar) $qphrase # $6 (NB: $6 contains $7) | # e.g. "(foo bar)" $word # $8 # e.g. (foo) /gox) 505 230 735
370 /
371 $word $equals $qphrase # $1 = $2 (NB: $2 contains $3)
372 | # e.g. (foo) = "(bar baz)"
373 $word $equals $word # $4 = $5
374 | # e.g. (foo) = (bar)
375 $qphrase # $6 (NB: $6 contains $7)
376 | # e.g. "(foo bar)"
377 $word # $8
378 # e.g. (foo)
379 /gxo) { # 'o' - compile regex once only
380  
381 505 ▶ if ($6 or $8) {
Branch: 1 branch
BranchTrueFalseTotal
if ($6 or $8) { } 336 169 505
Condition66%2/3
$6 or $8
l!l&&r!l&&!r
0336169
MC/DC50%1/2
$6 or $8
$6 $8
Truth table66%2/3
A or B
A= $6B= $8
ABresult
1X1
011
000
382 # if $6 or $8 is defined, we found a simple flag. This gets
383 # pushed directly onto the tokens list
384 336 ▶ push(@tokens, defined($6) ? $6 : $8);
Branch: 1 branch
BranchTrueFalseTotal
defined $6 ? : 0 336 336
385 }
386 else {
387 # $6 and $8 undefined so use $1 = $2, or $4 = $5. This
388 # "name = value" pair get pushed onto the token list as
389 # an array reference
390 169 ▶ push(@tokens, [
Branch: 2 branches
BranchTrueFalseTotal
defined $1 ? : 71 98 169
defined $1 ? : 71 98 169
391 defined($1) ? $1 : $4,
392 defined($1) ? $2 : $5
393 ]);
394 }
395 }
396  
397 # return a reference to the tokens list
398 230 \@tokens;
399 }
400  
401  
402  
403 #========================================================================
404 #
405 # sub _error($errmsg, @params)
406 #
407 # Formats the error message format, $errmsg, and any additional parameters,
408 # @params with sprintf and sets the $self->{ ERROR } variable with the
409 # resulting string. This is then available via the public error() method.
410 # The package variable, $ERROR, is also set so that the error can be
411 # determined when the constructor fails (and hence there would be no $self
412 # in which to store $self->{ ERROR }). Calling error() as a package
413 # function, rather than an object method, triggers this response.
414 #
415 # If $errmsg is undefined, the $self->{ ERROR } variable is undefined to
416 # effectively clear any previous error condition.
417 #
418 #========================================================================
419  
420 0 ▶sub _error {
Subroutine _error: not called CC=2 SCAR=17.9
421 0 my $self = shift;
422 0 my $msg = shift;
423  
424 0 ▶ $self->{ ERROR } = $ERROR = defined ($msg)
Branch: 1 branch
BranchTrueFalseTotal
defined $msg ? : 0 0 0
425 ? sprintf($msg, @_)
426 : undef;
427 }
428  
429  
430  
431 9 1;
432  
433 =head1 NAME
434  
435 Text::MetaText::Factory - Factory class for instatiating Directive objects.
436  
437 =head1 SYNOPSIS
438  
439 use Text::MetaText::Factory;
440 my $factory = Text::MetaText::Factory->new(\%cfg);
441  
442 =head1 DESCRIPTION
443  
444 The Text::MetaText::Factory module is used by Text::MetaText to instantiate
445 Text::MetaText::Directive objects. The Factory and Directive classes can
446 be sub-classed to create a more specific processing system.
447  
448 =head1 AUTHOR
449  
450 Andy Wardley E<lt>abw@kfs.orgE<gt>
451  
452 See also:
453  
454 http://www.kfs.org/~abw/
455  
456 =head1 REVISION
457  
458 $Revision: 0.2 $
459  
460 =head1 COPYRIGHT
461  
462 Copyright (c) 1996-1998 Andy Wardley. All Rights Reserved.
463  
464 This program is free software; you can redistribute it and/or modify it
465 under the terms of the Perl Artistic License.
466  
467 =head1 SEE ALSO
468  
469 For more information, see the main Text::MetaText documentation:
470  
471 perldoc Text::MetaText
472
473 For more information about the author and other Perl development work:
474  
475 http://www.kfs.org/~abw/
476 http://www.kfs.org/~abw/perl/
477 http://www.cre.canon.co.uk/perl/
478  
479 For more information about Perl in general:
480  
481 http://www.perl.com/
482  
483 =cut
484  
485  
« MetaText.pm ↑ Summary MetaText/Directive.pm »