| 1 | package Document::Maker::Pattern; | ||
| 2 | |||
| 3 | use strict; | ||
| 4 | use warnings; | ||
| 5 | |||
| 6 | use Moose; | ||
| 7 | |||
| 8 | with map { "Document::Maker::Role::$_" } qw/Logging/; # TODO Should be component | ||
| 9 | |||
| 10 | has pattern => (qw/is ro required 1/); | ||
| 11 | has template => (qw/is ro/); | ||
| 12 | has matcher => (qw/is ro/); | ||
| 13 | |||
| 14 | sub BUILD { | ||
| 15 | my $self = shift; | ||
| 16 | my $pattern = $self->pattern; | ||
| 17 | |||
| 18 | my $template = $pattern; # $template should be of the form "-%-" or whatever | ||
| 19 | if ($template =~ m/%\(.*\)/) { | ||
| 20 | $template =~ s/%\((.*)\)/%/; | ||
| 21 | } | ||
| 22 | |||
| 23 | my $matcher = $pattern; | ||
| 24 | if ($matcher =~ m/%\(.*\)/) { | ||
| 25 | $matcher =~ s/%\((.*)\)/($1)/; | ||
| 26 | } | ||
| 27 | else { | ||
| 28 | $matcher =~ s/\%/(.*)/; | ||
| 29 | } | ||
| 30 | $matcher = qr/$matcher/; | ||
| 31 | |||
| 32 | $self->log->debug("Pattern template is: $template"); | ||
| 33 | $self->log->debug("Pattern matcher is: $matcher"); | ||
| 34 | |||
| 35 | $self->{template} = $template; | ||
| 36 | $self->{matcher} = $matcher; | ||
| 37 | |||
| 38 | return $self; | ||
| 39 | } | ||
| 40 | |||
| 41 | sub substitute { | ||
| 42 | my $self = shift; | ||
| 43 | my $nickname = shift; | ||
| 44 | |||
| 45 | return $nickname if $nickname =~ $self->matcher; | ||
| 46 | |||
| 47 | my $name = $self->template; | ||
| 48 | $name =~ s/\%/$nickname/; | ||
| 49 | return $name; | ||
| 50 | } | ||
| 51 | |||
| 52 | sub match { | ||
| 53 | my $self = shift; | ||
| 54 | my $name = shift;; | ||
| 55 | my $matcher = $self->matcher; | ||
| 56 | my ($nickname) = $name =~ $matcher; | ||
| 57 | return $nickname; | ||
| 58 | } | ||
| 59 | |||
| 60 | sub nickname { | ||
| 61 | my $self = shift; | ||
| 62 | my $nickname = shift; | ||
| 63 | |||
| 64 | return $nickname unless $nickname =~ $self->matcher; | ||
| 65 | |||
| 66 | return $self->match($nickname); | ||
| 67 | } | ||
| 68 | |||
| 69 | 1; |