| 1 | package Web::Components::ReverseMap; | ||
| 2 | |||
| 3 | use Unexpected::Types qw( HashRef ); | ||
| 4 | use List::Util qw( pairs ); | ||
| 5 | use Scalar::Util qw( blessed ); | ||
| 6 | use Moo::Role; | ||
| 7 | |||
| 8 | requires qw( log ); | ||
| 9 | |||
| 10 | =encoding utf-8 | ||
| 11 | |||
| 12 | =head1 Name | ||
| 13 | |||
| 14 | Web::Components::ReverseMap - Creates a reverse routing map | ||
| 15 | |||
| 16 | =head1 Synopsis | ||
| 17 | |||
| 18 | use Moo; | ||
| 19 | |||
| 20 | with 'Web::Components::ReverseMap'; | ||
| 21 | |||
| 22 | =head1 Description | ||
| 23 | |||
| 24 | Creates a reverse routing map | ||
| 25 | |||
| 26 | =head1 Configuration and Environment | ||
| 27 | |||
| 28 | Defines the following attributes; | ||
| 29 | |||
| 30 | =over 3 | ||
| 31 | |||
| 32 | =item C<action_path_map> | ||
| 33 | |||
| 34 | A reverse map of routes extracted using regular expression from the controller | ||
| 35 | source | ||
| 36 | |||
| 37 | =cut | ||
| 38 | |||
| 39 | has 'action_path_map' => is => 'lazy', isa => HashRef, default => sub { | ||
| 40 | my $self = shift; | ||
| 41 | my $class = blessed $self; | ||
| 42 | my $map = {}; | ||
| 43 | |||
| 44 | for my $pair (pairs $self->dispatch_request) { | ||
| 45 | my @parts = split m{ / }mx, $pair->value->()->[0]; | ||
| 46 | my $action = $parts[0] . '/' . $parts[-1]; | ||
| 47 | my ($uri) = $pair->key =~ m{ [\+] \s* / ([^\+]+) }mx; | ||
| 48 | |||
| 49 | next unless $uri; | ||
| 50 | |||
| 51 | $uri =~ s{ [ ]+ \z }{}mx; | ||
| 52 | $uri = [ split m{ \s+? \| \s+? /? }mx, $uri ] if $uri =~ m{ \| }mx; | ||
| 53 | |||
| 54 | $map->{$action} = $uri; | ||
| 55 | } | ||
| 56 | |||
| 57 | $self->log->warn("No routes found in ${class}") unless scalar keys %{$map}; | ||
| 58 | |||
| 59 | return $map; | ||
| 60 | }; | ||
| 61 | |||
| 62 | =back | ||
| 63 | |||
| 64 | =head1 Subroutines/Methods | ||
| 65 | |||
| 66 | Defines the no methods | ||
| 67 | |||
| 68 | =over 3 | ||
| 69 | |||
| 70 | =cut | ||
| 71 | |||
| 72 | use namespace::autoclean; | ||
| 73 | |||
| 74 | 1; | ||
| 75 | |||
| 76 | __END__ |