blib/lib/Template/Stash.pm untested

filter: Statementstmt 0.0% 0 / 218 Branchbran 0.0% 0 / 142 Conditioncond 0.0% 0 / 103 MC/DCmcdc n/a Subroutinesub 0.0% 0 / 17 Podpod 0.0% 0 / 12 totaltotal 0.0% 0 / 492 CC 67 SCAR 64.7
CC
67
Cov
0%
_dotop
1406.0
_assign
90.0
getref
30.0
CRAP 643.8
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.105';
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 $result // $self->undefined($ident, $args);
232 }
233  
234  
235 #------------------------------------------------------------------------
236 # set($ident, $value, $default)
237 #
238 # Updates the value for a variable in the stash. The first parameter
239 # should be the variable name or array, as per get(). The second
240 # parameter should be the intended value for the variable. The third,
241 # optional parameter is a flag which may be set to indicate 'default'
242 # mode. When set true, the variable will only be updated if it is
243 # currently undefined or has a false value. The magical 'IMPORT'
244 # variable identifier may be used to indicate that $value is a hash
245 # reference whose values should be imported. Returns the value set,
246 # or an empty string if not set (e.g. default mode). In the case of
247 # IMPORT, returns the number of items imported from the hash.
248 #------------------------------------------------------------------------
249  
250 sub set {
251 my ($self, $ident, $value, $default) = @_;
252 my ($root, $result, $error);
253  
254 $root = $self;
255  
256 ELEMENT: {
257 if (ref $ident eq 'ARRAY'
258 || (index($ident,'.') != -1) # has a '.' in it somewhere
259 && ($ident = [
260 map { s/\(.*$//; ($_, 0) }
261 split(/\./, $ident)
262 ])) {
263  
264 # a compound identifier may contain multiple elements (e.g.
265 # foo.bar.baz) and we must first resolve all but the last,
266 # using _dotop() with the $lvalue flag set which will create
267 # intermediate hashes if necessary...
268 my $size = $#$ident;
269 foreach (my $i = 0; $i < $size - 2; $i += 2) {
270 $result = $self->_dotop($root, @$ident[$i, $i+1], 1);
271 last ELEMENT unless defined $result;
272 $root = $result;
273 }
274  
275 # then we call _assign() to assign the value to the last element
276 $result = $self->_assign(
277 $root, @$ident[$size-1, $size],
278 $value, $default
279 );
280 }
281 else {
282 $result = $self->_assign($root, $ident, 0, $value, $default);
283 }
284 }
285  
286 return $result // '';
287 }
288  
289  
290 #------------------------------------------------------------------------
291 # getref($ident)
292 #
293 # Returns a "reference" to a particular item. This is represented as a
294 # closure which will return the actual stash item when called.
295 #------------------------------------------------------------------------
296  
297 sub getref {
298 my ($self, $ident, $args) = @_;
299 my ($root, $item, $result);
300 $root = $self;
301  
302 if (ref $ident eq 'ARRAY') {
303 my $size = $#$ident;
304  
305 foreach (my $i = 0; $i <= $size; $i += 2) {
306 ($item, $args) = @$ident[$i, $i + 1];
307 last if $i >= $size - 2; # don't evaluate last node
308 last unless defined
309 ($root = $self->_dotop($root, $item, $args));
310 }
311 }
312 else {
313 $item = $ident;
314 }
315  
316 if (defined $root) {
317 return sub {
318 my @args = (@{$args||[]}, @_);
319 $self->_dotop($root, $item, \@args);
320 }
321 }
322 else {
323 return sub { '' };
324 }
325 }
326  
327  
328  
329  
330 #------------------------------------------------------------------------
331 # update(\%params)
332 #
333 # Update multiple variables en masse. No magic is performed. Simple
334 # variable names only.
335 #------------------------------------------------------------------------
336  
337 sub update {
338 my ($self, $params) = @_;
339  
340 # look out for magical 'import' argument to import another hash
341 my $import = $params->{ import };
342 if (ref $import eq 'HASH') {
343 @$self{ keys %$import } = values %$import;
344 delete $params->{ import };
345 }
346  
347 @$self{ keys %$params } = values %$params;
348 }
349  
350  
351 #------------------------------------------------------------------------
352 # undefined($ident, $args)
353 #
354 # Method called when a get() returns an undefined value. Can be redefined
355 # in a subclass to implement alternate handling.
356 #------------------------------------------------------------------------
357  
358 sub undefined {
359 my ($self, $ident, $args) = @_;
360  
361 if ($self->{ _STRICT }) {
362 # .defined must work on undefined values even in STRICT mode —
363 # it would be nonsensical to throw "undefined variable" when the
364 # user is explicitly testing whether a variable is defined (GH #170)
365 if (ref $ident eq 'ARRAY') {
366 my $last_item = $ident->[$#$ident - 1];
367 return '' if defined $last_item && $last_item eq 'defined';
368 }
369  
370 # Sorry, but we can't provide a sensible source file and line without
371 # re-designing the whole architecture of TT (see TT3)
372 die Template::Exception->new(
373 $UNDEF_TYPE,
374 sprintf(
375 $UNDEF_INFO,
376 $self->_reconstruct_ident($ident)
377 )
378 ) if $self->{ _STRICT };
379 }
380 else {
381 # There was a time when I thought this was a good idea. But it's not.
382 return '';
383 }
384 }
385  
386 sub _reconstruct_ident {
387 my ($self, $ident) = @_;
388 my ($name, $args, @output);
389 my @input = ref $ident eq 'ARRAY' ? @$ident : ($ident);
390  
391 while (@input) {
392 $name = shift @input;
393 $args = shift @input || 0;
394 $name .= '(' . join(', ', map { /^\d+$/ ? $_ : "'$_'" } @$args) . ')'
395 if $args && ref $args eq 'ARRAY';
396 push(@output, $name);
397 }
398  
399 return join('.', @output);
400 }
401  
402  
403 #========================================================================
404 # ----- PRIVATE OBJECT METHODS -----
405 #========================================================================
406  
407 #------------------------------------------------------------------------
408 # _dotop($root, $item, \@args, $lvalue)
409 #
410 # This is the core 'dot' operation method which evaluates elements of
411 # variables against their root. All variables have an implicit root
412 # which is the stash object itself (a hash). Thus, a non-compound
413 # variable 'foo' is actually '(stash.)foo', the compound 'foo.bar' is
414 # '(stash.)foo.bar'. The first parameter is a reference to the current
415 # root, initially the stash itself. The second parameter contains the
416 # name of the variable element, e.g. 'foo'. The third optional
417 # parameter is a reference to a list of any parenthesised arguments
418 # specified for the variable, which are passed to sub-routines, object
419 # methods, etc. The final parameter is an optional flag to indicate
420 # if this variable is being evaluated on the left side of an assignment
421 # (e.g. foo.bar.baz = 10). When set true, intermediated hashes will
422 # be created (e.g. bar) if necessary.
423 #
424 # Returns the result of evaluating the item against the root, having
425 # performed any variable "magic". The value returned can then be used
426 # as the root of the next _dotop() in a compound sequence. Returns
427 # undef if the variable is undefined.
428 #------------------------------------------------------------------------
429  
430 sub _dotop {
431 my ($self, $root, $item, $args, $lvalue) = @_;
432 my $rootref = ref $root;
433 my $atroot = (blessed $root && $root->isa(ref $self));
434 my ($value, @result);
435  
436 $args ||= [ ];
437 $lvalue ||= 0;
438  
439 # print STDERR "_dotop(root=$root, item=$item, args=[@$args])\n"
440 # if $DEBUG;
441  
442 # return undef without an error if either side of the dot is unviable
443 return undef unless defined($root) and defined($item);
444  
445 # or if an attempt is made to access a private member, starting _ or .
446 return undef if $PRIVATE && $item =~ /$PRIVATE/;
447  
448 if ($atroot || $rootref eq 'HASH') {
449 # if $root is a regular HASH or a Template::Stash kinda HASH (the
450 # *real* root of everything). We first lookup the named key
451 # in the hash, or create an empty hash in its place if undefined
452 # and the $lvalue flag is set. Otherwise, we check the HASH_OPS
453 # pseudo-methods table, calling the code if found, or return undef.
454  
455 if (defined($value = $root->{ $item })) {
456 return $value unless ref $value eq 'CODE'; ## RETURN
457 @result = &$value(@$args); ## @result
458 }
459 elsif ($lvalue) {
460 # we create an intermediate hash if this is an lvalue
461 return $root->{ $item } = { }; ## RETURN
462 }
463 # ugly hack: only allow import vmeth to be called on root stash
464 elsif (($value = $HASH_OPS->{ $item })
465 && (! $atroot || $item eq 'import')) {
466 @result = &$value($root, @$args); ## @result
467 }
468 elsif ( ref $item eq 'ARRAY' ) {
469 # hash slice
470 return [@$root{@$item}]; ## RETURN
471 }
472 }
473 elsif ($rootref eq 'ARRAY') {
474 # if root is an ARRAY then we check for a LIST_OPS pseudo-method
475 # or return the numerical index into the array, or undef
476 if ($value = $LIST_OPS->{ $item }) {
477 @result = &$value($root, @$args); ## @result
478 }
479 elsif ($item =~ /^-?\d+$/) {
480 $value = $root->[$item];
481 return $value unless ref $value eq 'CODE'; ## RETURN
482 @result = &$value(@$args); ## @result
483 }
484 elsif ( ref $item eq 'ARRAY' ) {
485 # array slice
486 return [@$root[@$item]]; ## RETURN
487 }
488 }
489  
490 # NOTE: we do the can-can because UNIVSERAL::isa($something, 'UNIVERSAL')
491 # doesn't appear to work with CGI, returning true for the first call
492 # and false for all subsequent calls.
493  
494 # UPDATE: that doesn't appear to be the case any more
495  
496 elsif (blessed($root) && $root->can('can')) {
497  
498 # if $root is a blessed reference (i.e. inherits from the
499 # UNIVERSAL object base class) then we call the item as a method.
500 # If that fails then we try to fallback on HASH behaviour if
501 # possible.
502 eval { @result = $root->$item(@$args); };
503  
504 if ($@) {
505 # temporary hack - required to propagate errors thrown
506 # by views; if $@ is a ref (e.g. Template::Exception
507 # object then we assume it's a real error that needs
508 # real throwing
509  
510 my $class = ref($root) || $root;
511  
512 # Fail only if the function exists
513 die $@ if ( ref($@) || $root->can($item) );
514  
515 # failed to call object method, so try some fallbacks
516 if (reftype $root eq 'HASH') {
517 if( defined($value = $root->{ $item })) {
518 return $value unless ref $value eq 'CODE'; ## RETURN
519 @result = &$value(@$args);
520 }
521 elsif ($value = $HASH_OPS->{ $item }) {
522 @result = &$value($root, @$args);
523 }
524 elsif ($value = $LIST_OPS->{ $item }) {
525 @result = &$value([$root], @$args);
526 }
527 }
528 elsif (reftype $root eq 'ARRAY') {
529 if( $value = $LIST_OPS->{ $item }) {
530 @result = &$value($root, @$args);
531 }
532 elsif( $item =~ /^-?\d+$/ ) {
533 $value = $root->[$item];
534 return $value unless ref $value eq 'CODE'; ## RETURN
535 @result = &$value(@$args); ## @result
536 }
537 elsif ( ref $item eq 'ARRAY' ) {
538 # array slice
539 return [@$root[@$item]]; ## RETURN
540 }
541 }
542 elsif ($value = $SCALAR_OPS->{ $item }) {
543 @result = &$value($root, @$args);
544 }
545 elsif ($value = $LIST_OPS->{ $item }) {
546 @result = &$value([$root], @$args);
547 }
548 elsif ($self->{ _DEBUG }) {
549 @result = (undef, $@);
550 }
551 }
552 }
553 elsif (($value = $SCALAR_OPS->{ $item }) && ! $lvalue) {
554 # at this point, it doesn't look like we've got a reference to
555 # anything we know about, so we try the SCALAR_OPS pseudo-methods
556 # table (but not for l-values)
557 @result = &$value($root, @$args); ## @result
558 }
559 elsif (($value = $LIST_OPS->{ $item }) && ! $lvalue) {
560 # last-ditch: can we promote a scalar to a one-element
561 # list and apply a LIST_OPS virtual method?
562 @result = &$value([$root], @$args);
563 }
564 elsif ($self->{ _DEBUG }) {
565 die "don't know how to access [ $root ].$item\n"; ## DIE
566 }
567 else {
568 @result = ();
569 }
570  
571 # fold multiple return items into a list unless first item is undef
572 if (defined $result[0]) {
573 return ## RETURN
574 scalar @result > 1 ? [ @result ] : $result[0];
575 }
576 elsif (defined $result[1]) {
577 die $result[1]; ## DIE
578 }
579 elsif ($self->{ _DEBUG }) {
580 die "$item is undefined\n"; ## DIE
581 }
582  
583 return undef;
584 }
585  
586  
587 #------------------------------------------------------------------------
588 # _assign($root, $item, \@args, $value, $default)
589 #
590 # Similar to _dotop() above, but assigns a value to the given variable
591 # instead of simply returning it. The first three parameters are the
592 # root item, the item and arguments, as per _dotop(), followed by the
593 # value to which the variable should be set and an optional $default
594 # flag. If set true, the variable will only be set if currently false
595 # (undefined/zero)
596 #------------------------------------------------------------------------
597  
598 sub _assign {
599 my ($self, $root, $item, $args, $value, $default) = @_;
600 my $rootref = ref $root;
601 my $atroot = (blessed $root && $root->isa(ref $self));
602 my $result;
603 $args ||= [ ];
604 $default ||= 0;
605  
606 # return undef without an error if either side of the dot is unviable
607 return undef unless $root and defined $item;
608  
609 # or if an attempt is made to update a private member, starting _ or .
610 return undef if $PRIVATE && $item =~ /$PRIVATE/;
611  
612 if ($rootref eq 'HASH' || $atroot) {
613 # if the root is a hash we set the named key
614 return ($root->{ $item } = $value) ## RETURN
615 unless $default && $root->{ $item };
616 }
617 elsif ($rootref eq 'ARRAY' && $item =~ /^-?\d+$/) {
618 # or set a list item by index number
619 return ($root->[$item] = $value) ## RETURN
620 unless $default && $root->[$item];
621 }
622 elsif (blessed($root)) {
623 # try to call the item as a method of an object
624  
625 return $root->$item(@$args, $value) ## RETURN
626 unless $default && $root->$item();
627  
628 # 2 issues:
629 # - method call should be wrapped in eval { }
630 # - fallback on hash methods if object method not found
631 #
632 # eval { $result = $root->$item(@$args, $value); };
633 #
634 # if ($@) {
635 # die $@ if ref($@) || ($@ !~ /Can't locate object method/);
636 #
637 # # failed to call object method, so try some fallbacks
638 # if (UNIVERSAL::isa($root, 'HASH') && exists $root->{ $item }) {
639 # $result = ($root->{ $item } = $value)
640 # unless $default && $root->{ $item };
641 # }
642 # }
643 # return $result; ## RETURN
644 }
645 else {
646 die "don't know how to assign to [$root].[$item]\n"; ## DIE
647 }
648  
649 return undef;
650 }
651  
652 1;
653  
654 __END__