OpenAPI/Modern/Utilities.pm

filter: Statementstmt 93.0% 241 / 259 Branchbran 85.4% 94 / 110 Conditioncond 76.1% 32 / 42 MC/DCmcdc 61.5% 16 / 26 Subroutinesub 100% 55 / 55 Podpod 0.0% 0 / 14 totaltotal 86.5% 438 / 506 CC 82 SCAR 22.9
CC
82
Cov
89%
convert_request
30.7
deserialize_multipart
16.0
coerce_primitive
16.0
CRAP 9.9
« JSON/Schema/Modern/Vocabulary/OpenAPI_3_0.pm ↑ Summary
1 18 ▶use strictures 2;
Subroutine BEGIN: called CC=1 SCAR=0.0
2 package OpenAPI::Modern::Utilities;
3 # vim: set ts=8 sts=2 sw=2 tw=100 et :
4 # ABSTRACT: Internal utilities and common definitions for OpenAPI::Modern
5  
6 18 our $VERSION = '0.153';
7  
8 18 ▶use 5.020;
Subroutine BEGIN: called CC=1 SCAR=0.0
9 18 ▶use strictures 2;
Subroutine BEGIN: called CC=1 SCAR=0.0
10 18 ▶use stable 0.031 'postderef';
Subroutine BEGIN: called CC=1 SCAR=0.0
11 18 ▶use experimental 'signatures';
Subroutine BEGIN: called CC=1 SCAR=0.0
12 18 ▶no autovivification warn => qw(fetch store exists delete);
Subroutine BEGIN: called CC=1 SCAR=0.0
13 18 ▶use if "$]" >= 5.022, experimental => 're_strict';
Subroutine BEGIN: called CC=1 SCAR=0.0
14 18 ▶no if "$]" >= 5.031009, feature => 'indirect';
Subroutine BEGIN: called CC=1 SCAR=0.0
15 18 ▶no if "$]" >= 5.033001, feature => 'multidimensional';
Subroutine BEGIN: called CC=1 SCAR=0.0
16 18 ▶no if "$]" >= 5.033006, feature => 'bareword_filehandles';
Subroutine BEGIN: called CC=1 SCAR=0.0
17 18 ▶no if "$]" >= 5.041009, feature => 'smartmatch';
Subroutine BEGIN: called CC=1 SCAR=0.0
18 18 ▶no feature 'switch';
Subroutine BEGIN: called CC=1 SCAR=0.0
19 18 ▶use File::ShareDir 'dist_dir';
Subroutine BEGIN: called CC=1 SCAR=0.0
20 18 ▶use List::Util 1.45 qw(uniqstr pairs);
Subroutine BEGIN: called CC=1 SCAR=0.0
21 18 ▶use Scalar::Util 'looks_like_number';
Subroutine BEGIN: called CC=1 SCAR=0.0
22 18 ▶use Mojo::Util qw(url_unescape url_escape);
Subroutine BEGIN: called CC=1 SCAR=0.0
23 18 ▶use Carp 'croak';
Subroutine BEGIN: called CC=1 SCAR=0.0
24 18 ▶use if "$]" < 5.041010, 'List::Util' => 'any';
Subroutine BEGIN: called CC=1 SCAR=0.0
25 18 ▶use if "$]" >= 5.041010, experimental => 'keyword_any';
Subroutine BEGIN: called CC=1 SCAR=0.0
26 18 ▶use builtin::compat qw(blessed indexed);
Subroutine BEGIN: called CC=1 SCAR=0.0
27 18 ▶use JSON::Schema::Modern::Utilities qw(register_schema load_cached_document true false match_media_type);
Subroutine BEGIN: called CC=1 SCAR=0.0
28 18 ▶use namespace::clean;
Subroutine BEGIN: called CC=1 SCAR=0.0
29  
30 18 ▶use Exporter 'import';
Subroutine BEGIN: called CC=1 SCAR=0.0
31  
32 18 our @EXPORT = qw(
33 SUPPORTED_OAD_VERSIONS
34 OAS_VERSIONS
35 DEFAULT_DIALECT
36 DEFAULT_BASE_METASCHEMA
37 DEFAULT_METASCHEMA
38 STRICT_METASCHEMA
39 STRICT_DIALECT
40 OAS_VOCABULARY
41 );
42  
43 18 our @EXPORT_OK = qw(
44 OAS_SCHEMAS
45 MEDIA_RANGE_RE
46 add_vocab_and_default_schemas
47 add_formats
48 convert_request
49 convert_response
50 uri_decode
51 uri_encode
52 uri_encode_strict
53 intersect_types
54 coerce_primitive
55 is_header_name
56 is_cookie_name
57 is_cookie_value
58 elem
59 deserialize_multipart
60 );
61  
62 18 our %EXPORT_TAGS = (
63 constants => \@EXPORT,
64 );
65  
66 # it is likely the case that we can support a point release beyond what's stated here -- but we may
67 # not, so we'll warn to that effect. Every effort will be made to upgrade this implementation to
68 # fully support the latest point release as soon as possible.
69 18 ▶use constant SUPPORTED_OAD_VERSIONS => [ '3.0.4', '3.1.2', '3.2.1' ];
Subroutine BEGIN: called CC=1 SCAR=0.0
70  
71 # in most things, such as checking for compatibility, we only use major.minor as the version number
72 18 ▶use constant OAS_VERSIONS => [ map s/^\d+\.\d+\K\.\d+\z//ar, SUPPORTED_OAD_VERSIONS->@* ];
Subroutine BEGIN: called CC=1 SCAR=0.0
73  
74 # see https://spec.openapis.org/#openapi-specification-schemas for the latest links
75 # these are updated automatically at build time via 'update-schemas'
76  
77 # the main OpenAPI document schema, with permissive (unvalidated) JSON Schemas
78 18 ▶use constant DEFAULT_METASCHEMA => {
Subroutine BEGIN: called CC=1 SCAR=0.0
79 '3.0' => 'https://spec.openapis.org/oas/3.0/schema/2024-10-18',
80 '3.1' => 'https://spec.openapis.org/oas/3.1/schema/2026-11-05',
81 '3.2' => 'https://spec.openapis.org/oas/3.2/schema/2026-11-12',
82 18 };
83  
84 # metaschema for JSON Schemas contained within OpenAPI documents:
85 # standard JSON Schema (presently draft2020-12) + OpenAPI vocabulary
86 18 ▶use constant DEFAULT_DIALECT => {
Subroutine BEGIN: called CC=1 SCAR=0.0
87 18 '3.0' => DEFAULT_METASCHEMA->{'3.0'}.'#/definitions/Schema',
88 '3.1' => 'https://spec.openapis.org/oas/3.1/dialect/2024-11-10',
89 '3.2' => 'https://spec.openapis.org/oas/3.2/dialect/2026-02-26',
90 18 };
91  
92 # OpenAPI document schema that forces the use of the JSON Schema dialect (no $schema overrides
93 # permitted)
94 18 ▶use constant DEFAULT_BASE_METASCHEMA => {
Subroutine BEGIN: called CC=1 SCAR=0.0
95 '3.0' => 'https://spec.openapis.org/oas/3.0/schema/2024-10-18', # same as standard
96 '3.1' => 'https://spec.openapis.org/oas/3.1/schema-base/2026-11-05',
97 '3.2' => 'https://spec.openapis.org/oas/3.2/schema-base/2026-11-12',
98 18 };
99  
100 # OpenAPI vocabulary definition
101 18 ▶use constant OAS_VOCABULARY => {
Subroutine BEGIN: called CC=1 SCAR=0.0
102 '3.1' => 'https://spec.openapis.org/oas/3.1/meta/2024-11-10',
103 '3.2' => 'https://spec.openapis.org/oas/3.2/meta/2026-02-26',
104 18 };
105  
106 # an OpenAPI schema and JSON Schema dialect which prohibit unknown keywords
107 18 ▶use constant STRICT_METASCHEMA => {
Subroutine BEGIN: called CC=1 SCAR=0.0
108 '3.1' => 'https://raw.githubusercontent.com/karenetheridge/OpenAPI-Modern/master/share/3.1/strict-schema.json',
109 '3.2' => 'https://raw.githubusercontent.com/karenetheridge/OpenAPI-Modern/master/share/3.2/strict-schema.json',
110 18 };
111  
112 18 ▶use constant STRICT_DIALECT => {
Subroutine BEGIN: called CC=1 SCAR=0.0
113 '3.1' => 'https://raw.githubusercontent.com/karenetheridge/OpenAPI-Modern/master/share/3.1/strict-dialect.json',
114 '3.2' => 'https://raw.githubusercontent.com/karenetheridge/OpenAPI-Modern/master/share/3.2/strict-dialect.json',
115 18 };
116  
117 # <uri> => <local filename> (under share/) - for internal use only!
118 18 ▶use constant _BUNDLED_SCHEMAS => {
Subroutine BEGIN: called CC=2 SCAR=6.9
119 map +(
120 DEFAULT_METASCHEMA->{$_} => 'oas/'.$_.'/schema.json',
121 $_ eq '3.0' ? () : (
122 DEFAULT_DIALECT->{$_} => 'oas/'.$_.'/dialect.json',
123 DEFAULT_BASE_METASCHEMA->{$_} => 'oas/'.$_.'/schema-base.json',
124 OAS_VOCABULARY->{$_} => 'oas/'.$_.'/vocabulary.json',
125 STRICT_METASCHEMA->{$_} => $_.'/strict-schema.json',
126 18 ▶ STRICT_DIALECT->{$_} => $_.'/strict-dialect.json',
Branch: 1 branch
BranchTrueFalseTotal
$_ eq '3.0' ? : 18 36 54
127 )
128 ), OAS_VERSIONS->@*
129 18 };
130  
131 # these are all loadable on demand, via JSON::Schema::Modern::load_cached_document,
132 # and also made available as s/<date>/latest/
133 # { <oas version> => [ <uri>, <uri>, .. ]
134 18 ▶use constant OAS_SCHEMAS => {
Subroutine BEGIN: called CC=1 SCAR=0.0
135 18 map do {
136 54 my $version = $_;
137 54 $version => [ grep m{/oas/$version/}, keys _BUNDLED_SCHEMAS->%* ]
138 }, OAS_VERSIONS->@*
139 18 };
140  
141 18 my ($OWS, $TOKEN, $QUOTED_STRING);
142 18 ▶BEGIN {
Subroutine BEGIN: called CC=1 SCAR=0.0
143 # see RFC9110 §8.3.1: ABNF "OWS": HT SP
144 18 $OWS = q{[\x09\x20]*};
145  
146 # see RFC9110 §5.6.2: ABNF "token" (identical to RFC2616 §2.2 "token")
147 18 $TOKEN = q{(?a:[[:alnum:]!#$%&'*+.^_`|~-]+)};
148  
149 # see RFC9110 §5.6.6: ABNF "quoted-string"
150 # quoted-string = DQUOTE *( qdtext / quoted-pair ) DQUOTE
151 # qdtext = HTAB / SP / %x21 / %x23-5B / %x5D-7E / obs-text ; everything but: " \ DEL
152 # quoted-pair = "\" ( HTAB / SP / VCHAR / obs-text )
153 18 $QUOTED_STRING = q{"((?:[\x09\x20\x21\x23-\x5B\x5D-\x7E\x80-\xFF]|\x5C[\x09\x20-\x7E\x80-\xFF])*)"};
154 }
155  
156 # note: unanchored!
157 18 ▶use constant MEDIA_RANGE_RE => "$TOKEN/$TOKEN(?:$OWS;$OWS$TOKEN=(?:$TOKEN|$QUOTED_STRING))*";
Subroutine BEGIN: called CC=1 SCAR=0.0
158  
159 599 ▶sub add_vocab_and_default_schemas ($evaluator, $version = OAS_VERSIONS->[-1]) {
Subroutine add_vocab_and_default_schemas: called CC=5 SCAR=16.1
Pod undocumented
160 599 ▶ return if ($evaluator->{__openapi_vocabs_loaded}//={})->{$version}++;
Branch: 1 branch
BranchTrueFalseTotal
if ($$evaluator{"__openapi_vocabs_loaded"} //= {})->{$version}++ 17 582 599
Condition100%2/2
$$evaluator{"__openapi_vocabs_loaded"} //= {}
l!l
18581
MC/DC100%1/1
$$evaluator{"__openapi_vocabs_loaded"} //= {}
$$evaluator{"__openapi_vocabs_loaded"}
Truth table100%2/2
A
A= $$evaluator{"__openapi_vocabs_loaded"}
Aresult
11
00
161  
162 582 $evaluator->add_vocabulary('JSON::Schema::Modern::Vocabulary::OpenAPI');
163  
164 582 foreach my $uri (OAS_SCHEMAS->{$version}->@*) {
165 2253 my $document = load_cached_document($evaluator, $uri);
166  
167 # add "latest" alias for each of these documents, mapping to the same document object
168 2253 $evaluator->add_document(($document->canonical_uri =~ s{/\d{4}-\d{2}-\d{2}\z}{}ar).'/latest', $document);
169 }
170 }
171  
172 601 ▶sub add_formats ($evaluator, $version = OAS_VERSIONS->[-1]) {
Subroutine add_formats: called CC=10 SCAR=23.0
Pod undocumented
173 601 ▶ return if ($evaluator->{__openapi_formats_loaded}//={})->{$version}++;
Branch: 1 branch
BranchTrueFalseTotal
if ($$evaluator{"__openapi_formats_loaded"} //= {})->{$version}++ 17 584 601
Condition100%2/2
$$evaluator{"__openapi_formats_loaded"} //= {}
l!l
18583
MC/DC100%1/1
$$evaluator{"__openapi_formats_loaded"} //= {}
$$evaluator{"__openapi_formats_loaded"}
Truth table100%2/2
A
A= $$evaluator{"__openapi_formats_loaded"}
Aresult
11
00
174  
175 $evaluator->add_format_validation(int32 => +{
176 type => 'number',
177 12 ▶ sub => sub ($x) {
Subroutine __ANON__: called CC=3 SCAR=11.0
178 12 require Math::BigInt; Math::BigInt->VERSION(1.999701);
179 12 $x = Math::BigInt->new($x);
180 12 ▶ return if $x->is_nan;
Branch: 1 branch
BranchTrueFalseTotal
if $x->is_nan 2 10 12
181 10 my $bound = Math::BigInt->new(2) ** 31;
182 10 ▶ $x >= -$bound && $x < $bound;
Branch: 1 branch
BranchTrueFalseTotal
$x >= -$bound and $x < $bound 8 2 10
183 }
184 584 ▶ }) if not $evaluator->_get_format_validation('int32');
Branch: 1 branch
BranchTrueFalseTotal
unless $evaluator->_get_format_validation("int32") 583 1 584
185  
186 $evaluator->add_format_validation(int64 => +{
187 type => 'number',
188 20 ▶ sub => sub ($x) {
Subroutine __ANON__: called CC=3 SCAR=11.0
189 20 require Math::BigInt; Math::BigInt->VERSION(1.999701);
190 20 $x = Math::BigInt->new($x);
191 20 ▶ return if $x->is_nan;
Branch: 1 branch
BranchTrueFalseTotal
if $x->is_nan 2 18 20
192 18 my $bound = Math::BigInt->new(2) ** 63;
193 18 ▶ $x >= -$bound && $x < $bound;
Branch: 1 branch
BranchTrueFalseTotal
$x >= -$bound and $x < $bound 16 2 18
194 }
195 584 ▶ }) if not $evaluator->_get_format_validation('int64');
Branch: 1 branch
BranchTrueFalseTotal
unless $evaluator->_get_format_validation("int64") 583 1 584
196  
197 12 ▶ $evaluator->add_format_validation(float => +{ type => 'number', sub => sub ($x) { 1 } })
Subroutine __ANON__: called CC=1 SCAR=0.0
198 584 ▶ if not $evaluator->_get_format_validation('float');
Branch: 1 branch
BranchTrueFalseTotal
unless $evaluator->_get_format_validation("float") 583 1 584
199 12 ▶ $evaluator->add_format_validation(double => +{ type => 'number', sub => sub ($x) { 1 } })
Subroutine __ANON__: called CC=1 SCAR=0.0
200 584 ▶ if not $evaluator->_get_format_validation('double');
Branch: 1 branch
BranchTrueFalseTotal
unless $evaluator->_get_format_validation("double") 583 1 584
201 2 ▶ $evaluator->add_format_validation(password => +{ type => 'string', sub => sub ($) { 1 } })
Subroutine __ANON__: called CC=1 SCAR=0.0
202 584 ▶ if not $evaluator->_get_format_validation('password');
Branch: 1 branch
BranchTrueFalseTotal
unless $evaluator->_get_format_validation("password") 583 1 584
203  
204 $evaluator->add_format_validation('media-range' => +{
205 type => 'string',
206 741 ▶ sub => sub ($x) {
Subroutine __ANON__: called CC=1 SCAR=0.0
207 # see RFC9110 §12.5.1: ABNF "media-range", RFC9110 §8.3.1: ABNF "media-type"
208 741 return 0+!!($x =~ ('^'.MEDIA_RANGE_RE.'\z'));
209 },
210 584 ▶ }) if not $evaluator->_get_format_validation('media-range');
Branch: 1 branch
BranchTrueFalseTotal
if not $evaluator->_get_format_validation("media-range") 583 1 584
211 }
212  
213 # generates the equivalent Mojo::Message::Request from any of:
214 # - HTTP::Request
215 # - Plack::Request
216 # - Catalyst::Request
217 # - Dancer2::Core::Request
218 # results may be unsatisfactory if not a valid HTTP request.
219 571 ▶sub convert_request ($request) {
Subroutine convert_request: called CC=14 SCAR=34.2
Pod undocumented
220 571 ▶ return $request if $request->isa('Mojo::Message::Request');
Branch: 1 branch
BranchTrueFalseTotal
if $request->isa("Mojo::Message::Request") 290 281 571
221  
222 281 my $req = Mojo::Message::Request->new;
223  
224 281 ▶ if ($request->isa('HTTP::Request')) {
Branch: 2 branches
BranchTrueFalseTotal
if ($request->isa('HTTP::Request')) { } 273 8 281
elsif ($request->isa('Plack::Request') or $request->isa('Catalyst::Request')) { } 0 8 8
225 273 $req->method($request->method);
226 273 $req->url(Mojo::URL->new($request->uri));
227 273 ▶ $req->version($request->protocol =~ s{^HTTP/(\d\.\d)\z}{$1}ar) if $request->protocol;
Branch: 1 branch
BranchTrueFalseTotal
if $request->protocol 272 1 273
228 # remember, if you're constructing $body manually, you need to =~ s/\n/\r\n/g;
229 273 my $body = $request->content;
230  
231 273 ▶ if (match_media_type(scalar $request->content_type, ['multipart/*'])) {
Branch: 1 branch
BranchTrueFalseTotal
if (match_media_type(scalar $request->content_type, ['multipart/*'])) { } 80 193 273
232 80 $req->content(Mojo::Content::MultiPart->new);
233 80 $req->headers->add(@$_) foreach pairs $request->headers->flatten;
234 80 $req->content->emit(read => $body);
235 }
236 else {
237 193 $req->headers->add(@$_) foreach pairs $request->headers->flatten;
238 193 ▶ $req->body($body) if length $body;
Branch: 1 branch
BranchTrueFalseTotal
if length $body 97 96 193
239 }
240 }
241 # note: Dancer2::Core::Request inherits from Plack::Request
242 ▶ elsif ($request->isa('Plack::Request') or $request->isa('Catalyst::Request')) {
Condition33%1/3
$request->isa("Plack::Request") or $request->isa("Catalyst::Request")
l!l&&r!l&&!r
008
MC/DC0%0/2
$request->isa("Plack::Request") or $request->isa("Catalyst::Request")
$request->isa("Plack::Request") $request->isa("Catalyst::Request")
Truth table33%1/3
A or B
A= $request->isa("Plack::Request")B= $request->isa("Catalyst::Request")
ABresult
1X1
011
000
243 # make $request->content work
244 0 ▶ $request = do { +require Plack::Request; Plack::Request->new($request->env) }
Branch: 1 branch
BranchTrueFalseTotal
unless $request->isa("Plack::Request") 0 0 0
245 if not $request->isa('Plack::Request');
246  
247 0 ▶ if (match_media_type($request->content_type, ['multipart/*'])) {
Branch: 1 branch
BranchTrueFalseTotal
if (match_media_type($request->content_type, ['multipart/*'])) { } 0 0 0
248 0 $req->content(Mojo::Content::MultiPart->new);
249 0 $req->parse($request->env);
250 0 $req->content->emit(read => $request->content);
251 }
252 else {
253 0 $req->parse($request->env); # parsing psgi.input alters it; must read content afterwards
254 0 my $body = $request->content;
255 0 ▶ $req->body($body) if length $body;
Branch: 1 branch
BranchTrueFalseTotal
if length $body 0 0 0
256 }
257  
258 # Plack is unable to distinguish between %2F and /, so the raw (undecoded) uri can be passed
259 # here. see PSGI::FAQ
260 0 ▶ $req->url(Mojo::URL->new($request->env->{REQUEST_URI})) if exists $request->env->{REQUEST_URI};
Branch: 1 branch
BranchTrueFalseTotal
if exists $request->env->{"REQUEST_URI"} 0 0 0
261 }
262 else {
263 8 return $req->error({ message => 'unknown type '.ref($request) });
264 }
265  
266 # we could call $req->fix_headers here to add a missing Content-Length or Host, but proper
267 # requests from the network should always have these set.
268  
269 273 $req->finish;
270 273 return $req;
271 }
272  
273 # generates the equivalent Mojo::Message::Response from any of:
274 # - HTTP::Response
275 # - Plack::Response
276 # - Catalyst::Response
277 # - Dancer2::Core::Response
278 # results may be unsatisfactory if not a valid HTTP response.
279 84 ▶sub convert_response ($response) {
Subroutine convert_response: called CC=11 SCAR=26.4
Pod undocumented
280 84 ▶ return $response if $response->isa('Mojo::Message::Response');
Branch: 1 branch
BranchTrueFalseTotal
if $response->isa("Mojo::Message::Response") 42 42 84
281  
282 42 my $res = Mojo::Message::Response->new;
283  
284 42 my (@headers, $body);
285 42 ▶ if ($response->isa('HTTP::Response')) {
Branch: 3 branches
BranchTrueFalseTotal
if ($response->isa('HTTP::Response')) { } 41 1 42
elsif ($response->isa('Plack::Response') or $response->isa('Dancer2::Core::Response')) { } 0 1 1
elsif ($response->isa('Catalyst::Response')) { } 0 1 1
286 41 $res->code($response->code);
287 41 ▶ $res->version($response->protocol =~ s{^HTTP/(\d\.\d)\z}{$1}ar) if $response->protocol;
Branch: 1 branch
BranchTrueFalseTotal
if $response->protocol 41 0 41
288 41 @headers = pairs $response->headers->flatten;
289 41 $body = $response->content;
290 }
291 ▶ elsif ($response->isa('Plack::Response') or $response->isa('Dancer2::Core::Response')) {
Condition33%1/3
$response->isa("Plack::Response") or $response->isa("Dancer2::Core::Response")
l!l&&r!l&&!r
001
MC/DC0%0/2
$response->isa("Plack::Response") or $response->isa("Dancer2::Core::Response")
$response->isa("Plack::Response") $response->isa("Dancer2::Core::Response")
Truth table33%1/3
A or B
A= $response->isa("Plack::Response")B= $response->isa("Dancer2::Core::Response")
ABresult
1X1
011
000
292 0 $res->code($response->status);
293 0 @headers = pairs $response->headers->psgi_flatten_without_sort->@*;
294 0 $body = $response->content;
295 }
296 elsif ($response->isa('Catalyst::Response')) {
297 0 $res->code($response->status);
298 0 HTTP::Headers->VERSION('6.07');
299 0 @headers = pairs $response->headers->flatten;
300 0 $body = $response->body;
301 }
302 else {
303 1 return $res->error({ message => 'unknown type '.ref($response) });
304 }
305  
306 41 ▶ if (match_media_type(scalar $response->content_type, ['multipart/*'])) {
Branch: 1 branch
BranchTrueFalseTotal
if (match_media_type(scalar $response->content_type, ['multipart/*'])) { } 2 39 41
307 2 $res->content(Mojo::Content::MultiPart->new);
308 2 $res->headers->add(@$_) foreach @headers;
309 2 $res->content->emit(read => $body);
310 }
311 else {
312 39 $res->headers->add(@$_) foreach @headers;
313 39 ▶ $res->body($body) if length $body;
Branch: 1 branch
BranchTrueFalseTotal
if length $body 25 14 39
314 }
315  
316 # we could call $res->fix_headers here to add a missing Content-Length, but proper responses from
317 # the network should always have it set.
318  
319 41 $res->finish;
320 41 return $res;
321 }
322  
323 # url-percent-decode and UTF-8-decode a string
324 1393 ▶sub uri_decode ($str) {
Subroutine uri_decode: called CC=1 SCAR=0.0
Pod undocumented
325 1393 Encode::decode('UTF-8', url_unescape($str), Encode::DIE_ON_ERR);
326 }
327  
328 # UTF-8-encode and url-percent-encode a string (only encoding characters that MUST be encoded)
329 77 ▶sub uri_encode ($str) {
Subroutine uri_encode: called CC=1 SCAR=0.0
Pod undocumented
330 77 url_escape(Encode::encode('UTF-8', $str, Encode::DIE_ON_ERR), '^A-Za-z0-9\-._~!$&\'()*+,;=:@');
331 }
332  
333 # UTF-8-encode and url-percent-encode a string (encoding all of reserved, gen-delims and sub-delims)
334 60 ▶sub uri_encode_strict ($str) {
Subroutine uri_encode_strict: called CC=1 SCAR=0.0
Pod undocumented
335 60 url_escape(Encode::encode('UTF-8', $str, Encode::DIE_ON_ERR));
336 }
337  
338 # find the intersection of all the lists, number and integer as equivalent
339 2271 ▶sub intersect_types (@lol) {
Subroutine intersect_types: called CC=4 SCAR=13.9
Pod undocumented
340 2271 my $count = @lol;
341 2271 my %vals;
342 2271 ▶ while (my $list = shift @lol) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $list = shift @lol) 2502 2271 4773
343 2502 ▶ ++$vals{$_} foreach uniqstr map +($_ eq 'integer' ? 'number' : $_), @$list;
Branch: 1 branch
BranchTrueFalseTotal
$_ eq 'integer' ? : 93 3532 3625
344 }
345  
346 2271 return grep $vals{$_} == $count, keys %vals;
347 }
348  
349 # Given a reference to a string or number, coerce it to the best-matching primitive in the allowed
350 # list other than object and array (which must be deserialized according to style rules first)
351 # The core types are: (array, object, null, boolean, string, number)
352 # Returns validity status, allowing the caller to fall back to the original value or generate an error.
353 1297 ▶sub coerce_primitive ($dataref, $types = []) {
Subroutine coerce_primitive: called CC=16 SCAR=27.7
Pod undocumented
354 1297 ▶ return if not @$types; # no type specified; indicate failure
Branch: 1 branch
BranchTrueFalseTotal
unless @$types 9 1288 1297
355 1288 ▶ return if not defined $$dataref; # null is an error
Branch: 1 branch
BranchTrueFalseTotal
unless defined $$dataref 3 1285 1288
356 1285 ▶ return if ref $$dataref; # booleans, arrays, objects are errors
Branch: 1 branch
BranchTrueFalseTotal
if ref $$dataref 6 1279 1285
357  
358 1279 my $data = $$dataref; # make copy to avoid unwanted mutation of the original
359  
360 1279 ▶ $$dataref = undef, return 1 if $data eq '' and elem('null', $types);
Branch: 1 branch
BranchTrueFalseTotal
if $data eq "" and elem("null", $types) 34 1245 1279
Condition100%3/3
$data eq "" and elem("null", $types)
!ll&&!rl&&r
12162934
MC/DC100%2/2
$data eq "" and elem("null", $types)
$data eq "" elem("null", $types)
Truth table100%3/3
A and B
A= $data eq ""B= elem("null", $types)
ABresult
0X0
100
111
361  
362 1245 ▶ if (elem('boolean', $types)) {
Branch: 1 branch
BranchTrueFalseTotal
if (elem("boolean", $types)) 120 1125 1245
363 120 ▶ $$dataref = false, return 1 if $data eq '0' or $data eq 'false' or $data eq '';
Branch: 1 branch
BranchTrueFalseTotal
if $data eq 0 or $data eq "false" or $data eq "" 52 68 120
Condition100%6/6
$data eq 0 or $data eq "false" or $data eq ""
l!l&&r!l&&!r
411168
$data eq 0 or $data eq "false"
l!l&&r!l&&!r
34779
MC/DC100%3/3
$data eq 0 or $data eq "false" or $data eq ""
$data eq 0 $data eq "false" $data eq ""
Truth table100%4/4
A or B or C
A= $data eq 0B= $data eq "false"C= $data eq ""
ABCresult
1XX1
01X1
0011
0000
364 68 ▶ $$dataref = true, return 1 if $data eq '1' or $data eq 'true';
Branch: 1 branch
BranchTrueFalseTotal
if $data eq 1 or $data eq "true" 40 28 68
Condition100%3/3
$data eq 1 or $data eq "true"
l!l&&r!l&&!r
31928
MC/DC100%2/2
$data eq 1 or $data eq "true"
$data eq 1 $data eq "true"
Truth table100%3/3
A or B
A= $data eq 1B= $data eq "true"
ABresult
1X1
011
000
365 }
366  
367 1153 ▶ $$dataref = 0+$$dataref, return 1 if elem('number', $types) and looks_like_number($$dataref);
Branch: 1 branch
BranchTrueFalseTotal
if elem("number", $types) and &looks_like_number($$dataref) 405 748 1153
Condition100%3/3
elem("number", $types) and &looks_like_number($$dataref)
!ll&&!rl&&r
72622405
MC/DC100%2/2
elem("number", $types) and &looks_like_number($$dataref)
elem("number", $types) &looks_like_number($$dataref)
Truth table100%3/3
A and B
A= elem("number", $types)B= &looks_like_number($$dataref)
ABresult
0X0
100
111
368  
369 748 ▶ $$dataref = ''.$$dataref, return 1 if elem('string', $types);
Branch: 1 branch
BranchTrueFalseTotal
if elem("string", $types) 703 45 748
370 }
371  
372  
373 # RFC9110 §5.1
374 # field-name = token
375 441 ▶sub is_header_name ($name) {
Subroutine is_header_name: called CC=2 SCAR=9.2
Pod undocumented
376 441 ▶ !!(defined $name && $name =~ /^$TOKEN\z/);
Condition33%1/3
defined $name && $name =~ /^$TOKEN\z/u
!ll&&!rl&&r
00441
MC/DC0%0/2
defined $name && $name =~ /^$TOKEN\z/u
defined $name $name =~ /^$TOKEN\z/u
Truth table33%1/3
A && B
A= defined $nameB= $name =~ /^$TOKEN\z/u
ABresult
0X0
100
111
377 }
378  
379 # RFC6265 §3.1 and §4.2.1
380 # cookie-header = "Cookie:" OWS cookie-string OWS
381 # cookie-string = cookie-pair *( ";" SP cookie-pair )
382 # cookie-pair = cookie-name "=" cookie-value
383 # cookie-name = token ; (defined in RFC2616 §2.2)
384 # cookie-value = *cookie-octet / ( DQUOTE *cookie-octet DQUOTE )
385 # cookie-octet = %x21 / %x23-2B / %x2D-3A / %x3C-5B / %x5D-7E ; US-ASCII characters excluding
386 # ; CTLs, whitespace, DQUOTE, comma, semicolon, and backslash
387  
388 286 ▶sub is_cookie_name ($name) {
Subroutine is_cookie_name: called CC=2 SCAR=7.2
Pod undocumented
389 286 ▶ !!(defined $name && $name =~ /^$TOKEN\z/);
Condition66%2/3
defined $name && $name =~ /^$TOKEN\z/u
!ll&&!rl&&r
03283
MC/DC50%1/2
defined $name && $name =~ /^$TOKEN\z/u
defined $name $name =~ /^$TOKEN\z/u
Truth table66%2/3
A && B
A= defined $nameB= $name =~ /^$TOKEN\z/u
ABresult
0X0
100
111
390 }
391  
392 280 ▶sub is_cookie_value ($value) {
Subroutine is_cookie_value: called CC=2 SCAR=7.2
Pod undocumented
393 280 ▶ !!(defined $value && $value =~ /^("?)[\x21\x23-\x2B\x2D-\x3A\x3C-\x5B\x5D-\x7E]*\1\z/);
Condition66%2/3
defined $value && $value =~ /^("?)[\x21\x23-\x2B\x2D-\x3A\x3C-\x5B\x5D-\x7E]*\1\z/u
!ll&&!rl&&r
07273
MC/DC50%1/2
defined $value && $value =~ /^("?)[\x21\x23-\x2B\x2D-\x3A\x3C-\x5B\x5D-\x7E]*\1\z/u
defined $value $value =~ /^("?)[\x21\x23-\x2B\x2D-\x3A\x3C-\x5B\x5D-\x7E]*\1\z/u
Truth table66%2/3
A && B
A= defined $valueB= $value =~ /^("?)[\x21\x23-\x2B\x2D-\x3A\x3C-\x5B\x5D-\x7E]*\1\z/u
ABresult
0X0
100
111
394 }
395  
396 # are any $items a member of $set?
397 8559 ▶sub elem ($items, $set) {
Subroutine elem: called CC=5 SCAR=16.5
Pod undocumented
398 8559 ▶ croak 'set is not an array' if ref $set ne 'ARRAY';
Branch: 1 branch
BranchTrueFalseTotal
if ref $set ne "ARRAY" 0 8559 8559
399 8559 ▶ $items = [ $items ] if ref $items ne 'ARRAY';
Branch: 1 branch
BranchTrueFalseTotal
if ref $items ne "ARRAY" 7181 1378 8559
400  
401 8559 any {
402 10153 my $item = $_;
403 10153 ▶ any { defined $item ? (defined $_ && $item eq $_) : (!defined $_) } @$set
Branch: 1 branch
BranchTrueFalseTotal
defined $item ? : 14014 0 14014
Condition66%2/3
defined $_ and $item eq $_
!ll&&!rl&&r
098494165
MC/DC50%1/2
defined $_ and $item eq $_
defined $_ $item eq $_
Truth table66%2/3
A and B
A= defined $_B= $item eq $_
ABresult
0X0
100
111
404 }
405 @$items;
406 }
407  
408 # Operates on a Mojo::Content object; returns two values:
409 # - all parts as an arrayref of objects:
410 # for multipart/form-data: [ { $name => $value }, { ... }, ]
411 # for other multipart/*: [ $value1, $value2, ... ]
412 # - headers for each part as an arrayref of objects:
413 # [ { $header1 => $value, $header2 => $value, ... }, { ... }, ... ]
414 # Operates recursively; parts within parts are also deserialized.
415 # Strings are not decoded with charset here, but individual fields' Content-Type are included so
416 # that can be done afterwards (or correlated with an encoding object)
417 # Based loosely on Mojo::Message::_parse_formdata
418 252 ▶sub deserialize_multipart ($content) {
Subroutine deserialize_multipart: called CC=16 SCAR=27.7
Pod undocumented
419 252 ▶ die 'body is not multipart' if not blessed $content or not $content->is_multipart;
Branch: 1 branch
BranchTrueFalseTotal
unless builtin::blessed($content) and $content->is_multipart 2 250 252
Condition66%2/3
builtin::blessed($content) and $content->is_multipart
!ll&&!rl&&r
20250
MC/DC50%1/2
builtin::blessed($content) and $content->is_multipart
builtin::blessed($content) $content->is_multipart
Truth table66%2/3
A and B
A= builtin::blessed($content)B= $content->is_multipart
ABresult
0X0
100
111
420  
421 250 my (@content, @headers);
422 250 my $is_form = match_media_type($content->headers->content_type, ['multipart/form-data']);
423  
424 250 my $part_num = 0;
425 250 foreach my $part ($content->parts->@*) {
426 577 my $headers = $part->headers->to_hash('multi');
427 577 ▶ $headers = +{ map +($_ => ($headers->{$_}->@* == 1 ? $headers->{$_}[0] : $headers->{$_} )),
Branch: 1 branch
BranchTrueFalseTotal
@{$$headers{$_}} == 1 ? : 847 6 853
428 keys $headers->%* };
429  
430 577 my $value;
431 577 ▶ if ($part->is_multipart) {
Branch: 1 branch
BranchTrueFalseTotal
if ($part->is_multipart) { } 72 505 577
432 72 ($value, my $new_headers) = deserialize_multipart($part);
433 # new_headers is an arrayref... copy into the $headers hash with array indices as hash keys
434 72 $headers = { %$headers, indexed $new_headers->@* };
435 }
436 else {
437 505 $value = $part->asset->slurp;
438 }
439  
440 577 ▶ if ($is_form) {
Branch: 1 branch
BranchTrueFalseTotal
if ($is_form) 425 152 577
441 425 my $disposition = $part->headers->content_disposition;
442 425 ▶ die 'missing Content-Disposition' if not defined $disposition;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $disposition 2 423 425
443  
444 # see ABNF at RFC2183 §2 (RFC6266 does not apply to multipart/form-data bodies)
445 423 my ($disposition_type) = ($disposition =~ /^($TOKEN)/);
446 423 ▶ next if $disposition_type ne 'form-data';
Branch: 1 branch
BranchTrueFalseTotal
if $disposition_type ne "form-data" 0 423 423
447  
448 423 pos($disposition) = length $&;
449 423 my ($leftovers, $part_name) = ($');
450 423 ▶ while ($disposition =~ /\G$OWS;$OWS($TOKEN)=($TOKEN|$QUOTED_STRING)/g) {
Branch: 1 branch
BranchTrueFalseTotal
if ($disposition =~ /\G$OWS;$OWS($TOKEN)=($TOKEN|$QUOTED_STRING)/gu) 426 423 849
451 426 my ($name, $value, $qs_value) = ($1, $2, $3); # $QUOTED_STRING contains $3
452 426 $leftovers = $';
453 426 ▶ next if $name ne 'name';
Branch: 1 branch
BranchTrueFalseTotal
if $name ne "name" 4 422 426
454 # RFC9110 §5.6.4: "The backslash octet ("\") can be used as a single-octet quoting mechanism
455 # within quoted-string and comment constructs. Recipients that process the value of a
456 # quoted-string MUST handle a quoted-pair as if it were replaced by the octet following the
457 # backslash."
458 # RFC9110 §5.6.6: "Parameter names are case-insensitive. Parameter values might or might not
459 # be case-sensitive, depending on the semantics of the parameter name."
460 # RFC7578 §5.1.1: "If non-ASCII field names are unavoidable, form or application creators
461 # SHOULD use UTF-8 uniformly. This will minimize interoperability problems."
462 422 ▶ $part_name = Encode::decode('UTF-8',
Branch: 1 branch
BranchTrueFalseTotal
defined $qs_value ? : 420 2 422
463 defined $qs_value ? ($qs_value =~ s/\x5C(.)/$1/gr) : $value,
464 Encode::DIE_ON_ERR | Encode::LEAVE_SRC);
465 }
466  
467 423 ▶ next if length $leftovers;
Branch: 1 branch
BranchTrueFalseTotal
if length $leftovers 0 423 423
468 423 ▶ $value = { $part_name // 'part_'.$part_num => $value };
Condition100%2/2
$part_name // 'part_' . $part_num
l!l
4221
MC/DC100%1/1
$part_name // 'part_' . $part_num
$part_name
Truth table100%2/2
A
A= $part_name
Aresult
11
00
469 }
470  
471 575 $part_num++;
472 575 push @content, $value;
473 575 push @headers, $headers;
474 }
475  
476 # remove empty header entries
477 248 my $seen_header;
478 248 foreach my $idx (reverse 0..$#headers) {
479 280 ▶ $seen_header++, last if keys $headers[$idx]->%*;
Branch: 1 branch
BranchTrueFalseTotal
if keys %{$headers[$idx]} 230 50 280
480 50 delete $headers[$idx];
481 }
482  
483 248 return (\@content, \@headers);
484 }
485  
486 {
487 # make all bundled schemas available via JSON::Schema::Modern::load_cached_document
488 18 my $share_dir = dist_dir('OpenAPI-Modern');
489 18 foreach my $uri (keys _BUNDLED_SCHEMAS->%*) {
490 234 register_schema($uri, $share_dir.'/'._BUNDLED_SCHEMAS->{$uri});
491 }
492 }
493  
494 18 1;
495  
496 __END__
« JSON/Schema/Modern/Vocabulary/OpenAPI_3_0.pm ↑ Summary