Debian Codegraph @

lib/Dancer2/Core/Route.pm

raw
1 package Dancer2::Core::Route;
2 # ABSTRACT: Dancer2's route handler
3 $Dancer2::Core::Route::VERSION = '2.2.2';
4 use Moo;
5 use Dancer2::Core::Types;
6 use Module::Runtime 'use_module';
7 use Carp 'croak';
8 use List::Util 'first';
9 use Scalar::Util 'blessed';
10 use Ref::Util qw< is_regexpref >;
11 use Type::Registry;
12
13 our ( $REQUEST, $RESPONSE, $RESPONDER, $WRITER, $ERROR_HANDLER );
14
15 has name => (
16 is => 'ro',
17 isa => Str,
18 predicate => 'has_name',
19 );
20
21 has method => (
22 is => 'ro',
23 isa => Dancer2Method,
24 required => 1,
25 );
26
27 has code => (
28 is => 'ro',
29 required => 1,
30 isa => CodeRef,
31 );
32
33 has regexp => (
34 is => 'ro',
35 required => 1,
36 );
37
38 has spec_route => ( is => 'ro' );
39
40 has prefix => (
41 is => 'ro',
42 isa => Maybe [Dancer2Prefix],
43 predicate => 1,
44 );
45
46 has options => (
47 is => 'ro',
48 isa => HashRef,
49 trigger => \&_check_options,
50 predicate => 1,
51 );
52
53 sub _check_options {
54 my ( $self, $options ) = @_;
55 return 1 unless defined $options;
56
57 my @supported_options = (
58 qw/content_type agent user_agent content_length
59 path_info/
60 );
61 for my $opt ( keys %{$options} ) {
62 croak "Not a valid option for route matching: `$opt'"
63 if not( grep {/^$opt$/} @supported_options );
64 }
65 return 1;
66 }
67
68 # private attributes
69
70 has _should_capture => (
71 is => 'ro',
72 isa => Bool,
73 );
74
75 has _match_data => (
76 is => 'rw',
77 isa => HashRef,
78 );
79
80 has _params => (
81 is => 'ro',
82 isa => ArrayRef,
83 default => sub { [] },
84 );
85
86 has _typed_params => (
87 is => 'ro',
88 isa => ArrayRef,
89 default => sub { [] },
90 );
91
92 sub match {
93 my ( $self, $request ) = @_;
94
95 if ( $self->has_options ) {
96 return unless $self->validate_options($request);
97 }
98
99 my @values = $request->path =~ $self->regexp;
100
101 return unless @values;
102
103 # if some named captures are found, return captures
104 # - Note no @values implies no named captures
105 if (my %captures = %+ ) {
106 return $self->_match_data( { captures => \%captures } );
107 }
108
109 # regex comments are how we know if we captured a token,
110 # splat or a megasplat
111 my @token_or_splat =
112 $self->regexp =~ /\(\?#((?:typed_)?token|(?:mega)?splat)\)/g;
113
114 if (@token_or_splat) {
115 # our named tokens
116 my @tokens = @{ $self->_params };
117 my @typed_tokens = @{ $self->_typed_params };
118
119 my %params;
120 my @splat;
121 for ( my $i = 0; $i < @values; $i++ ) {
122 # Is this value from a token?
123 if ( defined $token_or_splat[$i] ) {
124 if ( $token_or_splat[$i] eq 'typed_token' ) {
125 my ( $token, $type ) = @{ shift @typed_tokens };
126
127 if (defined $values[$i]) {
128 # undef value mean that token was marked as optional so
129 # we only do type check on defined value
130 return
131 unless $type->check($values[$i]);
132 }
133 $params{$token} = $values[$i];
134 next;
135 }
136 if ( $token_or_splat[$i] eq 'token' ) {
137 $params{ shift @tokens } = $values[$i];
138 next;
139 }
140
141 # megasplat values are split on '/'
142 if ($token_or_splat[$i] eq 'megasplat') {
143 $values[$i] = [
144 defined $values[$i] ? split( m{/} , $values[$i], -1 ) : ()
145 ];
146 }
147 }
148 push @splat, $values[$i];
149 }
150 return $self->_match_data( {
151 %params,
152 (splat => \@splat)x!! @splat,
153 });
154 }
155
156 if ( $self->_should_capture ) {
157 return $self->_match_data( { splat => \@values } );
158 }
159
160 return $self->_match_data( {} );
161 }
162
163 sub execute {
164 my ( $self, $app, @args ) = @_;
165 local $REQUEST = $app->request;
166 local $RESPONSE = $app->response;
167
168 my $content = $self->code->( $app, @args );
169
170 # users may set content in the response. If the response has
171 # content, and the returned value from the route code is not
172 # an object (well, reference) we ignore the returned value
173 # and use the existing content in the response instead.
174 $RESPONSE->has_content && !ref $content
175 and return $app->_prep_response( $RESPONSE );
176
177 my $type = blessed($content)
178 or return $app->_prep_response( $RESPONSE, $content );
179
180 # Plack::Response: proper ArrayRef-style response
181 $type eq 'Plack::Response'
182 and $RESPONSE = Dancer2::Core::Response->new_from_plack($RESPONSE);
183
184 # CodeRef: raw PSGI response
185 # do we want to allow it and forward it back?
186 # do we want to upgrade it to an asynchronous response?
187 $type eq 'CODE'
188 and die "We do not support returning code references from routes.\n";
189
190 # Dancer2::Core::Response, Dancer2::Core::Response::Delayed:
191 # proper responses
192 $type eq 'Dancer2::Core::Response'
193 and return $RESPONSE;
194
195 $type eq 'Dancer2::Core::Response::Delayed'
196 and return $content;
197
198 # we can't handle arrayref or hashref
199 # because those might be serialized back
200 die "Unrecognized response type from route: $type.\n";
201 }
202
203 # private subs
204
205 sub BUILDARGS {
206 my ( $class, %args ) = @_;
207
208 my $prefix = $args{prefix};
209 my $regexp = $args{regexp};
210
211 my $type_library = delete $args{type_library};
212 if ( $type_library) {
213 eval { use_module($type_library); 1 }
214 or croak "type_library $type_library cannot be loaded";
215 }
216 $type_library ||= 'Dancer2::Core::Types';
217
218 # init prefix
219 if ( $prefix ) {
220 $args{regexp} =
221 is_regexpref($regexp) ? qr{^\Q${prefix}\E${regexp}$} :
222 $prefix . $regexp;
223 }
224 elsif ( !is_regexpref($regexp) ) {
225 # No prefix, so ensure regexp begins with a '/'
226 index( $regexp, '/', 0 ) == 0 or $args{regexp} = "/$regexp";
227 }
228
229 # init regexp
230 $regexp = $args{regexp}; # updated value
231 $args{spec_route} = $regexp;
232
233 if ( is_regexpref($regexp)) {
234 $args{_should_capture} = 1;
235 }
236 else {
237 @args{qw/ regexp _params _typed_params _should_capture/} =
238 @{ _build_regexp_from_string($regexp, $type_library) };
239 }
240
241 return \%args;
242 }
243
244 sub _build_regexp_from_string {
245 my ($string, $type_library) = @_;
246
247 my $capture = 0;
248 my ( @params, @typed_params );
249
250 my $type_registry = Type::Registry->new;
251 $type_registry->add_types($type_library);
252
253 # look for route with tokens [aka params] (/hello/:foo)
254 if ( $string =~ /:/ ) {
255 my @found = $string =~ m|:([^/.\?]+)|g;
256 foreach my $token ( @found ) {
257 if ( $token =~ s/\[(.+)\]$// ) {
258
259 # typed token
260 my $type = $type_registry->lookup($1);
261 push @typed_params, [ $token, $type ];
262 }
263 else {
264 push @params, $token;
265 }
266 }
267 if (@typed_params) {
268 $string =~ s!(:[^/.\?]+\[[^/.\?]+\])!(?#typed_token)([^/]+)!g;
269 $capture = 1;
270 }
271 if (@params) {
272 first { $_ eq 'splat' } @params
273 and croak q{Named placeholder 'splat' is deprecated};
274
275 first { $_ eq 'captures' } @params
276 and croak q{Named placeholder 'captures' is deprecated};
277
278 $string =~ s!(:[^\/\.\?]+)!(?#token)([^/]+)!g;
279 $capture = 1;
280 }
281 }
282
283 # parse megasplat
284 # we use {0,} instead of '*' not to fall in the splat rule
285 # same logic for [^\n] instead of '.'
286 $capture = 1 if $string =~ s!\Q**\E!(?#megasplat)([^\n]+)!g;
287
288 # parse wildcards
289 $capture = 1 if $string =~ s!\*!(?#splat)([^/]+)!g;
290
291 # escape dots
292 $string =~ s/\./\\\./g if $string =~ /\./;
293
294 # escape slashes
295 $string =~ s/\//\\\//g;
296
297 return [ "^$string\$", \@params, \@typed_params, $capture ];
298 }
299
300 sub validate_options {
301 my ( $self, $request ) = @_;
302
303 for my $option ( keys %{ $self->options } ) {
304 return 0
305 if (
306 ( not $request->$option )
307 || ( $request->$option !~ $self->options->{ $option } )
308 )
309 }
310 return 1;
311 }
312
313 1;
314
315 __END__
316
317 =pod
318
319 =encoding UTF-8
320
321 =head1 NAME
322
323 Dancer2::Core::Route - Dancer2's route handler
324
325 =head1 VERSION
326
327 version 2.2.2
328
329 =head1 ATTRIBUTES
330
331 =head2 method
332
333 The HTTP method of the route (lowercase). Required.
334
335 =head2 code
336
337 The code reference to execute when the route is ran. Required.
338
339 =head2 regexp
340
341 The regular expression that defines the path of the route.
342 Required. Coerce from Dancer2's route I<patterns>.
343
344 =head2 prefix
345
346 The prefix to prepend to the C<regexp>. Optional.
347
348 =head2 options
349
350 A HashRef of conditions on which the matching will depend. Optional.
351
352 =head1 METHODS
353
354 =head2 match
355
356 Try to match the route with a given L<Dancer2::Core::Request> object.
357 Returns the hash of matching data if success (captures and values of the route
358 against the path of the request) or C<undef> if not.
359
360 my $match = $route->match( $request );
361
362 =head2 execute
363
364 Runs the coderef of the route.
365
366 =head1 AUTHOR
367
368 Dancer Core Developers
369
370 =head1 COPYRIGHT AND LICENSE
371
372 This software is copyright (c) 2026 by Alexis Sukrieh.
373
374 This is free software; you can redistribute it and/or modify it under
375 the same terms as the Perl 5 programming language system itself.
376
377 =cut