Commit | Line | Data |
fbb43338 |
1 | use strict; |
2 | use warnings; |
3 | |
4 | use Test::More tests=>15; |
5 | use Moose::Util::TypeConstraints; |
6 | use Moose::Meta::TypeConstraint::Parameterizable; |
968cdea9 |
7 | |
b454ba9e |
8 | use Data::Dump qw/dump/; |
fbb43338 |
9 | |
1e60caec |
10 | ## Sketch for how this could work |
968cdea9 |
11 | |
fbb43338 |
12 | ok my $Optional = Moose::Meta::TypeConstraint::Parameterizable->new( |
13 | name => 'Optional', |
14 | package_defined_in => __PACKAGE__, |
15 | parent => find_type_constraint('Item'), |
16 | constraint => sub { 1 }, |
17 | constraint_generator => sub { |
968cdea9 |
18 | my ($type_parameter, @args) = @_; |
19 | my $check = $type_parameter->_compiled_type_constraint(); |
fbb43338 |
20 | return sub { |
968cdea9 |
21 | my (@args) = @_; |
fbb43338 |
22 | if(exists($args[0])) { |
23 | ## If it exists, we need to validate it |
24 | $check->($args[0]); |
25 | } else { |
26 | ## But it's is okay if the value doesn't exists |
27 | return 1; |
28 | } |
29 | } |
30 | } |
31 | ); |
32 | |
1e60caec |
33 | Moose::Util::TypeConstraints::register_type_constraint($Optional); |
fbb43338 |
34 | Moose::Util::TypeConstraints::add_parameterizable_type($Optional); |
1e60caec |
35 | ## END SKETCH |
fbb43338 |
36 | |
37 | isa_ok $Optional, 'Moose::Meta::TypeConstraint::Parameterizable'; |
38 | |
1e60caec |
39 | ok my $int = Moose::Util::TypeConstraints::find_or_parse_type_constraint('Int') |
40 | => 'Got Int'; |
fbb43338 |
41 | |
1e60caec |
42 | ok my $arrayref = Moose::Util::TypeConstraints::find_or_parse_type_constraint('ArrayRef[Int]') |
43 | => 'Got ArrayRef[Int]'; |
fbb43338 |
44 | |
1e60caec |
45 | ok my $Optional_Int = $Optional->parameterize($int), 'Parameterized Int'; |
46 | ok my $Optional_ArrayRef = $Optional->parameterize($arrayref), 'Parameterized ArrayRef'; |
fbb43338 |
47 | |
48 | ok $Optional_Int->check() => 'Optional is allowed to not exist'; |
b454ba9e |
49 | |
fbb43338 |
50 | ok !$Optional_Int->check(undef) => 'Optional is NOT allowed to be undef'; |
51 | ok $Optional_Int->check(199) => 'Correctly validates 199'; |
52 | ok !$Optional_Int->check("a") => 'Correctly fails "a"'; |
53 | |
54 | ok $Optional_ArrayRef->check() => 'Optional is allowed to not exist'; |
55 | ok !$Optional_ArrayRef->check(undef) => 'Optional is NOT allowed to be undef'; |
56 | ok $Optional_ArrayRef->check([1,2,3]) => 'Correctly validates [1,2,3]'; |
57 | ok !$Optional_ArrayRef->check("a") => 'Correctly fails "a"'; |
58 | ok !$Optional_ArrayRef->check(["a","b"]) => 'Correctly fails ["a","b"]'; |