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