- Restored Regex behaviour and added LocalRegex
[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 =over 4
20
21 =item $self->list($c)
22
23 =cut
24
25 sub list {
26     my ( $self, $c ) = @_;
27     my $re = Text::SimpleTable->new( [ 36, 'Regex' ], [ 37, 'Private' ] );
28     for my $regex ( @{ $self->{compiled} } ) {
29         my $compiled = $regex->{re};
30         my $action   = $regex->{action};
31         $re->row( $compiled, "/$action" );
32     }
33     $c->log->debug( "Loaded Regex actions:\n" . $re->draw )
34       if ( @{ $self->{compiled} } );
35 }
36
37 =item $self->match( $c, $path )
38
39 =cut
40
41 sub match {
42     my ( $self, $c, $path ) = @_;
43
44     return if $self->SUPER::match( $c, $path );
45
46     # Check path against plain text first
47
48     foreach my $compiled ( @{ $self->{compiled} || [] } ) {
49         if ( my @snippets = ( $path =~ $compiled->{re} ) ) {
50             $c->req->action( $compiled->{path} );
51             $c->req->match($path);
52             $c->req->snippets( \@snippets );
53             $c->action( $compiled->{action} );
54             $c->namespace( $compiled->{action}->namespace );
55             return 1;
56         }
57     }
58
59     return 0;
60 }
61
62 =item $self->register( $c, $action )
63
64 =cut
65
66 sub register {
67     my ( $self, $c, $action ) = @_;
68     my $attrs = $action->attributes;
69     my @register = map { @{ $_ || [] } } @{$attrs}{ 'Regex', 'Regexp' };
70     foreach
71       my $r ( map { @{ $_ || [] } } @{$attrs}{ 'LocalRegex', 'LocalRegexp' } )
72     {
73         unless ( $r =~ s/^\^// ) { $r = "(?:.*?)$r"; }
74         push( @register, '^' . $action->namespace . '/' . $r );
75     }
76
77     foreach my $r (@register) {
78         $self->register_path( $c, $r, $action );
79         $self->register_regex( $c, $r, $action );
80     }
81 }
82
83 =item $self->register_regex($c, $re, $action)
84
85 =cut
86
87 sub register_regex {
88     my ( $self, $c, $re, $action ) = @_;
89     push(
90         @{ $self->{compiled} },    # and compiled regex for us
91         {
92             re     => qr#$re#,
93             action => $action,
94             path   => $re,
95         }
96     );
97 }
98
99 =back
100
101 =head1 AUTHOR
102
103 Matt S Trout
104 Sebastian Riedel, C<sri@cpan.org>
105
106 =head1 COPYRIGHT
107
108 This program is free software, you can redistribute it and/or modify it under
109 the same terms as Perl itself.
110
111 =cut
112
113 1;