blib/lib/Template/Context.pm untested

filter: Statementstmt 0.0% 0 / 302 Branchbran 0.0% 0 / 176 Conditioncond 0.0% 0 / 121 MC/DCmcdc n/a Subroutinesub 0.0% 0 / 37 Podpod 0.0% 0 / 24 totaltotal 0.0% 0 / 660 CC 88 SCAR 49.5
CC
88
Cov
0%
template
420.0
process
306.0
insert
110.0
CRAP 141.4
1 #============================================================= -*-Perl-*-
2 #
3 # Template::Context
4 #
5 # DESCRIPTION
6 # Module defining a context in which a template document is processed.
7 # This is the runtime processing interface through which templates
8 # can access the functionality of the Template Toolkit.
9 #
10 # AUTHOR
11 # Andy Wardley <abw@wardley.org>
12 #
13 # COPYRIGHT
14 # Copyright (C) 1996-2022 Andy Wardley. All Rights Reserved.
15 #
16 # This module is free software; you can redistribute it and/or
17 # modify it under the same terms as Perl itself.
18 #
19 #============================================================================
20  
21 package Template::Context;
22  
23 use strict;
24 use warnings;
25 use base 'Template::Base';
26  
27 use Template::Base;
28 use Template::Config;
29 use Template::Constants;
30 use Template::Exception;
31 use Scalar::Util 'blessed';
32  
33 use constant DOCUMENT => 'Template::Document';
34 use constant EXCEPTION => 'Template::Exception';
35 use constant BADGER_EXCEPTION => 'Badger::Exception';
36 use constant MSWin32 => $^O eq 'MSWin32';
37  
38 our $VERSION = '3.105';
39 our $DEBUG = 0 unless defined $DEBUG;
40 our $DEBUG_FORMAT = "\n## \$file line \$line : [% \$text %] ##\n";
41 our $VIEW_CLASS = 'Template::View';
42 our $AUTOLOAD;
43  
44 #========================================================================
45 # ----- PUBLIC METHODS -----
46 #========================================================================
47  
48 #------------------------------------------------------------------------
49 # template($name)
50 #
51 # General purpose method to fetch a template and return it in compiled
52 # form. In the usual case, the $name parameter will be a simple string
53 # containing the name of a template (e.g. 'header'). It may also be
54 # a reference to Template::Document object (or sub-class) or a Perl
55 # sub-routine. These are considered to be compiled templates and are
56 # returned intact. Finally, it may be a reference to any other kind
57 # of valid input source accepted by Template::Provider (e.g. scalar
58 # ref, glob, IO handle, etc).
59 #
60 # Templates may be cached at one of 3 different levels. The internal
61 # BLOCKS member is a local cache which holds references to all
62 # template blocks used or imported via PROCESS since the context's
63 # reset() method was last called. This is checked first and if the
64 # template is not found, the method then walks down the BLOCKSTACK
65 # list. This contains references to the block definition tables in
66 # any enclosing Template::Documents that we're visiting (e.g. we've
67 # been called via an INCLUDE and we want to access a BLOCK defined in
68 # the template that INCLUDE'd us). If nothing is defined, then we
69 # iterate through the LOAD_TEMPLATES providers list as a 'chain of
70 # responsibility' (see Design Patterns) asking each object to fetch()
71 # the template if it can.
72 #
73 # Returns the compiled template. On error, undef is returned and
74 # the internal ERROR value (read via error()) is set to contain an
75 # error message of the form "$name: $error".
76 #------------------------------------------------------------------------
77  
78 sub template {
79 my ($self, $name) = @_;
80 my ($prefix, $blocks, $defblocks, $provider, $template, $error);
81 my ($shortname, $blockname, $providers);
82  
83 $self->debug("template($name)") if $self->{ DEBUG };
84  
85 # references to Template::Document (or sub-class) objects, or
86 # CODE references are assumed to be pre-compiled templates and are
87 # returned intact
88 return $name
89 if (blessed($name) && $name->isa(DOCUMENT))
90 || ref($name) eq 'CODE';
91  
92 $shortname = $name;
93  
94 unless (ref $name) {
95  
96 $self->debug("looking for block [$name]") if $self->{ DEBUG };
97  
98 # we first look in the BLOCKS hash for a BLOCK that may have
99 # been imported from a template (via PROCESS)
100 return $template
101 if ($template = $self->{ BLOCKS }->{ $name });
102  
103 # then we iterate through the BLKSTACK list to see if any of the
104 # Template::Documents we're visiting define this BLOCK
105 foreach $blocks (@{ $self->{ BLKSTACK } }) {
106 return $template
107 if $blocks && ($template = $blocks->{ $name });
108 }
109  
110 # now it's time to ask the providers, so we look to see if any
111 # prefix is specified to indicate the desired provider set.
112 if (MSWin32) {
113 # let C:/foo through
114 $prefix = $1 if $shortname =~ s/^(\w{2,})://o;
115 }
116 else {
117 $prefix = $1 if $shortname =~ s/^(\w+)://;
118 }
119  
120 if (defined $prefix) {
121 $providers = $self->{ PREFIX_MAP }->{ $prefix }
122 || return $self->throw( Template::Constants::ERROR_FILE,
123 "no providers for template prefix '$prefix'");
124 }
125 }
126 $providers = $self->{ PREFIX_MAP }->{ default }
127 || $self->{ LOAD_TEMPLATES }
128 unless $providers;
129  
130  
131 # Finally we try the regular template providers which will
132 # handle references to files, text, etc., as well as templates
133 # reference by name. If
134  
135 $blockname = '';
136 while ($shortname) {
137 $self->debug("asking providers for [$shortname] [$blockname]")
138 if $self->{ DEBUG };
139  
140 foreach my $provider (@$providers) {
141 ($template, $error) = $provider->fetch($shortname, $prefix);
142 if ($error) {
143 if ($error == Template::Constants::STATUS_ERROR) {
144 # $template contains exception object
145 if (blessed($template) && $template->isa(EXCEPTION)
146 && $template->type eq Template::Constants::ERROR_FILE) {
147 $self->throw($template);
148 }
149 else {
150 $self->throw( Template::Constants::ERROR_FILE, $template );
151 }
152 }
153 # DECLINE is ok, carry on
154 }
155 elsif (length $blockname) {
156 return $template
157 if $template = $template->blocks->{ $blockname };
158 }
159 else {
160 return $template;
161 }
162 }
163  
164 last if ref $shortname || ! $self->{ EXPOSE_BLOCKS };
165 $shortname =~ s{/([^/]+)$}{} || last;
166 $blockname = length $blockname ? "$1/$blockname" : $1;
167 }
168  
169 $self->throw(Template::Constants::ERROR_FILE, "$name: not found");
170 }
171  
172  
173 #------------------------------------------------------------------------
174 # plugin($name, \@args)
175 #
176 # Calls on each of the LOAD_PLUGINS providers in turn to fetch() (i.e. load
177 # and instantiate) a plugin of the specified name. Additional parameters
178 # passed are propagated to the new() constructor for the plugin.
179 # Returns a reference to a new plugin object or other reference. On
180 # error, undef is returned and the appropriate error message is set for
181 # subsequent retrieval via error().
182 #------------------------------------------------------------------------
183  
184 sub plugin {
185 my ($self, $name, $args) = @_;
186 my ($provider, $plugin, $error);
187  
188 $self->debug("plugin($name, ", defined $args ? @$args : '[ ]', ')')
189 if $self->{ DEBUG };
190  
191 # request the named plugin from each of the LOAD_PLUGINS providers in turn
192 foreach my $provider (@{ $self->{ LOAD_PLUGINS } }) {
193 ($plugin, $error) = $provider->fetch($name, $args, $self);
194 return $plugin unless $error;
195 if ($error == Template::Constants::STATUS_ERROR) {
196 $self->throw($plugin) if ref $plugin;
197 $self->throw(Template::Constants::ERROR_PLUGIN, $plugin);
198 }
199 }
200  
201 $self->throw(Template::Constants::ERROR_PLUGIN, "$name: plugin not found");
202 }
203  
204  
205 #------------------------------------------------------------------------
206 # filter($name, \@args, $alias)
207 #
208 # Similar to plugin() above, but querying the LOAD_FILTERS providers to
209 # return filter instances. An alias may be provided which is used to
210 # save the returned filter in a local cache.
211 #------------------------------------------------------------------------
212  
213 sub filter {
214 my ($self, $name, $args, $alias) = @_;
215 my ($provider, $filter, $error);
216  
217 $self->debug("filter($name, ",
218 defined $args ? @$args : '[ ]',
219 $alias // '<no alias>', ')')
220 if $self->{ DEBUG };
221  
222 # use any cached version of the filter if no params provided
223 return $filter
224 if ! $args && ! ref $name
225 && ($filter = $self->{ FILTER_CACHE }->{ $name });
226  
227 # request the named filter from each of the FILTERS providers in turn
228 foreach my $provider (@{ $self->{ LOAD_FILTERS } }) {
229 ($filter, $error) = $provider->fetch($name, $args, $self);
230 last unless $error;
231 if ($error == Template::Constants::STATUS_ERROR) {
232 $self->throw($filter) if ref $filter;
233 $self->throw(Template::Constants::ERROR_FILTER, $filter);
234 }
235 # return $self->error($filter)
236 # if $error == &Template::Constants::STATUS_ERROR;
237 }
238  
239 return $self->error("$name: filter not found")
240 unless $filter;
241  
242 # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
243 # commented out by abw on 19 Nov 2001 to fix problem with xmlstyle
244 # plugin which may re-define a filter by calling define_filter()
245 # multiple times. With the automatic aliasing/caching below, any
246 # new filter definition isn't seen. Don't think this will cause
247 # any problems as filters explicitly supplied with aliases will
248 # still work as expected.
249 # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
250 # alias defaults to name if undefined
251 # $alias = $name
252 # unless defined($alias) or ref($name) or $args;
253  
254 # cache FILTER if alias is valid
255 $self->{ FILTER_CACHE }->{ $alias } = $filter
256 if $alias;
257  
258 return $filter;
259 }
260  
261  
262 #------------------------------------------------------------------------
263 # view(\%config)
264 #
265 # Create a new Template::View bound to this context.
266 #------------------------------------------------------------------------
267  
268 sub view {
269 my $self = shift;
270 require Template::View;
271 return $VIEW_CLASS->new($self, @_)
272 || $self->throw(
273 &Template::Constants::ERROR_VIEW,
274 $VIEW_CLASS->error
275 );
276 }
277  
278  
279 #------------------------------------------------------------------------
280 # process($template, \%params) [% PROCESS template var=val ... %]
281 # process($template, \%params, $local) [% INCLUDE template var=val ... %]
282 #
283 # Processes the template named or referenced by the first parameter.
284 # The optional second parameter may reference a hash array of variable
285 # definitions. These are set before the template is processed by
286 # calling update() on the stash. Note that, unless the third parameter
287 # is true, the context is not localised and these, and any other
288 # variables set in the template will retain their new values after this
289 # method returns. The third parameter is in place so that this method
290 # can handle INCLUDE calls: the stash will be localized.
291 #
292 # Returns the output of processing the template. Errors are thrown
293 # as Template::Exception objects via die().
294 #------------------------------------------------------------------------
295  
296 sub process {
297 my ($self, $template, $params, $localize) = @_;
298 my ($trim, $blocks) = @$self{ qw( TRIM BLOCKS ) };
299 my (@compiled, $name, $compiled);
300 my ($stash, $component, $tblocks, $error, $tmpout);
301 my $output = '';
302  
303 $template = [ $template ] unless ref $template eq 'ARRAY';
304  
305 $self->debug("process([ ", join(', ', @$template), ' ], ',
306 $params // '<no params>', ', ',
307 $localize ? '<localized>' : '<unlocalized>', ')')
308 if $self->{ DEBUG };
309  
310 # fetch compiled template for each name specified
311 foreach $name (@$template) {
312 push(@compiled, $self->template($name));
313 }
314  
315 if ($localize) {
316 # localise the variable stash with any parameters passed
317 $stash = $self->{ STASH } = $self->{ STASH }->clone($params);
318 } else {
319 # update stash with any new parameters passed
320 $self->{ STASH }->update($params);
321 $stash = $self->{ STASH };
322 }
323  
324 eval {
325 # save current component
326 eval { $component = $stash->get('component') };
327  
328 foreach $name (@$template) {
329 $compiled = shift @compiled;
330 my $element = ref $compiled eq 'CODE'
331 ? { (name => (ref $name ? '' : $name), modtime => time()) }
332 : $compiled;
333  
334 if (blessed($component) && $component->isa(DOCUMENT)) {
335 $element->{ caller } = $component->{ name };
336 $element->{ callers } = $component->{ callers } || [];
337 push(@{$element->{ callers }}, $element->{ caller });
338 }
339  
340 $stash->set('component', $element);
341  
342 unless ($localize) {
343 # merge any local blocks defined in the Template::Document
344 # into our local BLOCKS cache
345 @$blocks{ keys %$tblocks } = values %$tblocks
346 if (blessed($compiled) && $compiled->isa(DOCUMENT))
347 && ($tblocks = $compiled->blocks);
348 }
349  
350 if (ref $compiled eq 'CODE') {
351 $tmpout = &$compiled($self);
352 }
353 elsif (ref $compiled) {
354 $tmpout = $compiled->process($self);
355 }
356 else {
357 $self->throw(
358 'file',
359 "invalid template reference: $compiled"
360 );
361 }
362  
363 if ($trim) {
364 for ($tmpout) {
365 s/^\s+//;
366 s/\s+$//;
367 }
368 }
369 $output .= $tmpout;
370  
371 # pop last item from callers.
372 # NOTE - this will not be called if template throws an
373 # error. The whole issue of caller and callers should be
374 # revisited to try and avoid putting this info directly into
375 # the component data structure. Perhaps use a local element
376 # instead?
377  
378 pop(@{$element->{ callers }})
379 if (blessed($component) && $component->isa(DOCUMENT));
380 }
381 $stash->set('component', $component);
382 };
383 $error = $@;
384  
385 if ($localize) {
386 # ensure stash is delocalised before dying
387 $self->{ STASH } = $self->{ STASH }->declone();
388 }
389  
390 $self->throw(
391 ref $error
392 ? $error
393 : (Template::Constants::ERROR_FILE, $error)
394 ) if $error;
395  
396 return $output;
397 }
398  
399  
400 #------------------------------------------------------------------------
401 # include($template, \%params) [% INCLUDE template var = val, ... %]
402 #
403 # Similar to process() above but processing the template in a local
404 # context. Any variables passed by reference to a hash as the second
405 # parameter will be set before the template is processed and then
406 # revert to their original values before the method returns. Similarly,
407 # any changes made to non-global variables within the template will
408 # persist only until the template is processed.
409 #
410 # Returns the output of processing the template. Errors are thrown
411 # as Template::Exception objects via die().
412 #------------------------------------------------------------------------
413  
414 sub include {
415 my ($self, $template, $params) = @_;
416 return $self->process($template, $params, 'localize me!');
417 }
418  
419 #------------------------------------------------------------------------
420 # insert($file)
421 #
422 # Insert the contents of a file without parsing.
423 #------------------------------------------------------------------------
424  
425 sub insert {
426 my ($self, $file) = @_;
427 my ($prefix, $providers, $text, $error);
428 my $output = '';
429  
430 my $files = ref $file eq 'ARRAY' ? $file : [ $file ];
431  
432 $self->debug("insert([ ", join(', ', @$files), " ])")
433 if $self->{ DEBUG };
434  
435  
436 FILE: foreach $file (@$files) {
437 my $name = $file;
438  
439 if (MSWin32) {
440 # let C:/foo through
441 $prefix = $1 if $name =~ s/^(\w{2,})://o;
442 }
443 else {
444 $prefix = $1 if $name =~ s/^(\w+)://;
445 }
446  
447 if (defined $prefix) {
448 $providers = $self->{ PREFIX_MAP }->{ $prefix }
449 || return $self->throw(
450 Template::Constants::ERROR_FILE,
451 "no providers for file prefix '$prefix'"
452 );
453 }
454 else {
455 $providers = $self->{ PREFIX_MAP }->{ default }
456 || $self->{ LOAD_TEMPLATES };
457 }
458  
459 foreach my $provider (@$providers) {
460 ($text, $error) = $provider->load($name, $prefix);
461 next FILE unless $error;
462 if ($error == Template::Constants::STATUS_ERROR) {
463 $self->throw($text) if ref $text;
464 $self->throw(Template::Constants::ERROR_FILE, $text);
465 }
466 }
467 $self->throw(Template::Constants::ERROR_FILE, "$file: not found");
468 }
469 continue {
470 $output .= $text;
471 }
472 return $output;
473 }
474  
475  
476 #------------------------------------------------------------------------
477 # throw($type, $info, \$output) [% THROW errtype "Error info" %]
478 #
479 # Throws a Template::Exception object by calling die(). This method
480 # may be passed a reference to an existing Template::Exception object;
481 # a single value containing an error message which is used to
482 # instantiate a Template::Exception of type 'undef'; or a pair of
483 # values representing the exception type and info from which a
484 # Template::Exception object is instantiated. e.g.
485 #
486 # $context->throw($exception);
487 # $context->throw("I'm sorry Dave, I can't do that");
488 # $context->throw('denied', "I'm sorry Dave, I can't do that");
489 #
490 # An optional third parameter can be supplied in the last case which
491 # is a reference to the current output buffer containing the results
492 # of processing the template up to the point at which the exception
493 # was thrown. The RETURN and STOP directives, for example, use this
494 # to propagate output back to the user, but it can safely be ignored
495 # in most cases.
496 #
497 # This method rides on a one-way ticket to die() oblivion. It does not
498 # return in any real sense of the word, but should get caught by a
499 # surrounding eval { } block (e.g. a BLOCK or TRY) and handled
500 # accordingly, or returned to the caller as an uncaught exception.
501 #------------------------------------------------------------------------
502  
503 sub throw {
504 my ($self, $error, $info, $output) = @_;
505 local $" = ', ';
506  
507 # die! die! die!
508 if (blessed($error) && $error->isa(EXCEPTION)) {
509 die $error;
510 }
511 elsif (blessed($error) && $error->isa(BADGER_EXCEPTION)) {
512 # convert a Badger::Exception to a Template::Exception so that
513 # things continue to work during the transition to Badger
514 die EXCEPTION->new($error->type, $error->info);
515 }
516 elsif (defined $info) {
517 die (EXCEPTION->new($error, $info, $output));
518 }
519 else {
520 $error ||= '';
521 die (EXCEPTION->new('undef', $error, $output));
522 }
523  
524 # not reached
525 }
526  
527  
528 #------------------------------------------------------------------------
529 # catch($error, \$output)
530 #
531 # Called by various directives after catching an error thrown via die()
532 # from within an eval { } block. The first parameter contains the error
533 # which may be a sanitized reference to a Template::Exception object
534 # (such as that raised by the throw() method above, a plugin object,
535 # and so on) or an error message thrown via die from somewhere in user
536 # code. The latter are coerced into 'undef' Template::Exception objects.
537 # Like throw() above, a reference to a scalar may be passed as an
538 # additional parameter to represent the current output buffer
539 # localised within the eval block. As exceptions are thrown upwards
540 # and outwards from nested blocks, the catch() method reconstructs the
541 # correct output buffer from these fragments, storing it in the
542 # exception object for passing further onwards and upwards.
543 #
544 # Returns a reference to a Template::Exception object..
545 #------------------------------------------------------------------------
546  
547 sub catch {
548 my ($self, $error, $output) = @_;
549  
550 if ( blessed($error)
551 && ( $error->isa(EXCEPTION) || $error->isa(BADGER_EXCEPTION) ) ) {
552 $error->text($output) if $output;
553 return $error;
554 }
555 else {
556 return EXCEPTION->new('undef', $error, $output);
557 }
558 }
559  
560  
561 #------------------------------------------------------------------------
562 # localise(\%params)
563 # delocalise()
564 #
565 # The localise() method creates a local copy of the current stash,
566 # allowing the existing state of variables to be saved and later
567 # restored via delocalise().
568 #
569 # A reference to a hash array may be passed containing local variable
570 # definitions which should be added to the cloned namespace. These
571 # values persist until delocalisation.
572 #------------------------------------------------------------------------
573  
574 sub localise {
575 my $self = shift;
576 $self->{ STASH } = $self->{ STASH }->clone(@_);
577 }
578  
579 sub delocalise {
580 my $self = shift;
581 $self->{ STASH } = $self->{ STASH }->declone();
582 }
583  
584  
585 #------------------------------------------------------------------------
586 # visit($document, $blocks)
587 #
588 # Each Template::Document calls the visit() method on the context
589 # before processing itself. It passes a reference to the hash array
590 # of named BLOCKs defined within the document, allowing them to be
591 # added to the internal BLKSTACK list which is subsequently used by
592 # template() to resolve templates.
593 # from a provider.
594 #------------------------------------------------------------------------
595  
596 sub visit {
597 my ($self, $document, $blocks) = @_;
598 unshift(@{ $self->{ BLKSTACK } }, $blocks)
599 }
600  
601  
602 #------------------------------------------------------------------------
603 # leave()
604 #
605 # The leave() method is called when the document has finished
606 # processing itself. This removes the entry from the BLKSTACK list
607 # that was added visit() above. For persistence of BLOCK definitions,
608 # the process() method (i.e. the PROCESS directive) does some extra
609 # magic to copy BLOCKs into a shared hash.
610 #------------------------------------------------------------------------
611  
612 sub leave {
613 my $self = shift;
614 shift(@{ $self->{ BLKSTACK } });
615 }
616  
617  
618 #------------------------------------------------------------------------
619 # define_block($name, $block)
620 #
621 # Adds a new BLOCK definition to the local BLOCKS cache. $block may
622 # be specified as a reference to a sub-routine or Template::Document
623 # object or as text which is compiled into a template. Returns a true
624 # value (the $block reference or compiled block reference) if
625 # successful or undef on failure. Call error() to retrieve the
626 # relevant error message (i.e. compilation failure).
627 #------------------------------------------------------------------------
628  
629 sub define_block {
630 my ($self, $name, $block) = @_;
631 $block = $self->template(\$block)
632 || return undef
633 unless ref $block;
634 $self->{ BLOCKS }->{ $name } = $block;
635 }
636  
637  
638 #------------------------------------------------------------------------
639 # define_filter($name, $filter, $is_dynamic)
640 #
641 # Adds a new FILTER definition to the local FILTER_CACHE.
642 #------------------------------------------------------------------------
643  
644 sub define_filter {
645 my ($self, $name, $filter, $is_dynamic) = @_;
646 my ($result, $error);
647 $filter = [ $filter, 1 ] if $is_dynamic;
648  
649 foreach my $provider (@{ $self->{ LOAD_FILTERS } }) {
650 ($result, $error) = $provider->store($name, $filter);
651 return 1 unless $error;
652 $self->throw(&Template::Constants::ERROR_FILTER, $result)
653 if $error == &Template::Constants::STATUS_ERROR;
654 }
655 $self->throw(
656 &Template::Constants::ERROR_FILTER,
657 "FILTER providers declined to store filter $name"
658 );
659 }
660  
661  
662 #------------------------------------------------------------------------
663 # define_vmethod($type, $name, \&sub)
664 #
665 # Passes $type, $name, and &sub on to stash->define_vmethod().
666 #------------------------------------------------------------------------
667  
668 sub define_vmethod {
669 my $self = shift;
670 $self->stash->define_vmethod(@_);
671 }
672  
673  
674 #------------------------------------------------------------------------
675 # define_view($name, $params)
676 #
677 # Defines a new view.
678 #------------------------------------------------------------------------
679  
680 sub define_view {
681 my ($self, $name, $params) = @_;
682 my $base;
683  
684 if (defined $params->{ base }) {
685 my $base = $self->{ STASH }->get($params->{ base });
686  
687 return $self->throw(
688 &Template::Constants::ERROR_VIEW,
689 "view base is not defined: $params->{ base }"
690 ) unless $base;
691  
692 return $self->throw(
693 &Template::Constants::ERROR_VIEW,
694 "view base is not a $VIEW_CLASS object: $params->{ base } => $base"
695 ) unless blessed($base) && $base->isa($VIEW_CLASS);
696  
697 $params->{ base } = $base;
698 }
699 my $view = $self->view($params);
700 $view->seal();
701 $self->{ STASH }->set($name, $view);
702 }
703  
704  
705 #------------------------------------------------------------------------
706 # define_views($views)
707 #
708 # Defines multiple new views.
709 #------------------------------------------------------------------------
710  
711 sub define_views {
712 my ($self, $views) = @_;
713  
714 # a list reference is better because the order is deterministic (and so
715 # allows an earlier VIEW to be the base for a later VIEW), but we'll
716 # accept a hash reference and assume that the user knows the order of
717 # processing is undefined
718 $views = [ %$views ]
719 if ref $views eq 'HASH';
720  
721 # make of copy so we don't destroy the original list reference
722 my @items = @$views;
723 my ($name, $view);
724  
725 while (@items) {
726 $self->define_view(splice(@items, 0, 2));
727 }
728 }
729  
730  
731 #------------------------------------------------------------------------
732 # reset()
733 #
734 # Reset the state of the internal BLOCKS hash to clear any BLOCK
735 # definitions imported via the PROCESS directive. Any original
736 # BLOCKS definitions passed to the constructor will be restored.
737 #------------------------------------------------------------------------
738  
739 sub reset {
740 my ($self, $blocks) = @_;
741 $self->{ BLKSTACK } = [ ];
742 $self->{ BLOCKS } = { %{ $self->{ INIT_BLOCKS } } };
743 }
744  
745  
746 #------------------------------------------------------------------------
747 # stash()
748 #
749 # Simple accessor methods to return the STASH values. This is likely
750 # to be called quite often so we provide a direct method rather than
751 # relying on the slower AUTOLOAD.
752 #------------------------------------------------------------------------
753  
754 sub stash {
755 return $_[0]->{ STASH };
756 }
757  
758  
759 #------------------------------------------------------------------------
760 # debugging($command, @args, \%params)
761 #
762 # Method for controlling the debugging status of the context. The first
763 # argument can be 'on' or 'off' to enable/disable debugging, 'format'
764 # to define the format of the debug message, or 'msg' to generate a
765 # debugging message reporting the file, line, message text, etc.,
766 # according to the current debug format.
767 #------------------------------------------------------------------------
768  
769 sub debugging {
770 my $self = shift;
771 my $hash = ref $_[-1] eq 'HASH' ? pop : { };
772 my @args = @_;
773  
774 if (@args) {
775 if ($args[0] eq '1' || lc($args[0]) eq 'on' ) {
776 $self->{ DEBUG_DIRS } = 1;
777 shift(@args);
778 }
779 elsif ($args[0] eq '0' || lc($args[0]) eq 'off') {
780 $self->{ DEBUG_DIRS } = 0;
781 shift(@args);
782 }
783 }
784  
785 if (@args) {
786 if (lc($args[0]) eq 'msg') {
787 return unless $self->{ DEBUG_DIRS };
788 my $format = $self->{ DEBUG_FORMAT } // $DEBUG_FORMAT;
789 $format =~ s/\$(\w+)/$hash->{ $1 }/ge;
790 return $format;
791 }
792 elsif ( lc($args[0]) eq 'format' ) {
793 $self->{ DEBUG_FORMAT } = $args[1];
794 }
795 # else ignore
796 }
797  
798 return '';
799 }
800  
801  
802 #------------------------------------------------------------------------
803 # AUTOLOAD
804 #
805 # Provides pseudo-methods for read-only access to various internal
806 # members. For example, templates(), plugins(), filters(),
807 # eval_perl(), load_perl(), etc. These aren't called very often, or
808 # may never be called at all.
809 #------------------------------------------------------------------------
810  
811 sub AUTOLOAD {
812 my $self = shift;
813 my $method = $AUTOLOAD;
814 my $result;
815  
816 $method =~ s/.*:://;
817 return if $method eq 'DESTROY';
818  
819 warn "no such context method/member: $method\n"
820 unless defined ($result = $self->{ uc $method });
821  
822 return $result;
823 }
824  
825  
826 #------------------------------------------------------------------------
827 # DESTROY
828 #
829 # Stash may contain references back to the Context via macro closures,
830 # etc. This breaks the circular references.
831 #------------------------------------------------------------------------
832  
833 sub DESTROY {
834 my $self = shift;
835 undef $self->{ STASH };
836 }
837  
838  
839  
840 #========================================================================
841 # -- PRIVATE METHODS --
842 #========================================================================
843  
844 #------------------------------------------------------------------------
845 # _init(\%config)
846 #
847 # Initialisation method called by Template::Base::new()
848 #------------------------------------------------------------------------
849  
850 sub _init {
851 my ($self, $config) = @_;
852 my ($name, $item, $method, $block, $blocks);
853 my @itemlut = (
854 LOAD_TEMPLATES => 'provider',
855 LOAD_PLUGINS => 'plugins',
856 LOAD_FILTERS => 'filters'
857 );
858  
859 # LOAD_TEMPLATE, LOAD_PLUGINS, LOAD_FILTERS - lists of providers
860 while (($name, $method) = splice(@itemlut, 0, 2)) {
861 $item = $config->{ $name }
862 || Template::Config->$method($config)
863 || return $self->error($Template::Config::ERROR);
864 $self->{ $name } = ref $item eq 'ARRAY' ? $item : [ $item ];
865 }
866  
867 my $providers = $self->{ LOAD_TEMPLATES };
868 my $prefix_map = $self->{ PREFIX_MAP } = $config->{ PREFIX_MAP } || { };
869 while (my ($key, $val) = each %$prefix_map) {
870 $prefix_map->{ $key } = [
871 ref $val
872 ? $val
873 : map { $providers->[$_] } split(/\D+/, $val)
874 ]
875 unless ref $val eq 'ARRAY';
876 }
877  
878 # STASH
879 $self->{ STASH } = $config->{ STASH } || do {
880 my $predefs = $config->{ VARIABLES }
881 || $config->{ PRE_DEFINE }
882 || { };
883  
884 # hack to get stash to know about debug mode
885 $predefs->{ _DEBUG } //= (
886 ($config->{ DEBUG } || 0) & &Template::Constants::DEBUG_UNDEF
887 ) ? 1 : 0;
888 $predefs->{ _STRICT } = $config->{ STRICT };
889  
890 Template::Config->stash($predefs)
891 || return $self->error($Template::Config::ERROR);
892 };
893  
894 # compile any template BLOCKS specified as text
895 $blocks = $config->{ BLOCKS } || { };
896 $self->{ INIT_BLOCKS } = $self->{ BLOCKS } = {
897 map {
898 $block = $blocks->{ $_ };
899 $block = $self->template(\$block)
900 || return undef
901 unless ref $block;
902 ($_ => $block);
903 }
904 keys %$blocks
905 };
906  
907 # define any VIEWS
908 $self->define_views( $config->{ VIEWS } )
909 if $config->{ VIEWS };
910  
911 # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
912 # RECURSION - flag indicating is recursion into templates is supported
913 # EVAL_PERL - flag indicating if PERL blocks should be processed
914 # TRIM - flag to remove leading and trailing whitespace from output
915 # BLKSTACK - list of hashes of BLOCKs defined in current template(s)
916 # CONFIG - original configuration hash
917 # EXPOSE_BLOCKS - make blocks visible as pseudo-files
918 # DEBUG_FORMAT - format for generating template runtime debugging messages
919 # DEBUG - format for generating template runtime debugging messages
920  
921 $self->{ RECURSION } = $config->{ RECURSION } || 0;
922 $self->{ EVAL_PERL } = $config->{ EVAL_PERL } || 0;
923 $self->{ TRIM } = $config->{ TRIM } || 0;
924 $self->{ BLKSTACK } = [ ];
925 $self->{ CONFIG } = $config;
926 $self->{ EXPOSE_BLOCKS } = $config->{ EXPOSE_BLOCKS } // 0;
927 $self->{ DEBUG_FORMAT } = $config->{ DEBUG_FORMAT };
928 $self->{ DEBUG_DIRS } = ($config->{ DEBUG } || 0)
929 & Template::Constants::DEBUG_DIRS;
930 $self->{ DEBUG } = defined $config->{ DEBUG }
931 ? $config->{ DEBUG }
932 & ( Template::Constants::DEBUG_CONTEXT
933 | Template::Constants::DEBUG_FLAGS )
934 : $DEBUG;
935  
936 return $self;
937 }
938  
939 1;
940  
941 __END__