Yancy/Controller/Yancy.pm

filter: Statementstmt 7.5% 17 / 224 Branchbran 0.0% 0 / 94 Conditioncond 0.0% 0 / 96 MC/DCmcdc 0.0% 0 / 51 Subroutinesub 22.7% 5 / 22 Podpod 100% 5 / 5 totaltotal 5.4% 27 / 492 CC 102 SCAR 62.7
CC
102
Cov
4%
set
1260.0
_get_list_args
650.0
delete
210.0
CRAP 530.2
↑ Summary Yancy/Plugin/Form/Bootstrap4.pm »
1 package Yancy::Controller::Yancy;
2 4 our $VERSION = '1.078';
3 # ABSTRACT: Basic controller for displaying content
4  
5 #pod =head1 SYNOPSIS
6 #pod
7 #pod use Mojolicious::Lite;
8 #pod plugin Yancy => {
9 #pod schema => {
10 #pod blog => {
11 #pod properties => {
12 #pod id => { type => 'integer' },
13 #pod title => { type => 'string' },
14 #pod html => { type => 'string' },
15 #pod },
16 #pod },
17 #pod },
18 #pod };
19 #pod
20 #pod app->routes->get( '/' )->to(
21 #pod 'yancy#list',
22 #pod schema => 'blog',
23 #pod template => 'index',
24 #pod );
25 #pod
26 #pod __DATA__
27 #pod @@ index.html.ep
28 #pod % for my $item ( @{ stash 'items' } ) {
29 #pod <h1><%= $item->{title} %></h1>
30 #pod <%== $item->{html} %>
31 #pod % }
32 #pod
33 #pod =head1 DESCRIPTION
34 #pod
35 #pod This controller contains basic route handlers for displaying content
36 #pod configured in Yancy schema. These route handlers reduce the amount
37 #pod of code you need to write to display or modify your content.
38 #pod
39 #pod Route handlers use the Mojolicious C<stash> for configuration. These values
40 #pod can be set at route creation, or by an C<under> route handler.
41 #pod
42 #pod Using these route handlers also gives you a built-in JSON API for your
43 #pod website. Any user agent that requests JSON will get JSON instead of
44 #pod HTML. For full details on how JSON clients are detected, see
45 #pod L<Mojolicious::Guides::Rendering/Content negotiation>.
46 #pod
47 #pod =head1 ACTION HOOKS
48 #pod
49 #pod Every action can call one or more of your application's
50 #pod L<helpers|https://mojolicious.org/perldoc/Mojolicious/Guides/Tutorial#Helpers>.
51 #pod These helpers can change the item before it is displayed or
52 #pod before it is saved to the database.
53 #pod
54 #pod These helpers get one argument: An item being displayed, created, saved,
55 #pod or deleted. The helper then returns the item to be displayed, created,
56 #pod or saved.
57 #pod
58 #pod use Mojolicious::Lite -signatures;
59 #pod plugin Yancy => { ... };
60 #pod
61 #pod # Set a last_updated timestamp when creating or updating events
62 #pod helper update_timestamp => sub( $c, $item ) {
63 #pod $item->{last_updated} = time;
64 #pod return $item;
65 #pod };
66 #pod post '/event/:event_id' => 'yancy#set',
67 #pod {
68 #pod event_id => undef,
69 #pod schema => 'events',
70 #pod helpers => [ 'update_timestamp' ],
71 #pod forward_to => 'events.get',
72 #pod },
73 #pod 'events.set';
74 #pod
75 #pod Helpers can also be anonymous subrefs for those times when you want a
76 #pod unique behavior for a single route.
77 #pod
78 #pod # Format the last_updated timestamp when showing event details
79 #pod use Time::Piece;
80 #pod get '/event/:event_id' => 'yancy#get',
81 #pod {
82 #pod schema => 'events',
83 #pod helpers => [
84 #pod sub( $c, $item ) {
85 #pod $item->{last_updated} = Time::Piece->new( $item->{last_updated} );
86 #pod return $item;
87 #pod },
88 #pod ],
89 #pod },
90 #pod 'events.get';
91 #pod
92 #pod =head1 EXTENDING
93 #pod
94 #pod Here are some tips for inheriting from this controller to add
95 #pod functionality.
96 #pod
97 #pod =over
98 #pod
99 #pod =item set
100 #pod
101 #pod =over
102 #pod
103 #pod =item *
104 #pod
105 #pod When setting field values to add to the updated/created item, use C<<
106 #pod $c->req->param >> not C<< $c->param >>. The underlying code uses C<<
107 #pod $c->req->param >> to get all of the params, which will not be updated if
108 #pod you use C<< $c->param >>.
109 #pod
110 #pod =back
111 #pod
112 #pod =back
113 #pod
114 #pod =head1 DIAGNOSTICS
115 #pod
116 #pod =over
117 #pod
118 #pod =item Page not found
119 #pod
120 #pod If you get a C<404 Not Found> response or Mojolicious's "Page not found... yet!" page,
121 #pod it could be from one of a few reasons:
122 #pod
123 #pod =over
124 #pod
125 #pod =item No route with the given path was found
126 #pod
127 #pod Check to make sure that your routes match the URL.
128 #pod
129 #pod =item Configured template not found
130 #pod
131 #pod Make sure the template is configured and named correctly and the correct format
132 #pod and renderer are being used.
133 #pod
134 #pod =back
135 #pod
136 #pod The Mojolicious debug log will have more information. Make sure you are
137 #pod logging at C<debug> level by running in C<development> mode (the
138 #pod default), or setting the C<MOJO_LOG_LEVEL> environment variable to
139 #pod C<debug>. See L<MODE in the Mojolicious
140 #pod tutorial|Mojolicious::Guides::Tutorial/Mode> for more information.
141 #pod
142 #pod =back
143 #pod
144 #pod =head1 TEMPLATES
145 #pod
146 #pod To override these templates, add your own at the designated path inside
147 #pod your app's C<templates/> directory.
148 #pod
149 #pod =head2 yancy/table.html.ep
150 #pod
151 #pod The default C<list> template. Uses the following additional stash values
152 #pod for configuration:
153 #pod
154 #pod =over
155 #pod
156 #pod =item properties
157 #pod
158 #pod An array reference of columns to display in the table. The same as
159 #pod C<x-list-columns> in the schema configuration. Defaults to
160 #pod C<x-list-columns> in the schema configuration or all of the schema's
161 #pod columns in C<x-order> order. See L<Yancy::Guides::Schema/Documenting
162 #pod Your Schema> for more information.
163 #pod
164 #pod =item table
165 #pod
166 #pod get '/events' => (
167 #pod controller => 'yancy',
168 #pod action => 'list',
169 #pod table => {
170 #pod thead => 0, # Disable column headers
171 #pod class => 'table table-responsive', # Add a class
172 #pod },
173 #pod );
174 #pod
175 #pod Attributes for the table tag. A hash reference of the following keys:
176 #pod
177 #pod =over
178 #pod
179 #pod =item thead
180 #pod
181 #pod Whether or not to display the table head section, which contains the
182 #pod column headings. Defaults to true (C<1>). Set to false (C<0>) to
183 #pod disable C<< <thead> >>.
184 #pod
185 #pod =item show_filter
186 #pod
187 #pod Show filter input boxes for each column in the header. Pressing C<Enter>
188 #pod will filter the table.
189 #pod
190 #pod =item id
191 #pod
192 #pod The ID of the table element.
193 #pod
194 #pod =item class
195 #pod
196 #pod The class(s) of the table element.
197 #pod
198 #pod =back
199 #pod
200 #pod =back
201 #pod
202 #pod =head1 SEE ALSO
203 #pod
204 #pod L<Yancy>
205 #pod
206 #pod =cut
207  
208 4 ▶use Mojo::Base 'Mojolicious::Controller';
Subroutine BEGIN: called CC=1 SCAR=0.0
209 4 ▶use Mojo::JSON qw( to_json );
Subroutine BEGIN: called CC=1 SCAR=0.0
210 4 ▶use Yancy::Util qw( derp is_type );
Subroutine BEGIN: called CC=1 SCAR=0.0
211 4 ▶use POSIX qw( ceil );
Subroutine BEGIN: called CC=1 SCAR=0.0
212  
213 #pod =method list
214 #pod
215 #pod $routes->get( '/' )->to(
216 #pod 'yancy#list',
217 #pod schema => $schema_name,
218 #pod template => $template_name,
219 #pod );
220 #pod
221 #pod This method is used to list content.
222 #pod
223 #pod =head4 Input Stash
224 #pod
225 #pod This method uses the following stash values for configuration:
226 #pod
227 #pod =over
228 #pod
229 #pod =item schema
230 #pod
231 #pod The schema to use. Required.
232 #pod
233 #pod =item template
234 #pod
235 #pod The name of the template to use. See L<Mojolicious::Guides::Rendering/Renderer>
236 #pod for how template names are resolved. Defaults to C<yancy/table>.
237 #pod
238 #pod =item limit
239 #pod
240 #pod The number of items to show on the page. Defaults to C<10>.
241 #pod
242 #pod =item page
243 #pod
244 #pod The page number to show. Defaults to C<1>. The page number will
245 #pod be used to calculate the C<offset> parameter to L<Yancy::Backend/list>.
246 #pod
247 #pod =item filter
248 #pod
249 #pod A hash reference of field/value pairs to filter the contents of the list
250 #pod or a subref that generates this hash reference. The subref will be passed
251 #pod the current controller object (C<$c>).
252 #pod
253 #pod This overrides any query filters and so can be used to enforce
254 #pod authorization / security.
255 #pod
256 #pod =item order_by
257 #pod
258 #pod Set the default order for the items. Supports any L<Yancy::Backend/list>
259 #pod C<order_by> structure.
260 #pod
261 #pod =item before_render
262 #pod
263 #pod An array reference of hooks to call once for each item in the C<items> list.
264 #pod See L</ACTION HOOKS> for usage.
265 #pod
266 #pod =back
267 #pod
268 #pod =head4 Output Stash
269 #pod
270 #pod The following stash values are set by this method:
271 #pod
272 #pod =over
273 #pod
274 #pod =item items
275 #pod
276 #pod An array reference of items to display.
277 #pod
278 #pod =item total
279 #pod
280 #pod The total number of items that match the given filters.
281 #pod
282 #pod =item total_pages
283 #pod
284 #pod The number of pages of items. Can be used for pagination.
285 #pod
286 #pod =back
287 #pod
288 #pod =head4 Query Params
289 #pod
290 #pod The following URL query parameters are allowed for this method:
291 #pod
292 #pod =over
293 #pod
294 #pod =item $page
295 #pod
296 #pod Instead of using the C<page> stash value, you can use the C<$page> query
297 #pod paremeter to set the page.
298 #pod
299 #pod =item $offset
300 #pod
301 #pod Instead of using the C<page> stash value, you can use the C<$offset>
302 #pod query parameter to set the page offset. This is overridden by the
303 #pod C<$page> query parameter.
304 #pod
305 #pod =item $limit
306 #pod
307 #pod Instead of using the C<limit> stash value, you can use the C<$limit>
308 #pod query parameter to allow users to specify their own page size.
309 #pod
310 #pod =item $order_by
311 #pod
312 #pod One or more fields to order by. Can be specified as C<< <name> >> or
313 #pod C<< asc:<name> >> to sort in ascending order or C<< desc:<field> >>
314 #pod to sort in descending order.
315 #pod
316 #pod =item $match
317 #pod
318 #pod How to match multiple field filters. Can be C<any> or C<all> (default
319 #pod C<all>). C<all> means all fields must match for a row to be returned.
320 #pod C<any> means at least one field must match for a row to be returned.
321 #pod
322 #pod =item Additional Field Filters
323 #pod
324 #pod Any named query parameter that matches a field in the schema will be
325 #pod used to further filter the results. The stash C<filter> will override
326 #pod this filter, so that the stash C<filter> can be used for security.
327 #pod
328 #pod =back
329 #pod
330 #pod =head4 Content Negotiation
331 #pod
332 #pod If the C<GET> request accepts content type is C<application/json>, or
333 #pod the URL ends in C<.json>, the results page will be returned as a JSON
334 #pod object with the following keys:
335 #pod
336 #pod =over
337 #pod
338 #pod =item items
339 #pod
340 #pod The array of items for this page.
341 #pod
342 #pod =item total
343 #pod
344 #pod The total number of results for the query.
345 #pod
346 #pod =item offset
347 #pod
348 #pod The current offset. Get the next page of results by increasing this
349 #pod number and setting the C<$offset> query parameter.
350 #pod
351 #pod =back
352 #pod
353 #pod =cut
354  
355 sub list {
356 0 ▶ my ( $c ) = @_;
Subroutine list: not called CC=4 SCAR=30.0
Pod documented
357 0 my ( $schema_name, $filter, $opt ) = $c->_get_list_args;
358 0 my $result = $c->yancy->backend->list( $schema_name, $filter, $opt );
359 0 ▶ for my $helper ( @{ $c->stash( 'before_render' ) // [] } ) {
Condition0%0/2
$c->stash("before_render") // []
l!l
00
MC/DC0%0/1
$c->stash("before_render") // []
$c->stash("before_render")
Truth table0%0/2
A
A= $c->stash("before_render")
Aresult
11
00
360 0 $c->$helper( $_ ) for @{ $result->{items} };
361 }
362 # By the time `any` is reached, the format will be blank. To support
363 # any format of template, we need to restore the format stash
364 0 my $format = $c->stash( 'format' );
365 return $c->respond_to(
366 json => sub {
367 0 ▶ $c->stash( json => { %$result, offset => $opt->{offset} } );
Subroutine __ANON__: not called CC=1 SCAR=6.9
368 },
369 any => sub {
370 0 ▶ if ( !$c->stash( 'template' ) ) {
Subroutine __ANON__: not called CC=2 SCAR=17.9
Branch: 1 branch
BranchTrueFalseTotal
unless ($c->stash("template")) 0 0 0
371 0 $c->stash( template => 'yancy/table' );
372 }
373 $c->stash(
374 ( format => $format )x!!$format,
375 %$result,
376 0 total_pages => ceil( $result->{total} / $opt->{limit} ),
377 );
378 },
379 0 );
380 }
381  
382 #pod =method get
383 #pod
384 #pod $routes->get( '/:id_field' )->to(
385 #pod 'yancy#get',
386 #pod schema => $schema_name,
387 #pod template => $template_name,
388 #pod );
389 #pod
390 #pod This method is used to show a single item.
391 #pod
392 #pod =head4 Input Stash
393 #pod
394 #pod This method uses the following stash values for configuration:
395 #pod
396 #pod =over
397 #pod
398 #pod =item schema
399 #pod
400 #pod The schema to use. Required.
401 #pod
402 #pod =item "id_field"
403 #pod
404 #pod The ID field(s) for the item should be defined as stash items, usually via
405 #pod route placeholders named after the field.
406 #pod
407 #pod # Schema ID field is "page_id"
408 #pod $routes->get( '/pages/:page_id' )
409 #pod
410 #pod =item template
411 #pod
412 #pod The name of the template to use. See L<Mojolicious::Guides::Rendering/Renderer>
413 #pod for how template names are resolved.
414 #pod
415 #pod =item before_render
416 #pod
417 #pod An array reference of helpers to call before the item is displayed. See
418 #pod L</ACTION HOOKS> for usage.
419 #pod
420 #pod =back
421 #pod
422 #pod =head4 Output Stash
423 #pod
424 #pod The following stash values are set by this method:
425 #pod
426 #pod =over
427 #pod
428 #pod =item item
429 #pod
430 #pod The item that is being displayed.
431 #pod
432 #pod =back
433 #pod
434 #pod =head4 Content Negotiation
435 #pod
436 #pod If the C<GET> request accepts content type is C<application/json>, or
437 #pod the URL ends in C<.json>, the item will be returned as a JSON object.
438 #pod
439 #pod =cut
440  
441 sub get {
442 0 ▶ my ( $c ) = @_;
Subroutine get: not called CC=10 SCAR=47.0
Pod documented
443 0 ▶ if ( $c->stash( 'collection' ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($c->stash("collection")) 0 0 0
444 0 derp '"collection" stash key is now "schema" in controller configuration';
445 }
446 0 ▶ my $schema_name = $c->stash( 'schema' ) || $c->stash( 'collection' )
Condition0%0/5
$c->stash('schema') || $c->stash('collection') || die('Schema name not defined in stash')
l!l
00
$c->stash("schema") or $c->stash("collection")
l!l&&r!l&&!r
000
MC/DC0%0/2
$c->stash('schema') || $c->stash('collection') || die('Schema name not defined in stash')
$c->stash("schema") $c->stash("collection")
Truth table0%0/3
A or B
A= $c->stash("schema")B= $c->stash("collection")
ABresult
1X1
011
000
447 || die "Schema name not defined in stash";
448 0 ▶ my $id_field = $c->yancy->schema( $schema_name )->{'x-id-field'} // 'id';
Condition0%0/2
$c->yancy->schema($schema_name)->{"x-id-field"} // "id"
l!l
00
MC/DC0%0/1
$c->yancy->schema($schema_name)->{"x-id-field"} // "id"
$c->yancy->schema($schema_name)->{"x-id-field"}
Truth table0%0/2
A
A= $c->yancy->schema($schema_name)->{"x-id-field"}
Aresult
11
00
449 my $id = ref $id_field eq 'ARRAY'
450 0 ▶ ? { map { $_ => $c->stash( $_ ) } grep defined $c->stash( $_ ), @$id_field }
Branch: 1 branch
BranchTrueFalseTotal
ref $id_field eq 'ARRAY' ? : 0 0 0
Condition0%0/2
$c->stash($id_field) // die(sprintf('ID field "%s" not defined in stash', $id_field))
l!l
00
MC/DC0%0/1
$c->stash($id_field) // die(sprintf('ID field "%s" not defined in stash', $id_field))
$c->stash($id_field)
Truth table0%0/2
A
A= $c->stash($id_field)
Aresult
11
00
451 : ( $c->stash( $id_field ) // die sprintf 'ID field "%s" not defined in stash', $id_field );
452 0 my $item = $c->yancy->backend->get( $schema_name => $id );
453 0 ▶ if ( !$item ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($item) 0 0 0
454 0 $c->reply->not_found;
455 0 return;
456 }
457 0 ▶ for my $helper ( @{ $c->stash( 'before_render' ) // [] } ) {
Condition0%0/2
$c->stash("before_render") // []
l!l
00
MC/DC0%0/1
$c->stash("before_render") // []
$c->stash("before_render")
Truth table0%0/2
A
A= $c->stash("before_render")
Aresult
11
00
458 0 $c->$helper( $item );
459 }
460 # By the time `any` is reached, the format will be blank. To support
461 # any format of template, we need to restore the format stash
462 0 my $format = $c->stash( 'format' );
463 return $c->respond_to(
464 0 ▶ json => sub { $c->stash( json => $item ) },
Subroutine __ANON__: not called CC=1 SCAR=6.9
465 0 ▶ any => sub { $c->stash( item => $item, ( format => $format )x!!$format ) },
Subroutine __ANON__: not called CC=1 SCAR=6.9
466 0 );
467 }
468  
469 #pod =method set
470 #pod
471 #pod # Update an existing item
472 #pod $routes->any( [ 'GET', 'POST' ] => '/:id_field/edit' )->to(
473 #pod 'yancy#set',
474 #pod schema => $schema_name,
475 #pod template => $template_name,
476 #pod );
477 #pod
478 #pod # Create a new item
479 #pod $routes->any( [ 'GET', 'POST' ] => '/create' )->to(
480 #pod 'yancy#set',
481 #pod schema => $schema_name,
482 #pod template => $template_name,
483 #pod forward_to => $route_name,
484 #pod );
485 #pod
486 #pod This route creates a new item or updates an existing item in
487 #pod a schema. If the user is making a C<GET> request, they will simply
488 #pod be shown the template. If the user is making a C<POST> or C<PUT>
489 #pod request, the form parameters will be read, the data will be validated
490 #pod against L<the schema configuration|Yancy::Guides::Schema>,
491 #pod and the user will either be shown the form again with the
492 #pod result of the form submission (success or failure) or the user will be
493 #pod forwarded to another place.
494 #pod
495 #pod Displaying a form could be done as a separate route using the C<yancy#get>
496 #pod method, but with more code:
497 #pod
498 #pod $routes->get( '/:id_field/edit' )->to(
499 #pod 'yancy#get',
500 #pod schema => $schema_name,
501 #pod template => $template_name,
502 #pod );
503 #pod $routes->post( '/:id_field/edit' )->to(
504 #pod 'yancy#set',
505 #pod schema => $schema_name,
506 #pod template => $template_name,
507 #pod );
508 #pod
509 #pod =head4 Input Stash
510 #pod
511 #pod This method uses the following stash values for configuration:
512 #pod
513 #pod =over
514 #pod
515 #pod =item schema
516 #pod
517 #pod The schema to use. Required.
518 #pod
519 #pod =item "id_field"
520 #pod
521 #pod The ID field(s) for the item should be defined as stash items, usually via
522 #pod route placeholders named after the field. Optional: If not specified, a new
523 #pod item will be created.
524 #pod
525 #pod # Schema ID field is "page_id"
526 #pod $routes->post( '/pages/:page_id' )
527 #pod
528 #pod =item template
529 #pod
530 #pod The name of the template to use. See L<Mojolicious::Guides::Rendering/Renderer>
531 #pod for how template names are resolved.
532 #pod
533 #pod =item before_write
534 #pod
535 #pod An array reference of helpers to call after the new values are applied
536 #pod to the item, but before the item is written to the database. See
537 #pod L</ACTION HOOKS> for usage.
538 #pod
539 #pod =item forward_to
540 #pod
541 #pod The name of a route to forward the user to on success. Optional. Any
542 #pod route placeholders that match item field names will be filled in.
543 #pod
544 #pod $routes->get( '/:blog_id/:slug' )->name( 'blog.view' );
545 #pod $routes->post( '/create' )->to(
546 #pod 'yancy#set',
547 #pod schema => 'blog',
548 #pod template => 'blog_edit.html.ep',
549 #pod forward_to => 'blog.view',
550 #pod );
551 #pod
552 #pod # { id => 1, slug => 'first-post' }
553 #pod # forward_to => '/1/first-post'
554 #pod
555 #pod Forwarding will not happen for JSON requests.
556 #pod
557 #pod =item properties
558 #pod
559 #pod Restrict this route to only setting the given properties. An array
560 #pod reference of properties to allow. Trying to set additional properties
561 #pod will result in an error.
562 #pod
563 #pod B<NOTE:> Unless restricted to certain properties using this
564 #pod configuration, this method accepts all valid data configured for the
565 #pod schema. The data being submitted can be more than just the fields
566 #pod you make available in the form. If you do not want certain data to be
567 #pod written through this form, you can prevent it by using this.
568 #pod
569 #pod =back
570 #pod
571 #pod =head4 Output Stash
572 #pod
573 #pod The following stash values are set by this method:
574 #pod
575 #pod =over
576 #pod
577 #pod =item item
578 #pod
579 #pod The item that is being edited, if the C<id> is given. Otherwise, the
580 #pod item that was created.
581 #pod
582 #pod =item errors
583 #pod
584 #pod An array of hash references of errors that occurred during data
585 #pod validation. Each hash reference is either a L<JSON::Validator::Error>
586 #pod object or a hash reference with a C<message> field. See L<the
587 #pod yancy.validate helper docs|Mojolicious::Plugin::Yancy/yancy.validate>
588 #pod and L<JSON::Validator/validate> for more details.
589 #pod
590 #pod =back
591 #pod
592 #pod =head4 Query Params
593 #pod
594 #pod This method accepts query parameters named for the fields in the schema.
595 #pod
596 #pod Each field in the item is also set as a param using
597 #pod L<Mojolicious::Controller/param> so that tag helpers like C<text_field>
598 #pod will be pre-filled with the values. See
599 #pod L<Mojolicious::Plugin::TagHelpers> for more information. This also means
600 #pod that fields can be pre-filled with initial data or new data by using GET
601 #pod query parameters.
602 #pod
603 #pod =head4 CSRF Protection
604 #pod
605 #pod This method is protected by L<Mojolicious's Cross-Site Request Forgery
606 #pod (CSRF) protection|Mojolicious::Guides::Rendering/Cross-site request
607 #pod forgery>. CSRF protection prevents other sites from tricking your users
608 #pod into doing something on your site that they didn't intend, such as
609 #pod editing or deleting content. You must add a C<< <%= csrf_field %> >> to
610 #pod your form in order to delete an item successfully. See
611 #pod L<Mojolicious::Guides::Rendering/Cross-site request forgery>.
612 #pod
613 #pod =head4 Content Negotiation
614 #pod
615 #pod If the C<POST> or C<PUT> request content type is C<application/json>,
616 #pod the request body will be treated as a JSON object to create/set. In this
617 #pod case, the form query parameters are not used.
618 #pod
619 #pod =cut
620  
621 sub set {
622 0 ▶ my ( $c ) = @_;
Subroutine set: not called CC=35 SCAR=71.4
Pod documented
623 0 ▶ if ( $c->stash( 'collection' ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($c->stash("collection")) 0 0 0
624 0 derp '"collection" stash key is now "schema" in controller configuration';
625 }
626 0 ▶ my $schema_name = $c->stash( 'schema' ) || $c->stash( 'collection' )
Condition0%0/5
$c->stash('schema') || $c->stash('collection') || die('Schema name not defined in stash')
l!l
00
$c->stash("schema") or $c->stash("collection")
l!l&&r!l&&!r
000
MC/DC0%0/2
$c->stash('schema') || $c->stash('collection') || die('Schema name not defined in stash')
$c->stash("schema") $c->stash("collection")
Truth table0%0/3
A or B
A= $c->stash("schema")B= $c->stash("collection")
ABresult
1X1
011
000
627 || die "Schema name not defined in stash";
628 0 ▶ my $id_field = $c->yancy->schema( $schema_name )->{'x-id-field'} // 'id';
Condition0%0/2
$c->yancy->schema($schema_name)->{"x-id-field"} // "id"
l!l
00
MC/DC0%0/1
$c->yancy->schema($schema_name)->{"x-id-field"} // "id"
$c->yancy->schema($schema_name)->{"x-id-field"}
Truth table0%0/2
A
A= $c->yancy->schema($schema_name)->{"x-id-field"}
Aresult
11
00
629 my $id = ref $id_field eq 'ARRAY'
630 0 ▶ ? { map { $_ => $c->stash( $_ ) } grep defined $c->stash( $_ ), @$id_field }
Branch: 1 branch
BranchTrueFalseTotal
ref $id_field eq 'ARRAY' ? : 0 0 0
631 : $c->stash( $id_field );
632 0 ▶ my $has_id = ref $id eq 'HASH' ? %$id : !!$id;
Branch: 1 branch
BranchTrueFalseTotal
ref $id eq 'HASH' ? : 0 0 0
633  
634 # Display the form, if requested. This makes the simple case of
635 # displaying and managing a form easier with a single route instead
636 # of two routes (one to "yancy#get" and one to "yancy#set")
637 0 ▶ if ( $c->req->method eq 'GET' ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($c->req->method eq "GET") 0 0 0
638 0 ▶ if ( $has_id ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($has_id) { } 0 0 0
639 0 my $item = $c->yancy->get( $schema_name => $id );
640 0 $c->stash( item => $item );
641 0 my $props = $c->yancy->schema( $schema_name )->{properties};
642 0 for my $key ( keys %$props ) {
643 # Mojolicious TagHelpers take current values through the
644 # params, but also we allow pre-filling values through the
645 # GET query parameters (except for passwords)
646 next if $props->{ $key }{ format }
647 0 ▶ && $props->{ $key }{ format } eq 'password';
Branch: 1 branch
BranchTrueFalseTotal
if $props->{$key}{"format"} and $props->{$key}{"format"} eq "password" 0 0 0
Condition0%0/3
$props->{$key}{"format"} and $props->{$key}{"format"} eq "password"
!ll&&!rl&&r
000
MC/DC0%0/2
$props->{$key}{"format"} and $props->{$key}{"format"} eq "password"
$props->{$key}{"format"} $props->{$key}{"format"} eq "password"
Truth table0%0/3
A and B
A= $props->{$key}{"format"}B= $props->{$key}{"format"} eq "password"
ABresult
0X0
100
111
648 0 ▶ $c->param( $key => $c->param( $key ) // $item->{ $key } );
Condition0%0/3
$c->param($key) // $item->{$key}
l!l&&r!l&&!r
000
MC/DC0%0/2
$c->param($key) // $item->{$key}
$c->param($key) $item->{$key}
Truth table0%0/3
A // B
A= $c->param($key)B= $item->{$key}
ABresult
1X1
011
000
649 }
650 }
651 else {
652 # Add an empty hashref for creating a new item
653 0 $c->stash( item => {} );
654 }
655  
656 0 $c->respond_to(
657 json => {
658 status => 400,
659 json => {
660 errors => [
661 {
662 message => 'GET request for JSON invalid',
663 },
664 ],
665 },
666 },
667 any => { },
668 );
669 0 return;
670 }
671  
672 0 ▶ if ( $c->accepts( 'html' ) && $c->validation->csrf_protect->has_error( 'csrf_token' ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($c->accepts("html") and $c->validation->csrf_protect->has_error("csrf_token")) 0 0 0
Condition0%0/3
$c->accepts("html") and $c->validation->csrf_protect->has_error("csrf_token")
!ll&&!rl&&r
000
MC/DC0%0/2
$c->accepts("html") and $c->validation->csrf_protect->has_error("csrf_token")
$c->accepts("html") $c->validation->csrf_protect->has_error("csrf_token")
Truth table0%0/3
A and B
A= $c->accepts("html")B= $c->validation->csrf_protect->has_error("csrf_token")
ABresult
0X0
100
111
673 0 $c->app->log->error( 'CSRF token validation failed' );
674 0 $c->render(
675 status => 400,
676 item => $c->yancy->get( $schema_name => $id ),
677 errors => [
678 {
679 message => 'CSRF token invalid.',
680 },
681 ],
682 );
683 0 return;
684 }
685  
686 0 ▶ my $data = eval { $c->req->json } || $c->req->params->to_hash;
Condition0%0/3
eval { do { $c->req->json } } || $c->req->params->to_hash
l!l&&r!l&&!r
000
MC/DC0%0/2
eval { do { $c->req->json } } || $c->req->params->to_hash
eval { do { $c->req->json } } $c->req->params->to_hash
Truth table0%0/3
A || B
A= eval { do { $c->req->json } }B= $c->req->params->to_hash
ABresult
1X1
011
000
687 0 delete $data->{csrf_token};
688  
689 0 my $props = $c->yancy->schema( $schema_name )->{properties};
690 0 for my $key ( keys %$props ) {
691 0 my $format = $props->{ $key }{ format };
692 0 ▶ next unless $format;
Branch: 1 branch
BranchTrueFalseTotal
unless $format 0 0 0
693  
694 # Password cannot be changed to an empty string
695 0 ▶ if ( $format eq 'password' ) {
Branch: 2 branches
BranchTrueFalseTotal
if ($format eq 'password') { } 0 0 0
elsif ($format eq 'filepath' and my $upload = $c->param($key)) { } 0 0 0
696 0 ▶ if ( exists $data->{ $key } &&
Branch: 1 branch
BranchTrueFalseTotal
if (exists $data->{$key} and !defined($data->{$key}) || $data->{$key} eq "") 0 0 0
Condition0%0/6
exists $data->{$key} and !defined($data->{$key}) || $data->{$key} eq ""
!ll&&!rl&&r
000
not defined $data->{$key} or $data->{$key} eq ""
l!l&&r!l&&!r
000
MC/DC0%0/3
exists $data->{$key} and !defined($data->{$key}) || $data->{$key} eq ""
exists $data->{$key} not defined $data->{$key} $data->{$key} eq ""
Truth table0%0/4
A and not(B) or C
A= exists $data->{$key}B= not defined $data->{$key}C= $data->{$key} eq ""
ABCresult
0XX0
1000
11X1
1011
697 ( !defined $data->{ $key } || $data->{ $key } eq '' )
698 ) {
699 0 delete $data->{ $key };
700 }
701 }
702 # Upload files
703 ▶ elsif ( $format eq 'filepath' and my $upload = $c->param( $key ) ) {
Condition0%0/3
$format eq "filepath" and my $upload = $c->param($key)
!ll&&!rl&&r
000
MC/DC0%0/2
$format eq "filepath" and my $upload = $c->param($key)
$format eq "filepath" my $upload = $c->param($key)
Truth table0%0/3
A and B
A= $format eq "filepath"B= my $upload = $c->param($key)
ABresult
0X0
100
111
704 0 my $path = $c->yancy->file->write( $upload );
705 0 $data->{ $key } = $path;
706 }
707 }
708  
709 0 ▶ for my $helper ( @{ $c->stash( 'before_write' ) // [] } ) {
Condition0%0/2
$c->stash("before_write") // []
l!l
00
MC/DC0%0/1
$c->stash("before_write") // []
$c->stash("before_write")
Truth table0%0/2
A
A= $c->stash("before_write")
Aresult
11
00
710 0 $c->$helper( $data );
711 }
712 # ID could change during our helpers
713 $id = ref $id_field eq 'ARRAY'
714 0 ▶ ? { map { $_ => $c->stash( $_ ) } grep defined $c->stash( $_ ), @$id_field }
Branch: 1 branch
BranchTrueFalseTotal
ref $id_field eq 'ARRAY' ? : 0 0 0
715 : $c->stash( $id_field );
716  
717 0 my %opt;
718 0 ▶ if ( my $props = $c->stash( 'properties' ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $props = $c->stash("properties")) 0 0 0
719 0 $opt{ properties } = $props;
720 }
721 0 ▶ if ( $has_id ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($has_id) { } 0 0 0
722 0 eval { $c->yancy->set( $schema_name, $id, $data, %opt ) };
723 # ID field(s) may have changed
724 0 ▶ if ( ref $id_field eq 'ARRAY' ) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $id_field eq 'ARRAY') { } 0 0 0
725 0 for my $field ( @$id_field ) {
726 0 ▶ $id->{ $field } = $data->{ $field } || $id->{ $field };
Condition0%0/3
$data->{$field} || $id->{$field}
l!l&&r!l&&!r
000
MC/DC0%0/2
$data->{$field} || $id->{$field}
$data->{$field} $id->{$field}
Truth table0%0/3
A || B
A= $data->{$field}B= $id->{$field}
ABresult
1X1
011
000
727 }
728 }
729 else {
730 0 ▶ $id = $data->{ $id_field } || $id;
Condition0%0/3
$data->{$id_field} || $id
l!l&&r!l&&!r
000
MC/DC0%0/2
$data->{$id_field} || $id
$data->{$id_field} $id
Truth table0%0/3
A || B
A= $data->{$id_field}B= $id
ABresult
1X1
011
000
731 }
732 #; $c->app->log->info( 'Set success, new id: ' . $id );
733 }
734 else {
735 0 $id = eval { $c->yancy->create( $schema_name, $data ) };
736 }
737  
738 0 ▶ if ( my $errors = $@ ) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $errors = $@) 0 0 0
739 0 ▶ if ( ref $errors eq 'ARRAY' ) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $errors eq 'ARRAY') { } 0 0 0
740 # Validation error
741 0 $c->res->code( 400 );
742 0 $errors = [map {{message => $_->message, path => $_->path }} @$errors];
743 }
744 else {
745 # Unknown error
746 0 $c->res->code( 500 );
747 0 $errors = [ { message => $errors } ];
748 }
749 0 my $item = $c->yancy->get( $schema_name, $id );
750 0 $c->respond_to(
751 json => { json => { errors => $errors } },
752 any => { item => $item, errors => $errors },
753 );
754 0 return;
755 }
756  
757 0 my $item = $c->yancy->get( $schema_name, $id );
758 return $c->respond_to(
759 json => sub {
760 0 ▶ $c->stash(
Subroutine __ANON__: not called CC=2 SCAR=17.9
Branch: 1 branch
BranchTrueFalseTotal
$has_id ? : 0 0 0
761 status => $has_id ? 200 : 201,
762 json => $item,
763 );
764 },
765 any => sub {
766 0 ▶ if ( my $route = $c->stash( 'forward_to' ) ) {
Subroutine __ANON__: not called CC=2 SCAR=17.9
Branch: 1 branch
BranchTrueFalseTotal
if (my $route = $c->stash("forward_to")) 0 0 0
767 0 $c->redirect_to( $route, %$item );
768 0 return;
769 }
770 0 $c->stash( item => $item );
771 },
772 0 );
773 }
774  
775 #pod =method delete
776 #pod
777 #pod $routes->any( [ 'GET', 'POST' ], '/delete/:id_field' )->to(
778 #pod 'yancy#delete',
779 #pod schema => $schema_name,
780 #pod template => $template_name,
781 #pod forward_to => $route_name,
782 #pod );
783 #pod
784 #pod This route deletes an item from a schema. If the user is making
785 #pod a C<GET> request, they will simply be shown the template (which can be
786 #pod used to confirm the delete). If the user is making a C<POST> or C<DELETE>
787 #pod request, the item will be deleted and the user will either be shown the
788 #pod form again with the result of the form submission (success or failure)
789 #pod or the user will be forwarded to another place.
790 #pod
791 #pod =head4 Input Stash
792 #pod
793 #pod This method uses the following stash values for configuration:
794 #pod
795 #pod =over
796 #pod
797 #pod =item schema
798 #pod
799 #pod The schema to use. Required.
800 #pod
801 #pod =item "id_field"
802 #pod
803 #pod The ID field(s) for the item should be defined as stash items, usually via
804 #pod route placeholders named after the field.
805 #pod
806 #pod # Schema ID field is "page_id"
807 #pod $routes->get( '/pages/:page_id' )
808 #pod
809 #pod =item template
810 #pod
811 #pod The name of the template to use. See L<Mojolicious::Guides::Rendering/Renderer>
812 #pod for how template names are resolved.
813 #pod
814 #pod =item forward_to
815 #pod
816 #pod The name of a route to forward the user to on success. Optional.
817 #pod Forwarding will not happen for JSON requests.
818 #pod
819 #pod =item before_delete
820 #pod
821 #pod An array reference of helpers to call just before the item is deleted.
822 #pod See L</ACTION HOOKS> for usage.
823 #pod
824 #pod =back
825 #pod
826 #pod =head4 Output Stash
827 #pod
828 #pod The following stash values are set by this method:
829 #pod
830 #pod =over
831 #pod
832 #pod =item item
833 #pod
834 #pod The item that will be deleted. If displaying the form again after the item is deleted,
835 #pod this will be C<undef>.
836 #pod
837 #pod =back
838 #pod
839 #pod =head4 CSRF Protection
840 #pod
841 #pod This method is protected by L<Mojolicious's Cross-Site Request Forgery
842 #pod (CSRF) protection|Mojolicious::Guides::Rendering/Cross-site request
843 #pod forgery>. CSRF protection prevents other sites from tricking your users
844 #pod into doing something on your site that they didn't intend, such as
845 #pod editing or deleting content. You must add a C<< <%= csrf_field %> >> to
846 #pod your form in order to delete an item successfully. See
847 #pod L<Mojolicious::Guides::Rendering/Cross-site request forgery>.
848 #pod
849 #pod =cut
850  
851 sub delete {
852 0 ▶ my ( $c ) = @_;
Subroutine delete: not called CC=14 SCAR=53.5
Pod documented
853 0 ▶ if ( $c->stash( 'collection' ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($c->stash("collection")) 0 0 0
854 0 derp '"collection" stash key is now "schema" in controller configuration';
855 }
856 0 ▶ my $schema_name = $c->stash( 'schema' ) || $c->stash( 'collection' )
Condition0%0/5
$c->stash('schema') || $c->stash('collection') || die('Schema name not defined in stash')
l!l
00
$c->stash("schema") or $c->stash("collection")
l!l&&r!l&&!r
000
MC/DC0%0/2
$c->stash('schema') || $c->stash('collection') || die('Schema name not defined in stash')
$c->stash("schema") $c->stash("collection")
Truth table0%0/3
A or B
A= $c->stash("schema")B= $c->stash("collection")
ABresult
1X1
011
000
857 || die "Schema name not defined in stash";
858 0 my $schema = $c->yancy->schema( $schema_name );
859 0 ▶ my $id_field = $c->yancy->schema( $schema_name )->{'x-id-field'} // 'id';
Condition0%0/2
$c->yancy->schema($schema_name)->{"x-id-field"} // "id"
l!l
00
MC/DC0%0/1
$c->yancy->schema($schema_name)->{"x-id-field"} // "id"
$c->yancy->schema($schema_name)->{"x-id-field"}
Truth table0%0/2
A
A= $c->yancy->schema($schema_name)->{"x-id-field"}
Aresult
11
00
860 my $id = ref $id_field eq 'ARRAY'
861 0 ▶ ? { map { $_ => $c->stash( $_ ) } grep defined $c->stash( $_ ), @$id_field }
Branch: 1 branch
BranchTrueFalseTotal
ref $id_field eq 'ARRAY' ? : 0 0 0
Condition0%0/2
$c->stash($id_field) // die(sprintf('ID field "%s" not defined in stash', $id_field))
l!l
00
MC/DC0%0/1
$c->stash($id_field) // die(sprintf('ID field "%s" not defined in stash', $id_field))
$c->stash($id_field)
Truth table0%0/2
A
A= $c->stash($id_field)
Aresult
11
00
862 : ( $c->stash( $id_field ) // die sprintf 'ID field "%s" not defined in stash', $id_field );
863  
864 # Display the form, if requested. This makes it easy to display
865 # a confirmation page in a single route.
866 0 ▶ if ( $c->req->method eq 'GET' ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($c->req->method eq "GET") 0 0 0
867 0 my $item = $c->yancy->get( $schema_name => $id );
868 0 $c->respond_to(
869 json => {
870 status => 400,
871 json => {
872 errors => [
873 {
874 message => 'GET request for JSON invalid',
875 },
876 ],
877 },
878 },
879 any => { item => $item },
880 );
881 0 return;
882 }
883  
884 0 ▶ if ( $c->accepts( 'html' ) && $c->validation->csrf_protect->has_error( 'csrf_token' ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($c->accepts("html") and $c->validation->csrf_protect->has_error("csrf_token")) 0 0 0
Condition0%0/3
$c->accepts("html") and $c->validation->csrf_protect->has_error("csrf_token")
!ll&&!rl&&r
000
MC/DC0%0/2
$c->accepts("html") and $c->validation->csrf_protect->has_error("csrf_token")
$c->accepts("html") $c->validation->csrf_protect->has_error("csrf_token")
Truth table0%0/3
A and B
A= $c->accepts("html")B= $c->validation->csrf_protect->has_error("csrf_token")
ABresult
0X0
100
111
885 0 $c->app->log->error( 'CSRF token validation failed' );
886 0 $c->render(
887 status => 400,
888 item => $c->yancy->get( $schema_name => $id ),
889 errors => [
890 {
891 message => 'CSRF token invalid.',
892 },
893 ],
894 );
895 0 return;
896 }
897  
898 0 my $item = $c->yancy->get( $schema_name => $id );
899 0 ▶ for my $helper ( @{ $c->stash( 'before_delete' ) // [] } ) {
Condition0%0/2
$c->stash("before_delete") // []
l!l
00
MC/DC0%0/1
$c->stash("before_delete") // []
$c->stash("before_delete")
Truth table0%0/2
A
A= $c->stash("before_delete")
Aresult
11
00
900 0 $c->$helper( $item );
901 }
902 # ID fields could change during helper
903 $id = ref $id_field eq 'ARRAY'
904 0 ▶ ? { map { $_ => $c->stash( $_ ) } grep defined $c->stash( $_ ), @$id_field }
Branch: 1 branch
BranchTrueFalseTotal
ref $id_field eq 'ARRAY' ? : 0 0 0
Condition0%0/2
$c->stash($id_field) // die(sprintf('ID field "%s" not defined in stash', $id_field))
l!l
00
MC/DC0%0/1
$c->stash($id_field) // die(sprintf('ID field "%s" not defined in stash', $id_field))
$c->stash($id_field)
Truth table0%0/2
A
A= $c->stash($id_field)
Aresult
11
00
905 : ( $c->stash( $id_field ) // die sprintf 'ID field "%s" not defined in stash', $id_field );
906 0 $c->yancy->delete( $schema_name, $id );
907  
908 return $c->respond_to(
909 json => sub {
910 0 ▶ $c->rendered( 204 );
Subroutine __ANON__: not called CC=1 SCAR=6.9
911 0 return;
912 },
913 any => sub {
914 0 ▶ if ( my $route = $c->stash( 'forward_to' ) ) {
Subroutine __ANON__: not called CC=2 SCAR=17.9
Branch: 1 branch
BranchTrueFalseTotal
if (my $route = $c->stash("forward_to")) 0 0 0
915 0 $c->redirect_to( $route );
916 0 return;
917 }
918 },
919 0 );
920 }
921  
922 #pod =method feed
923 #pod
924 #pod $routes->websocket( '/' )->to(
925 #pod 'yancy#feed',
926 #pod schema => $schema_name,
927 #pod );
928 #pod
929 #pod Subscribe to a feed of changes to the given schema. This first sends a list result
930 #pod (like L</list> would). Then it sends change messages. Change messages are JSON objects
931 #pod with different fields based on the method of change:
932 #pod
933 #pod # An item in the list was changed
934 #pod {
935 #pod method => "set",
936 #pod # The position of the changed item in the list, 0-based
937 #pod index => 2,
938 #pod item => {
939 #pod # These are the fields that changed
940 #pod name => 'Lars Fillmore',
941 #pod },
942 #pod }
943 #pod
944 #pod # An item was added to the list
945 #pod {
946 #pod method => "create",
947 #pod # The position of the new item in the list, 0-based
948 #pod index => 0,
949 #pod item => {
950 #pod # The entire, newly-created item
951 #pod # ...
952 #pod },
953 #pod }
954 #pod
955 #pod # An item was removed from the list. This does not necessarily mean
956 #pod # the item was removed from the database.
957 #pod {
958 #pod method => "delete",
959 #pod # The position of the item removed from the list, 0-based
960 #pod index => 0,
961 #pod }
962 #pod
963 #pod B<TODO:> Allow the client to send change messages to the server.
964 #pod
965 #pod =head4 Input Stash
966 #pod
967 #pod This method uses the following stash values for configuration:
968 #pod
969 #pod =over
970 #pod
971 #pod =item schema
972 #pod
973 #pod The schema to use. Required.
974 #pod
975 #pod =item limit
976 #pod
977 #pod The number of items to show on the page. Defaults to C<10>.
978 #pod
979 #pod =item page
980 #pod
981 #pod The page number to show. Defaults to C<1>. The page number will
982 #pod be used to calculate the C<offset> parameter to L<Yancy::Backend/list>.
983 #pod
984 #pod =item filter
985 #pod
986 #pod A hash reference of field/value pairs to filter the contents of the list
987 #pod or a subref that generates this hash reference. The subref will be passed
988 #pod the current controller object (C<$c>).
989 #pod
990 #pod This overrides any query filters and so can be used to enforce
991 #pod authorization / security.
992 #pod
993 #pod =item order_by
994 #pod
995 #pod Set the default order for the items. Supports any L<Yancy::Backend/list>
996 #pod C<order_by> structure.
997 #pod
998 #pod =item before_render
999 #pod
1000 #pod An array reference of hooks to call once for each item in the C<items> list
1001 #pod before they are sent as messages. See L</ACTION HOOKS> for usage.
1002 #pod
1003 #pod =back
1004 #pod
1005 #pod =head4 Query Params
1006 #pod
1007 #pod The following URL query parameters are allowed for this method:
1008 #pod
1009 #pod =over
1010 #pod
1011 #pod =item $page
1012 #pod
1013 #pod Instead of using the C<page> stash value, you can use the C<$page> query
1014 #pod parameter to set the page.
1015 #pod
1016 #pod =item $offset
1017 #pod
1018 #pod Instead of using the C<page> stash value, you can use the C<$offset>
1019 #pod query parameter to set the page offset. This is overridden by the
1020 #pod C<$page> query parameter.
1021 #pod
1022 #pod =item $limit
1023 #pod
1024 #pod Instead of using the C<limit> stash value, you can use the C<$limit>
1025 #pod query parameter to allow users to specify their own page size.
1026 #pod
1027 #pod =item $order_by
1028 #pod
1029 #pod One or more fields to order by. Can be specified as C<< <name> >> or
1030 #pod C<< asc:<name> >> to sort in ascending order or C<< desc:<field> >>
1031 #pod to sort in descending order.
1032 #pod
1033 #pod =item $match
1034 #pod
1035 #pod How to match multiple field filters. Can be C<any> or C<all> (default
1036 #pod C<all>). C<all> means all fields must match for a row to be returned.
1037 #pod C<any> means at least one field must match for a row to be returned.
1038 #pod
1039 #pod =item Additional Field Filters
1040 #pod
1041 #pod Any named query parameter that matches a field in the schema will be
1042 #pod used to further filter the results. The stash C<filter> will override
1043 #pod this filter, so that the stash C<filter> can be used for security.
1044 #pod
1045 #pod =back
1046 #pod
1047 #pod =cut
1048  
1049 sub feed {
1050 0 ▶ my ( $c ) = @_;
Subroutine feed: not called CC=7 SCAR=38.8
Pod documented
1051 0 $c->inactivity_timeout( 3600 );
1052  
1053 # First, send the message for the initial page
1054 0 my ( $schema_name, $filter, $opt ) = $c->_get_list_args;
1055 0 my $result = $c->yancy->backend->list( $schema_name, $filter, $opt );
1056 0 ▶ for my $helper ( @{ $c->stash( 'before_render' ) // [] } ) {
Condition0%0/2
$c->stash("before_render") // []
l!l
00
MC/DC0%0/1
$c->stash("before_render") // []
$c->stash("before_render")
Truth table0%0/2
A
A= $c->stash("before_render")
Aresult
11
00
1057 0 $c->$helper( $_ ) for @{ $result->{items} };
1058 }
1059 0 ▶ my $x_id_field = $c->yancy->schema( $schema_name )->{'x-id-field'} // 'id';
Condition0%0/2
$c->yancy->schema($schema_name)->{"x-id-field"} // "id"
l!l
00
MC/DC0%0/1
$c->yancy->schema($schema_name)->{"x-id-field"} // "id"
$c->yancy->schema($schema_name)->{"x-id-field"}
Truth table0%0/2
A
A= $c->yancy->schema($schema_name)->{"x-id-field"}
Aresult
11
00
1060 0 ▶ my @id_fields = ref $x_id_field eq 'ARRAY' ? @$x_id_field : ( $x_id_field );
Branch: 1 branch
BranchTrueFalseTotal
ref $x_id_field eq 'ARRAY' ? : 0 0 0
1061 #; $c->log->debug( 'Original result: ' . $c->dumper( $result ) );
1062 0 $c->send({ json => { %$result, method => 'list' } });
1063  
1064 # Now, poll the database for updates every few seconds.
1065 # XXX: Create Yancy::Plugin::PubSub to do push messaging instead of
1066 # ugly polling...
1067 my $id = Mojo::IOLoop->recurring( $c->stash( 'interval' ) // 10, sub {
1068 0 ▶ my $new_result = $c->yancy->backend->list( $schema_name, $filter, $opt );
Subroutine __ANON__: not called CC=7 SCAR=37.9
1069 #; $c->log->debug( 'New result: ' . $c->dumper( $new_result ) );
1070 0 my %seen_items;
1071 my @created_items;
1072 0 NEW_ITEM: for my $new_i ( 0..$#{ $new_result->{items} } ) {
1073 0 my $new_item = $new_result->{items}[$new_i];
1074 # Loop through the old result to find the existing items by
1075 # their ID fields
1076 0 for my $old_i ( 0..$#{ $result->{items} } ) {
1077 0 my $old_item = $result->{items}[$old_i];
1078 0 ▶ if ( @id_fields == grep { $new_item->{ $_ } eq $old_item->{ $_ } } @id_fields ) {
Branch: 1 branch
BranchTrueFalseTotal
if (@id_fields == grep({$new_item->{$_} eq $old_item->{$_};} @id_fields)) 0 0 0
1079 # Found it!
1080 0 $seen_items{ $old_i }++;
1081 my %diff =
1082 0 map { $_ => $new_item->{ $_ } }
1083 4 ▶ grep {; no warnings 'uninitialized'; $new_item->{ $_ } ne $old_item->{ $_ } }
Subroutine BEGIN: called CC=1 SCAR=0.6
1084 keys %$new_item, keys %$old_item
1085 ;
1086 0 ▶ if ( keys %diff ) {
Branch: 1 branch
BranchTrueFalseTotal
if (keys %diff) 0 0 0
1087 0 my $message = {
1088 method => 'set',
1089 index => $old_i,
1090 item => \%diff,
1091 };
1092 #$c->log->debug( $c->dumper( $message ) );
1093 0 $c->send({ json => $message });
1094 }
1095 0 next NEW_ITEM;
1096 }
1097 }
1098 # If we can't find the new item, it must have been added.
1099 # Queue it up to send after deletes to maintain indexes.
1100 0 push @created_items, {
1101 method => 'create',
1102 index => $new_i,
1103 item => $new_item,
1104 };
1105 }
1106 # Any items we did not see must have been removed from the list,
1107 # or pushed out by newly-created items. Send these in reverse to
1108 # maintain indexes.
1109 0 for my $old_i ( reverse grep { !$seen_items{ $_ } } 0..$#{ $result->{items} } ) {
1110 0 my $message = {
1111 method => 'delete',
1112 index => $old_i,
1113 };
1114 #$c->log->debug( $c->dumper( $message ) );
1115 0 $c->send({ json => $message });
1116 }
1117 # Now we can send the created items, from lowest index to
1118 # highest index
1119 0 for my $item ( @created_items ) {
1120 #$c->log->debug( $c->dumper( $item ) );
1121 0 $c->send({ json => $item });
1122 }
1123  
1124 0 $result = $new_result;
1125 0 ▶ } );
Condition0%0/2
$c->stash("interval") // 10
l!l
00
MC/DC0%0/1
$c->stash("interval") // 10
$c->stash("interval")
Truth table0%0/2
A
A= $c->stash("interval")
Aresult
11
00
1126 0 ▶ $c->on( finish => sub { Mojo::IOLoop->remove( $id ) } );
Subroutine __ANON__: not called CC=1 SCAR=6.9
1127 # XXX: Allow client to send "list" message to change the parameters
1128 # of the list. Respond with an entirely new result (not a diff).
1129 # XXX: Allow client to send "create", "set", and "delete" messages
1130 # to create, set, and delete items
1131 }
1132  
1133 sub _get_list_args {
1134 0 ▶ my ( $c ) = @_;
Subroutine _get_list_args: not called CC=25 SCAR=64.8
1135  
1136 0 ▶ if ( $c->stash( 'collection' ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($c->stash("collection")) 0 0 0
1137 0 derp '"collection" stash key is now "schema" in controller configuration';
1138 }
1139 0 ▶ my $schema_name = $c->stash( 'schema' ) || $c->stash( 'collection' )
Condition0%0/5
$c->stash('schema') || $c->stash('collection') || die('Schema name not defined in stash')
l!l
00
$c->stash("schema") or $c->stash("collection")
l!l&&r!l&&!r
000
MC/DC0%0/2
$c->stash('schema') || $c->stash('collection') || die('Schema name not defined in stash')
$c->stash("schema") $c->stash("collection")
Truth table0%0/3
A or B
A= $c->stash("schema")B= $c->stash("collection")
ABresult
1X1
011
000
1140 || die "Schema name not defined in stash";
1141 0 ▶ my $limit = $c->param( '$limit' ) // $c->stash->{ limit } // 10;
Condition0%0/5
($c->param("\$limit") // $c->stash->{"limit"}) // 10
l!l
00
$c->param("\$limit") // $c->stash->{"limit"}
l!l&&r!l&&!r
000
MC/DC0%0/2
($c->param("\$limit") // $c->stash->{"limit"}) // 10
$c->param("\$limit") $c->stash->{"limit"}
Truth table0%0/3
A // B
A= $c->param("\$limit")B= $c->stash->{"limit"}
ABresult
1X1
011
000
1142 my $offset = $c->param( '$page' ) ? ( $c->param( '$page' ) - 1 ) * $limit
1143 : $c->param( '$offset' ) ? $c->param( '$offset' )
1144 0 ▶ : ( ( $c->stash->{page} // 1 ) - 1 ) * $limit;
Branch: 2 branches
BranchTrueFalseTotal
$c->param('$page') ? : 0 0 0
$c->param('$offset') ? : 0 0 0
Condition0%0/2
$c->stash->{"page"} // 1
l!l
00
MC/DC0%0/1
$c->stash->{"page"} // 1
$c->stash->{"page"}
Truth table0%0/2
A
A= $c->stash->{"page"}
Aresult
11
00
1145 0 $c->stash( page => int( $offset / $limit ) + 1 );
1146 0 my $opt = {
1147 limit => $limit,
1148 offset => $offset,
1149 };
1150  
1151 0 ▶ if ( my $order_by = $c->param( '$order_by' ) ) {
Branch: 2 branches
BranchTrueFalseTotal
if (my $order_by = $c->param('$order_by')) { } 0 0 0
elsif ($order_by = $c->stash('order_by')) { } 0 0 0
1152 $opt->{order_by} = [
1153 0 ▶ map +{ "-" . ( $_->[1] ? $_->[0] : 'asc' ) => $_->[1] // $_->[0] },
Branch: 1 branch
BranchTrueFalseTotal
$_->[1] ? : 0 0 0
Condition0%0/3
$_->[1] // $_->[0]
l!l&&r!l&&!r
000
MC/DC0%0/2
$_->[1] // $_->[0]
$_->[1] $_->[0]
Truth table0%0/3
A // B
A= $_->[1]B= $_->[0]
ABresult
1X1
011
000
1154 map +[ split /:/ ],
1155 split /,/, $order_by
1156 ];
1157 }
1158 elsif ( $order_by = $c->stash( 'order_by' ) ) {
1159 0 $opt->{order_by} = $order_by;
1160 }
1161  
1162 0 my $schema = $c->yancy->schema( $schema_name ) ;
1163 0 my $props = $schema->{properties};
1164 0 my %param_filter = ();
1165 0 for my $key ( @{ $c->req->params->names } ) {
1166 0 ▶ next unless exists $props->{ $key };
Branch: 1 branch
BranchTrueFalseTotal
unless exists $props->{$key} 0 0 0
1167 0 ▶ my $type = $props->{$key}{type} || 'string';
Condition0%0/2
$props->{$key}{'type'} || 'string'
l!l
00
MC/DC0%0/1
$props->{$key}{'type'} || 'string'
$props->{$key}{'type'}
Truth table0%0/2
A
A= $props->{$key}{'type'}
Aresult
11
00
1168 0 my $value = $c->param( $key );
1169 0 ▶ if ( is_type( $type, 'string' ) ) {
Branch: 4 branches
BranchTrueFalseTotal
if (is_type($type, 'string')) { } 0 0 0
elsif (grep is_type($type, $_), ('number', 'integer')) { } 0 0 0
elsif (is_type($type, 'boolean')) { } 0 0 0
elsif (is_type($type, 'array')) { } 0 0 0
1170 0 ▶ if ( ( $value =~ tr/*/%/ ) <= 0 ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($value =~ tr/*/%/ <= 0) 0 0 0
1171 0 $value = "\%$value\%";
1172 }
1173 0 $param_filter{ $key } = { -like => $value };
1174 }
1175 elsif ( grep is_type( $type, $_ ), qw(number integer) ) {
1176 0 $param_filter{ $key } = $value ;
1177 }
1178 elsif ( is_type( $type, 'boolean' ) ) {
1179 0 ▶ $param_filter{ ($value && $value ne 'false')? '-bool' : '-not_bool' } = $key;
Branch: 1 branch
BranchTrueFalseTotal
$value && $value ne 'false' ? : 0 0 0
Condition0%0/3
$value and $value ne "false"
!ll&&!rl&&r
000
MC/DC0%0/2
$value and $value ne "false"
$value $value ne "false"
Truth table0%0/3
A and B
A= $valueB= $value ne "false"
ABresult
0X0
100
111
1180 }
1181 elsif ( is_type($type, 'array') ) {
1182 0 $param_filter{ $key } = { '-has' => $value };
1183 }
1184 else {
1185 0 die "Sorry type '" .
1186 to_json( $type ) .
1187 "' is not handled yet, only string|number|integer|boolean|array is supported."
1188 }
1189 }
1190 my $filter = {
1191 %param_filter,
1192 # Stash filter always overrides param filter, for security
1193 0 %{ $c->_resolve_filter },
1194 };
1195 0 ▶ if ( $c->param( '$match' ) && $c->param( '$match' ) eq 'any' ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($c->param("\$match") and $c->param("\$match") eq "any") 0 0 0
Condition0%0/3
$c->param("\$match") and $c->param("\$match") eq "any"
!ll&&!rl&&r
000
MC/DC0%0/2
$c->param("\$match") and $c->param("\$match") eq "any"
$c->param("\$match") $c->param("\$match") eq "any"
Truth table0%0/3
A and B
A= $c->param("\$match")B= $c->param("\$match") eq "any"
ABresult
0X0
100
111
1196 $filter = [
1197 0 map +{ $_ => $filter->{ $_ } }, keys %$filter
1198 ];
1199 }
1200  
1201 #; use Data::Dumper;
1202 #; $c->app->log->info( Dumper $filter );
1203 #; $c->app->log->info( Dumper $opt );
1204  
1205 0 return ( $schema_name, $filter, $opt );
1206 }
1207  
1208 sub _resolve_filter {
1209 0 ▶ my ( $c ) = @_;
Subroutine _resolve_filter: not called CC=3 SCAR=24.8
1210 0 my $filter = $c->stash( 'filter' );
1211 0 ▶ if ( ref $filter eq 'CODE' ) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $filter eq "CODE") 0 0 0
1212 0 return $filter->( $c );
1213 }
1214 0 ▶ return $filter // {};
Condition0%0/2
$filter // {}
l!l
00
MC/DC0%0/1
$filter // {}
$filter
Truth table0%0/2
A
A= $filter
Aresult
11
00
1215 }
1216  
1217 4 1;
1218  
1219 __END__
↑ Summary Yancy/Plugin/Form/Bootstrap4.pm »