Controller/ExtJS/REST.pm untested

filter: Statementstmt 0.0% 0 / 371 Branchbran 0.0% 0 / 134 Conditioncond 0.0% 0 / 78 MC/DCmcdc 0.0% 0 / 44 Subroutinesub 0.0% 0 / 41 Podpod 0.0% 0 / 28 totaltotal 0.0% 0 / 696 CC 68 SCAR 46.4
CC
68
Cov
0%
object
342.0
list
240.0
paging_rs
56.0
CRAP 103.1
1 #
2 # This file is part of CatalystX-ExtJS-REST
3 #
4 # This software is Copyright (c) 2014 by Moritz Onken.
5 #
6 # This is free software, licensed under:
7 #
8 # The (three-clause) BSD License
9 #
10 package CatalystX::Controller::ExtJS::REST;
11 # ABSTRACT: RESTful interface to dbic objects
12 $CatalystX::Controller::ExtJS::REST::VERSION = '2.1.3';
13 use Moose;
14 extends qw(Catalyst::Controller::REST);
15 use MooseX::MethodAttributes;
16  
17 use Config::Any;
18 use Scalar::Util ();
19 use Carp qw/ croak /;
20 use HTML::FormFu::ExtJS 0.076;
21 use Path::Class;
22 use HTML::Entities;
23 use Lingua::EN::Inflect;
24 use JSON;
25 use Try::Tiny;
26  
27 use Moose::Util::TypeConstraints;
28 subtype 'PathClassDir', as 'Path::Class::Dir';
29 coerce 'PathClassDir', from 'ArrayRef', via { Path::Class::Dir->new( @{$_[0]} ) };
30 coerce 'PathClassDir', from 'Str', via { Path::Class::Dir->new( $_[0] ) };
31 subtype 'PathClassFile', as 'Path::Class::File';
32 coerce 'PathClassFile', from 'ArrayRef', via { Path::Class::File->new( @{$_[0]} ) };
33 coerce 'PathClassFile', from 'Str', via { Path::Class::File->new( $_[0] ) };
34 no Moose::Util::TypeConstraints;
35  
36 __PACKAGE__->config(
37 actions => {
38 begin => {
39 ActionClass => '+CatalystX::Action::ExtJS::Deserialize',
40 },
41 end => {
42 ActionClass => 'Serialize',
43 },
44 list => {
45 Chained => '/',
46 NSListPathPart => undef,
47 Args => undef,
48 Direct => undef,
49 DirectArgs => 1,
50 },
51 base => {
52 Chained => '/',
53 NSPathPart => undef,
54 CaptureArgs => 1,
55 },
56 object => {
57 Chained => '/',
58 NSPathPart => undef,
59 Args => undef,
60 ActionClass => '+CatalystX::Action::ExtJS::REST',
61 Direct => undef,
62 },
63 object_GET => { Private => undef },
64 object_PUT => { Private => undef },
65 object_POST => { Private => undef },
66 object_DELETE => { Private => undef },
67 }
68 );
69  
70 has '_extjs_config' => ( is => 'rw', isa => 'HashRef', builder => '_extjs_config_builder', lazy => 1 );
71  
72 has 'form_base_path' => ( is => 'rw', lazy_build => 1, isa => 'PathClassDir', coerce => 1 );
73  
74 has 'form_base_file' => ( is => 'rw', lazy_build => 1, isa => 'PathClassFile', coerce => 1 );
75  
76 has 'list_base_path' => ( is => 'rw', lazy_build => 1, isa => 'PathClassDir', coerce => 1 );
77  
78 has 'list_base_file' => ( is => 'rw', lazy_build => 1, isa => 'PathClassFile', coerce => 1 );
79  
80 has 'list_options_file' => ( is => 'rw', lazy_build => 1, isa => 'PathClassFile|Undef', coerce => 1 );
81  
82 has 'form_config_cache' => ( is => 'rw', isa => 'HashRef', clearer => 'clear_form_config_cache', default => sub {{}});
83  
84 has 'default_resultset' => ( is => 'rw', isa => 'Str', lazy_build => 1 );
85  
86 has 'root_property' => ( is => 'rw', isa => 'Str', default => 'data' );
87  
88 has 'limit' => ( is => 'rw', default => 100 );
89  
90 has 'order_by' => ( is => 'rw' );
91  
92 has 'forms' => ( is => 'rw', isa => 'HashRef', predicate => 'has_forms' );
93  
94 # backwards compat
95 sub base_file { shift->form_base_file(@_) };
96 sub base_path { shift->form_base_path(@_) };
97  
98  
99 sub _extjs_config_builder {
100 my $self = shift;
101 my $c = $self->_application;
102 my $default_rs_method = lc($self->default_resultset);
103 $default_rs_method =~ s/::/_/g;
104
105 my $defaults = {
106 model_config => {
107 schema => 'DBIC',
108 resultset => $self->default_resultset
109 },
110 default_rs_method => 'extjs_rest_'.$default_rs_method,
111 context_stash => 'context',
112 list_options_validation => {
113 elements => [
114 { name => 'start', constraints => ['Integer', { type => 'MinRange', min => 0}] },
115 { name => 'dir', constraints => { type => 'Set', set => [qw(asc desc ASC DESC)] } },
116 { name => 'limit', constraints => ['Integer', { type => 'Range', min => 0, max => $self->limit || 9999 }] },
117 { name => 'sort' },
118 ]
119 },
120 find_method => 'find',
121 };
122 my $self_config = $self->config || {};
123 my $parent_config = $self->merge_config_hashes(
124 $c->config->{'ControllerX::ExtJS::REST'} || {},
125 $c->config->{'ControllerX::Controller::ExtJS::REST'} || {} );
126  
127 # merge hashes with right hand precedence
128 my $merged_config = $self->merge_config_hashes( $defaults, $self_config );
129 $merged_config = $self->merge_config_hashes( $merged_config, $parent_config );
130  
131 return $merged_config;
132
133 }
134  
135 sub _build_form_base_path {
136 my $self = shift;
137 return Path::Class::Dir->new( $self->_app->path_to(qw(root forms)) );
138 }
139  
140 sub _build_form_base_file {
141 my $self = shift;
142 my @path = split( /\//, $self->action_namespace );
143 my $file = pop @path;
144 return $self->form_base_path->subdir(@path)->file($file . '.yml');
145 }
146  
147 sub _build_list_base_path {
148 my $self = shift;
149 return Path::Class::Dir->new( $self->_app->path_to(qw(root lists)) );
150 }
151  
152 sub _build_list_base_file {
153 my $self = shift;
154 my @path = split( /\//, $self->action_namespace );
155 my $file = pop @path;
156 $file = $self->list_base_path->subdir(@path)->file($file . '.yml');
157 return -e $file ? $file : $self->form_base_file;
158 }
159  
160 sub _build_list_options_file {
161 my $self = shift;
162 my @path = split( /\//, $self->action_namespace );
163 my $file = pop @path;
164 $file = $self->list_base_path->subdir(@path)->file($file . '_options.yml');
165 return -e $file ? $file : undef;
166 }
167  
168 sub _build_default_resultset {
169 my ($self, $c) = @_;
170 my $class = ref $self;
171 my $prefix;
172
173 # Copied from Catalyst::Utils
174 if($class =~ /^.+?::([MVC]|Model|View|Controller)::(API::)?(.+)$/ ) {
175 $prefix = $3;
176 }
177 return $prefix;
178 }
179  
180 sub clear_caches {
181 my ($self) = @_;
182 $self->form_config_cache({});
183 }
184  
185 sub validate_options {
186 my ($self, $c) = @_;
187 my $form = HTML::FormFu::ExtJS->new;
188 $form->populate($self->_extjs_config->{list_options_validation});
189 if($self->has_forms) {
190 my $config = $self->forms->{options} || {};
191 $config = { elements => $config } if(ref $config eq 'ARRAY');
192 $form->populate( $config );
193 } elsif($self->list_options_file) {
194 $c->log->debug('found configuration file for parameters') if($c->debug);
195 $form->load_config_file($self->list_options_file);
196 }
197 $form->process($c->req->params);
198 return $form;
199 }
200  
201 sub list {
202 my ( $self, $c ) = @_;
203 $self->clear_caches if($c->debug);
204 my $form = $self->get_form($c, 'list');
205 my $config = $form->model_config;
206 croak "Need resultset and schema" unless($config->{resultset} && $config->{schema});
207 my $model = join('::', $config->{schema}, $config->{resultset});
208
209 my $validate_options = $self->validate_options($c);
210
211 if($validate_options->has_errors) {
212 $self->status_bad_request($c, message => 'One ore more parameters did not pass the validation');
213 $c->stash->{rest} = { errors => $validate_options->validation_response->{errors}, status => \0 };
214 return;
215 }
216  
217 my $rs = $c->model($model);
218 $rs = $self->paging_rs($c, $form, $rs);
219
220 # collect rs methods from URI, body and request param
221 my @args = map {$_ => [] } @{$c->req->args};
222 my $data = $c->req->data;
223 if($data && (ref $data eq 'ARRAY') && ref $data->[0] eq 'ARRAY') {
224 $data = $data->[0];
225 for(my $i = 0; $i < @$data; $i++) {
226 my $argv = $data->[$i+1] if(ref $data->[$i+1]);
227 $argv = [$argv] unless(ref $argv eq 'ARRAY');
228 push(@args, $data->[$i], $argv);
229 $i++ if(ref $data->[$i+1]);
230 }
231 }
232 push(@args, map { $_ => [] } $c->req->param('resultset'));
233 unshift(@args, $self->_extjs_config->{default_rs_method} => ['list']);
234
235 for(my $i = 0; $i < @args; $i+=2) {
236 next unless(my $rs_method = $args[$i]);
237 my ($m, @params) = split(/,/, $rs_method);
238 if($rs_method && DBIx::Class::ResultSet->can($m)) {
239 $c->log->warn('Possibly malicious method "'.$m.'" on resultset '.$m.' has not been called');
240 next;
241 }
242 push(@params, @{$args[$i+1]});
243 if($rs->can($m)) {
244 if($c->debug) {
245 my $debug = qq(Calling resultset method $m);
246 $debug .= q( with arguments ').join(q(', '), @params).q(') if(@params);
247 $c->log->debug($debug);
248 }
249 $rs = $rs->$m($c, @params);
250 } elsif($c->debug) {
251 $c->log->debug(qq(Resultset method $m could not be found));
252 }
253 }
254
255 my ($pk, $too_much) = $rs->result_source->primary_columns;
256
257 my $grid_data = $form->grid_data([$rs->all], {metaData => {root => $self->root_property, idProperty => $pk, messageProperty => 'message' }});
258 if ($self->_extjs_config->{no_list_metadata}) {
259 delete $grid_data->{metaData};
260 } else {
261 $grid_data->{$self->root_property} = delete $grid_data->{rows};
262 }
263 my $count = $rs->search(undef, { rows => undef, offset => undef })->count;
264 $grid_data->{results} = $count;
265 $self->status_ok( $c, entity => $grid_data);
266 }
267  
268 sub paging_rs {
269 my ($self, $c, $form, $rs) = @_;
270 my $params = $c->req->params;
271
272 my $start = abs(int($params->{start} || 0));
273
274 my $limit = abs(int($params->{limit} || $self->limit));
275  
276 return $rs if($start == 0 && $limit == 0);
277  
278 my @direction = grep { $_ eq (lc($params->{dir} || 'asc')) } qw(asc desc);
279 my $direction = q{-}.(shift @direction);
280
281 my $sort = $params->{sort} || $self->order_by || undef;
282 if(ref $sort eq 'HASH') {
283 ($direction, $sort) = %$sort;
284 }
285
286 unless($form->get_all_element({ nested_name => $sort })) {
287 $sort =~ s/(?<=[a-z])([A-Z])/\.\l$1/gsx; # relationshipColumn => relationship.column
288 undef $sort unless($form->get_all_element({ nested_name => $sort }));
289 }
290
291 my $paged = $rs->search(undef, { offset => $start, rows => $limit || undef});
292 $sort = join('.', $rs->current_source_alias, $sort) unless(!$sort || $sort =~ /\./);
293 $paged = $paged->search(undef, { order_by => [ { $direction => $sort } ] })
294 if $sort;
295 return $paged;
296 }
297  
298 sub base {
299 my ( $self, $c, $id ) = @_;
300 $self->object($c, $id);
301 }
302  
303 sub object {
304 my ( $self, $c, $id ) = @_;
305 $self->clear_caches if($c->debug);
306 my $config = $self->has_forms ? $self->forms->{default} : $self->load_config_file($self->form_base_file);
307 $config = { elements => $config } if(ref $config eq 'ARRAY');
308 $config = { %{$self->_extjs_config->{model_config}}, %{$config->{model_config} || {}} };
309 $config->{resultset} ||= $self->default_resultset;
310 croak "Need resultset and schema" unless($config->{resultset} && $config->{schema});
311 $c->stash->{extjs_formfu_model_config} = $config;
312  
313 my $object = $c->model(join('::', $config->{schema}, $config->{resultset}));
314  
315 my $req_method = lc($c->req->method);
316
317 unless(defined $id) {
318 my ($pk, $too_much) = $object->result_source->primary_columns;
319 croak 'Not able to process result classes with multiple primary keys' if($too_much);
320 $id = $c->req->params->{$pk};
321 }
322
323 if(!defined $id && $req_method eq 'get') {
324 $c->forward('list');
325 return;
326 }
327
328 my $guard = $c->model($config->{schema})->txn_scope_guard;
329
330 if(my $rs = $self->_extjs_config->{default_rs_method}) {
331 if($object->can($rs)) {
332 $c->log->debug(qq(Calling default resultset method $rs)) if($c->debug);
333 $object = $object->$rs($c, 'object');
334 } elsif($c->debug) {
335 $c->log->debug(qq(Default resultset method $rs cannot be found));
336 }
337 }
338  
339 my $method = $config->{find_method} || $self->_extjs_config->{find_method};
340 if (defined $id && defined $object) {
341 $object = $object->search( undef, { for => 'update' })
342 if($req_method ne 'get');
343 $object = $object->$method($id);
344 $c->stash->{object} = $object;
345 }
346
347 $c->stash->{form} =
348 $self->get_form($c, $req_method);
349 if($req_method eq 'get') {
350 $c->forward('object_GET');
351 } elsif($req_method eq 'put' || $req_method eq 'post' && $c->stash->{object}) {
352 $c->forward('object_PUT');
353 } elsif($req_method eq 'post') {
354 $c->forward('object_POST');
355 } elsif($req_method eq 'delete') {
356 $c->forward('object_DELETE');
357 }
358 $guard->commit;
359 }
360  
361  
362 sub object_PUT {
363 my ( $self, $c ) = @_;
364 my $object = $c->stash->{object};
365 my $form = $c->stash->{form};
366  
367 # Check if row object exists
368 if(!$c->stash->{object}) {
369 $self->status_not_found($c, message => 'Object could not be found.');
370 return;
371 }
372  
373 $self->object_PUT_or_POST($c, $form, $object);
374
375 $form->model("DBIC")->default_values($object);
376 my $model = $form->model("HashRef");
377 $model->flatten(1);
378 $model->options(0);
379 my $req = { %{$model->create}, %{$c->req->params} };
380
381 $form->process( $req );
382
383 if ( $form->submitted_and_valid ) {
384 my $row = $form->model->update($object);
385 $self->handle_uploads($c, $row, $form);
386 my $data = $form->form_data( $row );
387
388 # get values from model
389 $self->status_ok( $c, entity => $data );
390 }
391 else {
392 # return form values and error messages
393 $self->status_ok( $c, entity => $form->validation_response );
394 }
395 }
396  
397 sub object_PUT_or_POST {
398 my ($self, $c, $form, $object) = @_;
399  
400 }
401  
402 sub object_POST {
403 my ( $self, $c ) = @_;
404 my $form = $c->stash->{form};
405
406 $self->object_PUT_or_POST($c, $form);
407
408 $form->process( $c->req );
409  
410 if ( $form->submitted_and_valid ) {
411 my $row = $form->model->create;
412 $self->handle_uploads($c, $row, $form);
413
414 $c->stash->{object} = $row;
415 # get values from model and set the primary key
416 my ($pk, $too_much) = $row->result_source->primary_columns;
417 my $data = $form->form_data( $row );
418 $data->{data}->{$pk} = $row->$pk;
419 $data->{$self->root_property} = $data->{data} if($self->root_property ne 'data');
420
421 $self->status_created(
422 $c,
423 location => $c->uri_for( '', $row->$pk ),
424 entity => $data
425 );
426
427 }
428 else {
429 # return form values and error messages
430 $self->status_ok( $c, entity => $form->validation_response );
431 }
432  
433 }
434  
435 sub object_GET {
436 my ( $self, $c ) = @_;
437 my $form = $c->stash->{form};
438  
439 if($c->stash->{object}) {
440 $self->status_ok( $c, entity => $form->form_data( $c->stash->{object} ) );
441 } else {
442 $self->status_not_found($c, message => 'Object could not be found.');
443 }
444 }
445  
446 sub object_DELETE {
447 my ( $self, $c ) = @_;
448 if($c->stash->{object}) {
449 $c->stash->{object}->delete;
450 $self->status_ok( $c, entity => { success => \1, data => {}, message => "Object has been deleted" } );
451 } else {
452 $self->status_not_found($c, message => 'Object could not be found.');
453 }
454 }
455  
456  
457 sub path_to_forms {
458 my ($self, $method) = @_;
459 (my $file = $self->form_base_file) =~ s/\.yml$//;
460 $file .= '_' . $method . '.yml';
461 $file = Path::Class::File->new($file);
462 return -e $file ? $file : $self->form_base_file;
463 }
464  
465 sub get_form {
466 my ($self, $c, $file) = @_;
467
468 my $form = HTML::FormFu::ExtJS->new();
469 $form->query_type('Catalyst');
470 my $model_stash = $self->_extjs_config->{model_stash};
471 $model_stash->{schema} ||= "DBIC";
472 for my $model ( keys %$model_stash ) {
473 $form->stash->{$model} = $c->model( $model_stash->{$model} );
474 }
475 $form->model_config($self->_extjs_config->{model_config});
476
477
478  
479 if ( $file && !ref $file ) {
480 if ( $self->has_forms ) {
481 my $config = $self->forms->{$file} || $self->forms->{default};
482 $config = { elements => $config } if(ref $config eq 'ARRAY');
483 $form->populate( $config );
484 } elsif ( $file eq 'list' ) {
485 $file = $self->list_base_file;
486 } else {
487 $file = $self->path_to_forms($file);
488 }
489 }
490  
491 if ( ref $file ) {
492 $c->log->debug( 'Loading form ' . $file ) if ( $c->debug );
493 my $config = $self->load_config_file($file);
494 $form->populate($config);
495 }
496  
497  
498 # To allow your form validation packages, etc, access to the catalyst
499 # context, a weakened reference of the context is copied into the form's
500 # stash.
501
502 my $context_stash = $self->_extjs_config->{context_stash};
503 $form->stash->{$context_stash} = $c;
504 Scalar::Util::weaken( $form->stash->{$context_stash} );
505 return $form;
506 }
507  
508 sub load_config_file {
509 my ($self, $file) = @_;
510 my $config;
511 unless($config = $self->form_config_cache->{$file . ""}) {
512 die "Neither __PACKAGE__->config->{forms} nor " . $file . " exist."
513 unless(-e $file);
514 $config = Config::Any->load_files( {
515 files => [$file],
516 use_ext => 1,
517 driver_args => { General => { -UTF8 => 1 }, },
518 } );
519 ( undef, $config ) = %{ $config->[0] };
520 $self->form_config_cache->{$file.""} = $config;
521 }
522 return $config;
523 }
524  
525 sub handle_uploads {
526 my ($self, $c, $row, $form) = @_;
527 my $uploads;
528 while(my ($k, $v) = each %{$c->req->uploads}) {
529 next unless $form->get_field($k);
530 $c->log->debug("Cannot handle multiple uploads per field") if($c->debug && ref $v eq "ARRAY");
531 $row->$k($v->fh);
532 }
533 $row->update;
534 }
535  
536 sub status_not_found {
537 my $self = shift;
538 $self->next::method(@_);
539 shift->stash->{rest}->{success} = \0;
540 }
541  
542 sub end {
543 my ( $self, $c ) = @_;
544 $self->next::method($c);
545 if(@{$c->error}) {
546 $self->status_bad_request($c, message => $c->debug ? "@{$c->error}" : 'An error occured while processing your request.');
547 $c->log->error(@{$c->error});
548 $c->clear_errors;
549 $c->stash->{rest}->{success} = \0;
550 }
551
552 if ( $c->req->is_ext_upload ) {
553 my $stash_key = (
554 $self->config->{'serialize'}
555 ? $self->config->{'serialize'}->{'stash_key'}
556 : $self->config->{'stash_key'}
557 )
558 || 'rest';
559 my $output;
560 eval { $output = encode_json( $c->stash->{$stash_key} ); };
561  
562 $c->res->content_type('text/html');
563 $c->res->output( encode_entities($output) );
564 }
565 }
566  
567 sub _parse_NSPathPart_attr {
568 my ( $self, $c ) = @_;
569 return ( PathPart => $self->action_namespace );
570 }
571  
572  
573 sub _parse_NSListPathPart_attr {
574 my ( $self, $c ) = @_;
575 if($self->config->{list_namespace}) {
576 return ( PathPart => $self->config->{list_namespace} )
577 } else {
578 my @path = split( /\//, $self->action_namespace );
579 $path[-1] = Lingua::EN::Inflect::PL(my $name = $path[-1]);
580 $path[-1] = "list_".$path[-1]
581 if($name eq $path[-1]);
582
583 return ( PathPart => join('/', @path) );
584 }
585 }
586  
587 1;
588  
589 __END__