blib/lib/Template/Stash.pm untested

filter: Statementstmt 0.0% 0 / 215 Branchbran 0.0% 0 / 142 Conditioncond 0.0% 0 / 92 MC/DCmcdc n/a Subroutinesub 0.0% 0 / 17 Podpod 0.0% 0 / 12 totaltotal 0.0% 0 / 478 CC 67 SCAR 64.7
CC
67
Cov
0%
_dotop
1406.0
_assign
90.0
getref
30.0
CRAP 643.5
1 #============================================================= -*-Perl-*-
2 #
3 # Template::Stash
4 #
5 # DESCRIPTION
6 # Definition of an object class which stores and manages access to
7 # variables for the Template Toolkit.
8 #
9 # AUTHOR
10 # Andy Wardley <abw@wardley.org>
11 #
12 # COPYRIGHT
13 # Copyright (C) 1996-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 #============================================================================
19  
20 package Template::Stash;
21  
22 use strict;
23 use warnings;
24 use Template::VMethods;
25 use Template::Exception;
26 use Scalar::Util qw( blessed reftype );
27  
28 our $VERSION = '3.100';
29 our $DEBUG = 0 unless defined $DEBUG;
30 our $PRIVATE = qr/^[_.]/;
31 our $UNDEF_TYPE = 'var.undef';
32 our $UNDEF_INFO = 'undefined variable: %s';
33  
34 # alias _dotop() to dotop() so that we have a consistent method name
35 # between the Perl and XS stash implementations
36 *dotop = \&_dotop;
37  
38  
39 #------------------------------------------------------------------------
40 # Virtual Methods
41 #
42 # If any of $ROOT_OPS, $SCALAR_OPS, $HASH_OPS or $LIST_OPS are already
43 # defined then we merge their contents with the default virtual methods
44 # define by Template::VMethods. Otherwise we can directly alias the
45 # corresponding Template::VMethod package vars.
46 #------------------------------------------------------------------------
47  
48 our $ROOT_OPS = defined $ROOT_OPS
49 ? { %{$Template::VMethods::ROOT_VMETHODS}, %$ROOT_OPS }
50 : $Template::VMethods::ROOT_VMETHODS;
51  
52 our $SCALAR_OPS = defined $SCALAR_OPS
53 ? { %{$Template::VMethods::TEXT_VMETHODS}, %$SCALAR_OPS }
54 : $Template::VMethods::TEXT_VMETHODS;
55  
56 our $HASH_OPS = defined $HASH_OPS
57 ? { %{$Template::VMethods::HASH_VMETHODS}, %$HASH_OPS }
58 : $Template::VMethods::HASH_VMETHODS;
59  
60 our $LIST_OPS = defined $LIST_OPS
61 ? { %{$Template::VMethods::LIST_VMETHODS}, %$LIST_OPS }
62 : $Template::VMethods::LIST_VMETHODS;
63  
64  
65 #------------------------------------------------------------------------
66 # define_vmethod($type, $name, \&sub)
67 #
68 # Defines a virtual method of type $type (SCALAR, HASH, or LIST), with
69 # name $name, that invokes &sub when called. It is expected that &sub
70 # be able to handle the type that it will be called upon.
71 #------------------------------------------------------------------------
72  
73 sub define_vmethod {
74 my ($class, $type, $name, $sub) = @_;
75 my $op;
76 $type = lc $type;
77  
78 if ($type eq 'scalar' || $type eq 'item') {
79 $op = $SCALAR_OPS;
80 }
81 elsif ($type eq 'hash') {
82 $op = $HASH_OPS;
83 }
84 elsif ($type eq 'list' || $type eq 'array') {
85 $op = $LIST_OPS;
86 }
87 else {
88 die "invalid vmethod type: $type\n";
89 }
90  
91 $op->{ $name } = $sub;
92  
93 return 1;
94 }
95  
96  
97 #========================================================================
98 # ----- CLASS METHODS -----
99 #========================================================================
100  
101 #------------------------------------------------------------------------
102 # new(\%params)
103 #
104 # Constructor method which creates a new Template::Stash object.
105 # An optional hash reference may be passed containing variable
106 # definitions that will be used to initialise the stash.
107 #
108 # Returns a reference to a newly created Template::Stash.
109 #------------------------------------------------------------------------
110  
111 sub new {
112 my $class = shift;
113 my $params = ref $_[0] eq 'HASH' ? shift(@_) : { @_ };
114  
115 my $self = {
116 global => { },
117 %$params,
118 %$ROOT_OPS,
119 '_PARENT' => undef,
120 };
121  
122 bless $self, $class;
123 }
124  
125  
126 #========================================================================
127 # ----- PUBLIC OBJECT METHODS -----
128 #========================================================================
129  
130 #------------------------------------------------------------------------
131 # clone(\%params)
132 #
133 # Creates a copy of the current stash object to effect localisation
134 # of variables. The new stash is blessed into the same class as the
135 # parent (which may be a derived class) and has a '_PARENT' member added
136 # which contains a reference to the parent stash that created it
137 # ($self). This member is used in a successive declone() method call to
138 # return the reference to the parent.
139 #
140 # A parameter may be provided which should reference a hash of
141 # variable/values which should be defined in the new stash. The
142 # update() method is called to define these new variables in the cloned
143 # stash.
144 #
145 # Returns a reference to a cloned Template::Stash.
146 #------------------------------------------------------------------------
147  
148 sub clone {
149 my ($self, $params) = @_;
150 $params ||= { };
151  
152 # look out for magical 'import' argument which imports another hash
153 my $import = $params->{ import };
154 if (ref $import eq 'HASH') {
155 delete $params->{ import };
156 }
157 else {
158 undef $import;
159 }
160  
161 my $clone = bless {
162 %$self, # copy all parent members
163 %$params, # copy all new data
164 '_PARENT' => $self, # link to parent
165 }, ref $self;
166  
167 # perform hash import if defined
168 &{ $HASH_OPS->{ import } }($clone, $import)
169 if defined $import;
170  
171 return $clone;
172 }
173  
174  
175 #------------------------------------------------------------------------
176 # declone($export)
177 #
178 # Returns a reference to the PARENT stash. When called in the following
179 # manner:
180 # $stash = $stash->declone();
181 # the reference count on the current stash will drop to 0 and be "freed"
182 # and the caller will be left with a reference to the parent. This
183 # contains the state of the stash before it was cloned.
184 #------------------------------------------------------------------------
185  
186 sub declone {
187 my $self = shift;
188 $self->{ _PARENT } || $self;
189 }
190  
191  
192 #------------------------------------------------------------------------
193 # get($ident)
194 #
195 # Returns the value for an variable stored in the stash. The variable
196 # may be specified as a simple string, e.g. 'foo', or as an array
197 # reference representing compound variables. In the latter case, each
198 # pair of successive elements in the list represent a node in the
199 # compound variable. The first is the variable name, the second a
200 # list reference of arguments or 0 if undefined. So, the compound
201 # variable [% foo.bar('foo').baz %] would be represented as the list
202 # [ 'foo', 0, 'bar', ['foo'], 'baz', 0 ]. Returns the value of the
203 # identifier or an empty string if undefined. Errors are thrown via
204 # die().
205 #------------------------------------------------------------------------
206  
207 sub get {
208 my ($self, $ident, $args) = @_;
209 my ($root, $result);
210 $root = $self;
211  
212 if (ref $ident eq 'ARRAY'
213 || (index($ident,'.') > -1)
214 && ($ident = [ map { s/\(.*$//; ($_, 0) } split(/\./, $ident) ])) {
215 my $size = $#$ident;
216  
217 # if $ident is a list reference, then we evaluate each item in the
218 # identifier against the previous result, using the root stash
219 # ($self) as the first implicit 'result'...
220  
221 foreach (my $i = 0; $i <= $size; $i += 2) {
222 $result = $self->_dotop($root, @$ident[$i, $i+1]);
223 last unless defined $result;
224 $root = $result;
225 }
226 }
227 else {
228 $result = $self->_dotop($root, $ident, $args);
229 }
230  
231 return defined $result
232 ? $result
233 : $self->undefined($ident, $args);
234 }
235  
236  
237 #------------------------------------------------------------------------
238 # set($ident, $value, $default)
239 #
240 # Updates the value for a variable in the stash. The first parameter
241 # should be the variable name or array, as per get(). The second
242 # parameter should be the intended value for the variable. The third,
243 # optional parameter is a flag which may be set to indicate 'default'
244 # mode. When set true, the variable will only be updated if it is
245 # currently undefined or has a false value. The magical 'IMPORT'
246 # variable identifier may be used to indicate that $value is a hash
247 # reference whose values should be imported. Returns the value set,
248 # or an empty string if not set (e.g. default mode). In the case of
249 # IMPORT, returns the number of items imported from the hash.
250 #------------------------------------------------------------------------
251  
252 sub set {
253 my ($self, $ident, $value, $default) = @_;
254 my ($root, $result, $error);
255  
256 $root = $self;
257  
258 ELEMENT: {
259 if (ref $ident eq 'ARRAY'
260 || (index($ident,'.') != -1) # has a '.' in it somewhere
261 && ($ident = [
262 map { s/\(.*$//; ($_, 0) }
263 split(/\./, $ident)
264 ])) {
265  
266 # a compound identifier may contain multiple elements (e.g.
267 # foo.bar.baz) and we must first resolve all but the last,
268 # using _dotop() with the $lvalue flag set which will create
269 # intermediate hashes if necessary...
270 my $size = $#$ident;
271 foreach (my $i = 0; $i < $size - 2; $i += 2) {
272 $result = $self->_dotop($root, @$ident[$i, $i+1], 1);
273 last ELEMENT unless defined $result;
274 $root = $result;
275 }
276  
277 # then we call _assign() to assign the value to the last element
278 $result = $self->_assign(
279 $root, @$ident[$size-1, $size],
280 $value, $default
281 );
282 }
283 else {
284 $result = $self->_assign($root, $ident, 0, $value, $default);
285 }
286 }
287  
288 return defined $result ? $result : '';
289 }
290  
291  
292 #------------------------------------------------------------------------
293 # getref($ident)
294 #
295 # Returns a "reference" to a particular item. This is represented as a
296 # closure which will return the actual stash item when called.
297 #------------------------------------------------------------------------
298  
299 sub getref {
300 my ($self, $ident, $args) = @_;
301 my ($root, $item, $result);
302 $root = $self;
303  
304 if (ref $ident eq 'ARRAY') {
305 my $size = $#$ident;
306  
307 foreach (my $i = 0; $i <= $size; $i += 2) {
308 ($item, $args) = @$ident[$i, $i + 1];
309 last if $i >= $size - 2; # don't evaluate last node
310 last unless defined
311 ($root = $self->_dotop($root, $item, $args));
312 }
313 }
314 else {
315 $item = $ident;
316 }
317  
318 if (defined $root) {
319 return sub {
320 my @args = (@{$args||[]}, @_);
321 $self->_dotop($root, $item, \@args);
322 }
323 }
324 else {
325 return sub { '' };
326 }
327 }
328  
329  
330  
331  
332 #------------------------------------------------------------------------
333 # update(\%params)
334 #
335 # Update multiple variables en masse. No magic is performed. Simple
336 # variable names only.
337 #------------------------------------------------------------------------
338  
339 sub update {
340 my ($self, $params) = @_;
341  
342 # look out for magical 'import' argument to import another hash
343 my $import = $params->{ import };
344 if (ref $import eq 'HASH') {
345 @$self{ keys %$import } = values %$import;
346 delete $params->{ import };
347 }
348  
349 @$self{ keys %$params } = values %$params;
350 }
351  
352  
353 #------------------------------------------------------------------------
354 # undefined($ident, $args)
355 #
356 # Method called when a get() returns an undefined value. Can be redefined
357 # in a subclass to implement alternate handling.
358 #------------------------------------------------------------------------
359  
360 sub undefined {
361 my ($self, $ident, $args) = @_;
362  
363 if ($self->{ _STRICT }) {
364 # Sorry, but we can't provide a sensible source file and line without
365 # re-designing the whole architecture of TT (see TT3)
366 die Template::Exception->new(
367 $UNDEF_TYPE,
368 sprintf(
369 $UNDEF_INFO,
370 $self->_reconstruct_ident($ident)
371 )
372 ) if $self->{ _STRICT };
373 }
374 else {
375 # There was a time when I thought this was a good idea. But it's not.
376 return '';
377 }
378 }
379  
380 sub _reconstruct_ident {
381 my ($self, $ident) = @_;
382 my ($name, $args, @output);
383 my @input = ref $ident eq 'ARRAY' ? @$ident : ($ident);
384  
385 while (@input) {
386 $name = shift @input;
387 $args = shift @input || 0;
388 $name .= '(' . join(', ', map { /^\d+$/ ? $_ : "'$_'" } @$args) . ')'
389 if $args && ref $args eq 'ARRAY';
390 push(@output, $name);
391 }
392  
393 return join('.', @output);
394 }
395  
396  
397 #========================================================================
398 # ----- PRIVATE OBJECT METHODS -----
399 #========================================================================
400  
401 #------------------------------------------------------------------------
402 # _dotop($root, $item, \@args, $lvalue)
403 #
404 # This is the core 'dot' operation method which evaluates elements of
405 # variables against their root. All variables have an implicit root
406 # which is the stash object itself (a hash). Thus, a non-compound
407 # variable 'foo' is actually '(stash.)foo', the compound 'foo.bar' is
408 # '(stash.)foo.bar'. The first parameter is a reference to the current
409 # root, initially the stash itself. The second parameter contains the
410 # name of the variable element, e.g. 'foo'. The third optional
411 # parameter is a reference to a list of any parenthesised arguments
412 # specified for the variable, which are passed to sub-routines, object
413 # methods, etc. The final parameter is an optional flag to indicate
414 # if this variable is being evaluated on the left side of an assignment
415 # (e.g. foo.bar.baz = 10). When set true, intermediated hashes will
416 # be created (e.g. bar) if necessary.
417 #
418 # Returns the result of evaluating the item against the root, having
419 # performed any variable "magic". The value returned can then be used
420 # as the root of the next _dotop() in a compound sequence. Returns
421 # undef if the variable is undefined.
422 #------------------------------------------------------------------------
423  
424 sub _dotop {
425 my ($self, $root, $item, $args, $lvalue) = @_;
426 my $rootref = ref $root;
427 my $atroot = (blessed $root && $root->isa(ref $self));
428 my ($value, @result);
429  
430 $args ||= [ ];
431 $lvalue ||= 0;
432  
433 # print STDERR "_dotop(root=$root, item=$item, args=[@$args])\n"
434 # if $DEBUG;
435  
436 # return undef without an error if either side of the dot is unviable
437 return undef unless defined($root) and defined($item);
438  
439 # or if an attempt is made to access a private member, starting _ or .
440 return undef if $PRIVATE && $item =~ /$PRIVATE/;
441  
442 if ($atroot || $rootref eq 'HASH') {
443 # if $root is a regular HASH or a Template::Stash kinda HASH (the
444 # *real* root of everything). We first lookup the named key
445 # in the hash, or create an empty hash in its place if undefined
446 # and the $lvalue flag is set. Otherwise, we check the HASH_OPS
447 # pseudo-methods table, calling the code if found, or return undef.
448  
449 if (defined($value = $root->{ $item })) {
450 return $value unless ref $value eq 'CODE'; ## RETURN
451 @result = &$value(@$args); ## @result
452 }
453 elsif ($lvalue) {
454 # we create an intermediate hash if this is an lvalue
455 return $root->{ $item } = { }; ## RETURN
456 }
457 # ugly hack: only allow import vmeth to be called on root stash
458 elsif (($value = $HASH_OPS->{ $item })
459 && (! $atroot || $item eq 'import')) {
460 @result = &$value($root, @$args); ## @result
461 }
462 elsif ( ref $item eq 'ARRAY' ) {
463 # hash slice
464 return [@$root{@$item}]; ## RETURN
465 }
466 }
467 elsif ($rootref eq 'ARRAY') {
468 # if root is an ARRAY then we check for a LIST_OPS pseudo-method
469 # or return the numerical index into the array, or undef
470 if ($value = $LIST_OPS->{ $item }) {
471 @result = &$value($root, @$args); ## @result
472 }
473 elsif ($item =~ /^-?\d+$/) {
474 $value = $root->[$item];
475 return $value unless ref $value eq 'CODE'; ## RETURN
476 @result = &$value(@$args); ## @result
477 }
478 elsif ( ref $item eq 'ARRAY' ) {
479 # array slice
480 return [@$root[@$item]]; ## RETURN
481 }
482 }
483  
484 # NOTE: we do the can-can because UNIVSERAL::isa($something, 'UNIVERSAL')
485 # doesn't appear to work with CGI, returning true for the first call
486 # and false for all subsequent calls.
487  
488 # UPDATE: that doesn't appear to be the case any more
489  
490 elsif (blessed($root) && $root->can('can')) {
491  
492 # if $root is a blessed reference (i.e. inherits from the
493 # UNIVERSAL object base class) then we call the item as a method.
494 # If that fails then we try to fallback on HASH behaviour if
495 # possible.
496 eval { @result = $root->$item(@$args); };
497  
498 if ($@) {
499 # temporary hack - required to propagate errors thrown
500 # by views; if $@ is a ref (e.g. Template::Exception
501 # object then we assume it's a real error that needs
502 # real throwing
503  
504 my $class = ref($root) || $root;
505  
506 # Fail only if the function exists
507 die $@ if ( ref($@) || $root->can($item) );
508  
509 # failed to call object method, so try some fallbacks
510 if (reftype $root eq 'HASH') {
511 if( defined($value = $root->{ $item })) {
512 return $value unless ref $value eq 'CODE'; ## RETURN
513 @result = &$value(@$args);
514 }
515 elsif ($value = $HASH_OPS->{ $item }) {
516 @result = &$value($root, @$args);
517 }
518 elsif ($value = $LIST_OPS->{ $item }) {
519 @result = &$value([$root], @$args);
520 }
521 }
522 elsif (reftype $root eq 'ARRAY') {
523 if( $value = $LIST_OPS->{ $item }) {
524 @result = &$value($root, @$args);
525 }
526 elsif( $item =~ /^-?\d+$/ ) {
527 $value = $root->[$item];
528 return $value unless ref $value eq 'CODE'; ## RETURN
529 @result = &$value(@$args); ## @result
530 }
531 elsif ( ref $item eq 'ARRAY' ) {
532 # array slice
533 return [@$root[@$item]]; ## RETURN
534 }
535 }
536 elsif ($value = $SCALAR_OPS->{ $item }) {
537 @result = &$value($root, @$args);
538 }
539 elsif ($value = $LIST_OPS->{ $item }) {
540 @result = &$value([$root], @$args);
541 }
542 elsif ($self->{ _DEBUG }) {
543 @result = (undef, $@);
544 }
545 }
546 }
547 elsif (($value = $SCALAR_OPS->{ $item }) && ! $lvalue) {
548 # at this point, it doesn't look like we've got a reference to
549 # anything we know about, so we try the SCALAR_OPS pseudo-methods
550 # table (but not for l-values)
551 @result = &$value($root, @$args); ## @result
552 }
553 elsif (($value = $LIST_OPS->{ $item }) && ! $lvalue) {
554 # last-ditch: can we promote a scalar to a one-element
555 # list and apply a LIST_OPS virtual method?
556 @result = &$value([$root], @$args);
557 }
558 elsif ($self->{ _DEBUG }) {
559 die "don't know how to access [ $root ].$item\n"; ## DIE
560 }
561 else {
562 @result = ();
563 }
564  
565 # fold multiple return items into a list unless first item is undef
566 if (defined $result[0]) {
567 return ## RETURN
568 scalar @result > 1 ? [ @result ] : $result[0];
569 }
570 elsif (defined $result[1]) {
571 die $result[1]; ## DIE
572 }
573 elsif ($self->{ _DEBUG }) {
574 die "$item is undefined\n"; ## DIE
575 }
576  
577 return undef;
578 }
579  
580  
581 #------------------------------------------------------------------------
582 # _assign($root, $item, \@args, $value, $default)
583 #
584 # Similar to _dotop() above, but assigns a value to the given variable
585 # instead of simply returning it. The first three parameters are the
586 # root item, the item and arguments, as per _dotop(), followed by the
587 # value to which the variable should be set and an optional $default
588 # flag. If set true, the variable will only be set if currently false
589 # (undefined/zero)
590 #------------------------------------------------------------------------
591  
592 sub _assign {
593 my ($self, $root, $item, $args, $value, $default) = @_;
594 my $rootref = ref $root;
595 my $atroot = ($root eq $self);
596 my $result;
597 $args ||= [ ];
598 $default ||= 0;
599  
600 # return undef without an error if either side of the dot is unviable
601 return undef unless $root and defined $item;
602  
603 # or if an attempt is made to update a private member, starting _ or .
604 return undef if $PRIVATE && $item =~ /$PRIVATE/;
605  
606 if ($rootref eq 'HASH' || $atroot) {
607 # if the root is a hash we set the named key
608 return ($root->{ $item } = $value) ## RETURN
609 unless $default && $root->{ $item };
610 }
611 elsif ($rootref eq 'ARRAY' && $item =~ /^-?\d+$/) {
612 # or set a list item by index number
613 return ($root->[$item] = $value) ## RETURN
614 unless $default && $root->[$item];
615 }
616 elsif (blessed($root)) {
617 # try to call the item as a method of an object
618  
619 return $root->$item(@$args, $value) ## RETURN
620 unless $default && $root->$item();
621  
622 # 2 issues:
623 # - method call should be wrapped in eval { }
624 # - fallback on hash methods if object method not found
625 #
626 # eval { $result = $root->$item(@$args, $value); };
627 #
628 # if ($@) {
629 # die $@ if ref($@) || ($@ !~ /Can't locate object method/);
630 #
631 # # failed to call object method, so try some fallbacks
632 # if (UNIVERSAL::isa($root, 'HASH') && exists $root->{ $item }) {
633 # $result = ($root->{ $item } = $value)
634 # unless $default && $root->{ $item };
635 # }
636 # }
637 # return $result; ## RETURN
638 }
639 else {
640 die "don't know how to assign to [$root].[$item]\n"; ## DIE
641 }
642  
643 return undef;
644 }
645  
646 1;
647  
648 __END__