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