- Fixes for rt.cpan #17322 and #17331
[catagits/Catalyst-Runtime.git] / lib / Catalyst / DispatchType / Regex.pm
1 package Catalyst::DispatchType::Regex;
2
3 use strict;
4 use base qw/Catalyst::DispatchType::Path/;
5 use Text::SimpleTable;
6
7 =head1 NAME
8
9 Catalyst::DispatchType::Regex - Regex DispatchType
10
11 =head1 SYNOPSIS
12
13 See L<Catalyst>.
14
15 =head1 DESCRIPTION
16
17 =head1 METHODS
18
19 =head2 $self->list($c)
20
21 =cut
22
23 sub list {
24     my ( $self, $c ) = @_;
25     my $re = Text::SimpleTable->new( [ 36, 'Regex' ], [ 37, 'Private' ] );
26     for my $regex ( @{ $self->{compiled} } ) {
27         my $action = $regex->{action};
28         $re->row( $regex->{path}, "/$action" );
29     }
30     $c->log->debug( "Loaded Regex actions:\n" . $re->draw )
31       if ( @{ $self->{compiled} } );
32 }
33
34 =head2 $self->match( $c, $path )
35
36 =cut
37
38 sub match {
39     my ( $self, $c, $path ) = @_;
40
41     return if $self->SUPER::match( $c, $path );
42
43     # Check path against plain text first
44
45     foreach my $compiled ( @{ $self->{compiled} || [] } ) {
46         if ( my @snippets = ( $path =~ $compiled->{re} ) ) {
47             $c->req->action( $compiled->{path} );
48             $c->req->match($path);
49             $c->req->snippets( \@snippets );
50             $c->action( $compiled->{action} );
51             $c->namespace( $compiled->{action}->namespace );
52             return 1;
53         }
54     }
55
56     return 0;
57 }
58
59 =head2 $self->register( $c, $action )
60
61 =cut
62
63 sub register {
64     my ( $self, $c, $action ) = @_;
65     my $attrs = $action->attributes;
66     my @register = map { @{ $_ || [] } } @{$attrs}{ 'Regex', 'Regexp' };
67     foreach
68       my $r ( map { @{ $_ || [] } } @{$attrs}{ 'LocalRegex', 'LocalRegexp' } )
69     {
70         unless ( $r =~ s/^\^// ) { $r = "(?:.*?)$r"; }
71         push( @register, '^' . $action->namespace . '/' . $r );
72     }
73
74     foreach my $r (@register) {
75         $self->register_path( $c, $r, $action );
76         $self->register_regex( $c, $r, $action );
77     }
78     return 1 if @register;
79     return 0;
80 }
81
82 =head2 $self->register_regex($c, $re, $action)
83
84 =cut
85
86 sub register_regex {
87     my ( $self, $c, $re, $action ) = @_;
88     push(
89         @{ $self->{compiled} },    # and compiled regex for us
90         {
91             re     => qr#$re#,
92             action => $action,
93             path   => $re,
94         }
95     );
96 }
97
98 =head1 AUTHOR
99
100 Matt S Trout
101 Sebastian Riedel, C<sri@cpan.org>
102
103 =head1 COPYRIGHT
104
105 This program is free software, you can redistribute it and/or modify it under
106 the same terms as Perl itself.
107
108 =cut
109
110 1;