blib/lib/Catalyst/Plugin/URLMap.pm

filter: Statementstmt 94.1% 64 / 68 Branchbran 66.6% 12 / 18 Conditioncond n/a MC/DCmcdc n/a Subroutinesub 100% 10 / 10 Podpod n/a totaltotal 89.5% 86 / 96 CC 11 SCAR 13.7
CC
11
Cov
88%
__ANON__
7.0
__ANON__
4.5
__ANON__
3.1
CRAP 3.9
↑ Summary
1 package Catalyst::Plugin::URLMap;
2  
3 2 ▶use Moose::Role;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 2 ▶use namespace::autoclean;
Subroutine BEGIN: called CC=1 SCAR=0.0
5 2 ▶use Plack::Util;
Subroutine BEGIN: called CC=1 SCAR=0.0
6 2 ▶use Plack::App::URLMap;
Subroutine BEGIN: called CC=1 SCAR=0.0
7 2 ▶use Scalar::Util 'blessed', 'weaken';
Subroutine BEGIN: called CC=1 SCAR=0.0
8 2 ▶use Catalyst::Utils;
Subroutine BEGIN: called CC=1 SCAR=0.0
9 2 ▶use Text::SimpleTable;
Subroutine BEGIN: called CC=1 SCAR=0.0
10  
11 2 our $VERSION = '0.002';
12  
13 3 ▶my $from_plack_app = sub {
Subroutine __ANON__: called CC=3 SCAR=15.1
14 3 my $app = shift;
15 3 ▶ if($app->can('to_app')) {
Branch: 2 branches
BranchTrueFalseTotal
if ($app->can('to_app')) { } 3 0 3
elsif ($app->can('psgi_app')) { } 0 0 0
16 3 return $app->to_app;
17 } elsif($app->can('psgi_app')) {
18 0 return $app->psgi_app;
19 } else {
20 0 die ref($app). " is not a plack compatible application";
21 }
22 2 };
23  
24 2 my ($do_mapping, $weakened_do_mapping);
25 2 ▶$do_mapping = $weakened_do_mapping = sub {
Subroutine __ANON__: called CC=7 SCAR=19.5
26 2 my ($psgi_app, $t, $root, %maps) = @_;
27  
28 2 foreach my $url_part (keys %maps) {
29 7 my $target = $maps{$url_part};
30 7 my $map_url = join ('', $root, $url_part);
31  
32 7 ▶ if(ref $target eq 'CODE') {
Branch: 4 branches
BranchTrueFalseTotal
if (ref $target eq 'CODE') { } 3 4 7
elsif (builtin::blessed($target)) { } 1 3 4
elsif (ref $target eq 'HASH') { } 2 1 3
elsif ($target) { } 1 0 1
33 3 $psgi_app->map($url_part, $target);
34 3 $t->row($map_url, 'CODE');
35 } elsif(blessed $target) {
36 1 $psgi_app->map($url_part, $from_plack_app->($target));
37 1 $t->row($map_url, ref $target);
38 } elsif(ref $target eq 'HASH') {
39 2 ▶ if( (%$target)[0] =~m/^\//) {
Branch: 1 branch
BranchTrueFalseTotal
if ((%$target)[0] =~ m[^/]) { } 1 1 2
40 1 my $localmap = Plack::App::URLMap->new;
41 1 weaken $weakened_do_mapping;
42 1 $localmap = $weakened_do_mapping->($localmap, $t, $map_url, %$target);
43 1 $psgi_app->map($url_part, $localmap->to_app);
44 } else {
45 1 my ($module, $args) = %{$target};
46 1 my $normalized_module = Plack::Util::load_class($module, 'Plack::App');
47 1 $psgi_app->map($url_part, $from_plack_app->($normalized_module->new(%$args)));
48 1 $t->row($map_url, $normalized_module);
49 }
50 } elsif($target) {
51 1 my $normalized_module = Plack::Util::load_class($target, 'Plack::App');
52 1 $psgi_app->map($url_part, $from_plack_app->($normalized_module->new));
53 1 $t->row($map_url, $normalized_module);
54 } else {
55 0 die "I don't know how to map $target to $map_url";
56 }
57 }
58  
59 2 return $psgi_app;
60 2 };
61  
62 1 ▶around 'psgi_app', sub {
Subroutine __ANON__: called CC=3 SCAR=11.2
63 1 my ($orig, $self, @args) = @_;
64 1 my $psgi_app = $self->$orig(@args);
65 1 ▶ return $psgi_app unless $self->config->{'Plugin::URLMap'};
Branch: 1 branch
BranchTrueFalseTotal
unless $self->config->{"Plugin::URLMap"} 0 1 1
66  
67 1 my %maps = %{$self->config->{'Plugin::URLMap'}};
68 1 (my $mapped_app = Plack::App::URLMap->new)
69 ->map('/' => $psgi_app);
70  
71 1 my $column_width = Catalyst::Utils::term_width() - 49;
72 1 my $t = Text::SimpleTable->new([40, 'Path'], [$column_width, 'Application']);
73 1 my $app = $do_mapping->($mapped_app, $t, '', %maps)->to_app;
74  
75 1 ▶ if ($self->debug) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->debug) 0 1 1
76 0 $self->log->debug( "Loaded Plack Middleware:\n" . $t->draw . "\n" );
77 }
78  
79 1 return $app;
80 2 };
81  
82 2 1;
83  
84 =head1 NAME
85  
86 Catalyst::Plugin::URLMap - Mount a Plack application using Catalyst Configuration
87  
88 =head1 SYNOPSIS
89  
90 package MyApp::Web;
91  
92 our $VERSION = '0.01';
93  
94 use Moose;
95 use Catalyst qw/URLMap/;
96  
97 extends 'Catalyst';
98  
99 __PACKAGE__->config(
100 'Plugin::URLMap',
101 {
102  
103 '/static', {
104 'File', {
105 root => __PACKAGE__->path_to(qw/share web static/),
106 },
107 },
108  
109 '/git' => '+Gitalist',
110  
111 '/mycustomapp', {
112 '+MyApp::CustomPlackApp', {
113 arg1 => 1,
114 arg2 => 2,
115 },
116 },
117  
118 '/thumbnails', {
119 '/large' => '+MyApp::LargeThumbServer',
120 '/small' => '+MyApp::SmallThumbServer',
121 },
122  
123 }
124 );
125  
126 __PACKAGE__->setup;
127 __PACKAGE__->meta->make_immutable;
128  
129 =head1 DESCRIPTION
130  
131 Modern versions of L<Catalyst> use L<Plack> as the underlying engine to
132 connect your application to an http server. This means that you can take
133 advantage of the full L<Plack> software ecosystem to grow your application
134 and to better componentize and re-use your code.
135  
136 In some cases you may wish to 'mount' other plack applications to certain root
137 URLs, and let that separate application handle requests to that path. The
138 common example is serving static files, as this is not something you normally
139 want to subject to a full L<Catalyst> request cycle. Here is how you might set
140 this up with the current version of L<Catalyst>:
141  
142 Example file is C<myapp_web.psgi> in root of your L<Catalyst> application.
143  
144 #!/usr/bin/env plackup
145  
146 use strict;
147 use warnings;
148  
149 use MyApp::Web; ## Your subclass of 'Catalyst'
150 use Plack::Builder;
151 use Plack::App::File;
152  
153 builder {
154  
155 mount '/static' => Plack::App::File
156 ->new(root=>MyApp::Web->path_to(qw/share web static/))
157 ->to_app,
158  
159 mount '/' => MyApp::Web->psgi_app;
160  
161 };
162  
163 Here we are using our C<psgi> file and some tools that come L<Plack> in order
164 to mount L<Plack::App::File> to handle everything under C</static>. You might
165 prefer this to using L<Catalyst::Plugin::Static::Simple>. This is a nice, clean
166 approach that cleanly separates your L<Catalyst> application from the other
167 mounted L<Plack> applications.
168  
169 However there may be cases when the additional L<Plack> applications are more
170 tightly associated with your L<Catalyst> application and you wish to express
171 this association better (but still achieve a rational decoupling). For example
172 your mapped application may make heavy use of your L<Catalyst> configuration,
173 as in the above example. Or you might choose different mappings and mapped
174 applications depending on the environment and wish to control this with
175 Catalyst configuration. In those cases you may want a way to express that URL
176 mapping within L<Catalyst>, and not externally, as in your C<psgi> file.
177  
178 This plugin lets you mount L<Plack> applications via configuration. For example,
179 the above mapping could be re-written as follows:
180  
181 package MyApp::Web;
182 our $VERSION = '0.01';
183  
184 use Moose;
185 use Catalyst qw/URLMap/;
186  
187 extends 'Catalyst';
188  
189 __PACKAGE__->config(
190 'Plugin::URLMap', {
191 '/static', { 'File',
192 {root => __PACKAGE__->path_to(qw/share web static/)} },
193 });
194  
195 __PACKAGE__->setup;
196 __PACKAGE__->meta->make_immutable;
197  
198 Then your C<myapp_web.psgi> would simply become:
199  
200 #!/usr/bin/env plackup
201  
202 use strict;
203 use warnings;
204  
205 use MyApp::Web; ## Your subclass of 'Catalyst'
206 MyApp::Web->psgi_app;
207  
208 And we'd manage the URL mappings inside the Catalyst configuration and in your
209 application class.
210  
211 You can of course use a configuration file and format (like Config::General)
212 instead of hard coding your configuration into the main application class.
213 This would allow you the ability to configure things differently in different
214 environments (one of the key reasons to take this approach).
215  
216 The approach isn't 'either/or' and merits to each are apparent. Choosing one
217 doesn't preclude the other.
218  
219 We use L<Plack::App::URLMap> under the hood to perform this work.
220  
221 =head1 CONFIGURATION
222  
223 Configuration for this plugin should be a hashref under the top level key
224 C<Plugin::URLMap>, as in the following:
225  
226 __PACKAGE__->config(
227 'Plugin::URLMap', \%maps);
228  
229 Where C<\%maps> has keys that refer to URL paths off your application root
230 (which is usually '/', but might be some other path if your L<Catalyst>
231 application itself is mounted into another application) and has values that are
232 either another hashref or a plain scalar. In other words:
233  
234 __PACKAGE__->config(
235 'Plugin::URLMap', {
236 '/path1' => $name_of_plack_app,
237 '/path2 => { $name_of_plack_app => \%init_args },
238 });
239  
240 Where C<$name_of_plack_app> is a scalar referring to the package name of your
241 L<Plack> class (basically any class that is initialized with C<new> and has
242 a method called either C<to_app> or C<psgi_app>, which must return a subref
243 that conforms to the PSGI specification) and where C<%init_args> are key - value
244 arguments passed to C<new> at initialization time.
245  
246 C<$name_of_plack_app> is loaded using the same technique as L<Plack::Builder>,
247 so if your application is under the L<Plack::App> namespace you can drop that
248 prefix. The following two configurations are essentially the same:
249  
250 __PACKAGE__->config(
251 'Plugin::URLMap', {
252 '/static', { 'Plack::App::File',
253 {root => __PACKAGE__->path_to(qw/share web static/)} },
254 });
255  
256 __PACKAGE__->config(
257 'Plugin::URLMap', {
258 '/static', { 'File',
259 {root => __PACKAGE__->path_to(qw/share web static/)} },
260 });
261  
262  
263 This means if you want to map an application under a different namespace, you
264 will need (as in L<Plack::Builder>) to prefix C<$name_of_plack_app> with a C<+>
265 as in the above and following example:
266  
267 __PACKAGE__->config(
268 'Plugin::URLMap', {
269 '/git' => '+Gitalist',
270 });
271  
272 I believe this is well optimized for the most common cases, and it also is
273 consistent with how L<Catalyst> plugins are loaded, so hopefully it will be
274 a reasonable convention.
275  
276 =head2 Deep URL Path Mapping
277  
278 There may be times when you wish to map urls more than one path level from the
279 root. For example you might wish to map the url C<http://myapp.com/one/two/>
280 from an application other than your main L<Catalyst> application. Here's how
281 you would do that:
282  
283 __PACKAGE__->config(
284 'Plugin::URLMap', {
285 '/one' => {
286 '/two' => { '+MyApp::PlackApp', \%init_args },
287 },
288 });
289  
290 Basically if your C<$name_of_plack_app> starts with a C</> we assume you are
291 creating some sub-mappings and proceed like that. You can add as many levels
292 of submappings as you wish.
293  
294 =head2 Mapping Pre-Initialized Plack Applications
295  
296 In some cases you may wish to map an already initialized L<Plack> application
297 to a given URL mount. You may do so by simply passing the instance as the
298 value of the URL mount string key:
299  
300 use Plack::App::File;
301 my $static = Plack::App::File->new(
302 root => __PACKAGE->path_to(qw/share static));
303  
304 __PACKAGE__->config(
305 'Plugin::URLMap', {
306 '/static' => $static,
307 });
308  
309 In this case, your object (such as C<$static>) should support a method called
310 C<to_app> or C<psgi_app>.
311  
312 =head2 Mapping a subroutine reference
313  
314 Similarly to mapping a pre-initialized object, you can map a subroutine
315 reference. This subroutine reference should conform to the L<PSGI>
316 specification:
317  
318 __PACKAGE__->config(
319 'Plugin::URLMap', {
320 '/hello_world' => sub {
321 my $env = shift;
322 return [ 200,
323 ['Content-Type' => 'text/plain'],
324 [ 'Hello World' ] ];
325 },
326 });
327  
328 =head2 URL Mapping '/'
329  
330 The '/' mount mapping is reserved for your L<Catalyst> Application. Trying to
331 map this path will result in an error.
332  
333 =head1 AUTHOR
334  
335 John Napiorkowski L<email:jjnapiork@cpan.org>
336  
337 =head1 SEE ALSO
338  
339 L<Plack>, L<Plack::App::URLMap>, L<Catalyst>
340  
341 =head1 COPYRIGHT & LICENSE
342  
343 Copyright 2012, John Napiorkowski L<email:jjnapiork@cpan.org>
344  
345 This library is free software; you can redistribute it and/or modify it under
346 the same terms as Perl itself.
347  
348 =cut
↑ Summary