view Lib/IMPL/Resources/Format.pm @ 335:e8be9062ecf2

improved resource classes, contracts are deprecated
author cin
date Thu, 13 Jun 2013 20:13:24 +0400
parents 4d0e1962161c
children 010ceafd0c5a
line wrap: on
line source

package IMPL::Resources::Format;
use strict;
use warnings;

require Exporter;
our @ISA = qw(Exporter);
our @EXPORT_OK = qw(&FormatMessage);

sub FormatMessage {
    my ($string,$args,$resolver) = @_;
    
    $args ||= {};
    $resolver ||= \&_defaultResolver;
    
    $string =~ s/%(\w+(?:\.\w+)*)%/_getvalue($args,$1,"\[$1\]",$resolver)/ge;
    
    return $string;
}

sub _getvalue {
    my ($obj,$path,$default,$resolver) = @_;
    
    foreach my $chunk (split /\./,$path) {
        return $default unless $obj;
        if (ref $obj eq 'HASH') {
            $obj = $obj->{$chunk};
        } else {
            $obj = $resolver->($obj,$chunk);
        }
    }
    return $obj;
}

sub _defaultResolver {
    my ($obj,$prop) = @_;
    
    return ( eval { $obj->can($prop) } ? $obj->$prop() : undef );
}

1;