File Coverage

blib/lib/Sah/Schema/str_or_code.pm
Criterion Covered Total %
statement 3 3 100.0
branch n/a
condition n/a
subroutine 1 1 100.0
pod n/a
total 4 4 100.0


line stmt bran cond sub pod time code
1             package Sah::Schema::str_or_code;
2              
3 1     1   253756 use strict;
  1         1  
  1         211  
4              
5             our $AUTHORITY = 'cpan:PERLANCAR'; # AUTHORITY
6             our $DATE = '2024-02-06'; # DATE
7             our $DIST = 'Sah-Schemas-Str'; # DIST
8             our $VERSION = '0.018'; # VERSION
9              
10             our $schema = [any => {
11             summary => 'String or coderef (if string is of the form `sub {...}`)',
12             description => <<'MARKDOWN',
13              
14             Either string or coderef is accepted.
15              
16             If string matches the regex `qr/\Asub\s*\{.*\}\z/s`, then it will be eval'ed
17             into a coderef. If the code fails to compile, the value will be rejected. Note
18             that this means you accept arbitrary code from the user to execute! Please make
19             sure first and foremost that this is acceptable in your case.
20              
21             Currently string is eval'ed in the `main` package, without `use strict` or `use
22             warnings`.
23              
24             This schema is handy if you want to accept string or coderef from the
25             command-line.
26              
27             What's the difference between this schema and `code_from_str` (from
28             )? Both this schema and `code_from_str` accept string,
29             but `code_from_str` will directly compile any input string while this schema
30             will only convert string to code if it is in the form of `sub { ... }`. In other
31             words, this schema can output either string or coderef, while `code_from_str`
32             will always produce coderef.
33              
34             MARKDOWN
35             of => [
36             ['str'],
37             ['code'],
38             ],
39              
40             prefilters => ['Str::maybe_eval'],
41              
42             examples => [
43             {value=>'', valid=>1},
44             {value=>'a', valid=>1},
45             {value=>{}, valid=>0, summary=>'Not a string'},
46              
47             {value=>'sub {}', valid=>1, code_validate=>sub { ref($_[0]) eq 'CODE' & !defined($_[0]->()) }},
48             {value=>'sub{"foo"}', valid=>1, code_validate=>sub { ref($_[0]) eq 'CODE' && $_[0]->() eq 'foo' }},
49             {value=>'sub {', valid=>1, summary=>'Becomes a string'},
50              
51             {value=>'sub {1=2}', valid=>0, summary=>'Code does not compile'},
52             ],
53              
54             }];
55              
56             1;
57             # ABSTRACT:
58              
59             __END__