blib/lib/Template/View.pm untested

filter: Statementstmt 0.0% 0 / 161 Branchbran 0.0% 0 / 112 Conditioncond 0.0% 0 / 71 MC/DCmcdc n/a Subroutinesub 0.0% 0 / 14 Podpod 0.0% 0 / 11 totaltotal 0.0% 0 / 369 CC 56 SCAR 54.6
CC
56
Cov
0%
AUTOLOAD
552.0
template
156.0
print
132.0
CRAP 236.0
1 #============================================================= -*-Perl-*-
2 #
3 # Template::View
4 #
5 # DESCRIPTION
6 # A custom view of a template processing context. Can be used to
7 # implement custom "skins".
8 #
9 # AUTHOR
10 # Andy Wardley <abw@kfs.org>
11 #
12 # COPYRIGHT
13 # Copyright (C) 2000-2022 Andy Wardley. All Rights Reserved.
14 #
15 # This module is free software; you can redistribute it and/or
16 # modify it under the same terms as Perl itself.
17 #
18 # TODO
19 # * allowing print to have a hash ref as final args will cause problems
20 # if you do this: [% view.print(hash1, hash2, hash3) %]. Current
21 # work-around is to do [% view.print(hash1); view.print(hash2);
22 # view.print(hash3) %] or [% view.print(hash1, hash2, hash3, { }) %]
23 #
24 #============================================================================
25  
26 package Template::View;
27  
28 use strict;
29 use warnings;
30 use base 'Template::Base';
31  
32 our $VERSION = '3.105';
33 our $DEBUG = 0 unless defined $DEBUG;
34 our @BASEARGS = qw( context );
35 our $AUTOLOAD;
36 our $MAP = {
37 HASH => 'hash',
38 ARRAY => 'list',
39 TEXT => 'text',
40 default => '',
41 };
42  
43  
44 #------------------------------------------------------------------------
45 # _init(\%config)
46 #
47 # Initialisation method called by the Template::Base class new()
48 # constructor. $self->{ context } has already been set, by virtue of
49 # being named in @BASEARGS. Remaining config arguments are presented
50 # as a hash reference.
51 #------------------------------------------------------------------------
52  
53 sub _init {
54 my ($self, $config) = @_;
55  
56 # move 'context' somewhere more private
57 $self->{ _CONTEXT } = $self->{ context };
58 delete $self->{ context };
59  
60 # generate table mapping object types to templates
61 my $map = $config->{ map } || { };
62 $map->{ default } //= $config->{ default };
63 $self->{ map } = {
64 %$MAP,
65 %$map,
66 };
67  
68 # local BLOCKs definition table
69 $self->{ _BLOCKS } = $config->{ blocks } || { };
70  
71 # name of presentation method which printed objects might provide
72 $self->{ method } = $config->{ method } // 'present';
73  
74 # view is sealed by default preventing variable update after
75 # definition, however we don't actually seal a view until the
76 # END of the view definition
77 my $sealed = $config->{ sealed };
78 $sealed //= 1;
79 $self->{ sealed } = $sealed ? 1 : 0;
80  
81 # copy remaining config items from $config or set defaults
82 foreach my $arg (qw( base prefix suffix notfound silent )) {
83 $self->{ $arg } = $config->{ $arg } || '';
84 }
85  
86 # check that any base specified is defined
87 return $self->error('Invalid base specified for view')
88 if exists $config->{ base } && ! $self->{ base };
89  
90 # name of data item used by view()
91 $self->{ item } = $config->{ item } || 'item';
92  
93 # map methods of form ${include_prefix}_foobar() to include('foobar')?
94 $self->{ include_prefix } = $config->{ include_prefix } || 'include_';
95 # what about mapping foobar() to include('foobar')?
96 $self->{ include_naked } = $config->{ include_naked } // 1;
97  
98 # map methods of form ${view_prefix}_foobar() to include('foobar')?
99 $self->{ view_prefix } = $config->{ view_prefix } || 'view_';
100 # what about mapping foobar() to view('foobar')?
101 $self->{ view_naked } = $config->{ view_naked } || 0;
102  
103 # the view is initially unsealed, allowing directives in the initial
104 # view template to create data items via the AUTOLOAD; once sealed via
105 # call to seal(), the AUTOLOAD will not update any internal items.
106 delete @$config{ qw(
107 base method map default prefix suffix notfound item
108 include_prefix include_naked silent sealed
109 view_prefix view_naked blocks
110 ) };
111 $config = { %{ $self->{ base }->{ data } }, %$config }
112 if $self->{ base };
113 $self->{ data } = $config;
114 $self->{ SEALED } = 0;
115  
116 return $self;
117 }
118  
119  
120 #------------------------------------------------------------------------
121 # seal()
122 # unseal()
123 #
124 # Seal or unseal the view to allow/prevent new data items from being
125 # automatically created by the AUTOLOAD method.
126 #------------------------------------------------------------------------
127  
128 sub seal {
129 my $self = shift;
130 $self->{ SEALED } = $self->{ sealed };
131 }
132  
133 sub unseal {
134 my $self = shift;
135 $self->{ SEALED } = 0;
136 }
137  
138  
139 #------------------------------------------------------------------------
140 # clone(\%config)
141 #
142 # Cloning method which takes a copy of $self and then applies to it any
143 # modifications specified in the $config hash passed as an argument.
144 # Configuration items may also be specified as a list of "name => $value"
145 # arguments. Returns a reference to the cloned Template::View object.
146 #
147 # NOTE: may need to copy BLOCKS???
148 #------------------------------------------------------------------------
149  
150 sub clone {
151 my $self = shift;
152 my $clone = bless { %$self }, ref $self;
153 my $config = ref $_[0] eq 'HASH' ? shift : { @_ };
154  
155 # merge maps
156 $clone->{ map } = {
157 %{ $self->{ map } },
158 %{ $config->{ map } || { } },
159 };
160  
161 # "map => { default=>'xxx' }" can be specified as "default => 'xxx'"
162 $clone->{ map }->{ default } = $config->{ default }
163 if defined $config->{ default };
164  
165 # update any remaining config items
166 my @args = qw(
167 base prefix suffix notfound item method include_prefix
168 include_naked view_prefix view_naked
169 );
170 foreach my $arg (@args) {
171 $clone->{ $arg } = $config->{ $arg } if defined $config->{ $arg };
172 }
173 push(@args, qw( default map ));
174 delete @$config{ @args };
175  
176 # anything left is data
177 my $data = $clone->{ data } = { %{ $self->{ data } } };
178 @$data{ keys %$config } = values %$config;
179  
180 return $clone;
181 }
182  
183  
184 #------------------------------------------------------------------------
185 # print(@items, ..., \%config)
186 #
187 # Prints @items in turn by mapping each to an appropriate template using
188 # the internal 'map' hash. If an entry isn't found and the item is an
189 # object that implements the method named in the internal 'method' item,
190 # (default: 'present'), then the method will be called passing a reference
191 # to $self, against which the presenter method may make callbacks (e.g.
192 # to view_item()). If the presenter method isn't implemented, then the
193 # 'default' map entry is consulted and used if defined. The final argument
194 # may be a reference to a hash array providing local overrides to the internal
195 # defaults for various items (prefix, suffix, etc). In the presence
196 # of this parameter, a clone of the current object is first made, applying
197 # any configuration updates, and control is then delegated to it.
198 #------------------------------------------------------------------------
199  
200 sub print {
201 my $self = shift;
202  
203 # if final config hash is specified then create a clone and delegate to it
204 # NOTE: potential problem when called print(\%data_hash1, \%data_hash2);
205 if ((scalar @_ > 1) && (ref $_[-1] eq 'HASH')) {
206 my $cfg = pop @_;
207 my $clone = $self->clone($cfg)
208 || return;
209 return $clone->print(@_)
210 || $self->error($clone->error());
211 }
212 my ($item, $type, $template, $present);
213 my $method = $self->{ method };
214 my $map = $self->{ map };
215 my $output = '';
216  
217 # print each argument
218 foreach $item (@_) {
219 my $newtype;
220  
221 if (! ($type = ref $item)) {
222 # non-references are TEXT
223 $type = 'TEXT';
224 $template = $map->{ $type };
225 }
226 elsif (! defined ($template = $map->{ $type })) {
227 # no specific map entry for object, maybe it implements a
228 # 'present' (or other) method?
229 if ( $method && UNIVERSAL::can($item, $method) ) {
230 $present = $item->$method($self); ## call item method
231 # undef returned indicates error, note that we expect
232 # $item to have called error() on the view
233 return unless defined $present;
234 $output .= $present;
235 next; ## NEXT
236 }
237 elsif ( ref($item) eq 'HASH'
238 && defined($newtype = $item->{$method})
239 && defined($template = $map->{"$method=>$newtype"})) {
240 }
241 elsif ( defined($newtype)
242 && defined($template = $map->{"$method=>*"}) ) {
243 $template =~ s/\*/$newtype/;
244 }
245 elsif (! ($template = $map->{ default }) ) {
246 # default not defined, so construct template name from type
247 ($template = $type) =~ s/\W+/_/g;
248 }
249 }
250 # else {
251 # $self->DEBUG("defined map type for $type: $template\n");
252 # }
253 $self->DEBUG("printing view '", $template || '', "', $item\n") if $DEBUG;
254 $output .= $self->view($template, $item)
255 if $template;
256 }
257 return $output;
258 }
259  
260  
261 #------------------------------------------------------------------------
262 # view($template, $item, \%vars)
263 #
264 # Wrapper around include() which expects a template name, $template,
265 # followed by a data item, $item, and optionally, a further hash array
266 # of template variables. The $item is added as an entry to the $vars
267 # hash (which is created empty if not passed as an argument) under the
268 # name specified by the internal 'item' member, which is appropriately
269 # 'item' by default. Thus an external object present() method can
270 # callback against this object method, simply passing a data item to
271 # be displayed. The external object doesn't have to know what the
272 # view expects the item to be called in the $vars hash.
273 #------------------------------------------------------------------------
274  
275 sub view {
276 my ($self, $template, $item) = splice(@_, 0, 3);
277 my $vars = ref $_[0] eq 'HASH' ? shift : { @_ };
278 $vars->{ $self->{ item } } = $item if defined $item;
279 $self->include($template, $vars);
280 }
281  
282  
283 #------------------------------------------------------------------------
284 # include($template, \%vars)
285 #
286 # INCLUDE a template, $template, mapped according to the current prefix,
287 # suffix, default, etc., where $vars is an optional hash reference
288 # containing template variable definitions. If the template isn't found
289 # then the method will default to any 'notfound' template, if defined
290 # as an internal item.
291 #------------------------------------------------------------------------
292  
293 sub include {
294 my ($self, $template, $vars) = @_;
295 my $context = $self->{ _CONTEXT };
296  
297 $template = $self->template($template);
298  
299 $vars = { } unless ref $vars eq 'HASH';
300 $vars->{ view } ||= $self;
301  
302 $context->include( $template, $vars );
303  
304 # DEBUGGING
305 # my $out = $context->include( $template, $vars );
306 # print STDERR "VIEW return [$out]\n";
307 # return $out;
308 }
309  
310  
311 #------------------------------------------------------------------------
312 # template($template)
313 #
314 # Returns a compiled template for the specified template name, according
315 # to the current configuration parameters.
316 #------------------------------------------------------------------------
317  
318 sub template {
319 my ($self, $name) = @_;
320 my $context = $self->{ _CONTEXT };
321 return $context->throw(
322 Template::Constants::ERROR_VIEW,
323 "no view template specified"
324 ) unless $name;
325  
326 my $notfound = $self->{ notfound };
327 my $base = $self->{ base };
328 my ($template, $block, $error);
329  
330 return $block
331 if ($block = $self->{ _BLOCKS }->{ $name });
332  
333 # try the named template
334 $template = $self->template_name($name);
335 $self->DEBUG("looking for $template\n") if $DEBUG;
336 eval { $template = $context->template($template) };
337  
338 # try asking the base view if not found
339 if (($error = $@) && $base) {
340 $self->DEBUG("asking base for $name\n") if $DEBUG;
341 eval { $template = $base->template($name) };
342 }
343  
344 # try the 'notfound' template (if defined) if that failed
345 if (($error = $@) && $notfound) {
346 unless ($template = $self->{ _BLOCKS }->{ $notfound }) {
347 $notfound = $self->template_name($notfound);
348 $self->DEBUG("not found, looking for $notfound\n") if $DEBUG;
349 eval { $template = $context->template($notfound) };
350  
351 return $context->throw(Template::Constants::ERROR_VIEW, $error)
352 if $@; # return first error
353 }
354 }
355 elsif ($error) {
356 $self->DEBUG("no 'notfound'\n")
357 if $DEBUG;
358 return $context->throw(Template::Constants::ERROR_VIEW, $error);
359 }
360 return $template;
361 }
362  
363  
364 #------------------------------------------------------------------------
365 # template_name($template)
366 #
367 # Returns the name of the specified template with any appropriate prefix
368 # and/or suffix added.
369 #------------------------------------------------------------------------
370  
371 sub template_name {
372 my ($self, $template) = @_;
373 $template = $self->{ prefix } . $template . $self->{ suffix }
374 if $template;
375  
376 $self->DEBUG("template name: $template\n") if $DEBUG;
377 return $template;
378 }
379  
380  
381 #------------------------------------------------------------------------
382 # default($val)
383 #
384 # Special case accessor to retrieve/update 'default' as an alias for
385 # '$map->{ default }'.
386 #------------------------------------------------------------------------
387  
388 sub default {
389 my $self = shift;
390 return @_
391 ? ($self->{ map }->{ default } = shift)
392 : $self->{ map }->{ default };
393 }
394  
395  
396 #------------------------------------------------------------------------
397 # AUTOLOAD
398 #
399 # Returns/updates public internal data items (i.e. not prefixed '_' or
400 # '.') or presents a view if the method matches the view_prefix item,
401 # e.g. view_foo(...) => view('foo', ...). Similarly, the
402 # include_prefix is used, if defined, to map include_foo(...) to
403 # include('foo', ...). If that fails then the entire method name will
404 # be used as the name of a template to include iff the include_named
405 # parameter is set (default: 1). Last attempt is to match the entire
406 # method name to a view() call, iff view_naked is set. Otherwise, a
407 # 'view' exception is raised reporting the error "no such view member:
408 # $method".
409 #------------------------------------------------------------------------
410  
411 sub AUTOLOAD {
412 my $self = shift;
413 my $item = $AUTOLOAD;
414 $item =~ s/.*:://;
415 return if $item eq 'DESTROY';
416  
417 my $starts_with = substr($item,0,1);
418 if ($starts_with eq '.' || $starts_with eq '_') {
419 return $self->{ _CONTEXT }->throw(Template::Constants::ERROR_VIEW,
420 "attempt to view private member: $item");
421 }
422 elsif (exists $self->{ $item }) {
423 # update existing config item (e.g. 'prefix') if unsealed
424 return $self->{ _CONTEXT }->throw(Template::Constants::ERROR_VIEW,
425 "cannot update config item in sealed view: $item")
426 if @_ && $self->{ SEALED };
427 $self->DEBUG("accessing item: $item\n") if $DEBUG;
428 return @_ ? ($self->{ $item } = shift) : $self->{ $item };
429 }
430 elsif (exists $self->{ data }->{ $item }) {
431 # get/update existing data item (must be unsealed to update)
432 if (@_ && $self->{ SEALED }) {
433 return $self->{ _CONTEXT }->throw(
434 Template::Constants::ERROR_VIEW,
435 "cannot update item in sealed view: $item"
436 ) unless $self->{ silent };
437 # ignore args if silent
438 @_ = ();
439 }
440 $self->DEBUG(@_
441 ? "updating data item: $item <= $_[0]\n"
442 : "returning data item: $item\n"
443 ) if $DEBUG;
444 return @_
445 ? ($self->{ data }->{ $item } = shift)
446 : $self->{ data }->{ $item };
447 }
448 elsif (@_ && ! $self->{ SEALED }) {
449 # set data item if unsealed
450 $self->DEBUG("setting unsealed data: $item => @_\n") if $DEBUG;
451 $self->{ data }->{ $item } = shift;
452 }
453 elsif ($item =~ s/^$self->{ view_prefix }//) {
454 $self->DEBUG("returning view($item)\n") if $DEBUG;
455 return $self->view($item, @_);
456 }
457 elsif ($item =~ s/^$self->{ include_prefix }//) {
458 $self->DEBUG("returning include($item)\n") if $DEBUG;
459 return $self->include($item, @_);
460 }
461 elsif ($self->{ include_naked }) {
462 $self->DEBUG("returning naked include($item)\n") if $DEBUG;
463 return $self->include($item, @_);
464 }
465 elsif ($self->{ view_naked }) {
466 $self->DEBUG("returning naked view($item)\n") if $DEBUG;
467 return $self->view($item, @_);
468 }
469 else {
470 return $self->{ _CONTEXT }->throw(
471 Template::Constants::ERROR_VIEW,
472 "no such view member: $item"
473 );
474 }
475 }
476  
477  
478 1;
479  
480  
481 __END__