blib/lib/APISchema/DSL.pm untested

filter: Statementstmt 0.0% 0 / 76 Branchbran 0.0% 0 / 6 Conditioncond 0.0% 0 / 3 MC/DCmcdc n/a Subroutinesub 0.0% 0 / 13 Podpod 0.0% 0 / 6 totaltotal 0.0% 0 / 104 CC 4 SCAR 18.7
CC
4
Cov
0%
process
20.0
include
2.0
title
2.0
CRAP 6.5
1 package APISchema::DSL;
2 use strict;
3 use warnings;
4  
5 # lib
6 use APISchema::Schema;
7  
8 # core
9 use Carp ();
10  
11 # cpan
12 use Exporter 'import';
13 use Path::Class qw(file);
14  
15 my %schema_meta = (
16 ( map { $_ => "${_}_resource" } qw(request response) ),
17 ( map { $_ => $_ } qw(title description destination option) ),
18 );
19  
20 our %METHODS = (
21 ( map { $_ => $_ } qw(HEAD GET POST PUT DELETE PATCH) ),
22 FETCH => [qw(GET HEAD)],
23 );
24 our @DIRECTIVES = (qw(include filter resource title description), keys %METHODS);
25 our @EXPORT = @DIRECTIVES;
26  
27 my $_directive = {};
28  
29 sub process (&) {
30 my $dsl = shift;
31  
32 my $schema = APISchema::Schema->new;
33  
34 local $_directive->{include} = sub {
35 my ($file) = @_;
36 -r $_[0] or Carp::croak(sprintf 'No such file: %s', $file);
37 my $content = file($file)->slurp;
38 my $with_utf8 = "use utf8;\n" . $content;
39 eval $with_utf8;
40 Carp::croak($@) if $@;
41 };
42 local $_directive->{title} = sub {
43 $schema->title(@_);
44 };
45 local $_directive->{description} = sub {
46 $schema->description(@_);
47 };
48  
49 my @filters;
50 local $_directive->{filter} = sub {
51 push @filters, $_[0];
52 };
53 local $_directive->{resource} = sub {
54 $schema->register_resource(@_);
55 };
56  
57 local @$_directive{keys %METHODS} = map {
58 my $m = $_;
59 sub {
60 my ($path, @args) = @_;
61 for my $filter (reverse @filters) {
62 local $Carp::CarpLevel += 1;
63 @args = $filter->(@args);
64 }
65 my ($definition, $option) = @args;
66  
67 $schema->register_route(
68 ( map {
69 defined $definition->{$_} ?
70 ( $schema_meta{$_} => $definition->{$_} ) : ();
71 } keys %schema_meta ),
72 defined $option ? (option => $option) : (),
73 route => $path,
74 method => $METHODS{$m},
75 );
76 };
77 } keys %METHODS;
78  
79 $dsl->();
80 return $schema;
81 }
82  
83 # dispatch directives to the definitions
84 sub include ($) { $_directive->{include}->(@_) }
85 sub title ($) { $_directive->{title}->(@_) }
86 sub description ($) { $_directive->{description}->(@_) }
87 sub filter (&) { $_directive->{filter}->(@_) }
88 sub resource ($@) { $_directive->{resource}->(@_) }
89 for my $method (keys %METHODS) {
90 no strict 'refs';
91 *$method = sub ($@) { goto \&{ $_directive->{$method} } };
92 }
93  
94 # disable the global definitions
95 @$_directive{@DIRECTIVES} = (sub {
96 Carp::croak(sprintf(
97 q(%s should be called inside 'process {}' block),
98 join '/', @DIRECTIVES
99 ));
100 }) x scalar @DIRECTIVES;
101  
102 1;
103 __END__